Skip to content

Commit

Permalink
fix(basic.gblib): Upgrade to https://github.com/vasyas/push-rpc.
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigorodriguez committed Mar 4, 2023
1 parent 4314a37 commit f3b7c1d
Show file tree
Hide file tree
Showing 11 changed files with 235 additions and 340 deletions.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@
"@microsoft/microsoft-graph-client": "3.0.4",
"@nlpjs/basic": "4.26.1",
"@nosferatu500/textract": "3.1.2",
"@push-rpc/core": "^1.5.7",
"@push-rpc/http": "^1.5.7",
"@push-rpc/websocket": "^1.5.7",
"@semantic-release/changelog": "5.0.1",
"@semantic-release/exec": "5.0.0",
"@semantic-release/git": "9.0.0",
Expand Down Expand Up @@ -171,6 +174,7 @@
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#fix-buttons-list",
"winston": "3.8.2",
"winston-logs-display": "1.0.0",
"ws": "^8.12.1",
"yarn": "1.22.19"
},
"devDependencies": {
Expand Down
111 changes: 83 additions & 28 deletions packages/basic.gblib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,43 @@
import { GBDialogStep, GBLog, GBMinInstance, IGBCoreService, IGBPackage } from 'botlib';
import { GuaribasSchedule } from '../core.gbapp/models/GBModel.js';
import { Sequelize } from 'sequelize-typescript';
import { createServerRouter } from 'typescript-rest-rpc/lib/server.js';
import { DialogKeywords } from './services/DialogKeywords.js';
import { SystemKeywords } from './services/SystemKeywords.js';
import { WebAutomationServices } from './services/WebAutomationServices.js';
import { ImageProcessingServices } from './services/ImageProcessingServices.js';
import { DebuggerService } from './services/DebuggerService.js';
import * as koaBody from 'koa-body';
import Koa from 'koa';

import {createRpcServer, createRpcClient} from "@push-rpc/core"
import {createKoaHttpMiddleware, createExpressHttpMiddleware, createHttpClient} from "@push-rpc/http"
import { GBServer } from '../../src/app.js';
const app = new Koa();
import {SocketServer} from "@push-rpc/core"
import * as koaBody from "koa-body"


export function createKoaHttpServer(
port: number,
getRemoteId: (ctx: Koa.Context) => string
): SocketServer {
const {onError, onConnection, middleware} = createKoaHttpMiddleware(getRemoteId)

const app = new Koa()
app.use(koaBody.koaBody({multipart: true}))
app.use(middleware)
const server = app.listen(port)

return {
onError,
onConnection,
close(cb) {
server.close(cb)
},
}
}





/**
* Package for core.gbapp.
Expand All @@ -60,9 +87,49 @@ export class GBBasicPackage implements IGBPackage {

public async loadPackage (core: IGBCoreService, sequelize: Sequelize): Promise<void> {
core.sequelize.addModels([GuaribasSchedule]);
//app.use(koaBody.koaBody({ multipart: true, }));

app.listen(1111);
const dk = new DialogKeywords();
const wa = new WebAutomationServices();
const sys = new SystemKeywords();
const dbg = new DebuggerService();
const img = new ImageProcessingServices();

// remote id is required for assigning separate HTTP requests to a single session
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
}





GBServer.globals.server.dk = createRpcServer(dk, createKoaHttpServer(5555, getRemoteId),{
listeners: {
unsubscribed(subscriptions: number): void {},
subscribed(subscriptions: number): void {},
disconnected(remoteId: string, connections: number): void {
console.log(`Client ${remoteId} disconnected`)
},
connected(remoteId: string, connections: number): void {
console.log(`New client ${remoteId} connected`)
},
messageIn(...params): void {
console.log("IN ", params)
},
messageOut(...params): void {
console.log("OUT ", params)
},
},
pingSendTimeout: null,
keepAliveTimeout: null,
})

console.log("RPC Server started at ws://localhost:5555")

// GBServer.globals.wa = createRpcServer(wa, createWebsocketServer({port: 1112}));
// GBServer.globals.sys = createRpcServer(sys, createWebsocketServer({port: 1113}));
// GBServer.globals.dbg = createRpcServer(dbg, createWebsocketServer({port: 1114}));
// GBServer.globals.img = createRpcServer(img, createWebsocketServer({port: 1115}));
}

public async getDialogs (min: GBMinInstance) {
Expand All @@ -81,28 +148,16 @@ export class GBBasicPackage implements IGBPackage {
GBLog.verbose(`onExchangeData called.`);
}
public async loadBot (min: GBMinInstance): Promise<void> {
const dk = new DialogKeywords(min, null, null);
const wa = new WebAutomationServices(min, null, dk);
const sys = new SystemKeywords(min, null, dk, wa);
const dbg = new DebuggerService(min, null, dk);
const img = new ImageProcessingServices(min, null, dk);
dk.wa = wa;
wa.sys = sys;
const dialogRouter = createServerRouter(`/api/v2/${min.botId}/dialog`, dk);
const waRouter = createServerRouter(`/api/v2/${min.botId}/webautomation`, wa);
const sysRouter = createServerRouter(`/api/v2/${min.botId}/system`, sys);
const dbgRouter = createServerRouter(`/api/v2/${min.botId}/debugger`, dbg);
const imgRouter = createServerRouter(`/api/v2/${min.botId}/imageprocessing`, dbg);
app.use(dialogRouter.routes());
app.use(sysRouter.routes());
app.use(waRouter.routes());
app.use(dbgRouter.routes());
app.use(imgRouter.routes());
app.use(async (ctx, next) => {
if(ctx['status'] === 404){
ctx.status = 404
ctx.body = {msg:'emmmmmmm, seems 404'};
}
});

const botId = min.botId;
GBServer.globals.debuggers[botId] = {};
GBServer.globals.debuggers[botId].state = 0;
GBServer.globals.debuggers[botId].breaks = [];
GBServer.globals.debuggers[botId].stateInfo = 'Stopped';
GBServer.globals.debuggers[botId].childProcess = null;
GBServer.globals.debuggers[botId].client = null;
GBServer.globals.debuggers[botId].conversationsMap = {};
GBServer.globals.debuggers[botId].watermarkMap = {};

}
}
87 changes: 17 additions & 70 deletions packages/basic.gblib/services/DebuggerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,44 +44,6 @@ import { spawn } from 'child_process';
* Web Automation services of conversation to be called by BASIC.
*/
export class DebuggerService {
/**
* Reference to minimal bot instance.
*/
public min: GBMinInstance;

/**
* Reference to the base system keywords functions to be called.
*/
public dk: DialogKeywords;

/**
* Current user object to get BASIC properties read.
*/
public user;

/**
* HTML browser for conversation over page interaction.
*/
browser: any;

sys: any;

/**
* The number used in this execution for HEAR calls (useful for SET SCHEDULE).
*/
hrOn: string;

userId: GuaribasUser;
debugWeb: boolean;
lastDebugWeb: Date;

/**
* SYSTEM account maxLines,when used with impersonated contexts (eg. running in SET SCHEDULE).
*/
maxLines: number = 2000;

conversationsMap = {};
watermarkMap = {};
static systemVariables = [
'AggregateError',
'Array',
Expand Down Expand Up @@ -173,28 +135,6 @@ export class DebuggerService {
'valueOf'
];

/**
* When creating this keyword facade,a bot instance is
* specified among the deployer service.
*/
constructor (min: GBMinInstance, user, dk) {
this.min = min;
this.user = user;
this.dk = dk;

this.debugWeb = this.min.core.getParam<boolean>(this.min.instance, 'Debug Web Automation', false);

const botId = min.botId;

GBServer.globals.debuggers[botId] = {};
GBServer.globals.debuggers[botId].state = 0;
GBServer.globals.debuggers[botId].breaks = [];
GBServer.globals.debuggers[botId].stateInfo = 'Stopped';
GBServer.globals.debuggers[botId].childProcess = null;
}

private client;

public async breakpoint ({ botId, line }) {
GBLog.info(`BASIC: Enabled breakpoint for ${botId} on ${line}.`);
GBServer.globals.debuggers[botId].breaks.push(Number.parseInt(line));
Expand Down Expand Up @@ -239,14 +179,18 @@ export class DebuggerService {
}

public async context ({ botId }) {
const conversationId = this.conversationsMap[botId];
const conversationsMap = GBServer.globals.debuggers[botId].conversationsMap;
const watermarkMap = GBServer.globals.debuggers[botId].watermarkMap;

const conversationId = conversationsMap[botId];
let messages = [];
if (this.client) {
const response = await this.client.Conversations.Conversations_GetActivities({
const client = GBServer.globals.debuggers[botId].client;
if (client) {
const response = await client.Conversations.Conversations_GetActivities({
conversationId: conversationId,
watermark: this.watermarkMap[botId]
watermark: watermarkMap[botId]
});
this.watermarkMap[botId] = response.obj.watermark;
watermarkMap[botId] = response.obj.watermark;
let activities = response.obj.activites;

if (activities && activities.length) {
Expand All @@ -272,6 +216,8 @@ export class DebuggerService {
}

public async getRunning ({ botId, botApiKey, scriptName }) {
const conversationsMap = GBServer.globals.debuggers[botId].conversationsMap;

let error;
botId = botId[0];
if (!GBServer.globals.debuggers[botId]) {
Expand All @@ -296,20 +242,21 @@ export class DebuggerService {

let min: GBMinInstance = GBServer.globals.minInstances.filter(p => p.instance.botId === botId)[0];

this.client = await new Swagger({
GBServer.globals.debuggers[botId].client = await new Swagger({
spec: JSON.parse(Fs.readFileSync('directline-3.0.json', 'utf8')),
usePromise: true
});
this.client.clientAuthorizations.add(
const client = GBServer.globals.debuggers[botId].client;
client.clientAuthorizations.add(
'AuthorizationBotConnector',
new Swagger.ApiKeyAuthorization('Authorization', `Bearer ${min.instance.webchatKey}`, 'header')
);
const response = await this.client.Conversations.Conversations_StartConversation();
const response = await client.Conversations.Conversations_StartConversation();
const conversationId = response.obj.conversationId;
this.conversationsMap[botId] = conversationId;
conversationsMap[botId] = conversationId;
GBServer.globals.debugConversationId = conversationId;

this.client.Conversations.Conversations_PostActivity({
client.Conversations.Conversations_PostActivity({
conversationId: conversationId,
activity: {
textFormat: 'plain',
Expand Down
Loading

0 comments on commit f3b7c1d

Please sign in to comment.