From 8a6626aeae85f76a53627221f81e73cbe6958de0 Mon Sep 17 00:00:00 2001 From: Edgard Date: Wed, 8 Mar 2023 22:41:15 -0300 Subject: [PATCH] feat: Added support to string, blob and file formats to WPP.chat.sendFileMessage --- src/chat/functions/sendFileMessage.ts | 2 +- src/util/convertToFile.ts | 47 +++++++++++++++++---------- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/chat/functions/sendFileMessage.ts b/src/chat/functions/sendFileMessage.ts index 7abee1ceee..4741f026f4 100644 --- a/src/chat/functions/sendFileMessage.ts +++ b/src/chat/functions/sendFileMessage.ts @@ -201,7 +201,7 @@ export interface VideoMessageOptions */ export async function sendFileMessage( chatId: any, - content: any, + content: string | Blob | File, options: | AutoDetectMessageOptions | AudioMessageOptions diff --git a/src/util/convertToFile.ts b/src/util/convertToFile.ts index 437f19e8ea..c16ea9cebd 100644 --- a/src/util/convertToFile.ts +++ b/src/util/convertToFile.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2021 WPPConnect Team + * Copyright 2023 WPPConnect Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,32 +20,43 @@ import parseDataURL from 'parse-data-url'; import { isBase64 } from '.'; export async function convertToFile( - data: string, + data: string | Blob | File, mimetype?: string, filename?: string ): Promise { - let parsed = parseDataURL(data); - - if (!parsed && isBase64(data)) { - parsed = parseDataURL('data:;base64,' + data); + if (data instanceof File) { + return data; } - if (!parsed) { - throw 'invalid_data_url'; - } + let blob: Blob | null = null; + if (typeof data === 'string') { + let parsed = parseDataURL(data); - if (!mimetype) { - mimetype = parsed.contentType; - } + if (!parsed && isBase64(data)) { + parsed = parseDataURL('data:;base64,' + data); + } - const buffer = parsed.toBuffer(); - const blob = new Blob( - [new Uint8Array(buffer, buffer.byteOffset, buffer.length)], - { type: mimetype } - ); + if (!parsed) { + throw 'invalid_data_url'; + } + + if (!mimetype) { + mimetype = parsed.contentType; + } + + const buffer = parsed.toBuffer(); + blob = new Blob( + [new Uint8Array(buffer, buffer.byteOffset, buffer.length)], + { + type: mimetype, + } + ); + } else { + blob = data; + } if (!filename || !mimetype) { - const result = await FileType.fromBuffer(buffer); + const result = await FileType.fromBuffer(await blob.arrayBuffer()); if (result) { const baseType = result.mime.split('/')[0]; filename = filename || `${baseType}.${result.ext}`;