diff --git a/src/api/integrations/channel/meta/whatsapp.business.service.ts b/src/api/integrations/channel/meta/whatsapp.business.service.ts index 098654c2d0..2e0ea7b84b 100644 --- a/src/api/integrations/channel/meta/whatsapp.business.service.ts +++ b/src/api/integrations/channel/meta/whatsapp.business.service.ts @@ -23,6 +23,7 @@ import { Events, wa } from '@api/types/wa.types'; import { AudioConverter, Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config'; import { BadRequestException, InternalServerErrorException } from '@exceptions'; import { createJid } from '@utils/createJid'; +import { detectAudioType } from '@utils/detectAudioType'; import { status } from '@utils/renderStatus'; import { sendTelemetry } from '@utils/sendTelemetry'; import axios from 'axios'; @@ -1481,7 +1482,12 @@ export class BusinessStartupService extends ChannelStartupService { prepareMedia.id = audio; prepareMedia.type = 'link'; } else if (audio && !file) { - mimetype = mimeTypes.lookup(prepareMedia.fileName); + // The base64 body carries no name or type, so use the real container instead of a fixed .mp3: + // Ogg/Opus voice notes uploaded as audio/mpeg are accepted by Meta but never delivered. + const audioType = detectAudioType(Buffer.from(audio.slice(0, 64), 'base64')); + prepareMedia.fileName = `${hash}.${audioType.extension}`; + prepareMedia.mimetype = audioType.mimetype; + mimetype = audioType.mimetype; const id = await this.getIdMedia(prepareMedia); prepareMedia.id = id; prepareMedia.type = 'id'; diff --git a/src/utils/detectAudioType.ts b/src/utils/detectAudioType.ts new file mode 100644 index 0000000000..960be4f8aa --- /dev/null +++ b/src/utils/detectAudioType.ts @@ -0,0 +1,48 @@ +export type AudioType = { mimetype: string; extension: string }; + +const MPEG: AudioType = { mimetype: 'audio/mpeg', extension: 'mp3' }; + +// Ogg page header: 'OggS', version, header type, granule (8), serial (4), sequence (4), CRC (4), segment count. +const OGG_PAGE_HEADER_SIZE = 27; + +/** + * Whether an Ogg stream carries Opus: the first page of an Ogg/Opus stream holds only the + * identification header, which starts with the 'OpusHead' magic right after the segment table. + */ +function isOggOpus(buffer: Buffer): boolean { + if (buffer.length <= OGG_PAGE_HEADER_SIZE) return false; + const start = OGG_PAGE_HEADER_SIZE + buffer[OGG_PAGE_HEADER_SIZE - 1]; + return buffer.length >= start + 8 && buffer.toString('latin1', start, start + 8) === 'OpusHead'; +} + +/** + * Detects the container of an audio buffer from its magic bytes, limited to the + * formats the WhatsApp Cloud API accepts (ogg/opus, mp3, aac, m4a, amr). + * Meta only accepts Ogg with the Opus codec ("base audio/ogg not supported"), so Opus is + * labelled with its codec, while other Ogg codecs (e.g. Vorbis) and unknown content fall + * back to audio/mpeg, which was the previous behaviour. + */ +export function detectAudioType(buffer: Buffer): AudioType { + if (!buffer || buffer.length < 4) return MPEG; + + if (buffer.toString('latin1', 0, 4) === 'OggS') { + return isOggOpus(buffer) ? { mimetype: 'audio/ogg; codecs=opus', extension: 'ogg' } : MPEG; + } + + if (buffer.toString('latin1', 0, 5) === '#!AMR') { + return { mimetype: 'audio/amr', extension: 'amr' }; + } + + if (buffer.length >= 8 && buffer.toString('latin1', 4, 8) === 'ftyp') { + return { mimetype: 'audio/mp4', extension: 'm4a' }; + } + + if (buffer.toString('latin1', 0, 3) === 'ID3') return MPEG; + + // ADTS (raw AAC): 12-bit sync word plus layer bits 00; MPEG audio frames use layer bits != 00. + if (buffer[0] === 0xff && (buffer[1] & 0xf6) === 0xf0) { + return { mimetype: 'audio/aac', extension: 'aac' }; + } + + return MPEG; +} diff --git a/test/whatsapp-business-audio.test.ts b/test/whatsapp-business-audio.test.ts new file mode 100644 index 0000000000..eb28a9cc6f --- /dev/null +++ b/test/whatsapp-business-audio.test.ts @@ -0,0 +1,107 @@ +// Run: npx tsx --test test/whatsapp-business-audio.test.ts +// Importing the service needs a generated Prisma client (npm run db:generate). +import '../src/api/server.module'; + +import { BusinessStartupService } from '../src/api/integrations/channel/meta/whatsapp.business.service'; +import { detectAudioType } from '../src/utils/detectAudioType'; +import assert from 'node:assert/strict'; +import { after, describe, it } from 'node:test'; + +after(() => setImmediate(() => process.exit(0))); + +// Synthetic headers only: enough bytes for the magic numbers, no real audio. +// First Ogg page: 27-byte header ending in the segment count, a one-entry segment table, then the codec header. +const oggPage = (packet: Buffer) => + Buffer.concat([ + Buffer.from('OggS', 'latin1'), + Buffer.from([0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, packet.length]), + packet, + Buffer.alloc(32), + ]); +const oggOpus = oggPage(Buffer.concat([Buffer.from('OpusHead', 'latin1'), Buffer.alloc(11)])); +const oggVorbis = oggPage(Buffer.concat([Buffer.from([1]), Buffer.from('vorbis', 'latin1'), Buffer.alloc(23)])); +const mp3Id3 = Buffer.concat([Buffer.from('ID3', 'latin1'), Buffer.from([4, 0, 0, 0, 0, 0, 0]), Buffer.alloc(32)]); +const mp3Frame = Buffer.concat([Buffer.from([0xff, 0xfb, 0x90, 0x64]), Buffer.alloc(32)]); +const aacAdts = Buffer.concat([Buffer.from([0xff, 0xf1, 0x50, 0x80]), Buffer.alloc(32)]); +const m4a = Buffer.concat([Buffer.from([0, 0, 0, 0x20]), Buffer.from('ftypM4A ', 'latin1'), Buffer.alloc(32)]); +const amr = Buffer.concat([Buffer.from('#!AMR\n', 'latin1'), Buffer.alloc(32)]); + +function fakeService() { + const uploads: any[] = []; + const self = { + configService: { get: () => ({}) }, + logger: { verbose: () => undefined }, + getIdMedia: async (media: any) => { + uploads.push({ ...media }); + return 'media-id'; + }, + }; + return { self, uploads }; +} + +describe('BusinessStartupService.processAudio (base64, no audio converter)', () => { + it('uploads Ogg/Opus voice notes as audio/ogg with the opus codec, not audio/mpeg', async () => { + const { self, uploads } = fakeService(); + const result = await BusinessStartupService.prototype.processAudio.call( + self, + oggOpus.toString('base64'), + '+55 11 90000-0000', + undefined, + ); + + assert.equal(uploads.length, 1); + assert.equal(uploads[0].mimetype, 'audio/ogg; codecs=opus'); + assert.match(uploads[0].fileName, /\.ogg$/); + assert.equal(result.mimetype, 'audio/ogg; codecs=opus'); + assert.equal(result.id, 'media-id'); + }); + + it('does not label Ogg/Vorbis as audio/ogg, which Meta only accepts with Opus', async () => { + const { self, uploads } = fakeService(); + const result = await BusinessStartupService.prototype.processAudio.call( + self, + oggVorbis.toString('base64'), + '5511900000000', + undefined, + ); + + assert.equal(uploads[0].mimetype, 'audio/mpeg'); + assert.match(uploads[0].fileName, /\.mp3$/); + assert.equal(result.mimetype, 'audio/mpeg'); + }); + + it('keeps MP3 uploads as audio/mpeg', async () => { + const { self, uploads } = fakeService(); + const result = await BusinessStartupService.prototype.processAudio.call( + self, + mp3Id3.toString('base64'), + '5511900000000', + undefined, + ); + + assert.equal(uploads[0].mimetype, 'audio/mpeg'); + assert.match(uploads[0].fileName, /\.mp3$/); + assert.equal(result.mimetype, 'audio/mpeg'); + }); +}); + +describe('detectAudioType', () => { + it('recognises the containers accepted by the Cloud API', () => { + assert.deepEqual(detectAudioType(oggOpus), { mimetype: 'audio/ogg; codecs=opus', extension: 'ogg' }); + assert.deepEqual(detectAudioType(mp3Id3), { mimetype: 'audio/mpeg', extension: 'mp3' }); + assert.deepEqual(detectAudioType(mp3Frame), { mimetype: 'audio/mpeg', extension: 'mp3' }); + assert.deepEqual(detectAudioType(aacAdts), { mimetype: 'audio/aac', extension: 'aac' }); + assert.deepEqual(detectAudioType(m4a), { mimetype: 'audio/mp4', extension: 'm4a' }); + assert.deepEqual(detectAudioType(amr), { mimetype: 'audio/amr', extension: 'amr' }); + }); + + it('only treats Ogg as supported when the first page carries OpusHead', () => { + assert.deepEqual(detectAudioType(oggVorbis), { mimetype: 'audio/mpeg', extension: 'mp3' }); + assert.deepEqual(detectAudioType(oggOpus.subarray(0, 30)), { mimetype: 'audio/mpeg', extension: 'mp3' }); + }); + + it('falls back to audio/mpeg for unknown or empty input', () => { + assert.deepEqual(detectAudioType(Buffer.from('hello world')), { mimetype: 'audio/mpeg', extension: 'mp3' }); + assert.deepEqual(detectAudioType(Buffer.alloc(0)), { mimetype: 'audio/mpeg', extension: 'mp3' }); + }); +});