botserver/deploy/core.gbapp/services/GBMinService.ts

390 lines
13 KiB
TypeScript
Raw Normal View History

2018-04-21 02:59:30 -03:00
/*****************************************************************************\
| ( )_ _ |
| _ _ _ __ _ _ __ ___ ___ _ _ | ,_)(_) ___ ___ _ |
| ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| | | |/',__)/' _ `\ /'_`\ |
| | (_) )| | ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| ( ) |( (_) ) |
| | ,__/'(_) `\__,_)`\__ |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/' |
| | | ( )_) | |
| (_) \___/' |
| |
| General Bots Copyright (c) Pragmatismo.io. All rights reserved. |
| Licensed under the AGPL-3.0. |
| |
| According to our dual licensing model, this program can be used either |
| under the terms of the GNU Affero General Public License, version 3, |
| or under a proprietary license. |
| |
| The texts of the GNU Affero General Public License with an additional |
| permission and of our proprietary license can be found at and |
| in the LICENSE file you have received along with this program. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU Affero General Public License for more details. |
| |
| "General Bots" is a registered trademark of Pragmatismo.io. |
| The licensing of the program under the AGPLv3 does not imply a |
| trademark license. Therefore any rights, title and interest in |
| our trademarks remain entirely with us. |
| |
\*****************************************************************************/
"use strict";
2018-09-04 15:09:52 -03:00
const { TextPrompt } = require("botbuilder-dialogs");
2018-04-21 02:59:30 -03:00
const UrlJoin = require("url-join");
const express = require("express");
2018-09-10 12:09:48 -03:00
const logger = require("../../../src/logger");
2018-04-21 02:59:30 -03:00
import {
BotFrameworkAdapter,
BotStateSet,
ConversationState,
MemoryStorage,
UserState
} from "botbuilder";
2018-04-21 02:59:30 -03:00
import { GBCoreService } from "./GBCoreService";
import { GBConversationalService } from "./GBConversationalService";
import * as request from "request-promise-native";
import {
GBMinInstance,
IGBPackage,
} from "botlib";
2018-04-21 02:59:30 -03:00
import { GBAnalyticsPackage } from "../../analytics.gblib";
import { GBCorePackage } from "../../core.gbapp";
import { GBKBPackage } from "../../kb.gbapp";
import { GBDeployer } from "./GBDeployer";
import { GBSecurityPackage } from "../../security.gblib";
import { GBAdminPackage } from "./../../admin.gbapp/index";
2018-04-21 02:59:30 -03:00
import { GBCustomerSatisfactionPackage } from "../../customer-satisfaction.gbapp";
import { GBWhatsappPackage } from "../../whatsapp.gblib";
2018-04-21 02:59:30 -03:00
/** Minimal service layer for a bot. */
export class GBMinService {
core: GBCoreService;
conversationalService: GBConversationalService;
deployer: GBDeployer;
corePackage = "core.gbai";
/**
* Static initialization of minimal instance.
2018-04-21 02:59:30 -03:00
*
* @param core Basic database services to identify instance, for example.
*/
constructor(
core: GBCoreService,
conversationalService: GBConversationalService,
deployer: GBDeployer
) {
this.core = core;
this.conversationalService = conversationalService;
this.deployer = deployer;
}
/**
*
* Constructs a new minimal instance for each bot.
*
2018-09-10 12:09:48 -03:00
* @param server An HTTP server.
* @param appPackages List of loaded .gbapp associated with this instance.
*
2018-09-10 12:09:48 -03:00
* @return Loaded minimal bot instance.
*
2018-09-10 12:09:48 -03:00
* */
2018-04-21 02:59:30 -03:00
async buildMin(
server: any,
appPackages: Array<IGBPackage>
): Promise<GBMinInstance> {
2018-04-21 02:59:30 -03:00
// Serves default UI on root address '/'.
let uiPackage = "default.gbui";
server.use(
"/",
2018-09-10 12:09:48 -03:00
express.static(UrlJoin(GBDeployer.deployFolder, uiPackage, "build"))
2018-04-21 02:59:30 -03:00
);
// Loads all bot instances from storage and starting loading them.
2018-04-21 02:59:30 -03:00
2018-09-09 14:39:37 -03:00
let instances = await this.core.loadInstances();
Promise.all(
instances.map(async instance => {
// Gets the authorization key for each instance from Bot Service.
let webchatToken = await this.getWebchatToken(instance);
// Serves the bot information object via HTTP so clients can get
// instance information stored on server.
server.get("/instances/:botId", (req, res) => {
(async () => {
// Returns the instance object to clients requesting bot info.
let botId = req.params.botId;
let instance = await this.core.loadInstance(botId);
if (instance) {
let speechToken = await this.getSTSToken(instance);
res.send(
JSON.stringify({
instanceId: instance.instanceId,
botId: botId,
theme: instance.theme,
secret: instance.webchatKey, // TODO: Use token.
speechToken: speechToken,
conversationId: webchatToken.conversationId
})
);
} else {
let error = `Instance not found: ${botId}.`;
res.sendStatus(error);
logger.error(error);
}
})();
});
// Build bot adapter.
2018-09-09 14:39:37 -03:00
var { min, adapter, conversationState } = await this.buildBotAdapter(
instance
);
// Call the loadBot context.activity for all packages.
this.invokeLoadBot(appPackages, min, server);
// Serves individual URL for each bot conversational interface...
let url = `/api/messages/${instance.botId}`;
server.post(url, async (req, res) => {
return this.receiver(
adapter,
req,
res,
conversationState,
min,
instance,
appPackages
);
});
logger.info(
`GeneralBots(${instance.engineName}) listening on: ${url}.`
);
// Serves individual URL for each bot user interface.
let uiUrl = `/${instance.botId}`;
server.use(
uiUrl,
express.static(UrlJoin(GBDeployer.deployFolder, uiPackage, "build"))
);
logger.info(`Bot UI ${uiPackage} acessible at: ${uiUrl}.`);
// Setups handlers.
// send: function (context.activity, next) {
// logger.info(
// `[SND]: ChannelID: ${context.activity.address.channelId}, ConversationID: ${context.activity.address.conversation},
// Type: ${context.activity.type} `);
// this.core.createMessage(
// this.min.conversation,
// this.min.conversation.startedBy,
// context.activity.source,
// (data, err) => {
// logger.info(context.activity.source);
// }
// );
// next();
})
);
2018-04-21 02:59:30 -03:00
}
2018-09-10 12:09:48 -03:00
private async buildBotAdapter(instance: any) {
let adapter = new BotFrameworkAdapter({
appId: instance.marketplaceId,
appPassword: instance.marketplacePassword
});
2018-04-21 02:59:30 -03:00
2018-09-10 12:09:48 -03:00
const storage = new MemoryStorage();
const conversationState = new ConversationState(storage);
const userState = new UserState(storage);
adapter.use(new BotStateSet(conversationState, userState));
// The minimal bot is built here.
2018-09-10 12:09:48 -03:00
let min = new GBMinInstance();
min.botId = instance.botId;
min.bot = adapter;
min.userState = userState;
min.core = this.core;
min.conversationalService = this.conversationalService;
min.instance = await this.core.loadInstance(min.botId);
min.dialogs.add("textPrompt", new TextPrompt());
2018-09-10 12:09:48 -03:00
return { min, adapter, conversationState };
}
2018-09-09 14:39:37 -03:00
2018-09-10 12:09:48 -03:00
private invokeLoadBot(appPackages: any[], min: any, server: any) {
appPackages.forEach(e => {
e.sysPackages = new Array<IGBPackage>();
[
GBAdminPackage,
GBAnalyticsPackage,
GBCorePackage,
GBSecurityPackage,
GBKBPackage,
GBCustomerSatisfactionPackage,
GBWhatsappPackage
].forEach(sysPackage => {
logger.info(`Loading sys package: ${sysPackage.name}...`);
let p = Object.create(sysPackage.prototype) as IGBPackage;
p.loadBot(min);
e.sysPackages.push(p);
if (sysPackage.name === "GBWhatsappPackage") {
let url = "/instances/:botId/whatsapp";
server.post(url, (req, res) => {
p["channel"].received(req, res);
});
}
}, this);
2018-09-10 12:09:48 -03:00
e.loadBot(min);
}, this);
}
2018-04-21 02:59:30 -03:00
/**
* Bot Service hook method.
*/
private receiver(
adapter: BotFrameworkAdapter,
req: any,
res: any,
conversationState: ConversationState,
min: any,
instance: any,
appPackages: any[]
) {
return adapter.processActivity(req, res, async context => {
2018-09-10 12:09:48 -03:00
const state = conversationState.get(context);
const dc = min.dialogs.createContext(context, state);
const user = min.userState.get(dc.context);
if (!user.loaded) {
await min.conversationalService.sendEvent(dc, "loadInstance", {
instanceId: instance.instanceId,
botId: instance.botId,
theme: instance.theme,
secret: instance.webchatKey
2018-09-10 12:09:48 -03:00
});
user.loaded = true;
user.subjects = [];
}
logger.info(`[RCV]: ${context.activity.type}, ChannelID: ${
context.activity.channelId
},
2018-09-10 12:09:48 -03:00
ConversationID: ${context.activity.conversation.id},
Name: ${context.activity.name}, Text: ${
context.activity.text
}.`);
if (
context.activity.type === "conversationUpdate" &&
context.activity.membersAdded.length > 0
) {
2018-09-10 12:09:48 -03:00
let member = context.activity.membersAdded[0];
if (member.name === "GeneralBots") {
logger.info(`Bot added to conversation, starting chat...`);
appPackages.forEach(e => {
e.onNewSession(min, dc);
});
await dc.begin("/");
} else {
2018-09-10 12:09:48 -03:00
logger.info(`Member added to conversation: ${member.name}`);
}
} else if (context.activity.type === "message") {
2018-09-10 12:09:48 -03:00
// Check to see if anyone replied. If not then start echo dialog
2018-09-10 12:09:48 -03:00
if (context.activity.text === "admin") {
await dc.begin("/admin");
} else {
2018-09-10 12:09:48 -03:00
await dc.continue();
}
} else if (context.activity.type === "event") {
2018-09-10 12:09:48 -03:00
if (context.activity.name === "whoAmI") {
await dc.begin("/whoAmI");
} else if (context.activity.name === "showSubjects") {
2018-09-10 12:09:48 -03:00
await dc.begin("/menu");
} else if (context.activity.name === "giveFeedback") {
2018-09-10 12:09:48 -03:00
await dc.begin("/feedback", {
fromMenu: true
});
} else if (context.activity.name === "showFAQ") {
2018-09-10 12:09:48 -03:00
await dc.begin("/faq");
} else if (context.activity.name === "ask") {
2018-09-10 16:24:32 -03:00
await dc.begin("/answer", {
query: (context.activity as any).data,
2018-09-10 12:09:48 -03:00
fromFaq: true
});
} else if (context.activity.name === "quality") {
2018-09-10 12:09:48 -03:00
await dc.begin("/quality", {
// TODO: score: context.activity.data
});
} else {
2018-09-10 12:09:48 -03:00
await dc.continue();
}
}
});
}
2018-09-10 12:09:48 -03:00
/**
* Get Webchat key from Bot Service.
*
2018-09-10 12:09:48 -03:00
* @param instance The Bot instance.
*
2018-09-10 12:09:48 -03:00
*/
async getWebchatToken(instance: any) {
let options = {
url: "https://directline.botframework.com/v3/directline/tokens/generate",
2018-09-10 12:09:48 -03:00
method: "POST",
headers: {
Authorization: `Bearer ${instance.webchatKey}`
}
};
try {
let json = await request(options);
return Promise.resolve(JSON.parse(json));
} catch (error) {
let msg = `Error calling Direct Line client, verify Bot endpoint on the cloud. Error is: ${error}.`;
logger.error(msg);
return Promise.reject(msg);
}
}
2018-09-10 12:09:48 -03:00
/**
* Gets a Speech to Text / Text to Speech token from the provider.
*
2018-09-10 12:09:48 -03:00
* @param instance The general bot instance.
*
2018-09-10 12:09:48 -03:00
*/
async getSTSToken(instance: any) {
// TODO: Make dynamic: https://CHANGE.api.cognitive.microsoft.com/sts/v1.0
2018-09-10 12:09:48 -03:00
let options = {
url: "https://westus.api.cognitive.microsoft.com/sts/v1.0/issueToken",
2018-09-10 12:09:48 -03:00
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": instance.speechKey
2018-04-21 02:59:30 -03:00
}
2018-09-10 12:09:48 -03:00
};
try {
return await request(options);
} catch (error) {
let msg = `Error calling Speech to Text client. Error is: ${error}.`;
logger.error(msg);
return Promise.reject(msg);
}
2018-04-21 02:59:30 -03:00
}
}