fix(kb.gbapp): API after new Bot #370.

This commit is contained in:
Rodrigo Rodriguez 2023-09-16 17:41:36 -03:00
parent 4ecc78e298
commit b7ac946fe7
4 changed files with 113 additions and 81 deletions

View file

@ -60,7 +60,7 @@ export function createKoaHttpServer(
app.use(koaBody.koaBody({ multipart: true }));
app.use(middleware);
const server = app.listen(port);
const SERVER_TIMEOUT = 60 * 60 * 24 * 1000; // Equals to client RPC set .
const SERVER_TIMEOUT = 60 * 60 * 24 * 1000; // Equals to client RPC set.
server.timeout = SERVER_TIMEOUT;
return {

View file

@ -310,6 +310,7 @@ export class GBDeployer implements IGBDeployer {
// Makes available bot to the channels and .gbui interfaces.
await GBServer.globals.minService.mountBot(instance);
await GBServer.globals.minService.ensureAPI();
}
// Saves final instance object and returns it.

View file

@ -148,6 +148,11 @@ export class GBMinService {
this.deployer = deployer;
}
public async enableAPI(min: GBMinInstance) {
}
/**
* Constructs a new minimal instance for each bot.
*/
@ -167,51 +172,10 @@ export class GBMinService {
GBServer.globals.server.get('/instances/:botId', this.handleGetInstanceForClient.bind(this));
}
function getRemoteId(ctx: Koa.Context) {
return '1'; // share a single session for now, real impl could use cookies or some other meaning for HTTP sessions
}
GBLogEx.info(0, 'Loading General Bots API...');
let proxies = {};
await CollectionUtil.asyncForEach(instances, async instance => {
const proxy = {
dk: new DialogKeywords(),
wa: new WebAutomationServices(),
sys: new SystemKeywords(),
dbg: new DebuggerService(),
img: new ImageProcessingServices()
};
proxies[instance.botId] = proxy;
});
const opts = {
pingSendTimeout: null,
keepAliveTimeout: null,
listeners: {
unsubscribed(subscriptions: number): void {},
subscribed(subscriptions: number): void {},
disconnected(remoteId: string, connections: number): void {},
connected(remoteId: string, connections: number): void {},
messageIn(...params): void {
params.shift();
GBLogEx.verbose(0, '[IN] ' + params);
},
messageOut(...params): void {
params.shift();
GBLogEx.verbose(0, '[OUT] ' + params);
}
}
};
GBServer.globals.server.dk = createRpcServer(
proxies,
createKoaHttpServer(GBVMService.API_PORT, getRemoteId, { prefix: `api/v3` }),
opts
);
await this.ensureAPI();
// Calls mountBot event to all bots.
let i = 1;
if (instances.length > 1) {
@ -292,7 +256,7 @@ export class GBMinService {
/**
* Unmounts the bot web site (default.gbui) secure domain, if any.
*/
public async unloadDomain(instance: IGBInstance) {}
public async unloadDomain(instance: IGBInstance) { }
/**
* Mount the instance by creating an BOT Framework bot object,
@ -579,8 +543,7 @@ export class GBMinService {
min.instance.authenticatorTenant,
'/oauth2/authorize'
);
authorizationUrl = `${authorizationUrl}?response_type=code&client_id=${
min.instance.marketplaceId
authorizationUrl = `${authorizationUrl}?response_type=code&client_id=${min.instance.marketplaceId
}&redirect_uri=${urlJoin(process.env.BOT_URL, min.instance.botId, 'token')}`;
GBLog.info(`HandleOAuthRequests: ${authorizationUrl}.`);
res.redirect(authorizationUrl);
@ -807,7 +770,7 @@ export class GBMinService {
// Builds bot numbers map in WhatsAppDirectLine globals.
let botNumber = min.core.getParam<string>(min.instance, 'Bot Number', null);
if (botNumber){
if (botNumber) {
WhatsappDirectLine.botsByNumber[botNumber] = min.whatsAppDirectLine;
}
@ -1077,8 +1040,7 @@ export class GBMinService {
await this.processEventActivity(min, user, context, step);
}
} catch (error) {
const msg = `ERROR: ${error.message} ${error.stack} ${error.error ? error.error.body : ''} ${
error.error ? (error.error.stack ? error.error.stack : '') : ''
const msg = `ERROR: ${error.message} ${error.stack} ${error.error ? error.error.body : ''} ${error.error ? (error.error.stack ? error.error.stack : '') : ''
}`;
GBLog.error(msg);
@ -1184,8 +1146,7 @@ export class GBMinService {
return utterance.match(Messages.global_quit);
}
private async handleUploads(min, step, user, params, autoSave)
{
private async handleUploads(min, step, user, params, autoSave) {
// Prepare Promises to download each attachment and then execute each Promise.
if (
@ -1420,7 +1381,7 @@ export class GBMinService {
if (notes && text && text !== "") {
const sys = new SystemKeywords();
await sys.note({pid, text});
await sys.note({ pid, text });
await step.context.sendActivity('OK.');
return;
}
@ -1468,8 +1429,7 @@ export class GBMinService {
try {
await step.continueDialog();
} catch (error) {
const msg = `ERROR: ${error.message} ${error.stack} ${error.error ? error.error.body : ''} ${
error.error ? (error.error.stack ? error.error.stack : '') : ''
const msg = `ERROR: ${error.message} ${error.stack} ${error.error ? error.error.body : ''} ${error.error ? (error.error.stack ? error.error.stack : '') : ''
}`;
GBLog.error(msg);
await min.conversationalService.sendText(
@ -1511,4 +1471,74 @@ export class GBMinService {
}
}
}
public async ensureAPI() {
const instances = GBServer.globals.minInstances;
function getRemoteId(ctx: Koa.Context) {
return '1'; // Each bot has its own API.
}
const close = async () => {
return new Promise(resolve => {
if (GBServer.globals.server.apiServer) {
GBServer.globals.server.apiServer.close(
cb => {
resolve(true);
GBLogEx.info(0, 'Reloading General Bots API...');
}
);
}
else{
resolve(true);
GBLogEx.info(0, 'Loading General Bots API...');
}
});
};
await close();
let proxies = {};
await CollectionUtil.asyncForEach(instances, async instance => {
const proxy = {
dk: new DialogKeywords(),
wa: new WebAutomationServices(),
sys: new SystemKeywords(),
dbg: new DebuggerService(),
img: new ImageProcessingServices()
};
proxies[instance.botId] = proxy;
});
const opts = {
pingSendTimeout: null,
keepAliveTimeout: null,
listeners: {
unsubscribed(subscriptions: number): void { },
subscribed(subscriptions: number): void { },
disconnected(remoteId: string, connections: number): void { },
connected(remoteId: string, connections: number): void { },
messageIn(...params): void {
params.shift();
GBLogEx.verbose(0, '[IN] ' + params);
},
messageOut(...params): void {
params.shift();
GBLogEx.verbose(0, '[OUT] ' + params);
}
}
};
GBServer.globals.server.apiServer = createKoaHttpServer(GBVMService.API_PORT, getRemoteId, { prefix: `api/v3` });
createRpcServer(
proxies,
GBServer.globals.server.apiServer,
opts
);
}
}

View file

@ -48,6 +48,7 @@ export class RootData {
public publicAddress: string; // URI for BotServer.
public server: any; // Express reference.
public httpsServer: any; // Express reference (HTTPS).
public apiServer: any; // Koa reference (HTTPS) for GB API (isolated from /).
public sysPackages: any[]; // Loaded system package list.
public appPackages: any[]; // Loaded .gbapp package list.
public minService: GBMinService; // Minimalist service core.