botserver/packages/core.gbapp/services/GBDeployer.ts

1061 lines
36 KiB
TypeScript
Raw Normal View History

2018-04-21 02:59:30 -03:00
/*****************************************************************************\
2024-01-09 17:40:48 -03:00
| ® |
| |
| |
| |
| |
2018-04-21 02:59:30 -03:00
| |
| General Bots Copyright (c) pragmatismo.cloud. All rights reserved. |
2018-04-21 02:59:30 -03:00
| Licensed under the AGPL-3.0. |
2018-11-11 19:09:18 -02:00
| |
2018-04-21 02:59:30 -03:00
| According to our dual licensing model, this program can be used either |
| under the terms of the GNU Affero General Public License, version 3, |
| or under a proprietary license. |
| |
| The texts of the GNU Affero General Public License with an additional |
| permission and of our proprietary license can be found at and |
| in the LICENSE file you have received along with this program. |
| |
| This program is distributed in the hope that it will be useful, |
2018-09-11 19:40:53 -03:00
| but WITHOUT ANY WARRANTY, without even the implied warranty of |
2018-04-21 02:59:30 -03:00
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU Affero General Public License for more details. |
| |
| "General Bots" is a registered trademark of pragmatismo.cloud. |
2018-04-21 02:59:30 -03:00
| The licensing of the program under the AGPLv3 does not imply a |
| trademark license. Therefore any rights, title and interest in |
| our trademarks remain entirely with us. |
| |
\*****************************************************************************/
2018-11-11 19:09:18 -02:00
/**
* @fileoverview General Bots server core.
*/
'use strict';
2024-09-06 15:30:03 -03:00
import path from 'path';
import express from 'express';
import child_process from 'child_process';
2024-05-25 19:11:01 -03:00
import { rimraf } from 'rimraf';
import urlJoin from 'url-join';
2024-09-10 23:25:07 -03:00
import fs from 'fs/promises';
2020-12-31 15:36:19 -03:00
import { GBError, GBLog, GBMinInstance, IGBCoreService, IGBDeployer, IGBInstance, IGBPackage } from 'botlib';
import { AzureSearch } from 'pragmatismo-io-framework';
2020-12-31 15:36:19 -03:00
import { CollectionUtil } from 'pragmatismo-io-framework';
import { GBServer } from '../../../src/app.js';
import { GBVMService } from '../../basic.gblib/services/GBVMService.js';
2024-08-19 17:09:23 -03:00
import Excel from 'exceljs';
import asyncPromise from 'async-promises';
import { GuaribasPackage } from '../models/GBModel.js';
import { GBAdminService } from './../../admin.gbapp/services/GBAdminService.js';
import { AzureDeployerService } from './../../azuredeployer.gbapp/services/AzureDeployerService.js';
import { KBService } from './../../kb.gbapp/services/KBService.js';
import { GBConfigService } from './GBConfigService.js';
import { GBImporter } from './GBImporterService.js';
import { TeamsService } from '../../teams.gblib/services/TeamsService.js';
import MicrosoftGraph from '@microsoft/microsoft-graph-client';
2023-02-26 06:05:57 -03:00
import { GBLogEx } from './GBLogEx.js';
import { GBUtil } from '../../../src/util.js';
import { HNSWLib } from '@langchain/community/vectorstores/hnswlib';
import { OpenAIEmbeddings } from '@langchain/openai';
2024-09-12 15:05:32 -03:00
import { GBMinService } from './GBMinService.js';
/**
2020-12-31 15:36:19 -03:00
* Deployer service for bots, themes, ai and more.
*/
export class GBDeployer implements IGBDeployer {
2020-12-26 19:47:38 -03:00
/**
* Where should deployer look into for general packages.
*/
public static deployFolder = 'packages';
2020-12-26 19:47:38 -03:00
/**
* The work folder used to download artifacts from bot storage.
*/
public static workFolder = 'work';
2020-12-26 19:47:38 -03:00
/**
* Reference to the core service.
*/
public core: IGBCoreService;
2020-12-26 19:47:38 -03:00
2020-12-31 15:36:19 -03:00
/**
2020-12-26 19:47:38 -03:00
* Reference to the importer service.
*/
public importer: GBImporter;
2018-09-10 12:09:48 -03:00
2020-12-26 19:47:38 -03:00
/**
* Deployer needs core and importer to be created.
*/
constructor(core: IGBCoreService, importer: GBImporter) {
this.core = core;
this.importer = importer;
2018-04-21 02:59:30 -03:00
}
2020-12-26 19:47:38 -03:00
/**
* Builds a connection string text to be used in direct
* use to database like the Indexer (Azure Search).
*/
public static getConnectionStringFromInstance(instance: IGBInstance) {
2024-05-25 19:11:01 -03:00
return `Server=tcp:${GBConfigService.get('STORAGE_SERVER')},1433;Database=${GBConfigService.get(
'STORAGE_NAME'
)};User ID=${GBConfigService.get('STORAGE_USERNAME')};Password=${GBConfigService.get(
'STORAGE_PASSWORD'
)};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;`;
}
/**
* Retrives token and initialize drive client API.
*/
public static async internalGetDriveClient(min: GBMinInstance) {
2023-08-25 19:09:03 -03:00
let token;
2024-05-25 19:11:01 -03:00
// Get token as root only if the bot does not have
// an custom tenant for retrieving packages.
2024-05-25 19:11:01 -03:00
token = await (min.adminService as any)['acquireElevatedToken'](
min.instance.instanceId,
min.instance.authenticatorTenant ? false : true
);
2023-08-25 19:09:03 -03:00
2024-05-25 19:11:01 -03:00
const siteId = process.env.STORAGE_SITE_ID;
2024-08-19 23:03:58 -03:00
const libraryId = GBConfigService.get('STORAGE_LIBRARY');
2023-08-25 19:09:03 -03:00
2024-05-25 19:11:01 -03:00
const client = MicrosoftGraph.Client.init({
authProvider: done => {
done(null, token);
}
});
const baseUrl = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}`;
min['cacheToken'] = { baseUrl, client };
2024-05-25 19:11:01 -03:00
return { baseUrl, client };
}
/**
* Performs package deployment in all .gbai or default.
*/
public async deployPackages(core: IGBCoreService, server: any, appPackages: IGBPackage[]) {
2020-12-26 19:47:38 -03:00
// Builds lists of paths to search for packages.
let paths = [urlJoin(process.env.PWD, GBDeployer.deployFolder), urlJoin(process.env.PWD, GBDeployer.workFolder)];
const additionalPath = GBConfigService.get('ADDITIONAL_DEPLOY_PATH');
if (additionalPath !== undefined && additionalPath !== '') {
paths = paths.concat(additionalPath.split(';'));
}
const botPackages: string[] = [];
const gbappPackages: string[] = [];
2020-12-31 15:36:19 -03:00
const generalPackages: string[] = [];
2024-09-07 00:08:23 -03:00
async function scanPackageDirectory(directory) {
2020-12-26 19:47:38 -03:00
// Gets all directories.
2024-09-07 18:13:36 -03:00
const isDirectory = async source => (await fs.lstat(source)).isDirectory();
const getDirectories = async source =>
2024-09-10 23:25:07 -03:00
(await fs.readdir(source)).map(name => path.join(source, name)).filter(isDirectory);
2024-09-09 10:28:38 -03:00
const dirs = await getDirectories(directory);
await CollectionUtil.asyncForEach(dirs, async element => {
2020-12-26 19:47:38 -03:00
// For each folder, checks its extensions looking for valid packages.
if (element === '.') {
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `Ignoring ${element}...`);
} else {
2024-09-06 15:30:03 -03:00
const name = path.basename(element);
2020-12-26 19:47:38 -03:00
// Skips what does not need to be loaded.
2022-11-19 23:34:58 -03:00
if (
process.env.GBAPP_SKIP &&
(process.env.GBAPP_SKIP.toLowerCase().indexOf(name) !== -1 || process.env.GBAPP_SKIP === 'true')
) {
return;
}
2020-12-26 19:47:38 -03:00
// Put it in corresponding collections.
if (element.endsWith('.gbot')) {
botPackages.push(element);
} else if (element.endsWith('.gbapp') || element.endsWith('.gblib')) {
gbappPackages.push(element);
} else {
generalPackages.push(element);
}
}
});
}
2020-12-26 19:47:38 -03:00
// Start the process of searching.
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `Deploying Application packages...`);
await CollectionUtil.asyncForEach(paths, async e => {
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `Looking in: ${e}...`);
await scanPackageDirectory(e);
});
// Deploys all .gblib files first.
2020-12-31 15:36:19 -03:00
const list = [];
for (let index = 0; index < gbappPackages.length; index++) {
const element = gbappPackages[index];
if (element.endsWith('.gblib')) {
list.push(element);
gbappPackages.splice(index, 1);
}
}
for (let index = 0; index < gbappPackages.length; index++) {
const element = gbappPackages[index];
list.push(element);
}
await this.deployAppPackages(list, core, appPackages);
2018-09-10 12:09:48 -03:00
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `App Package deployment done.`);
2018-09-10 12:09:48 -03:00
}
2020-12-26 19:47:38 -03:00
/**
* Deploys a new blank bot to the database, cognitive services and other services.
*/
public async deployBlankBot(botId: string, mobile: string, email: string) {
2020-12-26 19:47:38 -03:00
// Creates a new row on the GuaribasInstance table.
2020-12-31 15:36:19 -03:00
const instance = await this.importer.createBotInstance(botId);
const bootInstance = GBServer.globals.bootInstance;
2020-12-26 19:47:38 -03:00
2024-08-20 15:13:43 -03:00
if (GBConfigService.get('STORAGE_NAME')) {
2024-08-19 23:03:58 -03:00
// Gets the access token to perform service operations.
2024-08-19 23:03:58 -03:00
const accessToken = await (GBServer.globals.minBoot.adminService as any)['acquireElevatedToken'](
bootInstance.instanceId,
true
);
2024-08-19 23:03:58 -03:00
// Creates the MSFT application that will be associated to the bot.
2020-12-26 19:47:38 -03:00
2024-08-19 23:03:58 -03:00
const service = await AzureDeployerService.createInstance(this);
const application = await service.createApplication(accessToken, botId);
// Fills new instance base information and get App secret.
2024-08-19 23:03:58 -03:00
instance.marketplaceId = (application as any).appId;
instance.marketplacePassword = await service.createApplicationSecret(accessToken, (application as any).id);
}
2020-12-26 19:47:38 -03:00
instance.adminPass = GBAdminService.getRndPassword();
instance.title = botId;
2024-05-25 19:11:01 -03:00
instance.activationCode = instance.botId.substring(0, 15);
instance.state = 'active';
2020-12-26 19:47:38 -03:00
instance.nlpScore = 0.8;
instance.searchScore = 0.25;
instance.params = JSON.stringify({ 'Can Publish': mobile, 'Admin Notify E-mail': email });
2020-12-26 19:47:38 -03:00
// Saves bot information to the store.
await this.core.saveInstance(instance);
2024-08-20 15:13:43 -03:00
if (GBConfigService.get('STORAGE_NAME')) {
2024-08-19 23:03:58 -03:00
await this.deployBotOnAzure(instance, GBServer.globals.publicAddress);
}
2024-08-21 13:09:50 -03:00
// Makes available bot to the channels and .gbui interfaces.
await GBServer.globals.minService.mountBot(instance);
2020-12-26 19:47:38 -03:00
// Creates remaining objects on the cloud and updates instance information.
2024-08-19 23:03:58 -03:00
return instance;
}
2020-12-26 19:47:38 -03:00
/**
* Verifies if bot exists on bot catalog.
*/
public async botExists(botId: string): Promise<boolean> {
const service = await AzureDeployerService.createInstance(this);
2020-12-31 15:36:19 -03:00
return await service.botExists(botId);
}
2020-12-26 19:47:38 -03:00
/**
2020-12-26 19:47:38 -03:00
* Performs all tasks of deploying a new bot on the cloud.
2018-09-09 14:39:37 -03:00
*/
2024-08-19 23:03:58 -03:00
public async deployBotOnAzure(instance: IGBInstance, publicAddress: string): Promise<IGBInstance> {
2020-12-26 19:47:38 -03:00
// Reads base configuration from environent file.
const service = await AzureDeployerService.createInstance(this);
const username = GBConfigService.get('CLOUD_USERNAME');
const password = GBConfigService.get('CLOUD_PASSWORD');
const accessToken = await GBAdminService.getADALTokenFromUsername(username, password);
2024-05-25 19:11:01 -03:00
const group = GBConfigService.get('CLOUD_GROUP') ?? GBConfigService.get('BOT_ID');
const subscriptionId = GBConfigService.get('CLOUD_SUBSCRIPTIONID');
2020-12-26 19:47:38 -03:00
// If the bot already exists, just update the endpoint.
if (await service.botExists(instance.botId)) {
await service.updateBot(
instance.botId,
group,
instance.title,
instance.description,
`${publicAddress}/api/messages/${instance.botId}`
);
2020-12-31 15:36:19 -03:00
} else {
2020-12-26 19:47:38 -03:00
// Internally create resources on cloud provider.
instance = await service.internalDeployBot(
instance,
accessToken,
instance.botId,
instance.title,
group,
instance.description,
`${publicAddress}/api/messages/${instance.botId}`,
'global',
instance.nlpAppId,
instance.nlpKey,
instance.marketplaceId,
instance.marketplacePassword,
subscriptionId
);
2024-08-28 19:42:12 -03:00
}
2020-12-26 19:47:38 -03:00
// Saves final instance object and returns it.
return await this.core.saveInstance(instance);
2018-04-21 02:59:30 -03:00
}
public async loadOrCreateEmptyVectorStore(min: GBMinInstance): Promise<HNSWLib> {
let vectorStore: HNSWLib;
2024-05-25 19:11:01 -03:00
2024-08-29 22:10:52 -03:00
const azureOpenAIKey = await (min.core as any)['getParam'](min.instance, 'Azure Open AI Key', null, true);
const azureOpenAIVersion = await (min.core as any)['getParam'](min.instance, 'Azure Open AI Version', null, true);
const azureOpenAIApiInstanceName = await (min.core as any)['getParam'](
min.instance,
'Azure Open AI Instance',
null,
true
);
const azureOpenAIEmbeddingModel = await (min.core as any)['getParam'](
min.instance,
'Azure Open AI Embedding Model',
null,
true
);
let embedding;
2024-05-25 19:11:01 -03:00
if (!azureOpenAIEmbeddingModel) {
return;
}
2024-05-25 19:11:01 -03:00
embedding = new OpenAIEmbeddings({
maxConcurrency: 5,
azureOpenAIApiKey: azureOpenAIKey,
azureOpenAIApiDeploymentName: azureOpenAIEmbeddingModel,
azureOpenAIApiVersion: azureOpenAIVersion,
azureOpenAIApiInstanceName: azureOpenAIApiInstanceName
});
2024-08-19 17:09:23 -03:00
try {
vectorStore = await HNSWLib.load(min['vectorStorePath'], embedding);
} catch {
vectorStore = new HNSWLib(embedding, {
2024-05-27 17:21:56 -03:00
space: 'cosine'
});
}
return vectorStore;
}
2020-12-26 19:47:38 -03:00
/**
* Performs the NLP publishing process on remote service.
*/
public async publishNLP(instance: IGBInstance): Promise<void> {
const service = await AzureDeployerService.createInstance(this);
2022-11-19 23:34:58 -03:00
const res = await service.publishNLP(instance.cloudLocation, instance.nlpAppId, instance.nlpAuthoringKey);
if (res.status !== 200 && res.status !== 201) {
throw res.bodyAsText;
}
2020-10-18 21:28:19 -03:00
}
2020-12-26 19:47:38 -03:00
/**
* Trains NLP on the remote service.
*/
public async trainNLP(instance: IGBInstance): Promise<void> {
const service = await AzureDeployerService.createInstance(this);
const res = await service.trainNLP(instance.cloudLocation, instance.nlpAppId, instance.nlpAuthoringKey);
2022-11-19 23:34:58 -03:00
if (res.status !== 200 && res.status !== 202) {
throw res.bodyAsText;
}
GBUtil.sleep(5000);
2020-10-18 21:28:19 -03:00
}
/**
* Return a zip file for importing bot in apps, currently MS Teams.
*/
public async getBotManifest(instance: IGBInstance): Promise<Buffer> {
const s = new TeamsService();
2022-11-19 23:34:58 -03:00
const manifest = await s.getManifest(
instance.marketplaceId,
2023-07-31 18:52:11 -03:00
instance.botId,
2022-11-19 23:34:58 -03:00
instance.description,
GBAdminService.generateUuid(),
instance.botId,
'General Bots'
);
return await s.getAppFile(manifest);
}
2020-12-26 19:47:38 -03:00
/**
* Refreshes NLP entities on the remote service.
*/
public async refreshNLPEntity(instance: IGBInstance, listName, listData): Promise<void> {
const service = await AzureDeployerService.createInstance(this);
const res = await service.refreshEntityList(
instance.cloudLocation,
instance.nlpAppId,
listName,
instance.nlpAuthoringKey,
listData
);
2022-11-19 23:34:58 -03:00
if (res.status !== 200) {
throw res.bodyAsText;
}
}
/**
* Deploys a bot to the storage from a .gbot folder.
*/
public async deployBotFromLocalPath(localPath: string, publicAddress: string): Promise<void> {
2024-09-06 15:30:03 -03:00
const packageName = path.basename(localPath);
2020-12-31 15:36:19 -03:00
const instance = await this.importer.importIfNotExistsBotPackage(undefined, packageName, localPath);
2024-08-19 23:03:58 -03:00
await this.deployBotOnAzure(instance, publicAddress);
}
2020-12-26 19:47:38 -03:00
/**
* Loads all para from tabular file Config.xlsx.
*/
2024-08-28 19:42:12 -03:00
2024-08-27 19:07:13 -03:00
public async loadParamsFromTabular(min: GBMinInstance, filePath: string): Promise<any> {
2024-09-06 15:30:03 -03:00
const xls = path.join(filePath, 'Config.xlsx');
const csv = path.join(filePath, 'config.csv');
2024-08-28 19:42:12 -03:00
let rows: any[] = [];
let obj: any = {};
const workbook = new Excel.Workbook();
2024-09-07 18:13:36 -03:00
if (await GBUtil.exists(xls)) {
2024-08-28 19:42:12 -03:00
await workbook.xlsx.readFile(xls);
let worksheet: any;
for (let t = 0; t < workbook.worksheets.length; t++) {
worksheet = workbook.worksheets[t];
if (worksheet) {
break;
}
}
2024-08-28 19:42:12 -03:00
rows = worksheet.getSheetValues();
2024-08-27 19:07:13 -03:00
// Skips the header lines.
for (let index = 0; index < 6; index++) {
2024-08-28 19:42:12 -03:00
rows.shift();
2024-08-27 19:07:13 -03:00
}
2024-09-07 18:13:36 -03:00
} else if (await GBUtil.exists(csv)) {
2024-08-29 19:53:56 -03:00
await workbook.csv.readFile(csv);
2024-08-28 19:42:12 -03:00
let worksheet = workbook.worksheets[0]; // Assuming the CSV file has only one sheet
rows = worksheet.getSheetValues();
// Skips the header lines.
rows.shift();
} else {
return [];
}
await asyncPromise.eachSeries(rows, async (line: any) => {
if (line && line.length > 0) {
obj[line[1]] = line[2];
}
});
2024-09-10 23:25:07 -03:00
GBLogEx.info(min, `Processing ${rows.length} rows from ${path.basename(filePath)}...`);
2024-08-28 19:42:12 -03:00
rows = null;
return obj;
}
2024-08-28 19:42:12 -03:00
/**
*/
public async downloadFolder(
2022-11-19 23:34:58 -03:00
min: GBMinInstance,
localPath: string,
remotePath: string,
baseUrl: string = null,
client = null
): Promise<any> {
2023-08-25 19:09:03 -03:00
GBLogEx.info(min, `downloadFolder: localPath=${localPath}, remotePath=${remotePath}, baseUrl=${baseUrl}`);
if (!baseUrl) {
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(min);
remotePath = remotePath.replace(/\\/gi, '/');
const parts = remotePath.split('/');
// Creates each subfolder.
let pathBase = localPath;
2024-09-10 23:25:07 -03:00
if (!(await GBUtil.exists(pathBase))) {
2024-09-07 18:13:36 -03:00
fs.mkdir(pathBase);
}
await CollectionUtil.asyncForEach(parts, async item => {
pathBase = path.join(pathBase, item);
2024-09-10 23:25:07 -03:00
if (!(await GBUtil.exists(pathBase))) {
2024-09-07 18:13:36 -03:00
fs.mkdir(pathBase);
}
});
// Retrieves all files in remote folder.
2024-09-18 18:43:19 -03:00
let packagePath = GBUtil.getGBAIPath(min.botId);
packagePath = urlJoin(packagePath, remotePath);
2024-09-07 00:08:23 -03:00
let url = `${baseUrl}/drive/root:/${packagePath}:/children`;
2024-09-10 23:25:07 -03:00
GBLogEx.info(min, `Downloading: ${url}`);
const res = await client.api(url).get();
const documents = res.value;
if (documents === undefined || documents.length === 0) {
GBLogEx.info(min, `${remotePath} is an empty folder.`);
return null;
}
// Download files or navigate to directory to recurse.
await CollectionUtil.asyncForEach(documents, async item => {
const itemPath = path.join(localPath, remotePath, item.name);
if (item.folder) {
2024-09-10 23:25:07 -03:00
if (!(await GBUtil.exists(itemPath))) {
2024-09-07 18:13:36 -03:00
fs.mkdir(itemPath);
}
const nextFolder = urlJoin(remotePath, item.name);
await this.downloadFolder(min, localPath, nextFolder);
} else {
let download = true;
2024-09-07 18:13:36 -03:00
if (await GBUtil.exists(itemPath)) {
2024-09-10 23:25:07 -03:00
const dt = await fs.stat(itemPath);
if (new Date(dt.mtime) >= new Date(item.lastModifiedDateTime)) {
download = false;
}
}
if (download) {
GBLogEx.verbose(min, `Downloading ${itemPath}...`);
const url = item['@microsoft.graph.downloadUrl'];
const response = await fetch(url);
2024-09-18 18:43:19 -03:00
await fs.writeFile(itemPath, Buffer.from(await response.arrayBuffer()), { encoding: null });
2024-09-07 18:13:36 -03:00
fs.utimes(itemPath, new Date(), new Date(item.lastModifiedDateTime));
2022-11-19 23:34:58 -03:00
} else {
2024-09-10 23:25:07 -03:00
GBLogEx.info(min, `Local is up to date: ${path.basename(itemPath)}...`);
}
}
});
}
}
/**
* UndDeploys a bot to the storage.
*/
public async undeployBot(botId: string, packageName: string): Promise<void> {
2020-12-26 19:47:38 -03:00
// Deletes Bot registration on cloud.
const service = await AzureDeployerService.createInstance(this);
2024-03-12 19:00:27 -03:00
const group = GBConfigService.get('BOT_ID');
if (await service.botExists(botId)) {
await service.deleteBot(botId, group);
}
2020-12-26 19:47:38 -03:00
// Unbinds resources and listeners.
GBServer.globals.minService.unmountBot(botId);
2020-12-26 19:47:38 -03:00
// Removes the bot from the storage.
await this.core.deleteInstance(botId);
}
2020-12-26 19:47:38 -03:00
/**
* Deploys a new package to the database storage (just a group).
*/
public async deployPackageToStorage(instanceId: number, packageName: string): Promise<GuaribasPackage> {
2022-01-03 13:11:21 -03:00
return await GuaribasPackage.create(<GuaribasPackage>{
2018-04-21 02:59:30 -03:00
packageName: packageName,
2018-11-27 22:56:11 -02:00
instanceId: instanceId
});
2018-04-21 02:59:30 -03:00
}
public async deployPackage(min: GBMinInstance, localPath: string) {
2023-09-13 19:42:45 -03:00
// TODO: Adjust interface mismatch.
}
2020-12-26 19:47:38 -03:00
/**
* Deploys a folder into the bot storage.
*/
2024-09-10 23:25:07 -03:00
public async deployPackage2(min: GBMinInstance, user, packageWorkFolder: string, download = false) {
const packageName = path.basename(packageWorkFolder);
const packageType = path.extname(packageWorkFolder);
let handled = false;
let pck = null;
2024-09-10 23:25:07 -03:00
const gbai = GBUtil.getGBAIPath(min.instance.botId);
if (download) {
if (packageType === '.gbkb' || packageType === '.gbtheme') {
2024-09-10 23:25:07 -03:00
await this.cleanupPackage(min.instance, packageName);
}
if (!GBConfigService.get('STORAGE_NAME')) {
2024-09-11 00:33:17 -03:00
const filePath = path.join(GBConfigService.get('STORAGE_LIBRARY'), gbai, packageName);
2024-09-11 21:02:19 -03:00
await GBUtil.copyIfNewerRecursive(filePath, packageWorkFolder);
2024-09-10 23:25:07 -03:00
} else {
await this.downloadFolder(min, path.join('work', `${gbai}`), packageName);
}
}
2020-12-26 19:47:38 -03:00
// Asks for each .gbapp if it will handle the package publishing.
2020-12-26 19:47:38 -03:00
const _this = this;
await CollectionUtil.asyncForEach(min.appPackages, async (e: IGBPackage) => {
// If it will be handled, create a temporary service layer to be
// called by .gbapp and manage the associated package row.
if (
(pck = await e.onExchangeData(min, 'handlePackage', {
2024-09-10 23:25:07 -03:00
name: packageWorkFolder,
createPackage: async packageName => {
return await _this.deployPackageToStorage(min.instance.instanceId, packageName);
},
updatePackage: async (p: GuaribasPackage) => {
p.save();
},
existsPackage: async (packageName: string) => {
return await _this.getStoragePackageByName(min.instance.instanceId, packageName);
}
}))
) {
handled = true;
}
});
if (handled) {
return pck;
}
2020-12-31 15:36:19 -03:00
// Deploy platform packages here accordingly to their extension.
2018-04-21 02:59:30 -03:00
switch (packageType) {
case '.gbot':
2020-12-26 19:47:38 -03:00
// Extracts configuration information from .gbot files.
2024-09-10 23:25:07 -03:00
min.instance.params = await this.loadParamsFromTabular(min, packageWorkFolder);
2024-08-28 19:42:12 -03:00
if (min.instance.params) {
let connections = [];
// Find all tokens in .gbot Config.
const strFind = ' Driver';
const conns = await min.core['findParam'](min.instance, strFind);
await CollectionUtil.asyncForEach(conns, async t => {
const connectionName = t.replace(strFind, '').trim();
2024-08-28 19:42:12 -03:00
let con = {};
con['name'] = connectionName;
con['storageDriver'] = min.core.getParam<string>(min.instance, `${connectionName} Driver`, null);
2024-08-29 19:53:56 -03:00
const storageName = min.core.getParam<string>(min.instance, `${connectionName} Name`, null);
let file = min.core.getParam<string>(min.instance, `${connectionName} File`, null);
if (storageName) {
con['storageName'] = storageName.trim();
2024-08-29 19:53:56 -03:00
con['storageServer'] = min.core.getParam<string>(min.instance, `${connectionName} Server`, null);
con['storageUsername'] = min.core.getParam<string>(min.instance, `${connectionName} Username`, null);
con['storagePort'] = min.core.getParam<string>(min.instance, `${connectionName} Port`, null);
con['storagePassword'] = min.core.getParam<string>(min.instance, `${connectionName} Password`, null);
} else if (file) {
2024-09-07 00:08:23 -03:00
const packagePath = GBUtil.getGBAIPath(min.botId, 'gbdata');
con['storageFile'] = path.join(GBConfigService.get('STORAGE_LIBRARY'), packagePath, file);
2024-08-29 19:53:56 -03:00
} else {
GBLogEx.debug(min, `No storage information found for ${connectionName}, missing storage name or file.`);
}
2024-08-28 19:42:12 -03:00
connections.push(con);
});
2024-09-07 00:08:23 -03:00
const packagePath = GBUtil.getGBAIPath(min.botId, null);
const localFolder = path.join('work', packagePath, 'connections.json');
2024-09-18 18:43:19 -03:00
await fs.writeFile(localFolder, JSON.stringify(connections), { encoding: null });
2024-08-28 19:42:12 -03:00
// Updates instance object.
await this.core.saveInstance(min.instance);
2024-08-29 22:10:52 -03:00
GBServer.globals.minService.unmountBot(min.botId);
GBServer.globals.minService.mountBot(min.instance);
2024-09-12 15:05:32 -03:00
2024-08-29 22:10:52 -03:00
GBLogEx.info(min, `Bot ${min.botId} reloaded.`);
2024-08-28 19:42:12 -03:00
}
break;
2018-04-21 02:59:30 -03:00
case '.gbkb':
2020-12-26 19:47:38 -03:00
// Deploys .gbkb into the storage.
const service = new KBService(this.core.sequelize);
2024-09-10 23:25:07 -03:00
await service.deployKb(this.core, this, packageWorkFolder, min);
break;
2018-04-21 02:59:30 -03:00
case '.gbdialog':
2020-12-26 19:47:38 -03:00
// Compiles files from .gbdialog into work folder and deploys
// it to the VM.
const vm = new GBVMService();
2024-09-10 23:25:07 -03:00
await vm.loadDialogPackage(packageWorkFolder, min, this.core, this);
GBLogEx.verbose(min, `Dialogs (.gbdialog) for ${min.botId} loaded.`);
break;
case '.gbtheme':
2020-12-26 19:47:38 -03:00
// Updates server listeners to serve theme files in .gbtheme.
const filePath = path.join(GBConfigService.get('STORAGE_TEMPLATE'), gbai, packageName);
GBServer.globals.server.use('/' + urlJoin('themes', packageName), express.static( filePath));
GBLogEx.info(min, `Theme (.gbtheme) assets accessible at: /themes/${packageName}.`);
break;
case '.gbapp':
2020-12-26 19:47:38 -03:00
// Dynamically compiles and loads .gbapp packages (Node.js packages).
2024-09-10 23:25:07 -03:00
await this.callGBAppCompiler(packageWorkFolder, this.core);
break;
case '.gblib':
2020-12-26 19:47:38 -03:00
// Dynamically compiles and loads .gblib packages (Node.js packages).
2024-09-10 23:25:07 -03:00
await this.callGBAppCompiler(packageWorkFolder, this.core);
break;
2018-04-21 02:59:30 -03:00
default:
2023-02-26 06:05:57 -03:00
throw GBError.create(`Unhandled package type: ${packageType}.`);
}
2018-04-21 02:59:30 -03:00
}
/**
2024-05-25 19:11:01 -03:00
* Removes the package local files from cache.
*/
public async cleanupPackage(instance: IGBInstance, packageName: string) {
2024-09-07 00:08:23 -03:00
const packagePath = GBUtil.getGBAIPath(instance.botId, null, packageName);
const localFolder = path.join('work', packagePath);
rimraf.sync(localFolder);
}
2023-09-13 21:02:33 -03:00
/**
* Removes the package from the storage and local work folders.
*/
public async undeployPackageFromPackageName(instance: IGBInstance, packageName: string) {
// Gets information about the package.
const p = await this.getStoragePackageByName(instance.instanceId, packageName);
2024-09-06 15:30:03 -03:00
const packagePath = GBUtil.getGBAIPath(instance.botId, null, packageName);
const localFolder = path.join('work', packagePath);
2023-09-13 21:02:33 -03:00
return await this.undeployPackageFromLocalPath(instance, localFolder);
}
2020-12-26 19:47:38 -03:00
/**
* Removes the package from the storage and local work folders.
*/
public async undeployPackageFromLocalPath(instance: IGBInstance, localPath: string) {
2020-12-26 19:47:38 -03:00
// Gets information about the package.
2024-09-06 15:30:03 -03:00
const packageType = path.extname(localPath);
const packageName = path.basename(localPath);
const p = await this.getStoragePackageByName(instance.instanceId, packageName);
2020-12-26 19:47:38 -03:00
// Removes objects from storage, cloud resources and local files if any.
2018-09-09 14:39:37 -03:00
switch (packageType) {
case '.gbot':
2024-09-07 18:13:36 -03:00
const packageObject = JSON.parse(await fs.readFile(urlJoin(localPath, 'package.json'), 'utf8'));
await this.undeployBot(packageObject.botId, packageName);
break;
case '.gbkb':
const service = new KBService(this.core.sequelize);
rimraf.sync(localPath);
2020-12-31 15:36:19 -03:00
if (p) {
2023-09-14 00:09:31 -03:00
await service.undeployKbFromStorage(instance, this, p.packageId);
}
2018-09-09 14:39:37 -03:00
2023-09-14 00:09:31 -03:00
return;
case '.gbui':
break;
case '.gbtheme':
break;
2018-09-09 14:39:37 -03:00
2018-11-27 22:56:11 -02:00
case '.gbdialog':
break;
case '.gblib':
break;
case '.gbapp':
break;
2018-09-09 14:39:37 -03:00
default:
const err = GBError.create(`Unhandled package type: ${packageType}.`);
Promise.reject(err);
break;
2018-09-09 14:39:37 -03:00
}
rimraf.sync(localPath);
2018-04-21 02:59:30 -03:00
}
2020-12-26 19:47:38 -03:00
/**
* Performs automation of the Indexer (Azure Search) and rebuild
* its index based on .gbkb structure.
*/
public async rebuildIndex(instance: IGBInstance, searchSchema: any) {
2024-05-25 19:11:01 -03:00
const key = instance.searchKey ? instance.searchKey : GBServer.globals.minBoot.instance.searchKey;
GBLogEx.info(instance.instanceId, `rebuildIndex running...`);
2024-05-25 19:11:01 -03:00
if (!key) {
return;
}
const searchIndex = instance.searchIndex ? instance.searchIndex : GBServer.globals.minBoot.instance.searchIndex;
const searchIndexer = instance.searchIndexer
? instance.searchIndexer
: GBServer.globals.minBoot.instance.searchIndexer;
const host = instance.searchHost ? instance.searchHost : GBServer.globals.minBoot.instance.searchHost;
// Prepares search.
2024-05-25 19:11:01 -03:00
const search = new AzureSearch(key, host, searchIndex, searchIndexer);
const connectionString = GBDeployer.getConnectionStringFromInstance(GBServer.globals.minBoot.instance);
const dsName = 'gb';
// Removes any previous index.
try {
await search.deleteDataSource(dsName);
2024-09-15 16:30:03 -03:00
} catch (error) {
// If it is a 404 there is nothing to delete as it is the first creation.
2020-12-26 19:47:38 -03:00
2024-09-15 16:30:03 -03:00
if (error.code !== 404) {
throw error;
2023-02-26 06:05:57 -03:00
}
}
2023-02-24 13:31:40 -03:00
// Removes the index.
try {
await search.deleteIndex();
2024-09-15 16:30:03 -03:00
} catch (error) {
// If it is a 404 there is nothing to delete as it is the first creation.
2024-09-15 16:30:03 -03:00
if (error.code !== 404 && error.code !== 'OperationNotAllowed') {
throw error;
}
}
// Creates the data source and index on the cloud.
try {
await search.createDataSource(dsName, dsName, 'GuaribasQuestion', 'azuresql', connectionString);
2024-09-15 16:30:03 -03:00
} catch (error) {
GBLog.error(error);
throw error;
}
await search.createIndex(searchSchema, dsName);
GBLogEx.info(instance.instanceId, `Released rebuildIndex mutex.`);
}
2020-12-26 19:47:38 -03:00
/**
* Finds a storage package by using package name.
*/
public async getStoragePackageByName(instanceId: number, packageName: string): Promise<GuaribasPackage> {
const where = { packageName: packageName, instanceId: instanceId };
return await GuaribasPackage.findOne({
2018-11-27 22:56:11 -02:00
where: where
});
2018-09-09 14:39:37 -03:00
}
2020-12-26 19:47:38 -03:00
/**
* Prepares the React application inside default.gbui folder and
* makes this web application available as default web front-end.
*/
2024-09-07 18:13:36 -03:00
public async setupDefaultGBUI() {
2020-12-26 19:47:38 -03:00
// Setups paths.
const root = 'packages/default.gbui';
const npm = urlJoin(process.env.PWD, 'node_modules', '.bin', 'npm');
2020-12-26 19:47:38 -03:00
// Checks if .gbapp compiliation is enabled.
2024-09-07 18:13:36 -03:00
if (!(await GBUtil.exists(`${root}/build`)) && process.env.DISABLE_WEB !== 'true') {
// Write a .env required to fix some bungs in create-react-app tool.
2020-12-26 19:47:38 -03:00
2024-09-18 18:43:19 -03:00
await fs.writeFile(`${root}/.env`, 'SKIP_PREFLIGHT_CHECK=true');
2020-12-26 19:47:38 -03:00
// Install modules and compiles the web app.
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `Installing modules default.gbui (It may take a few minutes)...`);
2022-01-28 21:59:26 -03:00
child_process.execSync(`${npm} install`, { cwd: root });
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `Transpiling default.gbui...`);
2022-01-23 21:27:35 -03:00
child_process.execSync(`${npm} run build`, { cwd: root });
}
}
2020-12-26 19:47:38 -03:00
/**
* Servers bot storage assets to be used by web, WhatsApp and other channels.
*/
public static mountGBKBAssets(packageName: any, botId: string, filename: string) {
const gbaiName = GBUtil.getGBAIPath(botId);
2020-12-26 19:47:38 -03:00
// Servers menu assets.
GBServer.globals.server.use(
`/kb/${gbaiName}/${packageName}/subjects`,
express.static(urlJoin(filename, 'subjects'))
);
2020-12-26 19:47:38 -03:00
// Servers all other assets in .gbkb folders.
2022-11-19 23:34:58 -03:00
GBServer.globals.server.use(
`/kb/${gbaiName}/${packageName}/assets`,
express.static(urlJoin('work', gbaiName, filename, 'assets'))
);
GBServer.globals.server.use(
`/kb/${gbaiName}/${packageName}/images`,
express.static(urlJoin('work', gbaiName, filename, 'images'))
);
2024-03-22 22:51:36 -03:00
GBServer.globals.server.use(
`/kb/${gbaiName}/${packageName}/docs`,
express.static(urlJoin('work', gbaiName, filename, 'docs'))
);
2022-11-19 23:34:58 -03:00
GBServer.globals.server.use(
`/kb/${gbaiName}/${packageName}/audios`,
express.static(urlJoin('work', gbaiName, filename, 'audios'))
);
GBServer.globals.server.use(
`/kb/${gbaiName}/${packageName}/videos`,
express.static(urlJoin('work', gbaiName, filename, 'videos'))
);
GBServer.globals.server.use(`/${botId}/cache`, express.static(urlJoin('work', gbaiName, 'cache')));
2024-09-10 23:25:07 -03:00
2024-09-04 15:23:56 -03:00
// FEAT-A7B1F6
2024-09-10 23:25:07 -03:00
2022-11-19 23:34:58 -03:00
GBServer.globals.server.use(
`/${gbaiName}/${botId}.gbdrive/public`,
2022-11-19 23:34:58 -03:00
express.static(urlJoin('work', gbaiName, `${botId}.gbdata`, 'public'))
);
GBLog.verbose(`KB (.gbkb) assets accessible at: /kb/${gbaiName}/${packageName}.`);
}
2020-12-26 19:47:38 -03:00
/**
* Invokes Type Script compiler for a given .gbapp package (Node.js based).
*/
public async callGBAppCompiler(
gbappPath: string,
core: IGBCoreService,
appPackages: any[] = undefined,
appPackagesProcessed: number = 0
) {
2020-12-26 19:47:38 -03:00
// Runs `npm install` for the package.
2024-09-06 15:30:03 -03:00
GBLogEx.info(0, `Deploying General Bots Application (.gbapp) or Library (.gblib): ${path.basename(gbappPath)}...`);
let folder = path.join(gbappPath, 'node_modules');
if (process.env.GBAPP_DISABLE_COMPILE !== 'true') {
2024-09-10 23:25:07 -03:00
if (!(await GBUtil.exists(folder))) {
GBLogEx.info(0, `Installing modules for ${path.basename(gbappPath)}...`);
child_process.execSync('npm install', { cwd: gbappPath });
}
}
2020-12-31 15:36:19 -03:00
2024-09-06 15:30:03 -03:00
folder = path.join(gbappPath, 'dist');
try {
2020-12-26 19:47:38 -03:00
// Runs TSC in .gbapp folder.
if (process.env.GBAPP_DISABLE_COMPILE !== 'true') {
2024-09-10 23:25:07 -03:00
GBLogEx.info(0, `Compiling: ${path.basename(gbappPath)}.`);
2024-09-06 15:30:03 -03:00
child_process.execSync(path.join(process.env.PWD, 'node_modules/.bin/tsc'), { cwd: gbappPath });
}
2020-12-26 19:47:38 -03:00
// After compiled, adds the .gbapp to the current server VM context.
if (gbappPath.endsWith('.gbapp') || gbappPath.endsWith('.gblib')) {
const m = await import(`file://${gbappPath}/dist/index.js`);
if (m.Package) {
const p = new m.Package();
// Adds a name property to the list of loaded .gbapp packages.
p['name'] = gbappPath;
await p.loadPackage(core, core.sequelize);
if (appPackages !== undefined) {
appPackages.push(p);
}
}
}
2024-04-21 23:39:39 -03:00
GBLogEx.info(0, `.gbapp or .gblib deployed: ${gbappPath}.`);
appPackagesProcessed++;
} catch (error) {
GBLog.error(`Error compiling package, message: ${error.message}\n${error.stack}`);
if (error.stdout) {
2020-12-26 19:47:38 -03:00
GBLog.error(`.gbapp stdout: ${gbappPath}:\n${error.stdout.toString()}`);
}
appPackagesProcessed++;
}
2020-12-31 15:36:19 -03:00
return appPackagesProcessed;
}
/**
* Determines if a given package is of system kind.
*/
private isSystemPackage(name: string): Boolean {
2020-12-31 15:36:19 -03:00
const names = [
'analytics.gblib',
'console.gblib',
'security.gbapp',
'whatsapp.gblib',
'sharepoint.gblib',
'core.gbapp',
'basic.gblib',
2020-12-31 15:36:19 -03:00
'admin.gbapp',
'azuredeployer.gbapp',
'customer-satisfaction.gbapp',
'kb.gbapp',
'google-chat.gblib',
2021-12-19 16:39:50 -03:00
'teams.gblib',
'hubspot.gblib',
2024-09-01 18:21:34 -03:00
'llm.gblib',
'saas.gbapp'
2020-12-31 15:36:19 -03:00
];
return names.indexOf(name) > -1;
}
/**
* Performs the process of compiling all .gbapp folders.
*/
private async deployAppPackages(gbappPackages: string[], core: any, appPackages: any[]) {
2020-12-31 15:36:19 -03:00
// Loops through all ready to load .gbapp packages.
let appPackagesProcessed = 0;
await CollectionUtil.asyncForEach(gbappPackages, async e => {
2024-09-06 15:30:03 -03:00
const filenameOnly = path.basename(e);
2020-12-31 15:36:19 -03:00
// Skips .gbapp inside deploy folder.
if (this.isSystemPackage(filenameOnly) === false) {
appPackagesProcessed = await this.callGBAppCompiler(e, core, appPackages, appPackagesProcessed);
}
});
return appPackagesProcessed;
}
2018-04-21 02:59:30 -03:00
}