fix(basic.gblib): #307 - Fixed user context in API.

This commit is contained in:
rodrigorodriguez 2023-01-31 11:46:37 -03:00
parent 20911af3d7
commit 4496cefa18
2 changed files with 72 additions and 72 deletions

View file

@ -57,17 +57,17 @@ import sgMail from '@sendgrid/mail';
import mammoth from 'mammoth'; import mammoth from 'mammoth';
import qrcode from 'qrcode'; import qrcode from 'qrcode';
import { json } from 'body-parser'; import { json } from 'body-parser';
/** /**
* Default check interval for user replay * Default check interval for user replay
*/ */
const DEFAULT_HEAR_POLL_INTERVAL = 500; const DEFAULT_HEAR_POLL_INTERVAL = 500;
/** /**
* Base services of conversation to be called by BASIC. * Base services of conversation to be called by BASIC.
*/ */
export class DialogKeywords { export class DialogKeywords {
/** /**
* Reference to minimal bot instance. * Reference to minimal bot instance.
*/ */
public min: GBMinInstance; public min: GBMinInstance;
@ -226,7 +226,7 @@ export class DialogKeywords {
* *
* @example x = TODAY * @example x = TODAY
*/ */
public async getToday({ }) { public async getToday({}) {
let d = new Date(), let d = new Date(),
month = '' + (d.getMonth() + 1), month = '' + (d.getMonth() + 1),
day = '' + d.getDate(), day = '' + d.getDate(),
@ -262,28 +262,28 @@ export class DialogKeywords {
* *
* @example EXIT * @example EXIT
*/ */
public async exit({ }) { } public async exit({}) {}
/** /**
* Get active tasks. * Get active tasks.
* *
* @example list = ACTIVE TASKS * @example list = ACTIVE TASKS
*/ */
public async getActiveTasks({ pid }) { } public async getActiveTasks({ pid }) {}
/** /**
* Creates a new deal. * Creates a new deal.
* *
* @example CREATE DEAL dealname,contato,empresa,amount * @example CREATE DEAL dealname,contato,empresa,amount
*/ */
public async createDeal({ pid, dealName, contact, company, amount }) { } public async createDeal({ pid, dealName, contact, company, amount }) {}
/** /**
* Finds contacts in XRM. * Finds contacts in XRM.
* *
* @example list = FIND CONTACT "Sandra" * @example list = FIND CONTACT "Sandra"
*/ */
public async fndContact({ pid, name }) { } public async fndContact({ pid, name }) {}
public getContentLocaleWithCulture(contentLocale) { public getContentLocaleWithCulture(contentLocale) {
switch (contentLocale) { switch (contentLocale) {
@ -426,11 +426,9 @@ export class DialogKeywords {
* @example TALK TOLIST (array,member) * @example TALK TOLIST (array,member)
* *
*/ */
public async getToLst(pid,array, member) { public async getToLst(pid, array, member) {
const { const { min, user } = await DialogKeywords.getProcessInfo(pid);
min, user
} = await DialogKeywords.getProcessInfo(pid);
if (!array) { if (!array) {
return '<Empty>'; return '<Empty>';
} }
@ -456,10 +454,8 @@ export class DialogKeywords {
* *
*/ */
public async getHourFromDate(pid, date) { public async getHourFromDate(pid, date) {
const { const { min, user } = await DialogKeywords.getProcessInfo(pid);
min, user
} = await DialogKeywords.getProcessInfo(pid);
function addZero(i) { function addZero(i) {
if (i < 10) { if (i < 10) {
i = '0' + i; i = '0' + i;
@ -490,7 +486,7 @@ export class DialogKeywords {
* @example SAVE "contacts.xlsx", name, email, NOW * @example SAVE "contacts.xlsx", name, email, NOW
* *
*/ */
public async getNow({ }) { public async getNow({}) {
const contentLocale = this.min.core.getParam<string>( const contentLocale = this.min.core.getParam<string>(
this.min.instance, this.min.instance,
'Default Content Language', 'Default Content Language',
@ -592,18 +588,24 @@ export class DialogKeywords {
this['id'] = this.sys().getRandomId(); this['id'] = this.sys().getRandomId();
} }
private async setOption({pid, name, value})
{
const process = GBServer.globals.processes[pid];
let { min, user, params } = await DialogKeywords.getProcessInfo(pid);
const sec = new SecService();
await sec.setParam(user.userId, name, value);
GBLog.info(`BASIC: ${name} = ${value} (botId: ${min.botId})`);
return { min, user, params };
}
/** /**
* Defines the maximum lines to scan in spreedsheets. * Defines the maximum lines to scan in spreedsheets.
* *
* @example SET MAX LINES 5000 * @example SET MAX LINES 5000
* *
*/ */
public async setMaxLines({ count }) { public async setMaxLines({ pid, count }) {
if (this.user) { await this.setOption({pid, name: "maxLines", value: count});
// #307 user.basicOptions.maxLines = count;
} else {
this.maxLines = count;
}
} }
/** /**
@ -612,8 +614,8 @@ export class DialogKeywords {
* @example SET MAX COLUMNS 5000 * @example SET MAX COLUMNS 5000
* *
*/ */
public async setMaxColumns({ count }) { public async setMaxColumns({ pid, count }) {
// #307 user.basicOptions.maxColumns = count; await this.setOption({pid, name: "setMaxColumns", value: count});
} }
/** /**
@ -622,8 +624,9 @@ export class DialogKeywords {
* @example SET WHOLE WORD ON * @example SET WHOLE WORD ON
* *
*/ */
public async setWholeWord({ on }) { public async setWholeWord({ pid, on }) {
// #307 user.basicOptions.wholeWord = (on.trim() === "on"); const value = (on.trim() === "on");
await this.setOption({pid, name: "wholeWord", value: value});
} }
/** /**
@ -632,8 +635,9 @@ export class DialogKeywords {
* @example SET THEME "themename" * @example SET THEME "themename"
* *
*/ */
public async setTheme({ theme }) { public async setTheme({ pid, theme }) {
// #307 user.basicOptions.theme = theme.trim(); const value = theme.trim();
await this.setOption({pid, name: "theme", value: value});
} }
/** /**
@ -642,24 +646,25 @@ export class DialogKeywords {
* @example SET TRANSLATOR ON | OFF * @example SET TRANSLATOR ON | OFF
* *
*/ */
public async setTranslatorOn({ on }) { public async setTranslatorOn({ pid, on }) {
// #307 user.basicOptions.translatorOn = (on.trim() === "on"); const value = (on.trim() === "on");
await this.setOption({pid, name: "translatorOn", value: value});
} }
/** /**
* Returns the name of the user acquired by WhatsApp API. * Returns the name of the user acquired by WhatsApp API.
*/ */
public async userName() { public async userName({pid}) {
// #307 WhatsappDirectLine.usernames[await this.userMobile()] : 'N/A'; let { min, user, params } = await DialogKeywords.getProcessInfo(pid);
return this.sys().getRandomId(); return user.userName;
} }
/** /**
* Returns current mobile number from user in conversation. * Returns current mobile number from user in conversation.
*/ */
public async userMobile() { public async userMobile({pid}) {
// #307 return GBMinService.userMobile(); let { min, user, params } = await DialogKeywords.getProcessInfo(pid);
return this.sys().getRandomId(); return user.userSystemId;
} }
/** /**
@ -668,10 +673,11 @@ export class DialogKeywords {
* @example MENU * @example MENU
* *
*/ */
public async showMenu({ }) { public async showMenu({}) {
// https://github.com/GeneralBots/BotServer/issues/237 // https://github.com/GeneralBots/BotServer/issues/237
// return await beginDialog('/menu'); // return await beginDialog('/menu');
} }
private static async downloadAttachmentAndWrite(attachment) { private static async downloadAttachmentAndWrite(attachment) {
const url = attachment.contentUrl; const url = attachment.contentUrl;
// https://github.com/GeneralBots/BotServer/issues/195 - '${botId}','uploads'); // https://github.com/GeneralBots/BotServer/issues/195 - '${botId}','uploads');
@ -730,11 +736,8 @@ export class DialogKeywords {
* *
*/ */
public async getHear({ pid, kind, arg }) { public async getHear({ pid, kind, arg }) {
const process = GBServer.globals.processes[pid]; const process = GBServer.globals.processes[pid];
let { let { min, user } = await DialogKeywords.getProcessInfo(pid);
min, user
} = await DialogKeywords.getProcessInfo(pid);
// Handles first arg as an array of args. // Handles first arg as an array of args.
@ -765,10 +768,8 @@ export class DialogKeywords {
// https://github.com/GeneralBots/BotServer/issues/266 // https://github.com/GeneralBots/BotServer/issues/266
if (args && args.length > 1) { if (args && args.length > 1) {
// https://github.com/pedroslopez/whatsapp-web.js/issues/1811 // https://github.com/pedroslopez/whatsapp-web.js/issues/1811
// //
// const list = new List( // const list = new List(
// 'Escolha um dos itens', // 'Escolha um dos itens',
// 'Itens1', // 'Itens1',
@ -781,7 +782,6 @@ export class DialogKeywords {
// 'Please select a product' // 'Please select a product'
// ); // );
// let i = 0; // let i = 0;
// await CollectionUtil.asyncForEach(args, async arg => { // await CollectionUtil.asyncForEach(args, async arg => {
// i++; // i++;
@ -792,7 +792,6 @@ export class DialogKeywords {
// const button = new wpp.Buttons(Messages[locale].choices, choices, ' ', ' '); // const button = new wpp.Buttons(Messages[locale].choices, choices, ' ', ' ');
// await this.talk(button); // await this.talk(button);
GBLog.info(`BASIC: HEAR with [${args.toString()}] (Asking for input).`); GBLog.info(`BASIC: HEAR with [${args.toString()}] (Asking for input).`);
} else { } else {
GBLog.info('BASIC: HEAR (Asking for input).'); GBLog.info('BASIC: HEAR (Asking for input).');
@ -852,7 +851,7 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null) { if (value === null) {
await this.talk({ pid, text: 'Por favor,digite um e-mail válido.' }); await this.talk({ pid, text: 'Por favor, digite um e-mail válido.' });
return await this.getHear({ pid, kind, arg }); return await this.getHear({ pid, kind, arg });
} }
@ -865,7 +864,7 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null || value.length != 1) { if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor,digite um nome válido.' }); await this.talk({ pid, text: 'Por favor, digite um nome válido.' });
return await this.getHear({ pid, kind, arg }); return await this.getHear({ pid, kind, arg });
} }
@ -878,7 +877,7 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null || value.length != 1) { if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor,digite um número válido.' }); await this.talk({ pid, text: 'Por favor, digite um número válido.' });
return await this.getHear({ pid, kind, arg }); return await this.getHear({ pid, kind, arg });
} }
@ -893,7 +892,7 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null || value.length != 1) { if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor,digite uma data no formato 12/12/2020.' }); 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.getHear({ pid, kind, arg });
} }
@ -906,7 +905,7 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null || value.length != 1) { if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor,digite um horário no formato hh:ss.' }); 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.getHear({ pid, kind, arg });
} }
@ -916,8 +915,7 @@ export class DialogKeywords {
// https://github.com/GeneralBots/BotServer/issues/307 // https://github.com/GeneralBots/BotServer/issues/307
if (user.locale === 'en') { if (user.locale === 'en') {
return text.match(/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/gi); return text.match(/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/gi);
} } else {
else {
return text.match(/(?:\d{1,3}.)*\d{1,3}(?:\,\d+)?/gi); return text.match(/(?:\d{1,3}.)*\d{1,3}(?:\,\d+)?/gi);
} }
return []; return [];
@ -926,7 +924,7 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null || value.length != 1) { if (value === null || value.length != 1) {
await this.talk({ pid, text: 'Por favor,digite um valor monetário.' }); await this.talk({ pid, text: 'Por favor, digite um valor monetário.' });
return await this.getHear({ pid, kind, arg }); return await this.getHear({ pid, kind, arg });
} }
@ -943,7 +941,7 @@ export class DialogKeywords {
return await this.getHear({ pid, kind, arg }); return await this.getHear({ pid, kind, arg });
} }
if (!phoneUtil.isPossibleNumber(phoneNumber)) { if (!phoneUtil.isPossibleNumber(phoneNumber)) {
await this.talk({ pid, text: 'Por favor,digite um número de telefone válido.' }); 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.getHear({ pid, kind, arg });
} }
@ -1053,24 +1051,23 @@ export class DialogKeywords {
public static async getProcessInfo(pid: number) { public static async getProcessInfo(pid: number) {
const proc = GBServer.globals.processes[pid]; const proc = GBServer.globals.processes[pid];
const min = GBServer.globals.minInstances.filter(p => const min = GBServer.globals.minInstances.filter(p => p.instance.instanceId == proc.instanceId)[0];
p.instance.instanceId == proc.instanceId)[0];
const sec = new SecService(); const sec = new SecService();
const user = await sec.getUserFromId(min.instance.instanceId, proc.userId); const user = await sec.getUserFromId(min.instance.instanceId, proc.userId);
const params = JSON.parse(user.params);
return { return {
min, user min,
user,
params
}; };
} }
/** /**
* Talks to the user by using the specified text. * Talks to the user by using the specified text.
*/ */
public async talk({ pid, text }) { public async talk({ pid, text }) {
GBLog.info(`BASIC: TALK '${text}'.`); GBLog.info(`BASIC: TALK '${text}'.`);
const { const { min, user } = await DialogKeywords.getProcessInfo(pid);
min, user
} = await DialogKeywords.getProcessInfo(pid);
if (user) { if (user) {
// TODO: const translate = this.user ? this.user.basicOptions.translatorOn : false; // TODO: const translate = this.user ? this.user.basicOptions.translatorOn : false;
@ -1089,9 +1086,7 @@ export class DialogKeywords {
private async internalSendFile({ pid, mobile, filename, caption }) { private async internalSendFile({ pid, mobile, filename, caption }) {
// Handles SEND FILE TO mobile,element in Web Automation. // Handles SEND FILE TO mobile,element in Web Automation.
const { const { min, user } = await DialogKeywords.getProcessInfo(pid);
min, user
} = await DialogKeywords.getProcessInfo(pid);
const element = filename._page ? filename._page : filename.screenshot ? filename : null; const element = filename._page ? filename._page : filename.screenshot ? filename : null;
if (element) { if (element) {

View file

@ -449,6 +449,11 @@ export class SystemKeywords {
* *
*/ */
public async set({ pid, file, address, value }): Promise<any> { public async set({ pid, file, address, value }): Promise<any> {
const {
min, user
} = await DialogKeywords.getProcessInfo(pid);
// Handles calls for HTML stuff // Handles calls for HTML stuff
if (file._javascriptEnabled) { if (file._javascriptEnabled) {
@ -463,9 +468,9 @@ export class SystemKeywords {
GBLog.info(`BASIC: Defining '${address}' in '${file}' to '${value}' (SET). `); GBLog.info(`BASIC: Defining '${address}' in '${file}' to '${value}' (SET). `);
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min); let { baseUrl, client } = await GBDeployer.internalGetDriveClient(min);
const botId = this.min.instance.botId; const botId = min.instance.botId;
const path = `/${botId}.gbai/${botId}.gbdata`; const path = `/${botId}.gbai/${botId}.gbdata`;
address = address.indexOf(':') !== -1 ? address : address + ':' + address; address = address.indexOf(':') !== -1 ? address : address + ':' + address;