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

840 lines
28 KiB
TypeScript
Raw Normal View History

2018-04-21 02:59:30 -03:00
/*****************************************************************************\
| ( )_ _ |
| _ _ _ __ _ _ __ ___ ___ _ _ | ,_)(_) ___ ___ _ |
| ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| | | |/',__)/' v `\ /'_`\ |
| | (_) )| | ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) ) |
2018-04-21 02:59:30 -03:00
| | ,__/'(_) `\__,_)`\__ |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/' |
| | | ( )_) | |
| (_) \___/' |
| |
| General Bots Copyright (c) Pragmatismo.io. All rights reserved. |
| 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.io. |
| 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';
const Path = require('path');
import urlJoin = require('url-join');
const Fs = require('fs');
const express = require('express');
const child_process = require('child_process');
const graph = require('@microsoft/microsoft-graph-client');
const rimraf = require('rimraf');
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';
2020-12-31 15:36:19 -03:00
import { GBVMService } from '../../basic.gblib/services/GBVMService';
import { GuaribasPackage } from '../models/GBModel';
import { GBAdminService } from './../../admin.gbapp/services/GBAdminService';
import { AzureDeployerService } from './../../azuredeployer.gbapp/services/AzureDeployerService';
import { KBService } from './../../kb.gbapp/services/KBService';
import { GBConfigService } from './GBConfigService';
import { GBImporter } from './GBImporterService';
const MicrosoftGraph = require('@microsoft/microsoft-graph-client');
/**
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.
*/
2018-04-21 02:59:30 -03:00
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) {
return `Server=tcp:${instance.storageServer},1433;Database=${instance.storageName};User ID=${instance.storageUsername};Password=${instance.storagePassword};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;`;
}
/**
* 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.toLowerCase().split(';'));
}
const botPackages: string[] = [];
const gbappPackages: string[] = [];
2020-12-31 15:36:19 -03:00
const generalPackages: string[] = [];
async function scanPackageDirectory(path) {
2020-12-26 19:47:38 -03:00
// Gets all directories.
const isDirectory = source => Fs.lstatSync(source).isDirectory();
const getDirectories = source =>
Fs.readdirSync(source)
.map(name => Path.join(source, name))
.filter(isDirectory);
const dirs = getDirectories(path);
await CollectionUtil.asyncForEach(dirs, async element => {
2020-12-26 19:47:38 -03:00
// For each folder, checks its extensions looking for valid packages.
element = element.toLowerCase();
if (element === '.') {
GBLog.info(`Ignoring ${element}...`);
} else {
const name = Path.basename(element).toLowerCase();
2020-12-26 19:47:38 -03:00
// Skips what does not need to be loaded.
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.
GBLog.info(`Starting looking for packages (.gbot, .gbtheme, .gbkb, .gbapp)...`);
await CollectionUtil.asyncForEach(paths, async e => {
GBLog.info(`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
GBLog.info(`App Package deployment done.`);
2020-12-26 19:47:38 -03:00
// Then all remaining general packages are loaded.
const instances = await core.loadInstances();
await CollectionUtil.asyncForEach(instances, async instance => {
this.mountGBKBAssets(`${instance.botId}.gbkb`,
2020-12-31 15:36:19 -03:00
instance.botId, `${instance.botId}.gbkb`);
2020-12-26 19:47:38 -03:00
});
GBLog.info(`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) {
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
// Gets the access token to perform service operations.
const accessToken = await GBServer.globals.minBoot.adminService.acquireElevatedToken(bootInstance.instanceId);
2020-12-26 19:47:38 -03:00
// Creates the MSFT application that will be associated to the bot.
const service = new AzureDeployerService(this);
2020-12-31 15:36:19 -03:00
const application = await service.createApplication(accessToken, botId);
2020-12-26 19:47:38 -03:00
// Fills new instance base information and get App secret.
instance.marketplaceId = (application as any).appId;
instance.marketplacePassword = await service.createApplicationSecret(accessToken, (application as any).id);
instance.adminPass = GBAdminService.getRndPassword();
instance.title = botId;
instance.activationCode = instance.botId;
instance.state = 'active';
2020-12-26 19:47:38 -03:00
instance.nlpScore = 0.8;
instance.searchScore = 0.45;
instance.whatsappServiceKey = bootInstance.whatsappServiceKey;
instance.whatsappServiceNumber = bootInstance.whatsappServiceNumber;
instance.whatsappServiceUrl = bootInstance.whatsappServiceUrl;
2020-12-26 19:47:38 -03:00
// Saves bot information to the store.
await this.core.saveInstance(instance);
2020-12-26 19:47:38 -03:00
// Creates remaining objects on the cloud and updates instance information.
return await this.deployBotFull(instance, GBServer.globals.publicAddress);
}
2020-12-26 19:47:38 -03:00
/**
* Verifies if bot exists on bot catalog.
*/
public async botExists(botId: string): Promise<boolean> {
const service = new AzureDeployerService(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
*/
public async deployBotFull(instance: IGBInstance, publicAddress: string): Promise<IGBInstance> {
2020-12-26 19:47:38 -03:00
// Reads base configuration from environent file.
const service = new AzureDeployerService(this);
const username = GBConfigService.get('CLOUD_USERNAME');
const password = GBConfigService.get('CLOUD_PASSWORD');
const accessToken = await GBAdminService.getADALTokenFromUsername(username, password);
const group = GBConfigService.get('CLOUD_GROUP');
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 {
const botId = GBConfigService.get('BOT_ID');
const bootInstance = await this.core.loadInstanceByBotId(botId);
instance.searchHost = bootInstance.searchHost;
instance.searchIndex = bootInstance.searchIndex;
instance.searchIndexer = bootInstance.searchIndexer;
instance.searchKey = bootInstance.searchKey;
instance.whatsappServiceKey = bootInstance.whatsappServiceKey;
instance.whatsappServiceNumber = bootInstance.whatsappServiceNumber;
instance.whatsappServiceUrl = bootInstance.whatsappServiceUrl;
instance.storageServer = bootInstance.storageServer;
instance.storageName = bootInstance.storageName;
instance.storageUsername = bootInstance.storageUsername;
instance.storagePassword = bootInstance.storagePassword;
instance.cloudLocation = bootInstance.cloudLocation;
instance.speechEndpoint = bootInstance.speechEndpoint;
instance.speechKey = bootInstance.speechKey;
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
);
2020-12-26 19:47:38 -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
// Saves final instance object and returns it.
return await this.core.saveInstance(instance);
2018-04-21 02:59:30 -03:00
}
2020-12-26 19:47:38 -03:00
/**
* Performs the NLP publishing process on remote service.
*/
2020-10-18 21:28:19 -03:00
public async publishNLP(instance: IGBInstance): Promise<void> {
const service = new AzureDeployerService(this);
const res = await service.publishNLP(instance.cloudLocation, instance.nlpAppId,
2020-12-31 15:36:19 -03:00
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.
*/
2020-10-18 21:28:19 -03:00
public async trainNLP(instance: IGBInstance): Promise<void> {
const service = new AzureDeployerService(this);
const res = await service.trainNLP(instance.cloudLocation, instance.nlpAppId, instance.nlpAuthoringKey);
2020-12-31 15:36:19 -03:00
if (res.status !== 200 && res.status !== 202) { throw res.bodyAsText; }
const sleep = ms => {
2020-10-18 21:28:19 -03:00
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
sleep(5000);
}
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 = new AzureDeployerService(this);
const res = await service.refreshEntityList(
instance.cloudLocation,
instance.nlpAppId,
listName,
instance.nlpAuthoringKey,
listData
);
2020-12-31 15:36:19 -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> {
const packageName = Path.basename(localPath);
2020-12-31 15:36:19 -03:00
const instance = await this.importer.importIfNotExistsBotPackage(undefined, packageName, localPath);
await this.deployBotFull(instance, publicAddress);
}
2020-12-26 19:47:38 -03:00
/**
* Loads all para from tabular file Config.xlsx.
*/
public async loadParamsFromTabular(min: GBMinInstance): Promise<any> {
const siteId = process.env.STORAGE_SITE_ID;
const libraryId = process.env.STORAGE_LIBRARY;
GBLog.info(`Connecting to Config.xslx (siteId: ${siteId}, libraryId: ${libraryId})...`);
2020-12-26 19:47:38 -03:00
// Connects to MSFT storage.
2020-12-31 15:36:19 -03:00
const token = await min.adminService.acquireElevatedToken(min.instance.instanceId);
const client = MicrosoftGraph.Client.init({
authProvider: done => {
done(null, token);
}
});
// Retrieves all files in .bot folder.
const botId = min.instance.botId;
const path = `/${botId}.gbai/${botId}.gbot`;
let url = `https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/root:${path}:/children`;
GBLog.info(`Loading .gbot from Excel: ${url}`);
2020-12-31 15:36:19 -03:00
const res = await client
.api(url)
.get();
2020-12-26 19:47:38 -03:00
// Finds Config.xlsx.
2020-12-31 15:36:19 -03:00
const document = res.value.filter(m => {
return m.name === 'Config.xlsx';
});
if (document === undefined || document.length === 0) {
GBLog.info(`Config.xlsx not found on .bot folder, check the package.`);
2020-12-31 15:36:19 -03:00
return null;
}
2020-12-26 19:47:38 -03:00
// Reads all rows in Config.xlsx that contains a pair of name/value
// and fills an object that is returned to be saved in params instance field.
2020-12-31 15:36:19 -03:00
const results = await client
.api(
`https://graph.microsoft.com/v1.0/sites/${siteId}/lists/${libraryId}/drive/items/${document[0].id}/workbook/worksheets('General')/range(address='A7:B100')`
)
.get();
2020-12-26 19:47:38 -03:00
let index = 0, obj = {};
for (; index < results.text.length; index++) {
if (results.text[index][0] === '') {
return obj;
}
obj[results.text[index][0]] = results.text[index][1];
}
2020-12-31 15:36:19 -03:00
return obj;
}
/**
* 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.
2020-12-26 19:47:38 -03:00
const service = new AzureDeployerService(this);
const group = GBConfigService.get('CLOUD_GROUP');
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> {
2020-12-05 17:27:27 -03:00
return await GuaribasPackage.create({
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
}
2020-12-26 19:47:38 -03:00
/**
* Deploys a folder into the bot storage.
*/
public async deployPackage(min: GBMinInstance, localPath: string) {
2018-04-21 02:59:30 -03:00
2020-12-26 19:47:38 -03:00
const packageType = Path.extname(localPath);
let handled = false;
let pck = null;
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) => {
try {
2020-12-26 19:47:38 -03:00
// 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', {
name: localPath,
createPackage: async packageName => {
return await _this.deployPackageToStorage(min.instance.instanceId, packageName);
},
updatePackage: async (p: GuaribasPackage) => {
p.save();
2020-12-05 17:27:27 -03:00
},
existsPackage: async (packageName: string) => {
return await _this.getStoragePackageByName(min.instance.instanceId, packageName);
}
}))
) {
handled = true;
}
} catch (error) {
GBLog.error(error);
}
});
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.
if (process.env.ENABLE_PARAMS_ONLINE === 'false') {
if (Fs.existsSync(localPath)) {
GBLog.info(`Loading .gbot from ${localPath}.`);
await this.deployBotFromLocalPath(localPath, GBServer.globals.publicAddress);
}
} else {
min.instance.params = await this.loadParamsFromTabular(min);
}
2020-12-26 19:47:38 -03:00
// Updates instance object.
await this.core.saveInstance(min.instance);
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);
await service.deployKb(this.core, this, localPath, 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();
await vm.loadDialogPackage(localPath, min, this.core, this);
break;
case '.gbtheme':
2020-12-26 19:47:38 -03:00
// Updates server listeners to serve theme files in .gbtheme.
const packageName = Path.basename(localPath);
GBServer.globals.server.use(`/themes/${packageName}`, express.static(localPath));
GBLog.info(`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).
await this.callGBAppCompiler(localPath, this.core);
break;
case '.gblib':
2020-12-26 19:47:38 -03:00
// Dynamically compiles and loads .gblib packages (Node.js packages).
await this.callGBAppCompiler(localPath, this.core);
break;
2018-04-21 02:59:30 -03:00
default:
const err = GBError.create(`Unhandled package type: ${packageType}.`);
Promise.reject(err);
break;
2018-04-21 02:59:30 -03:00
}
}
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.
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':
const packageObject = JSON.parse(Fs.readFileSync(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
return await service.undeployKbFromStorage(instance, this, p.packageId);
2018-09-09 14:39:37 -03:00
case '.gbui':
break;
case '.gbtheme':
rimraf.sync(localPath);
break;
2018-09-09 14:39:37 -03:00
2018-11-27 22:56:11 -02:00
case '.gbdialog':
rimraf.sync(localPath);
2018-11-27 22:56:11 -02:00
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) {
2020-12-26 19:47:38 -03:00
// Prepares search.
const search = new AzureSearch(
instance.searchKey,
instance.searchHost,
instance.searchIndex,
2018-11-27 22:56:11 -02:00
instance.searchIndexer
);
const connectionString = GBDeployer.getConnectionStringFromInstance(instance);
const dsName = 'gb';
2020-12-26 19:47:38 -03:00
// Removes any previous index.
try {
await search.deleteDataSource(dsName);
} catch (err) {
2020-12-26 19:47:38 -03:00
// If it is a 404 there is nothing to delete as it is the first creation.
if (err.code !== 404) {
2020-12-26 19:47:38 -03:00
throw err;
}
}
2020-12-26 19:47:38 -03:00
// Removes the index.
try {
await search.deleteIndex();
} catch (err) {
2020-12-26 19:47:38 -03:00
// If it is a 404 there is nothing to delete as it is the first creation.
if (err.code !== 404) {
throw err;
}
}
2020-12-26 19:47:38 -03:00
// Creates the data source and index on the cloud.
try {
await search.createDataSource(dsName, dsName, 'GuaribasQuestion', 'azuresql', connectionString);
} catch (err) {
GBLog.error(err);
throw err;
}
await search.createIndex(searchSchema, dsName);
}
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.
*/
public 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.
if (!Fs.existsSync(`${root}/build`) && process.env.DISABLE_WEB !== 'true') {
// Write a .env required to fix some bungs in create-react-app facility.
Fs.writeFileSync(`${root}/.env`, 'SKIP_PREFLIGHT_CHECK=true');
2020-12-26 19:47:38 -03:00
// Install modules and compiles the web app.
GBLog.info(`Installing modules default.gbui (It may take a few minutes)...`);
child_process.execSync(`${npm} install`, { cwd: root });
GBLog.info(`Transpiling default.gbui...`);
child_process.execSync(`${npm} run build`, { cwd: root });
}
2020-12-26 19:47:38 -03:00
// Clean up node_modules folder as it is only needed during compile time.
2020-12-26 19:47:38 -03:00
GBLog.info(`Cleaning default.gbui node_modules...`);
const nodeModules = urlJoin(root, 'node_modules');
rimraf.sync(nodeModules);
}
2020-12-26 19:47:38 -03:00
/**
* Servers bot storage assets to be used by web, WhatsApp and other channels.
*/
public mountGBKBAssets(packageName: any, botId: string, filename: string) {
2020-12-31 15:36:19 -03:00
2020-12-26 19:47:38 -03:00
// Servers menu assets.
GBServer.globals.server.use(
`/kb/${botId}.gbai/${packageName}/subjects`,
express.static(urlJoin(filename, 'subjects'))
);
2020-12-26 19:47:38 -03:00
// Servers all other assets in .gbkb folders.
2020-12-26 19:47:38 -03:00
const gbaiName = `${botId}.gbai`;
2020-12-31 15:36:19 -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')));
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')));
GBLog.info(`KB (.gbkb) assets accessible at: /kb/${botId}.gbai/${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.
GBLog.info(`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') {
if (!Fs.existsSync(folder)) {
GBLog.info(`Installing modules for ${gbappPath}...`);
child_process.execSync('npm install', { cwd: gbappPath });
}
}
2020-12-31 15:36:19 -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') {
GBLog.info(`Compiling: ${gbappPath}.`);
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')) {
const m = await import(gbappPath);
const p = new m.Package();
await p.loadPackage(core, core.sequelize);
if (appPackages !== undefined) {
appPackages.push(p);
}
}
GBLog.info(`.gbapp or .gblib deployed: ${gbappPath}.`);
appPackagesProcessed++;
2020-12-26 19:47:38 -03:00
} 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 {
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'
];
return names.indexOf(name) > -1;
}
/**
* Performs the process of compiling all .gbapp folders.
*/
private async deployAppPackages(gbappPackages: string[], core: any, appPackages: any[]) {
// Loops through all ready to load .gbapp packages.
let appPackagesProcessed = 0;
await CollectionUtil.asyncForEach(gbappPackages, async e => {
const filenameOnly = Path.basename(e);
// 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
}