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

@ -144,6 +144,9 @@ 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;
try {
if (text === 'quit') { if (text === 'quit') {
return await step.replaceDialog('/'); return await step.replaceDialog('/');
} else if (cmdName === 'deployPackage') { } else if (cmdName === 'deployPackage') {
@ -183,10 +186,13 @@ export class AdminDialog extends IGBDialog {
} else { } else {
await step.context.sendActivity(Messages[locale].finished_working); await step.context.sendActivity(Messages[locale].finished_working);
} }
await step.endDialog();
return await step.replaceDialog('/answer', { query: text }); } catch (error) {
await step.context.sendActivity(error.message);
} }
await step.replaceDialog('/ask', { isReturning: true });
}
]) ])
); );
} }

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

@ -246,14 +246,7 @@ 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); 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);
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,
@ -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) => {
try {
const id = req.body.messages[0].chatId.split('@')[0]; const id = req.body.messages[0].chatId.split('@')[0];
const text = req.body.messages[0].body;
let sec = new SecService(); if (req.body.messages[0].fromMe) {
res.end();
const minBoot = GBServer.globals.minInstances[0]; return; // Exit here.
let user = await sec.getUserFromPhone(id);
if (user === null) {
user = await sec.ensureUser(minBoot.instance.instanceId, id,
minBoot.botId, id, "", "whatsapp", id, id);
} }
let botId = user.currentBotId; const minBoot = GBServer.globals.bootInstance;
const min = GBServer.globals.minInstances.filter(p => p.botId === botId)[0]; const toSwitchMin = GBServer.globals.minInstances.filter(p => p.botId === text)[0];
(min as any).whatsAppDirectLine.received(req, res); let activeMin = toSwitchMin ? toSwitchMin : minBoot;
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}`);
}
}); });
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
} }
}); });