feat(systemkeywords.ts): introducing executionid feature in api

This commit is contained in:
Alan Perdomo 2023-01-10 09:55:30 -03:00
parent 0b746670cb
commit 52dea442d5
5 changed files with 95 additions and 93 deletions

View file

@ -264,21 +264,21 @@ export class DialogKeywords {
* *
* @example list = ACTIVE TASKS * @example list = ACTIVE TASKS
*/ */
public async getActiveTasks({}) {} public async getActiveTasks({ executionId }) {}
/** /**
* 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({ dealName, contact, company, amount }) {} public async createDeal({ executionId, 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({ name }) {} public async fndContact({ executionId, name }) {}
public getContentLocaleWithCulture(contentLocale) { public getContentLocaleWithCulture(contentLocale) {
switch (contentLocale) { switch (contentLocale) {
@ -293,7 +293,7 @@ export class DialogKeywords {
} }
} }
public async getCoded({ value }) { public async getCoded({ executionId, value }) {
// Checks if it is a GB FILE object. // Checks if it is a GB FILE object.
if (value.data && value.filename) { if (value.data && value.filename) {
@ -309,14 +309,14 @@ export class DialogKeywords {
* @example day = WEEKDAY (date) * @example day = WEEKDAY (date)
* *
*/ */
public getWeekFromDate(date) { public getWeekFromDate(executionId, date) {
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',
GBConfigService.get('DEFAULT_CONTENT_LANGUAGE') GBConfigService.get('DEFAULT_CONTENT_LANGUAGE')
); );
let dt = SystemKeywords.getDateFromLocaleString(date, contentLocale); let dt = SystemKeywords.getDateFromLocaleString(executionId, date, contentLocale);
GBLog.info(`BASIC WEEKDAY contentLocale: ${this.getContentLocaleWithCulture(contentLocale)}`); GBLog.info(`BASIC WEEKDAY contentLocale: ${this.getContentLocaleWithCulture(contentLocale)}`);
GBLog.info(`BASIC WEEKDAY date: ${dt}`); GBLog.info(`BASIC WEEKDAY date: ${dt}`);
GBLog.info(dt.toLocaleString(this.getContentLocaleWithCulture(contentLocale), { weekday: 'short' })); GBLog.info(dt.toLocaleString(this.getContentLocaleWithCulture(contentLocale), { weekday: 'short' }));
@ -446,7 +446,7 @@ export class DialogKeywords {
* @example hour = HOUR (date) * @example hour = HOUR (date)
* *
*/ */
public getHourFromDate(date) { public getHourFromDate(executionId, date) {
function addZero(i) { function addZero(i) {
if (i < 10) { if (i < 10) {
i = '0' + i; i = '0' + i;
@ -460,7 +460,7 @@ export class DialogKeywords {
GBConfigService.get('DEFAULT_CONTENT_LANGUAGE') GBConfigService.get('DEFAULT_CONTENT_LANGUAGE')
); );
let dt = SystemKeywords.getDateFromLocaleString(date, contentLocale); let dt = SystemKeywords.getDateFromLocaleString(executionId, date, contentLocale);
if (dt) { if (dt) {
if (!(dt instanceof Date)) { if (!(dt instanceof Date)) {
@ -502,7 +502,7 @@ export class DialogKeywords {
* SEND MAIL "email@domain.com","Subject", "Message text." * SEND MAIL "email@domain.com","Subject", "Message text."
* *
*/ */
public async sendEmail({ to, subject, body }) { public async sendEmail({ executionId, to, subject, body }) {
// tslint:disable-next-line:no-console // tslint:disable-next-line:no-console
GBLog.info(`[E-mail]: to:${to},subject: ${subject},body: ${body}.`); GBLog.info(`[E-mail]: to:${to},subject: ${subject},body: ${body}.`);
@ -540,9 +540,9 @@ export class DialogKeywords {
* @example SEND FILE TO "+199988887777","image.jpg",caption * @example SEND FILE TO "+199988887777","image.jpg",caption
* *
*/ */
public async sendFileTo({ mobile, filename, caption }) { public async sendFileTo({ executionId, mobile, filename, caption }) {
GBLog.info(`BASIC: SEND FILE TO '${mobile}',filename '${filename}'.`); GBLog.info(`BASIC: SEND FILE TO '${mobile}',filename '${filename}'.`);
return await this.internalSendFile({ mobile, filename, caption }); return await this.internalSendFile({ executionId, mobile, filename, caption });
} }
/** /**
@ -551,10 +551,10 @@ export class DialogKeywords {
* @example SEND FILE "image.jpg" * @example SEND FILE "image.jpg"
* *
*/ */
public async sendFile({ filename, caption }) { public async sendFile({ executionId, filename, caption }) {
const mobile = await this.userMobile(); const mobile = await this.userMobile();
GBLog.info(`BASIC: SEND FILE (current: ${mobile},filename '${filename}'.`); GBLog.info(`BASIC: SEND FILE (current: ${mobile},filename '${filename}'.`);
return await this.internalSendFile({ mobile, filename, caption }); return await this.internalSendFile({ executionId, mobile, filename, caption });
} }
/** /**
@ -716,7 +716,7 @@ export class DialogKeywords {
* @example HEAR name * @example HEAR name
* *
*/ */
public async getHear({ kind, arg }) { public async getHear({ executionId, kind, arg }) {
// Handles first arg as an array of args. // Handles first arg as an array of args.
let args = []; let args = [];
@ -829,8 +829,8 @@ export class DialogKeywords {
const value = extractEntity(text); const value = extractEntity(text);
if (value === null) { if (value === null) {
await this.talk({ text: 'Por favor,digite um e-mail válido.' }); await this.talk({ executionId, text: 'Por favor,digite um e-mail válido.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value; result = value;
@ -842,8 +842,8 @@ 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({ text: 'Por favor,digite um nome válido.' }); await this.talk({ executionId, text: 'Por favor,digite um nome válido.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value; result = value;
@ -855,8 +855,8 @@ 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({ text: 'Por favor,digite um número válido.' }); await this.talk({ executionId, text: 'Por favor,digite um número válido.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value; result = value;
@ -870,8 +870,8 @@ 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({ text: 'Por favor,digite uma data no formato 12/12/2020.' }); await this.talk({ executionId, text: 'Por favor,digite uma data no formato 12/12/2020.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value; result = value;
@ -883,8 +883,8 @@ 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({ text: 'Por favor,digite um horário no formato hh:ss.' }); await this.talk({ executionId, text: 'Por favor,digite um horário no formato hh:ss.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value; result = value;
@ -903,8 +903,8 @@ 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({ text: 'Por favor,digite um valor monetário.' }); await this.talk({ executionId, text: 'Por favor,digite um valor monetário.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value; result = value;
@ -917,11 +917,11 @@ export class DialogKeywords {
} catch (error) { } catch (error) {
await this.talk(Messages[locale].validation_enter_valid_mobile); await this.talk(Messages[locale].validation_enter_valid_mobile);
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
if (!phoneUtil.isPossibleNumber(phoneNumber)) { if (!phoneUtil.isPossibleNumber(phoneNumber)) {
await this.talk({ text: 'Por favor,digite um número de telefone válido.' }); await this.talk({ executionId, text: 'Por favor,digite um número de telefone válido.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = phoneNumber; result = phoneNumber;
@ -940,8 +940,8 @@ 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({ text: 'Por favor, digite um CEP válido.' }); await this.talk({ executionId, text: 'Por favor, digite um CEP válido.' });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
result = value[0]; result = value[0];
@ -955,8 +955,8 @@ export class DialogKeywords {
}); });
if (result === null) { if (result === null) {
await this.talk({ text: `Escolha por favor um dos itens sugeridos.` }); await this.talk({ executionId, text: `Escolha por favor um dos itens sugeridos.` });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
} else if (kind === 'language') { } else if (kind === 'language') {
result = null; result = null;
@ -987,8 +987,8 @@ export class DialogKeywords {
}); });
if (result === null) { if (result === null) {
await this.talk({ text: `Escolha por favor um dos itens sugeridos.` }); await this.talk({ executionId, text: `Escolha por favor um dos itens sugeridos.` });
return await this.getHear({ kind, arg }); return await this.getHear({ executionId, kind, arg });
} }
} }
return result; return result;
@ -1045,7 +1045,7 @@ export class DialogKeywords {
/** /**
* Talks to the user by using the specified text. * Talks to the user by using the specified text.
*/ */
public async talk({ text }) { public async talk({ executionId, text }) {
GBLog.info(`BASIC: TALK '${text}'.`); GBLog.info(`BASIC: TALK '${text}'.`);
if (this.user) { if (this.user) {
const translate = this.user ? this.user.basicOptions.translatorOn : false; const translate = this.user ? this.user.basicOptions.translatorOn : false;
@ -1062,7 +1062,7 @@ export class DialogKeywords {
/** /**
* Processes the sending of the file. * Processes the sending of the file.
*/ */
private async internalSendFile({ mobile, filename, caption }) { private async internalSendFile({ executionId, mobile, filename, caption }) {
// Handles SEND FILE TO mobile,element in Web Automation. // Handles SEND FILE TO mobile,element in Web Automation.
const element = filename._page ? filename._page : filename.screenshot ? filename : null; const element = filename._page ? filename._page : filename.screenshot ? filename : null;
@ -1107,7 +1107,7 @@ export class DialogKeywords {
} }
} }
public async getQRCode({ text }) { public async getQRCode({ executionId, text }) {
const img = await qrcode.toDataURL(text); const img = await qrcode.toDataURL(text);
const data = img.replace(/^data:image\/\w+;base64,/, ''); const data = img.replace(/^data:image\/\w+;base64,/, '');
const buf = Buffer.from(data, 'base64'); const buf = Buffer.from(data, 'base64');

View file

@ -86,7 +86,7 @@ export class SystemKeywords {
this.dk = dk; this.dk = dk;
} }
public async callVM ({ text }) { public async callVM ({ executionId, text }) {
const min = null; const min = null;
const step = null; const step = null;
@ -95,7 +95,7 @@ export class SystemKeywords {
return await GBVMService.callVM(text, min, step, deployer, false); return await GBVMService.callVM(text, min, step, deployer, false);
} }
public async append ({ args }) { public async append ({ executionId, args }) {
let array = [].concat(...args); let array = [].concat(...args);
return array.filter(function (item, pos) { return array.filter(function (item, pos) {
return item; return item;
@ -107,7 +107,7 @@ export class SystemKeywords {
* @example SEE CAPTION OF url AS variable * @example SEE CAPTION OF url AS variable
* *
*/ */
public async seeCaption ({ url }) { public async seeCaption ({ executionId, url }) {
const computerVisionClient = new ComputerVisionClient.ComputerVisionClient( const computerVisionClient = new ComputerVisionClient.ComputerVisionClient(
new ApiKeyCredentials.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': process.env.VISION_KEY } }), new ApiKeyCredentials.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': process.env.VISION_KEY } }),
process.env.VISION_ENDPOINT process.env.VISION_ENDPOINT
@ -130,7 +130,7 @@ export class SystemKeywords {
* @example SEE TEXT OF url AS variable * @example SEE TEXT OF url AS variable
* *
*/ */
public async seeText ({ url }) { public async seeText ({ executionId, url }) {
const computerVisionClient = new ComputerVisionClient.ComputerVisionClient( const computerVisionClient = new ComputerVisionClient.ComputerVisionClient(
new ApiKeyCredentials.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': process.env.VISION_KEY } }), new ApiKeyCredentials.ApiKeyCredentials({ inHeader: { 'Ocp-Apim-Subscription-Key': process.env.VISION_KEY } }),
process.env.VISION_ENDPOINT process.env.VISION_ENDPOINT
@ -156,7 +156,7 @@ export class SystemKeywords {
return final; return final;
} }
public async sortBy ({ array, memberName }) { public async sortBy ({ executionId, array, memberName }) {
memberName = memberName.trim(); memberName = memberName.trim();
const contentLocale = this.min.core.getParam<string>( const contentLocale = this.min.core.getParam<string>(
this.min.instance, this.min.instance,
@ -167,7 +167,7 @@ export class SystemKeywords {
// Detects data type from the first element of array. // Detects data type from the first element of array.
let dt = array[0] ? array[0][memberName] : null; let dt = array[0] ? array[0][memberName] : null;
let date = SystemKeywords.getDateFromLocaleString(dt, contentLocale); let date = SystemKeywords.getDateFromLocaleString(executionId, dt, contentLocale);
if (date) { if (date) {
return array return array
? array.sort((a, b) => { ? array.sort((a, b) => {
@ -328,17 +328,17 @@ export class SystemKeywords {
return [url, localName]; return [url, localName];
} }
public async asPDF ({ data, filename }) { public async asPDF ({ executionId, data, filename }) {
let file = await this.renderTable(data, true, false); let file = await this.renderTable(data, true, false);
return file[0]; return file[0];
} }
public async asImage ({ data, filename }) { public async asImage ({ executionId, data, filename }) {
let file = await this.renderTable(data, false, true); let file = await this.renderTable(data, false, true);
return file[0]; return file[0];
} }
public async executeSQL ({ data, sql, tableName }) { public async executeSQL ({ executionId, data, sql, tableName }) {
let objectMode = false; let objectMode = false;
if (Object.keys(data[0])) { if (Object.keys(data[0])) {
objectMode = true; objectMode = true;
@ -358,7 +358,7 @@ export class SystemKeywords {
/** /**
* Retrives the content of a given URL. * Retrives the content of a given URL.
*/ */
public async getFileContents ({ url, headers }) { public async getFileContents ({ executionId, url, headers }) {
const options = { const options = {
method: 'GET', method: 'GET',
encoding: 'binary', encoding: 'binary',
@ -382,7 +382,7 @@ export class SystemKeywords {
/** /**
* Retrives stock inforation for a given symbol. * Retrives stock inforation for a given symbol.
*/ */
public async getStock ({ symbol }) { public async getStock ({ executionId, symbol }) {
const url = `http://live-nse.herokuapp.com/?symbol=${symbol}`; const url = `http://live-nse.herokuapp.com/?symbol=${symbol}`;
let data = await fetch(url); let data = await fetch(url);
return data; return data;
@ -394,7 +394,7 @@ export class SystemKeywords {
* @example WAIT 5 ' This will wait five seconds. * @example WAIT 5 ' This will wait five seconds.
* *
*/ */
public async wait ({ seconds }) { public async wait ({ executionId, seconds }) {
// tslint:disable-next-line no-string-based-set-timeout // tslint:disable-next-line no-string-based-set-timeout
GBLog.info(`BASIC: WAIT for ${seconds} second(s).`); GBLog.info(`BASIC: WAIT for ${seconds} second(s).`);
const timeout = async (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); const timeout = async (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
@ -407,7 +407,7 @@ export class SystemKeywords {
* @example TALK TO "+199988887777", "Message text here" * @example TALK TO "+199988887777", "Message text here"
* *
*/ */
public async talkTo ({ mobile, message }) { public async talkTo ({ executionId, mobile, message }) {
GBLog.info(`BASIC: Talking '${message}' to a specific user (${mobile}) (TALK TO). `); GBLog.info(`BASIC: Talking '${message}' to a specific user (${mobile}) (TALK TO). `);
await this.min.conversationalService.sendMarkdownToMobile(this.min, null, mobile, message); await this.min.conversationalService.sendMarkdownToMobile(this.min, null, mobile, message);
} }
@ -418,7 +418,7 @@ export class SystemKeywords {
* @example SEND SMS TO "+199988887777", "Message text here" * @example SEND SMS TO "+199988887777", "Message text here"
* *
*/ */
public async sendSmsTo ({ mobile, message }) { public async sendSmsTo ({ executionId, mobile, message }) {
GBLog.info(`BASIC: SEND SMS TO '${mobile}', message '${message}'.`); GBLog.info(`BASIC: SEND SMS TO '${mobile}', message '${message}'.`);
await this.min.conversationalService.sendSms(this.min, mobile, message); await this.min.conversationalService.sendSms(this.min, mobile, message);
} }
@ -432,7 +432,7 @@ export class SystemKeywords {
* @example SET page, "elementHTMLSelector", "text" * @example SET page, "elementHTMLSelector", "text"
* *
*/ */
public async set ({ file, address, value }): Promise<any> { public async set ({ executionId, file, address, value }): Promise<any> {
// Handles calls for HTML stuff // Handles calls for HTML stuff
if (file._javascriptEnabled) { if (file._javascriptEnabled) {
@ -493,7 +493,7 @@ export class SystemKeywords {
* @exaple SAVE variable as "my.txt" * @exaple SAVE variable as "my.txt"
* *
*/ */
public async saveFile ({ file, data }): Promise<any> { public async saveFile ({ executionId, file, data }): Promise<any> {
GBLog.info(`BASIC: Saving '${file}' (SAVE file).`); GBLog.info(`BASIC: Saving '${file}' (SAVE file).`);
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min); let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min);
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
@ -523,7 +523,7 @@ export class SystemKeywords {
* @exaple SAVE "customers.xlsx", name, email, phone, address, city, state, country * @exaple SAVE "customers.xlsx", name, email, phone, address, city, state, country
* *
*/ */
public async save ({ args }): Promise<any> { public async save ({ executionId, args }): Promise<any> {
const file = args[0]; const file = args[0];
args.shift(); args.shift();
GBLog.info(`BASIC: Saving '${file}' (SAVE). Args: ${args.join(',')}.`); GBLog.info(`BASIC: Saving '${file}' (SAVE). Args: ${args.join(',')}.`);
@ -572,9 +572,10 @@ export class SystemKeywords {
* @example value = GET "file.xlsx", "A2" * @example value = GET "file.xlsx", "A2"
* *
*/ */
public async get ({ file, addressOrHeaders, httpUsername, httpPs, qs, streaming }): Promise<any> { public async get ({ executionId, file, addressOrHeaders, httpUsername, httpPs, qs, streaming }): Promise<any> {
if (file.startsWith('http')) { if (file.startsWith('http')) {
return await this.getByHttp({ return await this.getByHttp({
executionId,
url: file, url: file,
headers: addressOrHeaders, headers: addressOrHeaders,
username: httpUsername, username: httpUsername,
@ -607,14 +608,14 @@ export class SystemKeywords {
} }
} }
public isValidDate ({ dt }) { public isValidDate ({ executionId, dt }) {
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',
GBConfigService.get('DEFAULT_CONTENT_LANGUAGE') GBConfigService.get('DEFAULT_CONTENT_LANGUAGE')
); );
let date = SystemKeywords.getDateFromLocaleString(dt, contentLocale); let date = SystemKeywords.getDateFromLocaleString(executionId, dt, contentLocale);
if (!date) { if (!date) {
return false; return false;
} }
@ -626,14 +627,14 @@ export class SystemKeywords {
return !isNaN(date.valueOf()); return !isNaN(date.valueOf());
} }
public isValidNumber ({ number }) { public isValidNumber ({ executionId, number }) {
if (number === '') { if (number === '') {
return false; return false;
} }
return !isNaN(number); return !isNaN(number);
} }
public isValidHour ({ value }) { public isValidHour ({ executionId, value }) {
return /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(value); return /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(value);
} }
@ -651,7 +652,7 @@ export class SystemKeywords {
* @see NPM package data-forge * @see NPM package data-forge
* *
*/ */
public async find ({ args }): Promise<any> { public async find ({ executionId, args }): Promise<any> {
const file = args[0]; const file = args[0];
args.shift(); args.shift();
@ -817,7 +818,7 @@ export class SystemKeywords {
if (this.isValidHour(filter.value)) { if (this.isValidHour(filter.value)) {
filter.dataType = 'hourInterval'; filter.dataType = 'hourInterval';
} else if (this.isValidDate(filter.value)) { } else if (this.isValidDate(filter.value)) {
filter.value = SystemKeywords.getDateFromLocaleString(filter.value, contentLocale); filter.value = SystemKeywords.getDateFromLocaleString(executionId, filter.value, contentLocale);
filter.dataType = 'date'; filter.dataType = 'date';
} else if (this.isValidNumber(filter.value)) { } else if (this.isValidNumber(filter.value)) {
filter.value = Number.parseInt(filter.value); filter.value = Number.parseInt(filter.value);
@ -941,7 +942,7 @@ export class SystemKeywords {
if (result.charAt(0) === "'") { if (result.charAt(0) === "'") {
result = result.substr(1); result = result.substr(1);
} }
const resultDate = SystemKeywords.getDateFromLocaleString(result, contentLocale); const resultDate = SystemKeywords.getDateFromLocaleString(executionId, result, contentLocale);
if (filter.value['dateOnly']) { if (filter.value['dateOnly']) {
resultDate.setHours(0, 0, 0, 0); resultDate.setHours(0, 0, 0, 0);
} }
@ -1000,7 +1001,7 @@ export class SystemKeywords {
} }
} }
public static getDateFromLocaleString (date: any, contentLocale: any) { public static getDateFromLocaleString (executionId, date: any, contentLocale: any) {
let ret = null; let ret = null;
let parts = /^([0-3]?[0-9]).([0-3]?[0-9]).((?:[0-9]{2})?[0-9]{2})\s*(10|11|12|0?[1-9]):([0-5][0-9])/gi.exec(date); let parts = /^([0-3]?[0-9]).([0-3]?[0-9]).((?:[0-9]{2})?[0-9]{2})\s*(10|11|12|0?[1-9]):([0-5][0-9])/gi.exec(date);
if (parts && parts[5]) { if (parts && parts[5]) {
@ -1070,7 +1071,7 @@ export class SystemKeywords {
* @example folder = CREATE FOLDER "notes\01" * @example folder = CREATE FOLDER "notes\01"
* *
*/ */
public async createFolder ({ name }) { public async createFolder ({ executionId, name }) {
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min); let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min);
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
let path = `/${botId}.gbai/${botId}.gbdrive`; let path = `/${botId}.gbai/${botId}.gbdrive`;
@ -1119,7 +1120,7 @@ export class SystemKeywords {
* SHARE FOLDER folder, "nome@domain.com", "E-mail message" * SHARE FOLDER folder, "nome@domain.com", "E-mail message"
* *
*/ */
public async shareFolder ({ folder, email, message }) { public async shareFolder ({ executionId, folder, email, message }) {
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min); let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min);
const root = urlJoin(`/${this.min.botId}.gbai/${this.min.botId}.gbdrive`, folder); const root = urlJoin(`/${this.min.botId}.gbai/${this.min.botId}.gbdrive`, folder);
@ -1146,7 +1147,7 @@ export class SystemKeywords {
* COPY "template.xlsx", "reports\" + customerName + "\final.xlsx" * COPY "template.xlsx", "reports\" + customerName + "\final.xlsx"
* *
*/ */
public async copyFile ({ src, dest }) { public async copyFile ({ executionId, src, dest }) {
GBLog.info(`BASIC: BEGINING COPY '${src}' to '${dest}'`); GBLog.info(`BASIC: BEGINING COPY '${src}' to '${dest}'`);
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min); let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min);
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
@ -1168,7 +1169,7 @@ export class SystemKeywords {
let folder; let folder;
if (dest.indexOf('/') !== -1) { if (dest.indexOf('/') !== -1) {
const pathOnly = Path.dirname(dest); const pathOnly = Path.dirname(dest);
folder = await this.createFolder({ name: pathOnly }); folder = await this.createFolder({executionId, name: pathOnly });
} else { } else {
folder = await client.api(`${baseUrl}/drive/root:/${root}`).get(); folder = await client.api(`${baseUrl}/drive/root:/${root}`).get();
} }
@ -1206,7 +1207,7 @@ export class SystemKeywords {
* CONVERT "customers.xlsx" TO "reports\" + today + ".pdf" * CONVERT "customers.xlsx" TO "reports\" + today + ".pdf"
* *
*/ */
public async convert ({ src, dest }) { public async convert ({ executionId, src, dest }) {
GBLog.info(`BASIC: CONVERT '${src}' to '${dest}'`); GBLog.info(`BASIC: CONVERT '${src}' to '${dest}'`);
let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min); let { baseUrl, client } = await GBDeployer.internalGetDriveClient(this.min);
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
@ -1228,7 +1229,7 @@ export class SystemKeywords {
let folder; let folder;
if (dest.indexOf('/') !== -1) { if (dest.indexOf('/') !== -1) {
const pathOnly = Path.dirname(dest); const pathOnly = Path.dirname(dest);
folder = await this.createFolder({ name: pathOnly }); folder = await this.createFolder({ executionId, name: pathOnly });
} else { } else {
folder = await client.api(`${baseUrl}/drive/root:/${root}`).get(); folder = await client.api(`${baseUrl}/drive/root:/${root}`).get();
} }
@ -1267,7 +1268,7 @@ export class SystemKeywords {
* @example pass = PASSWORD * @example pass = PASSWORD
* *
*/ */
public generatePassword () { public generatePassword ( executionId ) {
return GBAdminService.getRndPassword(); return GBAdminService.getRndPassword();
} }
@ -1277,7 +1278,7 @@ export class SystemKeywords {
* @example user = get "http://server/users/1" * @example user = get "http://server/users/1"
* *
*/ */
public async getByHttp ({ url, headers, username, ps, qs}) { public async getByHttp ({ executionId, url, headers, username, ps, qs}) {
let options = { }; let options = { };
if (headers) { if (headers) {
options['headers'] = headers; options['headers'] = headers;
@ -1312,7 +1313,7 @@ export class SystemKeywords {
* talk "The updated user area is" + user.area * talk "The updated user area is" + user.area
* *
*/ */
public async putByHttp ({ url, data, headers }) { public async putByHttp ({ executionId, url, data, headers }) {
const options = { const options = {
json: data, json: data,
headers: headers headers: headers
@ -1332,7 +1333,7 @@ export class SystemKeywords {
* talk "The updated user area is" + user.area * talk "The updated user area is" + user.area
* *
*/ */
public async postByHttp ({ url, data, headers }) { public async postByHttp ({ executionId, url, data, headers }) {
const options = { const options = {
json: data, json: data,
headers: headers headers: headers
@ -1344,7 +1345,7 @@ export class SystemKeywords {
return result ? (typeof result === 'object' ? result : JSON.parse(result)) : true; return result ? (typeof result === 'object' ? result : JSON.parse(result)) : true;
} }
public async numberOnly (text: string) { public async numberOnly ({executionId, text}) {
return text.replace(/\D/gi, ''); return text.replace(/\D/gi, '');
} }
@ -1355,7 +1356,7 @@ export class SystemKeywords {
* doc = FILL "templates/template.docx", data * doc = FILL "templates/template.docx", data
* *
*/ */
public async fill ({ templateName, data }) { public async fill ({ executionId, templateName, data }) {
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
const gbaiName = `${botId}.gbai`; const gbaiName = `${botId}.gbai`;
const path = `/${botId}.gbai/${botId}.gbdata`; const path = `/${botId}.gbai/${botId}.gbdata`;
@ -1389,8 +1390,8 @@ export class SystemKeywords {
return buf; return buf;
} }
public screenCapture () { public screenCapture (executionId) {
// scrcpy // scrcpy Disabled
// function captureImage({ x, y, w, h }) { // function captureImage({ x, y, w, h }) {
// const pic = robot.screen.capture(x, y, w, h) // const pic = robot.screen.capture(x, y, w, h)
// const width = pic.byteWidth / pic.bytesPerPixel // pic.width is sometimes wrong! // const width = pic.byteWidth / pic.bytesPerPixel // pic.width is sometimes wrong!
@ -1441,7 +1442,7 @@ export class SystemKeywords {
* MERGE "second.xlsx" WITH data BY customer_id * MERGE "second.xlsx" WITH data BY customer_id
* *
*/ */
public async merge ({ file, data, key1, key2 }): Promise<any> { public async merge ({ executionId, file, data, key1, key2 }): Promise<any> {
GBLog.info(`BASIC: MERGE running on ${file} and key1: ${key1}, key2: ${key2}...`); GBLog.info(`BASIC: MERGE running on ${file} and key1: ${key1}, key2: ${key2}...`);
const botId = this.min.instance.botId; const botId = this.min.instance.botId;
@ -1543,7 +1544,7 @@ export class SystemKeywords {
const address = `${cell}:${cell}`; const address = `${cell}:${cell}`;
if (value !== found[columnName]) { if (value !== found[columnName]) {
await this.set({ file, address, value }); await this.set({ executionId, file, address, value });
merges++; merges++;
} }
} }
@ -1554,7 +1555,7 @@ export class SystemKeywords {
args.push(row[keys[j]]); args.push(row[keys[j]]);
} }
await this.save({ args }); await this.save({ executionId, args });
adds++; adds++;
} }
} }
@ -1568,7 +1569,7 @@ export class SystemKeywords {
} }
} }
public async tweet ({ text }) { public async tweet ({ executionId, text }) {
const consumer_key = this.min.core.getParam(this.min.instance, 'Twitter Consumer Key', null); const consumer_key = this.min.core.getParam(this.min.instance, 'Twitter Consumer Key', null);
const consumer_secret = this.min.core.getParam(this.min.instance, 'Twitter Consumer Key Secret', null); const consumer_secret = this.min.core.getParam(this.min.instance, 'Twitter Consumer Key Secret', null);
const access_token_key = this.min.core.getParam(this.min.instance, 'Twitter Access Token', null); const access_token_key = this.min.core.getParam(this.min.instance, 'Twitter Access Token', null);

View file

@ -189,12 +189,12 @@ export class WebAutomationKeywords {
/** /**
* Simulates a mouse hover an web page element. * Simulates a mouse hover an web page element.
*/ */
public async hover ({ handle, selector }) { public async hover ({ executionId, handle, selector }) {
const page = this.getPageByHandle(handle); const page = this.getPageByHandle(handle);
GBLog.info(`BASIC: Web Automation HOVER element: ${selector}.`); GBLog.info(`BASIC: Web Automation HOVER element: ${selector}.`);
await this.getBySelector({ handle, selector: selector }); await this.getBySelector({ handle, selector: selector });
await page.hover(selector); await page.hover(selector);
await this.debugStepWeb(page); await this.debugStepWeb(executionId, page);
} }
/** /**
@ -202,7 +202,7 @@ export class WebAutomationKeywords {
* *
* @example CLICK page,"#idElement" * @example CLICK page,"#idElement"
*/ */
public async click ({ handle, frameOrSelector, selector }) { public async click ({ executionId, handle, frameOrSelector, selector }) {
const page = this.getPageByHandle(handle); const page = this.getPageByHandle(handle);
GBLog.info(`BASIC: Web Automation CLICK element: ${frameOrSelector}.`); GBLog.info(`BASIC: Web Automation CLICK element: ${frameOrSelector}.`);
if (selector) { if (selector) {
@ -215,10 +215,10 @@ export class WebAutomationKeywords {
await page.waitForSelector(frameOrSelector); await page.waitForSelector(frameOrSelector);
await page.click(frameOrSelector); await page.click(frameOrSelector);
} }
await this.debugStepWeb(page); await this.debugStepWeb(executionId, page);
} }
private async debugStepWeb (page) { private async debugStepWeb (executionId, page) {
let refresh = true; let refresh = true;
if (this.lastDebugWeb) { if (this.lastDebugWeb) {
refresh = new Date().getTime() - this.lastDebugWeb.getTime() > 5000; refresh = new Date().getTime() - this.lastDebugWeb.getTime() > 5000;
@ -228,7 +228,7 @@ export class WebAutomationKeywords {
const mobile = this.min.core.getParam(this.min.instance, 'Bot Admin Number', null); const mobile = this.min.core.getParam(this.min.instance, 'Bot Admin Number', null);
const filename = page; const filename = page;
if (mobile) { if (mobile) {
await this.dk.sendFileTo({ mobile, filename, caption: 'General Bots Debugger' }); await this.dk.sendFileTo({executionId, mobile, filename, caption: 'General Bots Debugger' });
} }
this.lastDebugWeb = new Date(); this.lastDebugWeb = new Date();
} }
@ -255,7 +255,7 @@ export class WebAutomationKeywords {
} }
} }
public async linkByText ({ handle, text, index }) { public async linkByText ({ executionId, handle, text, index }) {
const page = this.getPageByHandle(handle); const page = this.getPageByHandle(handle);
GBLog.info(`BASIC: Web Automation CLICK LINK TEXT: ${text} ${index}.`); GBLog.info(`BASIC: Web Automation CLICK LINK TEXT: ${text} ${index}.`);
if (!index) { if (!index) {
@ -263,7 +263,7 @@ export class WebAutomationKeywords {
} }
const els = await page.$x(`//a[contains(.,'${text}')]`); const els = await page.$x(`//a[contains(.,'${text}')]`);
await els[index - 1].click(); await els[index - 1].click();
await this.debugStepWeb(page); await this.debugStepWeb(executionId, page);
} }
/** /**
@ -291,14 +291,14 @@ export class WebAutomationKeywords {
* *
* @example SET page,"selector","text" * @example SET page,"selector","text"
*/ */
public async setElementText ({ handle, selector, text }) { public async setElementText ({ executionId, handle, selector, text }) {
const page = this.getPageByHandle(handle); const page = this.getPageByHandle(handle);
GBLog.info(`BASIC: Web Automation TYPE on ${selector}: ${text}.`); GBLog.info(`BASIC: Web Automation TYPE on ${selector}: ${text}.`);
const e = await this.getBySelector({ handle, selector }); const e = await this.getBySelector({ handle, selector });
await e.click({ clickCount: 3 }); await e.click({ clickCount: 3 });
await page.keyboard.press('Backspace'); await page.keyboard.press('Backspace');
await e.type(text, { delay: 200 }); await e.type(text, { delay: 200 });
await this.debugStepWeb(page); await this.debugStepWeb(executionId, page);
} }
/** /**

View file

@ -906,6 +906,7 @@ export class GBMinService {
const headers = { Authorization: `Bearer ${botToken}` }; const headers = { Authorization: `Bearer ${botToken}` };
const t = new SystemKeywords(null, null, null, null); const t = new SystemKeywords(null, null, null, null);
const data = await t.getByHttp({ const data = await t.getByHttp({
executionId: 0,
url: file.contentUrl, url: file.contentUrl,
headers, headers,
username: null, username: null,

View file

@ -203,7 +203,7 @@ export class WhatsappDirectLine extends GBService {
msg msg
); );
s.sendEmail({ to: adminEmail, subject: `Check your WhatsApp for bot ${this.botId}`, body: msg }); s.sendEmail({executionId: 0, to: adminEmail, subject: `Check your WhatsApp for bot ${this.botId}`, body: msg });
}).bind(this) }).bind(this)
); );