Skip to content

Commit

Permalink
fix(whatsapp.gblib): Enabling Whatsapp.
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigorodriguez committed May 16, 2019
1 parent 85249e5 commit 74f5936
Show file tree
Hide file tree
Showing 11 changed files with 1,869 additions and 467 deletions.
1,655 changes: 1,655 additions & 0 deletions directline-3.0.json

Large diffs are not rendered by default.

579 changes: 155 additions & 424 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@
"simple-git": "1.113.0",
"sqlite3": "4.0.8",
"strict-password-generator": "1.1.2",
"swagger-client": "3.8.25",
"swagger-client": "^2.1.18",
"tedious": "6.1.1",
"temperature-js": "0.1.0",
"ts-node": "8.1.0",
Expand Down
11 changes: 6 additions & 5 deletions packages/admin.gbapp/dialogs/AdminDialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

'use strict';

var crypto = require('crypto')
import { WaterfallDialog } from 'botbuilder-dialogs';
import { GBMinInstance, IGBDialog } from 'botlib';
import urlJoin = require('url-join');
Expand Down Expand Up @@ -205,11 +206,11 @@ export class AdminDialog extends IGBDialog {

const url = `https://login.microsoftonline.com/${
min.instance.authenticatorTenant
}/oauth2/authorize?client_id=${min.instance.authenticatorClientId}&response_type=code&redirect_uri=${urlJoin(
min.instance.botEndpoint,
min.instance.botId,
'/token'
)}&state=${state}&response_mode=query`;
}/oauth2/authorize?client_id=${min.instance.authenticatorClientId}&response_type=code&redirect_uri=${urlJoin(
min.instance.botEndpoint,
min.instance.botId,
'/token'
)}&state=${state}&response_mode=query`;

await step.context.sendActivity(Messages[locale].consent(url));

Expand Down
8 changes: 6 additions & 2 deletions packages/core.gbapp/services/GBAPIService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import { TurnContext } from 'botbuilder';
import { WaterfallStepContext } from 'botbuilder-dialogs';
import { GBLog, GBMinInstance } from 'botlib';
import * as crypto from 'crypto';
import * as request from 'request-promise-native';
import urlJoin = require('url-join');
import { GBAdminService } from '../../admin.gbapp/services/GBAdminService';
Expand Down Expand Up @@ -104,7 +105,7 @@ class SysClass {
public async httpGet(url: string, qs) {

const options = {
uri: urlJoin(url , qs)
uri: urlJoin(url, qs)
};

return request.get(options);
Expand Down Expand Up @@ -132,7 +133,10 @@ export class DialogClass {
}

public async hear(cb) {
const idCallback = crypto.getRandomValues(new Uint32Array(16))[0];
function random(low, high) {
return Math.random() * (high - low) + low
}
const idCallback = random(0, 120000000);E
this.min.cbMap[idCallback] = cb;
await this.step.beginDialog('/hear', { id: idCallback });
}
Expand Down
4 changes: 3 additions & 1 deletion packages/core.gbapp/services/GBDeployer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export class GBDeployer {
case '.gbdialog':
const vm = new GBVMService();

return vm.loadDialogPackage(localPath, min, this.core, this);
await vm.loadDialogPackage(localPath, min, this.core, this);

default:
const err = GBError.create(`Unhandled package type: ${packageType}.`);
Expand Down Expand Up @@ -375,6 +375,8 @@ export class GBDeployer {
// Already Handled
} else if (Path.extname(filename) === '.gbdialog') {
// Already Handled
} else if (Path.extname(filename) === '.gbignore') {
// Ignored
} else {
// Unknown package format.
const err = new Error(`Package type not handled: ${filename}.`);
Expand Down
5 changes: 3 additions & 2 deletions packages/core.gbapp/services/GBMinService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export class GBMinService {

// Install default VBA module.

// DISABLED: deployer.deployPackage(min, 'packages/default.gbdialog');
deployer.deployPackage(min, 'packages/default.gbdialog');

// Call the loadBot context.activity for all packages.

Expand Down Expand Up @@ -336,6 +336,7 @@ export class GBMinService {
min.instance = await this.core.loadInstance(min.botId);
min.cbMap = {};
min.scriptMap = {};
min.sandBoxMap = {};
min.userProfile = conversationState.createProperty('userProfile');
const dialogState = conversationState.createProperty('dialogState');

Expand Down Expand Up @@ -396,7 +397,7 @@ export class GBMinService {
await adapter.processActivity(req, res, async context => {
// Get loaded user state
const step = await min.dialogs.createContext(context);
step.context.activity.locale = 'en-US';
step.context.activity.locale = 'pt-BR';

try {
const user = await min.userProfile.get(context, {});
Expand Down
17 changes: 6 additions & 11 deletions packages/core.gbapp/services/GBVMService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,9 @@ export class GBVMService extends GBService {
let parsedCode = code;
const hearExp = /(\w+).*hear.*\(\)/;

let match1 = hearExp.exec(code);
let match1;

while (match1 !== undefined) {
while ((match1 = hearExp.exec(code))) {
let pos = 0;

// Writes async body.
Expand All @@ -185,9 +185,8 @@ export class GBVMService extends GBService {

let right = 0;
let left = 1;
let match2 = /\{|\}/.exec(tempCode);

while (match2 !== undefined) {
let match2;
while ((match2 = /\{|\}/.exec(tempCode))) {
const c = tempCode.substring(match2.index, match2.index + 1);

if (c === '}') {
Expand All @@ -202,7 +201,6 @@ export class GBVMService extends GBService {
if (left === right) {
break;
}
match1 = hearExp.exec(code);
}

parsedCode += code.substring(start + match1[0].length + 1, pos + match1[0].length);
Expand All @@ -212,19 +210,19 @@ export class GBVMService extends GBService {
// A interaction will be made for each hear.

code = parsedCode;
match2 = /\{|\}/.exec(tempCode);
}

parsedCode = this.handleThisAndAwait(parsedCode);

parsedCode = beautify(parsedCode, { indent_size: 2, space_in_empty_paren: true });
parsedCode = beautify(parsedCode, { indent_size: 2, space_in_empty_paren: true })
fs.writeFileSync(jsfile, parsedCode);

const sandbox: DialogClass = new DialogClass(min, deployer);
const context = vm.createContext(sandbox);
vm.runInContext(parsedCode, context);
min.sandBoxMap[mainName] = sandbox;
GBLog.info(`[GBVMService] Finished loading of ${filename}`);

}
}

Expand Down Expand Up @@ -259,9 +257,6 @@ export class GBVMService extends GBService {
return await step.prompt('textPrompt', {});
},
async step => {
min.sandbox.context = step.context;
min.sandbox.step = step;

const cbId = step.activeDialog.state.cbId;
const cb = min.cbMap[cbId];
cb.bind({ step: step, context: step.context });
Expand Down
2 changes: 1 addition & 1 deletion packages/whatsapp.gblib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export class GBWhatsappPackage implements IGBPackage {
min.instance.whatsappServiceKey,
min.instance.whatsappServiceNumber,
min.instance.whatsappServiceUrl,
min.instance.whatsappServiceWebhookUrl
min.instance.botId
);
}
}
Expand Down
30 changes: 16 additions & 14 deletions packages/whatsapp.gblib/services/WhatsappDirectLine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { GBServer } from '../../../src/app';
export class WhatsappDirectLine extends GBService {
public pollInterval = 1000;
public directLineClientName = 'DirectLineClient';
public directLineSpecUrl = 'https://docs.botframework.com/en-us/restapi/directline3/swagger.json';

public directLineClient: any;
public whatsappServiceKey: string;
Expand All @@ -39,15 +38,16 @@ export class WhatsappDirectLine extends GBService {
this.whatsappServiceNumber = whatsappServiceNumber;
this.whatsappServiceUrl = whatsappServiceUrl;
this.whatsappServiceWebhookUrl = whatsappServiceWebhookUrl;
var fs = require('fs')

this.directLineClient = rp(this.directLineSpecUrl)
.then(spec => {
return new Swagger({
spec: JSON.parse(spec.trim()),
usePromise: true
});
})
this.directLineClient =
new Swagger({
spec: JSON.parse(fs.readFileSync('directline-3.0.json', 'utf8')),
usePromise: true
});
this.directLineClient
.then(async client => {

client.clientAuthorizations.add(
'AuthorizationBotConnector',
new Swagger.ApiKeyAuthorization('Authorization', `Bearer ${directLineSecret}`, 'header')
Expand All @@ -72,11 +72,6 @@ export class WhatsappDirectLine extends GBService {
} catch (error) {
GBLog.error(`Error initializing 3rd party Whatsapp provider(1) ${error}`);
}

return client;
})
.catch(err => {
GBLog.error(`Error initializing 3rd party Whatsapp provider(2) ${err}`);
});
}

Expand Down Expand Up @@ -158,7 +153,7 @@ export class WhatsappDirectLine extends GBService {
if (activities && activities.length) {
// Ignore own messages.

activities = activities.filter(m => m.from.id === 'GeneralBots' && m.type === 'message');
activities = activities.filter(m => m.from.id === this.botId && m.type === 'message');

if (activities.length) {
// Print other messages.
Expand Down Expand Up @@ -215,5 +210,12 @@ export class WhatsappDirectLine extends GBService {
'cache-control': 'no-cache'
}
};

try {
const result = request.post(options);
GBLog.info(result);
} catch (error) {
GBLog.error(`Error sending message to Whatsapp provider ${error}`);
}
}
}
23 changes: 17 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,30 @@
"resolveJsonModule": true,
"outDir": "./dist",
"paths": {
"*": ["types/*"],
"botlib/*": ["node_modules/botlib/*"],
"pragmatismo-io-framework/*": ["node_modules/pragmatismo-io-framework/*"]
"*": [
"types/*"
],
"botlib/*": [
"node_modules/botlib/*"
],
"pragmatismo-io-framework/*": [
"node_modules/pragmatismo-io-framework/*"
]
},
"sourceMap": true,
"target": "es6",
"typeRoots": ["node_modules/@types"]
"typeRoots": [
"node_modules/@types"
]
},
"include": [
"test/**/*",
"src/**/*",
"packages/*.gbapp/**/*",
"packages/*.gblib/**/*"
],
"exclude": ["dist", "node_modules"]
}
"exclude": [
"dist",
"node_modules"
]
}

0 comments on commit 74f5936

Please sign in to comment.