Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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';
Expand Down
48 changes: 48 additions & 0 deletions src/utils/detectAudioType.ts
Original file line number Diff line number Diff line change
@@ -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 {
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
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;
}
107 changes: 107 additions & 0 deletions test/whatsapp-business-audio.test.ts
Original file line number Diff line number Diff line change
@@ -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' });
});
});