Skip to content

Commit

Permalink
fix(whatsapp.gblib): User can say the activation code as the first me…
Browse files Browse the repository at this point in the history
…ssage.
  • Loading branch information
rodrigorodriguez committed Aug 23, 2019
1 parent 650779e commit 3f6668d
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 83 deletions.
110 changes: 58 additions & 52 deletions packages/admin.gbapp/dialogs/AdminDialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);

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;
try {


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 === '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 });
}

])
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core.gbapp/dialogs/SwitchBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
30 changes: 13 additions & 17 deletions packages/core.gbapp/services/GBDeployer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ export class GBDeployer {
);

} else {

let botId = GBConfigService.get('BOT_ID');
let bootInstance = await this.core.loadInstance(botId);

Expand All @@ -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,
Expand All @@ -223,7 +223,7 @@ export class GBDeployer {
await GBServer.globals.minService.mountBot(instance);
}
await this.core.saveInstance(instance);

}


Expand All @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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;

Expand All @@ -321,7 +316,7 @@ export class GBDeployer {
break;

case '.gbtheme':
this.undeployTheme(packageName);
// Just remove the package.
break;

case '.gbdialog':
Expand All @@ -333,6 +328,7 @@ export class GBDeployer {
Promise.reject(err);
break;
}
rimraf.sync(localPath);
}

public async rebuildIndex(instance: IGBInstance, searchSchema: any) {
Expand Down Expand Up @@ -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
});
}
Expand Down
45 changes: 34 additions & 11 deletions packages/core.gbapp/services/GBMinService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 0 additions & 2 deletions packages/security.gblib/services/SecService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
});
Expand Down

0 comments on commit 3f6668d

Please sign in to comment.