new(basic.gblib): SEND FILE pdf as temporary images.

This commit is contained in:
me@rodrigorodriguez.com 2024-10-04 00:55:10 -03:00
parent 975d4961a4
commit 25245a010e
5 changed files with 111 additions and 60 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1110,16 +1110,15 @@ export class GBMinService {
} }
} }
} }
GBMinService.pidsConversation[conversationId] = pid; GBMinService.pidsConversation[conversationId] = pid;
step.context.activity['pid'] = pid; step.context.activity['pid'] = pid;
const notes = min.core.getParam(min.instance, 'Notes', null); const notes = min.core.getParam(min.instance, 'Notes', null);
if (await this.handleUploads(min, step, user, params, notes != null)) if (await this.handleUploads(min, step, user, params, notes != null)) {
{
return; return;
} }
// Required for MSTEAMS handling of persisted conversations. // Required for MSTEAMS handling of persisted conversations.
if (step.context.activity.channelId === 'msteams') { if (step.context.activity.channelId === 'msteams') {
@ -1334,16 +1333,16 @@ export class GBMinService {
const base64Data = url.split(';base64,')[1]; const base64Data = url.split(';base64,')[1];
buffer = Buffer.from(base64Data, 'base64'); buffer = Buffer.from(base64Data, 'base64');
} else { } else {
const options = { const options = {
method: 'GET', method: 'GET',
encoding: 'binary' encoding: 'binary'
}; };
const res = await fetch(url, options); const res = await fetch(url, options);
buffer = arrayBufferToBuffer(await res.arrayBuffer()); buffer = arrayBufferToBuffer(await res.arrayBuffer());
} }
await fs.writeFile(localFileName, buffer); await fs.writeFile(localFileName, buffer);
return { return {
name: attachment.name, name: attachment.name,
filename: localFileName, filename: localFileName,
@ -1363,19 +1362,18 @@ export class GBMinService {
private async handleUploads(min, step, user, params, autoSave) { private async handleUploads(min, step, user, params, autoSave) {
// Prepare Promises to download each attachment and then execute each Promise. // Prepare Promises to download each attachment and then execute each Promise.
let ret = false;
if ( if (
step.context.activity.attachments && step.context.activity.attachments &&
step.context.activity.attachments[0] && step.context.activity.attachments[0] &&
step.context.activity.attachments[0].contentType != 'text/html' step.context.activity.attachments[0].contentType != 'text/html'
) { ) {
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 })
); );
const successfulSaves = await Promise.all(promises); const successfulSaves = await Promise.all(promises);
async function replyForReceivedAttachments(attachmentData) { async function replyForReceivedAttachments(attachmentData) {
if (attachmentData) { if (attachmentData) {
// In case of not having HEAR activated before, it is // In case of not having HEAR activated before, it is
// a upload with no Dialog, so run Auto Save to .gbdrive. // a upload with no Dialog, so run Auto Save to .gbdrive.
@ -1412,7 +1410,6 @@ export class GBMinService {
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) {
ret = true;
class GBFile { class GBFile {
data: Buffer; data: Buffer;
filename: string; filename: string;
@ -1436,13 +1433,11 @@ export class GBMinService {
throw new Error('It is only possible to upload one file per message, right now.'); throw new Error('It is only possible to upload one file per message, right now.');
} }
min.cbMap[user.userId].promise = results[0]; min.cbMap[user.userId].promise = results[0];
return;
} else {
return;
} }
} }
return successfulSaves.length > 0;
} }
return ret; return false;
} }
/** /**

View file

@ -693,7 +693,7 @@ export class WhatsappDirectLine extends GBService {
break; break;
case 'image/png': case 'image/png':
await this.sendFileToDevice(to, attachment.contentUrl, attachment.name, attachment.name, 0, 0); await this.sendFileToDevice(to, attachment.contentUrl, attachment.name, attachment.name, 0, false);
return; return;
@ -710,7 +710,7 @@ export class WhatsappDirectLine extends GBService {
return `${attachment.content.title} - ${attachment.content.text}`; return `${attachment.content.title} - ${attachment.content.text}`;
} }
public async sendFileToDevice(to, url, filename, caption, chatId, viewOnce) { public async sendFileToDevice(to, url, filename, caption, chatId, isViewOnce = false) {
let options; let options;
switch (this.provider) { switch (this.provider) {
case 'meta': case 'meta':
@ -724,7 +724,7 @@ export class WhatsappDirectLine extends GBService {
whatsappServiceNumber = GBServer.globals.minBoot.instance.whatsappServiceNumber; whatsappServiceNumber = GBServer.globals.minBoot.instance.whatsappServiceNumber;
whatsappServiceKey = GBServer.globals.minBoot.instance.whatsappServiceKey; whatsappServiceKey = GBServer.globals.minBoot.instance.whatsappServiceKey;
} }
if (viewOnce) { if (isViewOnce) {
await this.sendImageViewOnce(to, url, caption); await this.sendImageViewOnce(to, url, caption);
} }
else { else {
@ -744,7 +744,7 @@ export class WhatsappDirectLine extends GBService {
} }
} }
await this.customClient.sendMessage(to, attachment, { caption: caption , viewOnce}); await this.customClient.sendMessage(to, attachment, { caption: caption, isViewOnce });
break; break;
} }
@ -923,7 +923,7 @@ export class WhatsappDirectLine extends GBService {
} }
public async sendToDevice(to: any, msg: string, conversationId, viewOnce= false) { public async sendToDevice(to: any, msg: string, conversationId, isViewOnce = false) {
try { try {
const cmd = '/audio '; const cmd = '/audio ';
let url; let url;
@ -947,7 +947,7 @@ export class WhatsappDirectLine extends GBService {
await CollectionUtil.asyncForEach(messages, async msg => { await CollectionUtil.asyncForEach(messages, async msg => {
await this.sendTextMessage(to, msg); await this.sendTextMessage(to, msg);
if (messages.length > 1) { if (messages.length > 1) {
await GBUtil.sleep(3000); await GBUtil.sleep(3000);
} }
@ -984,7 +984,7 @@ export class WhatsappDirectLine extends GBService {
} }
} }
if ((await this.customClient.getState()) === WAState.CONNECTED) { if ((await this.customClient.getState()) === WAState.CONNECTED) {
await this.customClient.sendMessage(to, msg, { isViewOnce: isViewOnce }); await this.customClient.sendMessage(to, msg, { isViewOnce });
} else { } else {
GBLogEx.info(this.min, `WhatsApp OFFLINE ${to}: ${msg}`); GBLogEx.info(this.min, `WhatsApp OFFLINE ${to}: ${msg}`);
} }
@ -1397,10 +1397,10 @@ export class WhatsappDirectLine extends GBService {
// Define the API base URL and endpoints // Define the API base URL and endpoints
const baseUrl = 'https://graph.facebook.com/v20.0'; // API version 20.0 const baseUrl = 'https://graph.facebook.com/v20.0'; // API version 20.0
const accessToken = this.whatsappServiceKey; const accessToken = this.whatsappServiceKey;
const sendMessageEndpoint = `${baseUrl}/${this.whatsappServiceNumber}/messages`; const sendMessageEndpoint = `${baseUrl}/${this.whatsappServiceNumber}/messages`;
const messageData = { const messageData = {
messaging_product: 'whatsapp', messaging_product: 'whatsapp',
to: mobile, to: mobile,
@ -1409,7 +1409,7 @@ export class WhatsappDirectLine extends GBService {
body: message, body: message,
} }
}; };
const response = await fetch(sendMessageEndpoint, { const response = await fetch(sendMessageEndpoint, {
method: 'POST', method: 'POST',
headers: { headers: {
@ -1418,15 +1418,15 @@ export class WhatsappDirectLine extends GBService {
}, },
body: JSON.stringify(messageData) body: JSON.stringify(messageData)
}); });
if (!response.ok) { if (!response.ok) {
const errorData = await response.json(); const errorData = await response.json();
throw new Error(`Failed to send message: ${JSON.stringify(errorData)}`); throw new Error(`Failed to send message: ${JSON.stringify(errorData)}`);
} }
const result = await response.json(); const result = await response.json();
GBLogEx.info(0, 'Message sent successfully:' + result); GBLogEx.info(0, 'Message sent successfully:' + result);
return result; return result;
} }
} }

View file

@ -1,7 +1,11 @@
TALK "Please, take a photo of the QR Code and send to me." TALK "Please, take a photo of the QR Code and send to me."
HEAR doc as QRCODE HEAR doc as QRCODE
TALK "Reading document " + doc + "..." text = null
text = GET doc
IF doc THEN
TALK "Reading document " + doc + "..."
text = GET doc
END IF
IF text THEN IF text THEN
@ -9,7 +13,7 @@ IF text THEN
SET CONTEXT text SET CONTEXT text
SET ANSWER MODE "document" SET ANSWER MODE "document"
TALK "Document ${doc} loaded. You can ask me anything about it." TALK "Document ${doc} loaded. You can ask me anything about it."
TALK "I will also send it to you..." TALK "Please, wait while I convert pages to images..."
SEND FILE doc SEND FILE doc
ELSE ELSE