Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): send a URL photo as a photo when its host says nothing
Yudhi Armyndharis37c50ef708f3
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 88ffc7a82..6035163a4 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -4379,6 +4379,12 @@ describe('outbound document mode (#989)', () => {'image/png','image/png',],+ [+ 'declared image type for a sticker survives binary/octet-stream',+ 'binary/octet-stream',+ 'image/png',+ 'image/png',+ ],])('%s', async (_name, fetchedContentType, declaredMimetype, expectedMimetype) => {(undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': fetchedContentType }));const sendMessage = jest.fn().mockResolvedValue(sentMessage);@@ -4478,6 +4484,67 @@ describe('outbound document mode (#989)', () => {expect.anything(),);});++ // WA Web classifies an attachment from its mimetype, so a photo whose host says nothing useful+ // (no Content-Type, or the S3 default for an object uploaded without one) would reach the+ // recipient as a document. The route already says what kind of media it is.+ it.each<[string, 'sendImageMessage' | 'sendVideoMessage' | 'sendAudioMessage', string, string]>([+ ['an image with application/octet-stream', 'sendImageMessage', 'application/octet-stream', 'image/jpeg'],+ ['an image with no Content-Type', 'sendImageMessage', '', 'image/jpeg'],+ ['a video with binary/octet-stream', 'sendVideoMessage', 'binary/octet-stream', 'video/mp4'],+ [+ 'an audio with a mixed-case, parameterised octet-stream',+ 'sendAudioMessage',+ 'Application/Octet-Stream; x=1',+ 'audio/mpeg',+ ],+ ])('falls back to the kind default for %s and no declared type', async (_name, send, fetched, expected) => {+ (undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': fetched }));+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);++ await ready({ sendMessage })[send]('[email protected]', {+ mimetype: 'application/octet-stream',+ data: 'https://files.example.com/media',+ });++ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mimetype: expected }),+ expect.anything(),+ );+ });++ it('keeps a specific fetched type on the video path', async () => {+ (undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': 'video/webm' }));+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);++ await ready({ sendMessage }).sendVideoMessage('[email protected]', {+ mimetype: 'application/octet-stream',+ data: 'https://files.example.com/clip',+ });++ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mimetype: 'video/webm' }),+ expect.anything(),+ );+ });++ it('leaves a document with a generic fetched type as it is', async () => {+ (undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': 'binary/octet-stream' }));+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);++ await ready({ sendMessage }).sendDocumentMessage('[email protected]', {+ mimetype: 'application/octet-stream',+ data: 'https://files.example.com/blob',+ });++ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mimetype: 'binary/octet-stream' }),+ expect.objectContaining({ sendMediaAsDocument: true }),+ );+ });});});diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 15c928de6..1a32894c7 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -129,7 +129,7 @@ export function isQuoteUnresolvedError(err: unknown): boolean {export async function toMessageMedia(media: MediaInput,sessionProxyUrl: string | undefined,- opts?: { trustDeclaredType?: boolean },+ opts?: { trustDeclaredType?: boolean; fallbackType?: string },): Promise<MessageMedia> {if (typeof media.data === 'string' && isHttpUrl(media.data)) {const fetched = await loadRemoteMedia(media.data, sessionProxyUrl);@@ -154,11 +154,20 @@ export async function toMessageMedia(const normalizeMediaType = (value?: string): string => (value ?? '').split(';', 1)[0].trim().toLowerCase();const fetchedType = normalizeMediaType(fetched.mimetype);const declaredType = normalizeMediaType(media.mimetype);- const fetchedTypeIsGeneric = !fetchedType || fetchedType === 'application/octet-stream';+ const fetchedTypeIsGeneric =+ !fetchedType || fetchedType === 'application/octet-stream' || fetchedType === 'binary/octet-stream';const declaredTypeIsConvertible = declaredType.startsWith('image/') || declaredType.startsWith('video/');if (opts?.trustDeclaredType === false && fetchedTypeIsGeneric && declaredTypeIsConvertible) {fetched.mimetype = declaredType;}+ // An image, video or audio route already says what kind of media it carries. When neither the+ // caller nor the host says more (the placeholder over an empty or generic response, the S3+ // default for an object uploaded without a type), WA Web would classify the bytes from that+ // generic type and deliver a photo as a document, so the route's default type stands in.+ const declaredTypeIsUnknown = !declaredType || declaredType === 'application/octet-stream';+ if (opts?.fallbackType && fetchedTypeIsGeneric && declaredTypeIsUnknown) {+ fetched.mimetype = opts.fallbackType;+ }if (media.filename) {fetched.filename = media.filename;}@@ -408,15 +417,15 @@ export class WwebjsMessaging {}async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- return this.sendMediaMessage(chatId, media);+ return this.sendMediaMessage(chatId, media, undefined, 'image/jpeg');}async sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- return this.sendMediaMessage(chatId, media);+ return this.sendMediaMessage(chatId, media, undefined, 'video/mp4');}async sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- return this.sendMediaMessage(chatId, media, media.ptt ? { sendAudioAsVoice: true } : undefined);+ return this.sendMediaMessage(chatId, media, media.ptt ? { sendAudioAsVoice: true } : undefined, 'audio/mpeg');}/**@@ -441,12 +450,13 @@ export class WwebjsMessaging {chatId: string,media: MediaInput,extraOptions?: { sendAudioAsVoice?: boolean; sendMediaAsDocument?: boolean },+ fallbackType?: string,): Promise<MessageResult> {this.host.ensureReady();this.host.ensureNotChannelRecipient(chatId);// Build the media once (a remote URL is fetched here); sendResolved may retry the send itself.- const messageMedia = await toMessageMedia(media, this.host.config.proxy?.url);+ const messageMedia = await toMessageMedia(media, this.host.config.proxy?.url, { fallbackType });// A nameless document reaches WA Web as `new File([blob], undefined)` and is labelled literally// "undefined". Only documents render a filename, so default just this path — as Baileys does.if (extraOptions?.sendMediaAsDocument && !messageMedia.filename) {