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, |
2018-09-11 19:40:53 -03:00
| but WITHOUT ANY WARRANTY, without even the implied warranty of |
2018-04-21 02:59:30 -03:00
| 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. |
| |
\*****************************************************************************/
2018-09-12 04:47:11 -03:00
"use strict"
2018-04-21 02:59:30 -03:00
2018-09-12 04:47:11 -03:00
const { TextPrompt } = require("botbuilder-dialogs")
const UrlJoin = require("url-join")
const express = require("express")
const logger = require("../../../src/logger")
2018-04-21 02:59:30 -03:00
import {
BotFrameworkAdapter,
BotStateSet,
ConversationState,
MemoryStorage,
UserState
2018-09-12 04:47:11 -03:00
} from "botbuilder"
import { GBCoreService } from "./GBCoreService"
import { GBConversationalService } from "./GBConversationalService"
import * as request from "request-promise-native"
import { GBMinInstance, IGBPackage } from "botlib"
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"
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 {
2018-09-12 04:47:11 -03:00
core: GBCoreService
conversationalService: GBConversationalService
deployer: GBDeployer
2018-04-21 02:59:30 -03:00
2018-09-12 04:47:11 -03:00
corePackage = "core.gbai"
2018-04-21 02:59:30 -03:00
/**
* 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
) {
2018-09-12 04:47:11 -03:00
this.core = core
this.conversationalService = conversationalService
this.deployer = deployer
2018-04-21 02:59:30 -03:00
}
/**
*
* 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 '/'.
2018-09-12 04:47:11 -03:00
let uiPackage = "default.gbui"
2018-04-21 02:59:30 -03:00
server.use(
"/",
2018-09-10 12:09:48 -03:00
express.static(UrlJoin(GBDeployer.deployFolder, uiPackage, "build"))
2018-09-12 04:47:11 -03:00
)
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-12 04:47:11 -03:00
let instances = await this.core.loadInstances()
Promise.all(
instances.map(async instance => {
// Gets the authorization key for each instance from Bot Service.
2018-09-12 04:47:11 -03:00
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.
2018-09-12 04:47:11 -03:00
let botId = req.params.botId
let instance = await this.core.loadInstance(botId)
if (instance) {
2018-09-12 04:47:11 -03:00
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
})
2018-09-12 04:47:11 -03:00
)
} else {
2018-09-12 04:47:11 -03:00
let error = `Instance not found: ${botId}.`
res.sendStatus(error)
logger.error(error)
}
2018-09-12 04:47:11 -03:00
})()
})
// Build bot adapter.
2018-09-09 14:39:37 -03:00
var { min, adapter, conversationState } = await this.buildBotAdapter(
instance
2018-09-12 04:47:11 -03:00
)
// Call the loadBot context.activity for all packages.
2018-09-12 04:47:11 -03:00
this.invokeLoadBot(appPackages, min, server)
// Serves individual URL for each bot conversational interface...
2018-09-12 04:47:11 -03:00
let url = `/api/messages/${instance.botId}`
server.post(url, async (req, res) => {
return this.receiver(
adapter,
req,
res,
conversationState,
min,
instance,
appPackages
2018-09-12 04:47:11 -03:00
)
})
logger.info(
`GeneralBots(${instance.engineName}) listening on: ${url}.`
2018-09-12 04:47:11 -03:00
)
// Serves individual URL for each bot user interface.
2018-09-12 04:47:11 -03:00
let uiUrl = `/${instance.botId}`
server.use(
uiUrl,
express.static(UrlJoin(GBDeployer.deployFolder, uiPackage, "build"))
2018-09-12 04:47:11 -03:00
)
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},
2018-09-11 19:40:53 -03:00
// Type: ${context.activity.type} `)
// this.core.createMessage(
// this.min.conversation,
// this.min.conversation.startedBy,
// context.activity.source,
// (data, err) => {
2018-09-11 19:40:53 -03:00
// logger.info(context.activity.source)
// }
2018-09-11 19:40:53 -03:00
// )
// next()
})
2018-09-12 04:47:11 -03:00
)
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-09-12 04:47:11 -03:00
})
2018-04-21 02:59:30 -03:00
2018-09-12 04:47:11 -03:00
const storage = new MemoryStorage()
const conversationState = new ConversationState(storage)
const userState = new UserState(storage)
adapter.use(new BotStateSet(conversationState, userState))
2018-09-10 12:09:48 -03:00
// The minimal bot is built here.
2018-09-12 04:47:11 -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-12 04:47:11 -03:00
return { min, adapter, conversationState }
2018-09-10 12:09:48 -03:00
}
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 => {
2018-09-12 04:47:11 -03:00
e.sysPackages = new Array<IGBPackage>()
2018-09-12 04:42:29 -03:00
[
GBAdminPackage,
GBAnalyticsPackage,
GBCorePackage,
GBSecurityPackage,
GBKBPackage,
GBCustomerSatisfactionPackage,
GBWhatsappPackage
].forEach(sysPackage => {
2018-09-12 04:47:11 -03:00
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") {
2018-09-12 04:47:11 -03:00
let url = "/instances/:botId/whatsapp"
server.post(url, (req, res) => {
2018-09-12 04:47:11 -03:00
p["channel"].received(req, res)
})
}
2018-09-12 04:47:11 -03:00
}, this)
e.loadBot(min)
}, this)
2018-09-10 12:09:48 -03:00
}
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-12 04:47:11 -03:00
const state = conversationState.get(context)
const dc = min.dialogs.createContext(context, state)
const user = min.userState.get(dc.context)
2018-09-12 04:42:29 -03:00
2018-09-10 12:09:48 -03:00
if (!user.loaded) {
await min.conversationalService.sendEvent(dc, "loadInstance", {
instanceId: instance.instanceId,
botId: instance.botId,
theme: instance.theme,
secret: instance.webchatKey
2018-09-12 04:47:11 -03:00
})
user.loaded = true
user.subjects = []
2018-09-10 12:09:48 -03:00
}
2018-09-12 04:42:29 -03:00
logger.info(
`[RCV]: ${context.activity.type}, ChannelID: ${
context.activity.channelId
}, Name: ${context.activity.name}, Text: ${context.activity.text}.`
2018-09-12 04:47:11 -03:00
)
if (
context.activity.type === "conversationUpdate" &&
context.activity.membersAdded.length > 0
) {
2018-09-12 04:47:11 -03:00
let member = context.activity.membersAdded[0]
2018-09-10 12:09:48 -03:00
if (member.name === "GeneralBots") {
2018-09-12 04:47:11 -03:00
logger.info(`Bot added to conversation, starting chat...`)
2018-09-10 12:09:48 -03:00
appPackages.forEach(e => {
2018-09-12 04:47:11 -03:00
e.onNewSession(min, dc)
})
await dc.begin("/")
} else {
2018-09-12 04:47:11 -03:00
logger.info(`Member added to conversation: ${member.name}`)
2018-09-10 12:09:48 -03:00
}
} 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") {
2018-09-12 04:47:11 -03:00
await dc.begin("/admin")
2018-09-12 04:42:29 -03:00
} else if (context.activity.text.startsWith("{\"title\"")) {
2018-09-12 04:47:11 -03:00
await dc.begin("/menu", {data:JSON.parse(context.activity.text)})
} else {
2018-09-12 04:47:11 -03:00
await dc.continue()
2018-09-10 12:09:48 -03:00
}
} else if (context.activity.type === "event") {
2018-09-10 12:09:48 -03:00
if (context.activity.name === "whoAmI") {
2018-09-12 04:47:11 -03:00
await dc.begin("/whoAmI")
} else if (context.activity.name === "showSubjects") {
2018-09-12 04:47:11 -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
2018-09-12 04:47:11 -03:00
})
} else if (context.activity.name === "showFAQ") {
2018-09-12 04:47:11 -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
2018-09-12 04:47:11 -03:00
})
} else if (context.activity.name === "quality") {
2018-09-10 12:09:48 -03:00
await dc.begin("/quality", {
// TODO: score: context.activity.data
2018-09-12 04:47:11 -03:00
})
} else {
2018-09-12 04:47:11 -03:00
await dc.continue()
2018-09-10 12:09:48 -03:00
}
}
2018-09-12 04:47:11 -03:00
})
2018-09-10 12:09:48 -03:00
}
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}`
}
2018-09-12 04:47:11 -03:00
}
2018-09-10 12:09:48 -03:00
try {
2018-09-12 04:47:11 -03:00
let json = await request(options)
return Promise.resolve(JSON.parse(json))
2018-09-10 12:09:48 -03:00
} catch (error) {
2018-09-12 04:47:11 -03:00
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
}
}
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-12 04:47:11 -03:00
}
2018-09-10 12:09:48 -03:00
try {
2018-09-12 04:47:11 -03:00
return await request(options)
2018-09-10 12:09:48 -03:00
} catch (error) {
2018-09-12 04:47:11 -03:00
let msg = `Error calling Speech to Text client. Error is: ${error}.`
logger.error(msg)
return Promise.reject(msg)
2018-09-10 12:09:48 -03:00
}
2018-04-21 02:59:30 -03:00
}
}