fix(basic.gblib): #227 - HEAR AS FILE defining where to save, per bot.

This commit is contained in:
rodrigorodriguez 2023-02-03 10:25:58 -03:00
parent bc5c1b0ced
commit 473cd9871d
4 changed files with 33 additions and 16 deletions

View file

@ -57,6 +57,7 @@ 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';
import { WebAutomationKeywords } from './WebAutomationKeywords.js';
/** /**
* Default check interval for user replay * Default check interval for user replay
@ -743,6 +744,10 @@ export class DialogKeywords {
// return await beginDialog('/t',{ to: to }); // return await beginDialog('/t',{ to: to });
} }
public static getFileByHandle (hash) {
return GBServer.globals.files[hash];
}
/** /**
* Hears something from user and put it in a variable * Hears something from user and put it in a variable
* *
@ -795,7 +800,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++;
@ -818,7 +822,7 @@ export class DialogKeywords {
setTimeout(resolve, ms); setTimeout(resolve, ms);
}); });
}; };
min.cbMap[userId] = {}; min.cbMap[userId] = {};
min.cbMap[userId]['promise'] = '!GBHEAR'; min.cbMap[userId]['promise'] = '!GBHEAR';
while (min.cbMap[userId].promise === '!GBHEAR') { while (min.cbMap[userId].promise === '!GBHEAR') {
@ -829,8 +833,9 @@ export class DialogKeywords {
if (kind === 'file') { if (kind === 'file') {
GBLog.info(`BASIC (${min.botId}): Upload done for ${answer.filename}.`); GBLog.info(`BASIC (${min.botId}): Upload done for ${answer.filename}.`);
// TODO: answer.filename, answer.data. const handle = WebAutomationKeywords.cyrb53(this.min.botId + answer.filename);
GBServer.globals.files[handle] = answer;
result = handle;
} else if (kind === 'boolean') { } else if (kind === 'boolean') {
if (isIntentYes('pt-BR', answer)) { if (isIntentYes('pt-BR', answer)) {
result = true; result = true;

View file

@ -88,7 +88,7 @@ export class WebAutomationKeywords {
pageMap = {}; pageMap = {};
cyrb53 = (str, seed = 0) => { public static cyrb53 = (str, seed = 0) => {
let h1 = 0xdeadbeef ^ seed, let h1 = 0xdeadbeef ^ seed,
h2 = 0x41c6ce57 ^ seed; h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) { for (let i = 0, ch; i < str.length; i++) {
@ -131,7 +131,7 @@ export class WebAutomationKeywords {
} }
await page.goto(url); await page.goto(url);
const handle = this.cyrb53(this.min.botId + url); const handle = WebAutomationKeywords.cyrb53(this.min.botId + url);
this.pageMap[handle] = page; this.pageMap[handle] = page;

View file

@ -1060,10 +1060,13 @@
await step.continueDialog(); await step.continueDialog();
} }
} }
/**
* Private handler which receives the Attachment and persists to disk.
* during a HEAR attachment AS FILE upload.
*/
private static async downloadAttachmentAndWrite(attachment) { private static async downloadAttachmentAndWrite(attachment) {
const url = attachment.contentUrl; const url = attachment.contentUrl;
// TODO: https://github.com/GeneralBots/BotServer/issues/195 - '${botId}','uploads');
const localFolder = Path.join('work'); const localFolder = Path.join('work');
const localFileName = Path.join(localFolder, `${this['min'].botId}.gbai`, 'uploads', attachment.name); const localFileName = Path.join(localFolder, `${this['min'].botId}.gbai`, 'uploads', attachment.name);
@ -1156,7 +1159,7 @@
} }
// Prepare Promises to download each attachment and then execute each Promise. // Prepare Promises to download each attachment and then execute each Promise.
const promises = step.context.activity.attachments.map( const promises = step.context.activity.attachments.map(
GBMinService.downloadAttachmentAndWrite.bind({ min, user, params }) GBMinService.downloadAttachmentAndWrite.bind({ min, user, params })
); );
@ -1170,18 +1173,26 @@
await this.sendActivity('Error uploading file. Please,start again.'); await this.sendActivity('Error uploading file. Please,start again.');
} }
} }
// Prepare Promises to reply to the user with information about saved attachments.
// The current TurnContext is bound so `replyForReceivedAttachments` can also send replies.
const replyPromises = successfulSaves.map(replyForReceivedAttachments.bind(step.context)); const replyPromises = successfulSaves.map(replyForReceivedAttachments.bind(step.context));
await Promise.all(replyPromises); await Promise.all(replyPromises);
if (successfulSaves.length > 0) { if (successfulSaves.length > 0) {
const result = {
data: Fs.readFileSync(successfulSaves[0]['localPath']), class GBFile {data:Buffer; filename: string};
filename: successfulSaves[0]['fileName']
}; const results = successfulSaves.reduce((accum:GBFile[], item)=>{
const result: GBFile = {
data: Fs.readFileSync(successfulSaves[0]['localPath']),
filename: successfulSaves[0]['fileName']
};
accum.push(result);
}, []) as GBFile[];
if (min.cbMap[userId] && min.cbMap[userId].promise == '!GBHEAR') { if (min.cbMap[userId] && min.cbMap[userId].promise == '!GBHEAR') {
min.cbMap[userId].promise = result; if (results.length>1)
{
throw new Error('It is only possible to upload one file per message, right now.');
}
min.cbMap[userId].promise = results[0];
} }
} }

View file

@ -42,6 +42,7 @@ import { GBMinService } from '../packages/core.gbapp/services/GBMinService.js';
export class RootData { export class RootData {
public processes: {}; // List of .gbdialog active executions. public processes: {}; // List of .gbdialog active executions.
public files: {}; // List of uploaded files handled.
public publicAddress: string; // URI for BotServer. public publicAddress: string; // URI for BotServer.
public server: any; // Express reference. public server: any; // Express reference.
public sysPackages: any[]; // Loaded system package list. public sysPackages: any[]; // Loaded system package list.