fix(whatsapp.gblib): await fix.

Merge branch 'master' of https://github.com/GeneralBots/BotServer

# Conflicts:
#	packages/whatsapp.gblib/index.ts
This commit is contained in:
Rodrigo Rodriguez 2020-04-08 21:35:02 -03:00
commit 4addca4dc1
12 changed files with 122 additions and 132 deletions

16
package-lock.json generated
View file

@ -69,11 +69,6 @@
"uuid": "^3.3.2" "uuid": "^3.3.2"
}, },
"dependencies": { "dependencies": {
"node-fetch": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz",
"integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA=="
},
"tslib": { "tslib": {
"version": "1.11.1", "version": "1.11.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz",
@ -3229,9 +3224,9 @@
} }
}, },
"botlib": { "botlib": {
"version": "1.4.3", "version": "1.4.5",
"resolved": "https://registry.npmjs.org/botlib/-/botlib-1.4.3.tgz", "resolved": "https://registry.npmjs.org/botlib/-/botlib-1.4.5.tgz",
"integrity": "sha512-XLE6ZarAYomTfTsOsU+UeK38ec/yTgJTakNFUqzxz51srpLC35HitKH2crUr6tHv3d6Q4wfTinhclRv+1HBONA==", "integrity": "sha512-y9HvVNCpMwwJbFvfXyBStHDJ/u+ujiw0PXVcehesWQY8K7zh+rsFHDIJg5rj1ocbAuR0LhkFTcKh3ZAZcin9SQ==",
"requires": { "requires": {
"async": "3.1.0", "async": "3.1.0",
"botbuilder": "4.7.0", "botbuilder": "4.7.0",
@ -9434,6 +9429,11 @@
"semver": "^5.7.0" "semver": "^5.7.0"
} }
}, },
"node-fetch": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz",
"integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA=="
},
"node-modules-regexp": { "node-modules-regexp": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz",

View file

@ -10,7 +10,8 @@
"João Ferreira <joao.parana@gmail.com>", "João Ferreira <joao.parana@gmail.com>",
"Jorge Ramos <jramos@pobox.com>", "Jorge Ramos <jramos@pobox.com>",
"PH <ph.an@outlook.com>", "PH <ph.an@outlook.com>",
"Dário Vieira <dario.junior3@gmail.com>" ], "Dário Vieira <dario.junior3@gmail.com>"
],
"engines": { "engines": {
"node": "=10.15.2" "node": "=10.15.2"
}, },

View file

@ -131,12 +131,15 @@ export class GBConfigService {
value = 'true'; value = 'true';
break; break;
case 'REVERSE_PROXY': case 'REVERSE_PROXY':
value = undefined; value = undefined;
break; break;
case 'DISABLE_WEB':
value = "false";
break;
case 'STORAGE_ACQUIRE_TIMEOUT': case 'STORAGE_ACQUIRE_TIMEOUT':
value = 40000; value = 40000;
break; break;
default: default:
GBLog.warn(`Invalid key on .env file: '${key}'`); GBLog.warn(`Invalid key on .env file: '${key}'`);
break; break;
} }

View file

@ -151,6 +151,8 @@ export class GBConversationalService implements IGBConversationalService {
InEmbedAddressBegin, InEmbedAddressBegin,
InEmbedAddressEnd, InEmbedAddressEnd,
InLineBreak, InLineBreak,
InLineBreak1,
InLineBreak2,
}; };
let state = State.InText; let state = State.InText;
let currentImage = ''; let currentImage = '';
@ -171,28 +173,50 @@ export class GBConversationalService implements IGBConversationalService {
else if (c === '[') { else if (c === '[') {
state = State.InEmbedBegin; state = State.InEmbedBegin;
} }
else if (c === '\n') { else if (c === '\n') {
state = State.InLineBreak; state = State.InLineBreak;
} }
else { else {
state = State.InText;
currentText = currentText.concat(c); currentText = currentText.concat(c);
} }
break; break;
case State.InLineBreak: case State.InLineBreak:
if (c === '\n') { if (c === '\n') {
if (currentText !== '') { state = State.InLineBreak1;
if (mobile === null) { }
await step.context.sendActivity(currentText); else if (c === '!') {
} state = State.InImageBegin;
else { }
this.sendToMobile(min, mobile, currentText); else if (c === '[') {
} state = State.InEmbedBegin;
await sleep(3000); } else {
currentText = currentText.concat('\n', c);
state = State.InText;
}
break;
case State.InLineBreak1:
if (c === '\n') {
if (mobile === null) {
await step.context.sendActivity(currentText);
} }
else {
this.sendToMobile(min, mobile, currentText);
}
await sleep(3000);
currentText = ''; currentText = '';
state = State.InText; state = State.InText;
} }
break; else if (c === '!') {
state = State.InImageBegin;
}
else if (c === '[') {
state = State.InEmbedBegin;
} else {
currentText = currentText.concat('\n', '\n', c);
state = State.InText;
}
break;
case State.InEmbedBegin: case State.InEmbedBegin:
if (c === '=') { if (c === '=') {
if (currentText !== '') { if (currentText !== '') {
@ -217,7 +241,7 @@ export class GBConversationalService implements IGBConversationalService {
await sleep(5000); await sleep(5000);
currentEmbedUrl = ''; currentEmbedUrl = '';
} }
else{ else {
currentEmbedUrl = currentEmbedUrl.concat(c); currentEmbedUrl = currentEmbedUrl.concat(c);
} }
break; break;

View file

@ -338,7 +338,7 @@ export class GBDeployer implements IGBDeployer {
case '.gbkb': case '.gbkb':
const service = new KBService(this.core.sequelize); const service = new KBService(this.core.sequelize);
return service.undeployKbFromStorage(instance, this, p.packageId); return await service.undeployKbFromStorage(instance, this, p.packageId);
case '.gbui': case '.gbui':
@ -528,26 +528,26 @@ export class GBDeployer implements IGBDeployer {
} }
} }
folder = Path.join(e, 'dist'); folder = Path.join(e, 'dist');
if (!Fs.existsSync()) {
GBLog.info(`Compiling ${e}...`);
try {
if (process.env.GBAPP_DISABLE_COMPILE !== "true") { try {
child_process.execSync(Path.join(process.env.PWD, 'node_modules/.bin/tsc'), { cwd: e }); if (process.env.GBAPP_DISABLE_COMPILE !== "true") {
} GBLog.info(`Compiling .gbapp: ${e}.`);
const m = await import(e); child_process.execSync(Path.join(process.env.PWD, 'node_modules/.bin/tsc'), { cwd: e });
const p = new m.Package();
p.loadPackage(core, core.sequelize);
appPackages.push(p);
GBLog.info(`App (.gbapp) deployed: ${e}.`);
appPackagesProcessed++;
} catch (error) {
GBLog.error(`Error compiling .gbapp package ${e}:\n${error.stdout.toString()}`);
appPackagesProcessed++;
} }
const m = await import(e);
const p = new m.Package();
p.loadPackage(core, core.sequelize);
appPackages.push(p);
GBLog.info(`App (.gbapp) deployed: ${e}.`);
appPackagesProcessed++;
} catch (error) {
GBLog.error(`Error message: ${error.message}`);
GBLog.error(`Error message: ${error.stack}`);
GBLog.error(`Error compiling .gbapp package ${e}:\n${error.stderr.toString()}`);
GBLog.error(`Error compiling .gbapp package ${e}:\n${error.stdout.toString()}`);
appPackagesProcessed++;
} }
} else {
appPackagesProcessed++;
} }
}); });

View file

@ -63,9 +63,10 @@ export class GBImporter {
} }
const instance = await this.core.loadInstance(botId); const instance = await this.core.loadInstance(botId);
if (instance.botId === undefined || instance.botId === null) { if (instance != null && instance.botId === null) {
console.log(`Null BotId after load instance with botId: ${botId}.`); console.log(`Null BotId after load instance with botId: ${botId}.`);
} }
return await this.createOrUpdateInstanceInternal(instance, botId, localPath, settingsJson); return await this.createOrUpdateInstanceInternal(instance, botId, localPath, settingsJson);
} }

View file

@ -44,6 +44,7 @@ const removeRoute = require('express-remove-route');
const AuthenticationContext = require('adal-node').AuthenticationContext; const AuthenticationContext = require('adal-node').AuthenticationContext;
const wash = require('washyourmouthoutwithsoap'); const wash = require('washyourmouthoutwithsoap');
import { AutoSaveStateMiddleware, BotFrameworkAdapter, ConversationState, MemoryStorage, UserState } from 'botbuilder'; import { AutoSaveStateMiddleware, BotFrameworkAdapter, ConversationState, MemoryStorage, UserState } from 'botbuilder';
import { CollectionUtil } from 'pragmatismo-io-framework';
import { ConfirmPrompt, WaterfallDialog } from 'botbuilder-dialogs'; import { ConfirmPrompt, WaterfallDialog } from 'botbuilder-dialogs';
import { import {
GBDialogStep, GBDialogStep,
@ -65,6 +66,7 @@ import { GBConfigService } from './GBConfigService';
import { GBDeployer } from './GBDeployer'; import { GBDeployer } from './GBDeployer';
import { SecService } from '../../security.gblib/services/SecService'; import { SecService } from '../../security.gblib/services/SecService';
import { AnalyticsService } from '../../analytics.gblib/services/AnalyticsService'; import { AnalyticsService } from '../../analytics.gblib/services/AnalyticsService';
import { WhatsappDirectLine } from '../../whatsapp.gblib/services/WhatsappDirectLine';
/** /**
* Minimal service layer for a bot. * Minimal service layer for a bot.
@ -137,33 +139,40 @@ export class GBMinService {
res.end(); res.end();
return; // Exit here. return; // Exit here.
} }
let activeMin;
if (process.env.WHATSAPP_WELCOME_DISABLED !== "true") {
const toSwitchMin = GBServer.globals.minInstances.filter(p => p.botId === text)[0]; const toSwitchMin = GBServer.globals.minInstances.filter(p => p.botId === text)[0];
let activeMin = toSwitchMin ? toSwitchMin : GBServer.globals.minBoot; activeMin = toSwitchMin ? toSwitchMin : GBServer.globals.minBoot;
let sec = new SecService(); let sec = new SecService();
let user = await sec.getUserFromPhone(id); let user = await sec.getUserFromPhone(id);
if (user === null) { if (user === null) {
user = await sec.ensureUser(activeMin.instance.instanceId, id, user = await sec.ensureUser(activeMin.instance.instanceId, id,
activeMin.botId, id, "", "whatsapp", id, id); activeMin.botId, id, "", "whatsapp", id, id);
await (activeMin as any).whatsAppDirectLine.sendToDevice(id, `Olá! Seja bem-vinda(o)!\nMe chamo ${activeMin.instance.title}. Como posso ajudar?`); await (activeMin as any).whatsAppDirectLine.sendToDevice(id, `Olá! Seja bem-vinda(o)!\nMe chamo ${activeMin.instance.title}. Como posso ajudar?`);
res.end();
} else {
// User wants to switch bots.
if (toSwitchMin !== undefined) {
await sec.updateCurrentBotId(id, text);
await (activeMin as any).whatsAppDirectLine.sendToDevice(id, `Agora falando com ${activeMin.instance.title}...`);
res.end(); res.end();
} else {
// User wants to switch bots.
if (toSwitchMin !== undefined) {
await sec.updateCurrentBotId(id, text);
await (activeMin as any).whatsAppDirectLine.sendToDevice(id, `Agora falando com ${activeMin.instance.title}...`);
res.end();
}
else {
activeMin = GBServer.globals.minInstances.filter(p => p.botId === user.currentBotId)[0];;
(activeMin as any).whatsAppDirectLine.received(req, res);
}
} }
else { }
activeMin = GBServer.globals.minInstances.filter(p => p.botId === user.currentBotId)[0];; else {
(activeMin as any).whatsAppDirectLine.received(req, res); (GBServer.globals.minBoot as any).whatsAppDirectLine.received(req, res);
}
} }
} catch (error) { } catch (error) {
GBLog.error(`Error on Whatsapp callback: ${error.message}`); GBLog.error(`Error on Whatsapp callback: ${error.message}`);
} }
}); });
await Promise.all( await Promise.all(
@ -395,6 +404,16 @@ export class GBMinService {
min.scriptMap = {}; min.scriptMap = {};
min.sandBoxMap = {}; min.sandBoxMap = {};
min.packages = sysPackages; min.packages = sysPackages;
if (min.instance.whatsappServiceKey !== null) {
min.whatsAppDirectLine = new WhatsappDirectLine(
min.botId,
min.instance.whatsappBotKey,
min.instance.whatsappServiceKey,
min.instance.whatsappServiceNumber,
min.instance.whatsappServiceUrl
);
}
min.userProfile = conversationState.createProperty('userProfile'); min.userProfile = conversationState.createProperty('userProfile');
const dialogState = conversationState.createProperty('dialogState'); const dialogState = conversationState.createProperty('dialogState');

View file

@ -1,10 +0,0 @@
import { expect } from 'chai';
import { GBImporter } from '../services/GBImporterService';
describe('Hello function', () => {
it('should return empty test', () => {
const service = new GBImporter(undefined);
const result = 0;
expect(result).to.equal(0);
});
});

View file

@ -1,50 +0,0 @@
/*****************************************************************************\
| ( )_ _ |
| _ _ _ __ _ _ __ ___ ___ _ _ | ,_)(_) ___ ___ _ |
| ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| | | |/',__)/' _ `\ /'_`\ |
| | (_) )| | ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) ) |
| | ,__/'(_) `\__,_)`\__ |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/' |
| | | ( )_) | |
| (_) \___/' |
| |
| General Bots Copyright (c) Pragmatismo.io. All rights reserved. |
| Licensed under the AGPL-3.0. |
| |
| 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, |
| but WITHOUT ANY WARRANTY, without even the implied warranty of |
| 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. |
| |
\*****************************************************************************/
'use strict';
/**
* @fileoverview Tests for General Bots VM.
*/
import { expect } from 'chai';
import { GBVMService } from '../services/GBVMService';
describe('Load function', () => {
it('should fail on invalid file', () => {
try {
const service = new GBVMService();
} catch (error) {
expect(error).to.equal(0);
}
});
});

View file

@ -79,7 +79,7 @@ export class FeedbackDialog extends IGBDialog {
async step => { async step => {
const locale = step.context.activity.locale; const locale = step.context.activity.locale;
const rate = step.result.entity; const rate = step.result.entity;
const user = await min.userProfile.get(context, {}); const user = await min.userProfile.get(step.context, {});
await service.updateConversationRate(user.conversation, rate); await service.updateConversationRate(user.conversation, rate);
await step.context.sendActivity(Messages[locale].thanks); await step.context.sendActivity(Messages[locale].thanks);

View file

@ -60,7 +60,7 @@ export class QualityDialog extends IGBDialog {
min.dialogs.add(new WaterfallDialog('/quality', [ min.dialogs.add(new WaterfallDialog('/quality', [
async step => { async step => {
const locale = step.context.activity.locale; const locale = step.context.activity.locale;
const user = await min.userProfile.get(context, {}); const user = await min.userProfile.get(step.context, {});
const score = step.result; const score = step.result;

View file

@ -128,7 +128,7 @@ export class GBServer {
GBServer.globals.publicAddress = await core.ensureProxy(port); GBServer.globals.publicAddress = await core.ensureProxy(port);
} }
} else { } else {
const serverAddress = `https://${process.env.WEBSITE_SITE_NAME}.azurewebsites.net`; const serverAddress = process.env.BOT_URL;
GBLog.info(`Defining server address at ${serverAddress}...`); GBLog.info(`Defining server address at ${serverAddress}...`);
GBServer.globals.publicAddress = serverAddress; GBServer.globals.publicAddress = serverAddress;
} }
@ -167,7 +167,7 @@ export class GBServer {
const fullInstance = Object.assign(packageInstance, GBServer.globals.bootInstance); const fullInstance = Object.assign(packageInstance, GBServer.globals.bootInstance);
await core.saveInstance(fullInstance); await core.saveInstance(fullInstance);
let instances: IGBInstance[] = await core.loadAllInstances(core, azureDeployer, let instances: IGBInstance[] = await core.loadAllInstances(core, azureDeployer,
GBServer.globals.publicAddress); GBServer.globals.publicAddress);
instances = await core.ensureInstances(instances, GBServer.globals.bootInstance, core); instances = await core.ensureInstances(instances, GBServer.globals.bootInstance, core);
if (GBServer.globals.bootInstance !== undefined) { if (GBServer.globals.bootInstance !== undefined) {
GBServer.globals.bootInstance = instances[0]; GBServer.globals.bootInstance = instances[0];
@ -182,7 +182,9 @@ export class GBServer {
// Deployment of local applications for the first time. // Deployment of local applications for the first time.
deployer.setupDefaultGBUI(); if (GBConfigService.get("DISABLE_WEB") !== "true") {
deployer.setupDefaultGBUI();
}
GBLog.info(`The Bot Server is in RUNNING mode...`); GBLog.info(`The Bot Server is in RUNNING mode...`);