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;
return await step.prompt('textPrompt', prompt);
// },
// async step => {
// const locale = step.context.activity.locale;
// const sensitive = step.result;
// },
// async step => {
// const locale = step.context.activity.locale;
// const sensitive = step.result;
// if (sensitive === GBConfigService.get('ADMIN_PASS')) {
// await step.context.sendActivity(Messages[locale].welcome);
// if (sensitive === GBConfigService.get('ADMIN_PASS')) {
// await step.context.sendActivity(Messages[locale].welcome);
// return await step.prompt('textPrompt', Messages[locale].which_task);
// } else {
// await step.context.sendActivity(Messages[locale].wrong_password);
// return await step.prompt('textPrompt', Messages[locale].which_task);
// } else {
// await step.context.sendActivity(Messages[locale].wrong_password);
// return await step.endDialog();
// }
// return await step.endDialog();
// }
},
async step => {
const locale: string = step.context.activity.locale;
@ -144,49 +144,55 @@ export class AdminDialog extends IGBDialog {
await step.context.sendActivity(Messages[locale].working(cmdName));
let unknownCommand = false;
if (text === 'quit') {
return await step.replaceDialog('/');
} else if (cmdName === 'deployPackage') {
await AdminDialog.deployPackageCommand(min, text, deployer);
try {
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 });
} else if (cmdName === 'syncBotServer') {
await AdminDialog.syncBotServerCommand(min, deployer);
if (text === 'quit') {
return await step.replaceDialog('/');
} else if (cmdName === 'deployPackage') {
await AdminDialog.deployPackageCommand(min, text, deployer);
return await step.replaceDialog('/admin', { firstRun: false });
} else if (cmdName === 'setupSecurity') {
return await step.beginDialog('/setupSecurity');
} else {
unknownCommand = true;
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 });
} 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);
}
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 });
await step.replaceDialog('/ask', { isReturning: true });
}
])
);
}

View file

@ -57,7 +57,7 @@ export class SwitchBotDialog extends IGBDialog {
async step => {
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?");
},
async step => {

View file

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

View file

@ -69,6 +69,7 @@ import { GBAdminPackage } from './../../admin.gbapp/index';
import { GBConfigService } from './GBConfigService';
import { GBDeployer } from './GBDeployer';
import { SecService } from '../../security.gblib/services/SecService';
import { isBreakOrContinueStatement } from 'typescript';
/**
* Minimal service layer for a bot.
@ -128,20 +129,42 @@ export class GBMinService {
}
const url = '/webhooks/whatsapp';
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];
let user = await sec.getUserFromPhone(id);
if (user === null) {
user = await sec.ensureUser(minBoot.instance.instanceId, id,
minBoot.botId, id, "", "whatsapp", id, id);
const minBoot = GBServer.globals.bootInstance;
const toSwitchMin = GBServer.globals.minInstances.filter(p => p.botId === text)[0];
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}`);
}
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(

View file

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