Skip to content

Commit

Permalink
fix(basic.gblib): Upgrade to https://github.com/vasyas/push-rpc from …
Browse files Browse the repository at this point in the history
…WS to HTTPS.
  • Loading branch information
rodrigorodriguez committed Mar 5, 2023
1 parent 39f1907 commit f3c756b
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 122 deletions.
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,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",
"@push-rpc/core": "1.1.5",
"@push-rpc/http": "1.1.5",
"@push-rpc/websocket": "1.1.5",
"@semantic-release/changelog": "5.0.1",
"@semantic-release/exec": "5.0.0",
"@semantic-release/git": "9.0.0",
Expand Down Expand Up @@ -165,7 +165,6 @@
"textract": "2.5.0",
"twitter-api-v2": "1.12.9",
"typescript": "4.9.5",
"typescript-rest-rpc": "1.0.7",
"url-join": "5.0.0",
"vbscript-to-typescript": "1.0.8",
"vhost": "3.0.2",
Expand Down
144 changes: 73 additions & 71 deletions packages/basic.gblib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

'use strict';

import { GBDialogStep, GBLog, GBMinInstance, IGBCoreService, IGBPackage } from 'botlib';
import { GBDialogStep, GBLog, GBMinInstance, IGBCoreService, IGBInstance, IGBPackage } from 'botlib';
import { GuaribasSchedule } from '../core.gbapp/models/GBModel.js';
import { Sequelize } from 'sequelize-typescript';
import { DialogKeywords } from './services/DialogKeywords.js';
Expand All @@ -45,38 +45,38 @@ import { WebAutomationServices } from './services/WebAutomationServices.js';
import { ImageProcessingServices } from './services/ImageProcessingServices.js';
import { DebuggerService } from './services/DebuggerService.js';
import Koa from 'koa';
import {createRpcServer, createRpcClient} from "@push-rpc/core"
import {createKoaHttpMiddleware, createExpressHttpMiddleware, createHttpClient} from "@push-rpc/http"
import { createRpcServer, createRpcClient } from '@push-rpc/core';
import { createHttpKoaMiddleware, createHttpClient } from '@push-rpc/http';
import { HttpServerOptions } from '@push-rpc/http/dist/server.js';
import { GBServer } from '../../src/app.js';
const app = new Koa();
import {SocketServer} from "@push-rpc/core"
import * as koaBody from "koa-body"

import { SocketServer } from '@push-rpc/core';
import * as koaBody from 'koa-body';
import { GBVMService } from './services/GBVMService.js';
import { GBLogEx } from '../core.gbapp/services/GBLogEx.js';
import { CollectionUtil } from 'pragmatismo-io-framework';

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

const app = new Koa()
app.use(koaBody.koaBody({multipart: true}))
app.use(middleware)
const server = app.listen(port)
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)
},
}
server.close(cb);
}
};
}





/**
* Package for core.gbapp.
*/
Expand All @@ -85,71 +85,74 @@ export class GBBasicPackage implements IGBPackage {
public sysPackages: IGBPackage[];
public CurrentEngineName = 'guaribas-1.0.0';

public async loadPackage (core: IGBCoreService, sequelize: Sequelize): Promise<void> {
public async loadPackage(core: IGBCoreService, sequelize: Sequelize): Promise<void> {
core.sequelize.addModels([GuaribasSchedule]);

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) {
public async getDialogs(min: GBMinInstance) {
GBLog.verbose(`getDialogs called.`);
}
public async unloadPackage (core: IGBCoreService): Promise<void> {
public async unloadPackage(core: IGBCoreService): Promise<void> {
GBLog.verbose(`unloadPackage called.`);
}
public async unloadBot (min: GBMinInstance): Promise<void> {
public async unloadBot(min: GBMinInstance): Promise<void> {
GBLog.verbose(`unloadBot called.`);
}
public async onNewSession (min: GBMinInstance, step: GBDialogStep): Promise<void> {
public async onNewSession(min: GBMinInstance, step: GBDialogStep): Promise<void> {
GBLog.verbose(`onNewSession called.`);
}
public async onExchangeData (min: GBMinInstance, kind: string, data: any) {
public async onExchangeData(min: GBMinInstance, kind: string, data: any) {
GBLog.verbose(`onExchangeData called.`);
}
public async loadBot (min: GBMinInstance): Promise<void> {

public async loadBot(min: GBMinInstance): Promise<void> {
const botId = min.botId;

const opts = {
pingSendTimeout: null,
keepAliveTimeout: null,
listeners: {
unsubscribed(subscriptions: number): void {},
subscribed(subscriptions: number): void {},
disconnected(remoteId: string, connections: number): void {
GBLogEx.info(min, `[GBAPI]: New client ${remoteId} disconnected`);
},
connected(remoteId: string, connections: number): void {
GBLogEx.info(min, `[GBAPI]: New client ${remoteId} connected`);
},
messageIn(...params): void {
GBLogEx.info(min, '[GBAPI]: IN ' + params);
},
messageOut(...params): void {
GBLogEx.info(min, '[GBAPI]: OUT ' + params);
}
}
};

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
}
let instances: IGBInstance[];
instances = await min.core.loadInstances();
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;
});

GBServer.globals.server.dk = createRpcServer(
proxies,
createKoaHttpServer(GBVMService.API_PORT, getRemoteId, { prefix: `api/v3` }),
opts
);

GBLogEx.info(min, '[GBAPI] RPC HTTP Server started at http://localhost:' + GBVMService.API_PORT);

GBServer.globals.debuggers[botId] = {};
GBServer.globals.debuggers[botId].state = 0;
GBServer.globals.debuggers[botId].breaks = [];
Expand All @@ -158,6 +161,5 @@ function getRemoteId(ctx: Koa.Context) {
GBServer.globals.debuggers[botId].client = null;
GBServer.globals.debuggers[botId].conversationsMap = {};
GBServer.globals.debuggers[botId].watermarkMap = {};

}
}
30 changes: 15 additions & 15 deletions packages/basic.gblib/services/DialogKeywords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ export class DialogKeywords {
* @example HEAR name
*
*/
public async getHear({ pid, kind, arg }) {
public async hear({ pid, kind, arg }) {
let { min, user, params } = await DialogKeywords.getProcessInfo(pid);

// Handles first arg as an array of args.
Expand Down Expand Up @@ -828,7 +828,7 @@ export class DialogKeywords {

if (result === null) {
await this.talk({ pid, text: `Escolha por favor um dos itens sugeridos.` });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

} else if (kind === 'file') {
Expand All @@ -851,7 +851,7 @@ export class DialogKeywords {

if (value === null) {
await this.talk({ pid, text: 'Por favor, digite um e-mail válido.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value;
Expand All @@ -864,7 +864,7 @@ export class DialogKeywords {

if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um nome válido.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value;
Expand All @@ -877,7 +877,7 @@ export class DialogKeywords {

if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um número válido.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value;
Expand All @@ -892,7 +892,7 @@ export class DialogKeywords {

if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite uma data no formato 12/12/2020.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value;
Expand All @@ -905,7 +905,7 @@ export class DialogKeywords {

if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um horário no formato hh:ss.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value;
Expand All @@ -924,7 +924,7 @@ export class DialogKeywords {

if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um valor monetário.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value;
Expand All @@ -937,18 +937,18 @@ export class DialogKeywords {
} catch (error) {
await this.talk({ pid, text: Messages[locale].validation_enter_valid_mobile });

return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}
if (!phoneUtil.isPossibleNumber(phoneNumber)) {
await this.talk({ pid, text: 'Por favor, digite um número de telefone válido.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = phoneNumber;
} else if (kind === 'qr-scanner'){
//https://github.com/GeneralBots/BotServer/issues/171
GBLog.info(`BASIC (${min.botId}): Upload done for ${answer.filename}.`);
const handle = WebAutomationServices.cyrb53(this.min.botId + answer.filename);
const handle = WebAutomationServices.cyrb53(min.botId + answer.filename);
GBServer.globals.files[handle] = answer;
QrScanner.scanImage(GBServer.globals.files[handle]).then(result => console.log(result)).catch(error => console.log(error || 'no QR code found.'));

Expand All @@ -968,7 +968,7 @@ export class DialogKeywords {

if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor, digite um CEP válido.' });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}

result = value[0];
Expand All @@ -983,7 +983,7 @@ export class DialogKeywords {

if (result === null) {
await this.talk({ pid, text: `Escolha por favor um dos itens sugeridos.` });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}
} else if (kind === 'language') {
result = null;
Expand Down Expand Up @@ -1015,7 +1015,7 @@ export class DialogKeywords {

if (result === null) {
await this.talk({ pid, text: `Escolha por favor um dos itens sugeridos.` });
return await this.getHear({ pid, kind, arg });
return await this.hear({ pid, kind, arg });
}
}
return result;
Expand Down Expand Up @@ -1077,7 +1077,7 @@ export class DialogKeywords {
const { min, user } = await DialogKeywords.getProcessInfo(pid);

if (user) {
// TODO: const translate = this.user ? this.user.basicOptions.translatorOn : false;
// TODO: const translate = user ? user.basicOptions.translatorOn : false;

await min.conversationalService['sendOnConversation'](min, user, text);
}
Expand Down

0 comments on commit f3c756b

Please sign in to comment.