fix(whatsapp.gblib): User can say the activation code as the first message.

This commit is contained in:
Rodrigo Rodriguez 2019-08-23 14:36:47 -03:00
parent 650779e363
commit 3f6668da0d
5 changed files with 103 additions and 80 deletions

View file

@ -120,20 +120,20 @@ export class AdminDialog extends IGBDialog {
const prompt = Messages[locale].authenticate; const prompt = Messages[locale].authenticate;
return await step.prompt('textPrompt', prompt); return await step.prompt('textPrompt', prompt);
// }, // },
// async step => { // async step => {
// const locale = step.context.activity.locale; // const locale = step.context.activity.locale;
// const sensitive = step.result; // const sensitive = step.result;
// if (sensitive === GBConfigService.get('ADMIN_PASS')) { // if (sensitive === GBConfigService.get('ADMIN_PASS')) {
// await step.context.sendActivity(Messages[locale].welcome); // await step.context.sendActivity(Messages[locale].welcome);
// return await step.prompt('textPrompt', Messages[locale].which_task); // return await step.prompt('textPrompt', Messages[locale].which_task);
// } else { // } else {
// await step.context.sendActivity(Messages[locale].wrong_password); // await step.context.sendActivity(Messages[locale].wrong_password);
// return await step.endDialog(); // return await step.endDialog();
// } // }
}, },
async step => { async step => {
const locale: string = step.context.activity.locale; const locale: string = step.context.activity.locale;
@ -144,49 +144,55 @@ export class AdminDialog extends IGBDialog {
await step.context.sendActivity(Messages[locale].working(cmdName)); await step.context.sendActivity(Messages[locale].working(cmdName));
let unknownCommand = false; let unknownCommand = false;
if (text === 'quit') { try {
return await step.replaceDialog('/');
} else if (cmdName === 'deployPackage') {
await AdminDialog.deployPackageCommand(min, text, deployer);
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'redeployPackage') {
await step.context.sendActivity('The package is being *unloaded*...');
await AdminDialog.undeployPackageCommand(text, min);
await step.context.sendActivity('Now, *deploying* package...');
await AdminDialog.deployPackageCommand(min, text, deployer);
await step.context.sendActivity('Package deployed. Just need to rebuild the index... Doing it right now.');
await AdminDialog.rebuildIndexPackageCommand(min, deployer);
await step.context.sendActivity('Finished importing of that .gbkb package. Thanks.');
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'undeployPackage') {
await step.context.sendActivity('The package is being *undeployed*...');
await AdminDialog.undeployPackageCommand(text, min);
await step.context.sendActivity('Package *undeployed*.');
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'rebuildIndex') {
await AdminDialog.rebuildIndexPackageCommand(min, deployer);
return await step.replaceDialog('/admin', { firstRun: false }); if (text === 'quit') {
} else if (cmdName === 'syncBotServer') { return await step.replaceDialog('/');
await AdminDialog.syncBotServerCommand(min, deployer); } else if (cmdName === 'deployPackage') {
await AdminDialog.deployPackageCommand(min, text, deployer);
return await step.replaceDialog('/admin', { firstRun: false }); return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'setupSecurity') { } else if (cmdName === 'redeployPackage') {
return await step.beginDialog('/setupSecurity'); await step.context.sendActivity('The package is being *unloaded*...');
} else { await AdminDialog.undeployPackageCommand(text, min);
unknownCommand = true; await step.context.sendActivity('Now, *deploying* package...');
await AdminDialog.deployPackageCommand(min, text, deployer);
await step.context.sendActivity('Package deployed. Just need to rebuild the index... Doing it right now.');
await AdminDialog.rebuildIndexPackageCommand(min, deployer);
await step.context.sendActivity('Finished importing of that .gbkb package. Thanks.');
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'undeployPackage') {
await step.context.sendActivity('The package is being *undeployed*...');
await AdminDialog.undeployPackageCommand(text, min);
await step.context.sendActivity('Package *undeployed*.');
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'rebuildIndex') {
await AdminDialog.rebuildIndexPackageCommand(min, deployer);
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'syncBotServer') {
await AdminDialog.syncBotServerCommand(min, deployer);
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'setupSecurity') {
return await step.beginDialog('/setupSecurity');
} else {
unknownCommand = true;
}
if (unknownCommand) {
await step.context.sendActivity(Messages[locale].unknown_command);
} else {
await step.context.sendActivity(Messages[locale].finished_working);
}
} catch (error) {
await step.context.sendActivity(error.message);
} }
await step.replaceDialog('/ask', { isReturning: true });
if (unknownCommand) {
await step.context.sendActivity(Messages[locale].unknown_command);
} else {
await step.context.sendActivity(Messages[locale].finished_working);
}
await step.endDialog();
return await step.replaceDialog('/answer', { query: text });
} }
]) ])
); );
} }

View file

@ -57,7 +57,7 @@ export class SwitchBotDialog extends IGBDialog {
async step => { async step => {
const locale = step.context.activity.locale; const locale = step.context.activity.locale;
await step.context.sendActivity(`${min.instance.description}`);
return await step.prompt('textPrompt', "Qual seria o código de ativação?"); return await step.prompt('textPrompt', "Qual seria o código de ativação?");
}, },
async step => { async step => {

View file

@ -190,7 +190,7 @@ export class GBDeployer {
); );
} else { } else {
let botId = GBConfigService.get('BOT_ID'); let botId = GBConfigService.get('BOT_ID');
let bootInstance = await this.core.loadInstance(botId); let bootInstance = await this.core.loadInstance(botId);
@ -203,7 +203,7 @@ export class GBDeployer {
instance.whatsappServiceNumber = bootInstance.whatsappServiceNumber; instance.whatsappServiceNumber = bootInstance.whatsappServiceNumber;
instance.whatsappServiceUrl = bootInstance.whatsappServiceUrl; instance.whatsappServiceUrl = bootInstance.whatsappServiceUrl;
instance.whatsappServiceWebhookUrl = bootInstance.whatsappServiceWebhookUrl; instance.whatsappServiceWebhookUrl = bootInstance.whatsappServiceWebhookUrl;
instance = await service.internalDeployBot( instance = await service.internalDeployBot(
instance, instance,
accessToken, accessToken,
@ -223,7 +223,7 @@ export class GBDeployer {
await GBServer.globals.minService.mountBot(instance); await GBServer.globals.minService.mountBot(instance);
} }
await this.core.saveInstance(instance); await this.core.saveInstance(instance);
} }
@ -245,15 +245,8 @@ export class GBDeployer {
} }
GBServer.globals.minService.unmountBot(botId); GBServer.globals.minService.unmountBot(botId);
await this.core.deleteInstance(botId); await this.core.deleteInstance(botId);
const packageFolder =Path.join(process.env.PWD, 'work', packageName);
rimraf.sync(packageFolder);
}
public async undeployTheme(packageName: string): Promise<void> {
const packageFolder = Path.join(process.env.PWD, 'work', packageName); const packageFolder = Path.join(process.env.PWD, 'work', packageName);
rimraf.sync(packageFolder);
} }
public async deployPackageToStorage(instanceId: number, packageName: string): Promise<GuaribasPackage> { public async deployPackageToStorage(instanceId: number, packageName: string): Promise<GuaribasPackage> {
return GuaribasPackage.create({ return GuaribasPackage.create({
packageName: packageName, packageName: packageName,
@ -291,7 +284,7 @@ export class GBDeployer {
const vm = new GBVMService(); const vm = new GBVMService();
await vm.loadDialogPackage(localPath, min, this.core, this); await vm.loadDialogPackage(localPath, min, this.core, this);
break; break;
default: default:
const err = GBError.create(`Unhandled package type: ${packageType}.`); const err = GBError.create(`Unhandled package type: ${packageType}.`);
Promise.reject(err); Promise.reject(err);
@ -303,12 +296,14 @@ export class GBDeployer {
const packageType = Path.extname(localPath); const packageType = Path.extname(localPath);
const packageName = Path.basename(localPath); const packageName = Path.basename(localPath);
const p = await this.getPackageByName(instance.instanceId, packageName); const p = await this.getStoragePackageByName(instance.instanceId, packageName);
if (p === null) {
throw new Error(`Package ${packageName} not found on instance: ${instance.botId}.`);
}
const packageObject = JSON.parse(Fs.readFileSync(urlJoin(localPath, 'package.json'), 'utf8'));
switch (packageType) { switch (packageType) {
case '.gbot': case '.gbot':
const packageObject = JSON.parse(Fs.readFileSync(urlJoin(localPath, 'package.json'), 'utf8'));
await this.undeployBot(packageObject.botId, packageName); await this.undeployBot(packageObject.botId, packageName);
break; break;
@ -321,7 +316,7 @@ export class GBDeployer {
break; break;
case '.gbtheme': case '.gbtheme':
this.undeployTheme(packageName); // Just remove the package.
break; break;
case '.gbdialog': case '.gbdialog':
@ -333,6 +328,7 @@ export class GBDeployer {
Promise.reject(err); Promise.reject(err);
break; break;
} }
rimraf.sync(localPath);
} }
public async rebuildIndex(instance: IGBInstance, searchSchema: any) { public async rebuildIndex(instance: IGBInstance, searchSchema: any) {
@ -368,10 +364,10 @@ export class GBDeployer {
await search.createIndex(searchSchema, dsName); await search.createIndex(searchSchema, dsName);
} }
public async getPackageByName(instanceId: number, packageName: string): Promise<GuaribasPackage> { public async getStoragePackageByName(instanceId: number, packageName: string): Promise<GuaribasPackage> {
const where = { packageName: packageName, instanceId: instanceId }; const where = { packageName: packageName, instanceId: instanceId };
return GuaribasPackage.findOne({ return await GuaribasPackage.findOne({
where: where where: where
}); });
} }

View file

@ -69,6 +69,7 @@ import { GBAdminPackage } from './../../admin.gbapp/index';
import { GBConfigService } from './GBConfigService'; 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 { isBreakOrContinueStatement } from 'typescript';
/** /**
* Minimal service layer for a bot. * Minimal service layer for a bot.
@ -128,20 +129,42 @@ export class GBMinService {
} }
const url = '/webhooks/whatsapp'; const url = '/webhooks/whatsapp';
GBServer.globals.server.post(url, async (req, res) => { GBServer.globals.server.post(url, async (req, res) => {
const id = req.body.messages[0].chatId.split('@')[0]; try {
let sec = new SecService(); const id = req.body.messages[0].chatId.split('@')[0];
const text = req.body.messages[0].body;
if (req.body.messages[0].fromMe) {
res.end();
return; // Exit here.
}
const minBoot = GBServer.globals.minInstances[0]; const minBoot = GBServer.globals.bootInstance;
let user = await sec.getUserFromPhone(id); const toSwitchMin = GBServer.globals.minInstances.filter(p => p.botId === text)[0];
if (user === null) { let activeMin = toSwitchMin ? toSwitchMin : minBoot;
user = await sec.ensureUser(minBoot.instance.instanceId, id,
minBoot.botId, id, "", "whatsapp", id, id); let sec = new SecService();
let user = await sec.getUserFromPhone(id);
if (user === null) {
user = await sec.ensureUser(activeMin.instance.instanceId, 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?`);
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);
}
}
} catch (error) {
GBLog.error(`Error on Whatsapp callback: ${error.message}`);
} }
let botId = user.currentBotId;
const min = GBServer.globals.minInstances.filter(p => p.botId === botId)[0];
(min as any).whatsAppDirectLine.received(req, res);
}); });
await Promise.all( await Promise.all(

View file

@ -91,13 +91,11 @@ export class SecService extends GBService {
} }
public async updateCurrentBotId( public async updateCurrentBotId(
instanceId: number,
userSystemId: string, userSystemId: string,
currentBotId: string currentBotId: string
): Promise<GuaribasUser> { ): Promise<GuaribasUser> {
let user = await GuaribasUser.findOne({ let user = await GuaribasUser.findOne({
where: { where: {
instanceId: instanceId,
userSystemId: userSystemId userSystemId: userSystemId
} }
}); });