Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(dashboard): attach a file or media URL to a bulk send in the message tester
Cares T.ad8ee9a3ef6f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5c7f9ca1..76629493f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- The dashboard Message Tester's Bulk mode can attach an image, video, audio file or document, using the media support `send-bulk` already has. A picked file travels inline and its kind is detected from its type, or a media URL can be given instead, which the gateway fetches for each recipient; the kind can be changed before sending, for example to send a photo as a document. The message text becomes the caption. A picked file that would push the request past the default 25 MB body limit once repeated for every recipient is refused before sending, pointing to the URL option instead.+### Changed- The PostgreSQL data connection is pinned to UTC: parameters bind as UTC, naive timestamps read back as UTC, every pooled connection sets its session `TimeZone`, and boot fails when the effective zone is not UTC year round.diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 65bc4363f..8c38d820c 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -712,6 +712,9 @@"bulkRecipientsCount": "المستلمون: {{count}}","bulkDelay": "التأخير بين الرسائل (مللي ثانية)","bulkDelayHint": "1000–60000 مللي ثانية (الافتراضي 3000)",+ "bulkMediaKind": "إرسال كـ",+ "bulkMediaHint": "عند إرفاق ملف تصبح الرسالة تعليقًا عليه. يُرسل الملف المختار داخل الطلب نفسه، لذا تحتاج الملفات الكبيرة لعدد كبير من المستلمين إلى رابط وسائط عام بدلًا منه.",+ "bulkMediaTooLarge": "هذا الملف كبير جدًا لإرساله مضمَّنًا إلى {{count}} مستلمين. استخدم رابط وسائط عامًا بدلًا منه، أو أرسل إلى عدد أقل من المستلمين.","send": "إرسال الرسالة","sending": "جارٍ الإرسال...","viewOnly": "للعرض فقط",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 6e38e5792..bc0f61d1c 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "Empfänger: {{count}}","bulkDelay": "Verzögerung zwischen Nachrichten (ms)","bulkDelayHint": "1000–60000 ms (Standard: 3000)",+ "bulkMediaKind": "Senden als",+ "bulkMediaHint": "Mit Anhang wird die Nachricht zu dessen Bildunterschrift. Eine ausgewählte Datei wird direkt in der Anfrage mitgesendet, daher brauchen große Dateien für viele Empfänger stattdessen eine öffentliche Medien-URL.",+ "bulkMediaTooLarge": "Diese Datei ist zu groß, um sie direkt an {{count}} Empfänger zu senden. Verwende stattdessen eine öffentliche Medien-URL oder sende an weniger Empfänger.","send": "Nachricht senden","sending": "Wird gesendet...","viewOnly": "Nur ansehen",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex c81058bde..a8b2db1cb 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "Recipients: {{count}}","bulkDelay": "Delay Between Messages (ms)","bulkDelayHint": "1000–60000 ms (default 3000)",+ "bulkMediaKind": "Send as",+ "bulkMediaHint": "With an attachment, the message becomes its caption. A picked file travels inside the request, so large files for many recipients need a public media URL instead.",+ "bulkMediaTooLarge": "This file is too large to send inline to {{count}} recipients. Use a public media URL instead, or send to fewer recipients.","send": "Send Message","sending": "Sending...","viewOnly": "View Only",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 2c708a375..905dfee40 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -648,6 +648,9 @@"bulkRecipientsCount": "Destinatarios: {{count}}","bulkDelay": "Retraso entre mensajes (ms)","bulkDelayHint": "1000–60000 ms (predeterminado: 3000)",+ "bulkMediaKind": "Enviar como",+ "bulkMediaHint": "Con un adjunto, el mensaje pasa a ser su pie de foto. Un archivo seleccionado viaja dentro de la solicitud, así que los archivos grandes para muchos destinatarios necesitan una URL de medios pública.",+ "bulkMediaTooLarge": "Este archivo es demasiado grande para enviarlo directamente a {{count}} destinatarios. Usa una URL de medios pública o envía a menos destinatarios.","send": "Enviar mensaje","sending": "Enviando...","viewOnly": "Solo lectura",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex bd1692da4..80237f887 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "Destinataires : {{count}}","bulkDelay": "Délai entre les messages (ms)","bulkDelayHint": "1000–60000 ms (par défaut : 3000)",+ "bulkMediaKind": "Envoyer en tant que",+ "bulkMediaHint": "Avec une pièce jointe, le message devient sa légende. Un fichier sélectionné est envoyé dans la requête elle-même : pour un gros fichier et de nombreux destinataires, utilisez plutôt une URL de média publique.",+ "bulkMediaTooLarge": "Ce fichier est trop volumineux pour être envoyé directement à {{count}} destinataires. Utilisez plutôt une URL de média publique ou envoyez à moins de destinataires.","send": "Envoyer le message","sending": "Envoi...","viewOnly": "Lecture seule",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 3c849d022..22b75dd84 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -706,6 +706,9 @@"bulkRecipientsCount": "נמענים: {{count}}","bulkDelay": "השהיה בין הודעות (אלפיות שנייה)","bulkDelayHint": "1000–60000 אלפיות שנייה (ברירת מחדל 3000)",+ "bulkMediaKind": "שליחה בתור",+ "bulkMediaHint": "כשמצורף קובץ, ההודעה הופכת לכיתוב שלו. קובץ שנבחר נשלח בתוך הבקשה עצמה, ולכן קבצים גדולים לנמענים רבים דורשים כתובת URL ציבורית למדיה במקום זאת.",+ "bulkMediaTooLarge": "הקובץ גדול מדי לשליחה ישירה אל {{count}} נמענים. יש להשתמש בכתובת URL ציבורית למדיה במקום זאת, או לשלוח לפחות נמענים.","send": "שליחת הודעה","sending": "שולח...","viewOnly": "צפייה בלבד",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 973fd5c2f..0db867385 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "Destinatari: {{count}}","bulkDelay": "Ritardo tra i messaggi (ms)","bulkDelayHint": "1000–60000 ms (predefinito: 3000)",+ "bulkMediaKind": "Invia come",+ "bulkMediaHint": "Con un allegato, il messaggio diventa la sua didascalia. Un file selezionato viaggia dentro la richiesta, quindi i file grandi per molti destinatari richiedono invece un URL multimediale pubblico.",+ "bulkMediaTooLarge": "Questo file è troppo grande per inviarlo direttamente a {{count}} destinatari. Usa invece un URL multimediale pubblico o invia a meno destinatari.","send": "Invia Messaggio","sending": "Invio in corso...","viewOnly": "Sola Visualizzazione",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 2bb71309a..2230d10a1 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "수신자: {{count}}","bulkDelay": "메시지 간 지연 (ms)","bulkDelayHint": "1000–60000ms (기본값 3000)",+ "bulkMediaKind": "전송 형식",+ "bulkMediaHint": "첨부 파일이 있으면 메시지가 캡션이 됩니다. 선택한 파일은 요청 안에 담겨 전송되므로, 큰 파일을 많은 수신자에게 보내려면 공개 미디어 URL을 사용해야 합니다.",+ "bulkMediaTooLarge": "이 파일은 {{count}}명의 수신자에게 직접 보내기에는 너무 큽니다. 대신 공개 미디어 URL을 사용하거나 수신자 수를 줄이세요.","send": "메시지 보내기","sending": "보내는 중...","viewOnly": "읽기 전용",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 753e753a1..a20a1fe6c 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -648,6 +648,9 @@"bulkRecipientsCount": "Destinatários: {{count}}","bulkDelay": "Intervalo entre mensagens (ms)","bulkDelayHint": "1000–60000 ms (padrão: 3000)",+ "bulkMediaKind": "Enviar como",+ "bulkMediaHint": "Com um anexo, a mensagem vira a legenda dele. Um arquivo selecionado vai dentro da própria requisição, então arquivos grandes para muitos destinatários precisam de uma URL de mídia pública.",+ "bulkMediaTooLarge": "Este arquivo é grande demais para enviar diretamente a {{count}} destinatários. Use uma URL de mídia pública ou envie para menos destinatários.","send": "Enviar mensagem","sending": "Enviando...","viewOnly": "Somente leitura",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex eaa4a8984..87332d9bb 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "గ్రహీతలు: {{count}}","bulkDelay": "సందేశాల మధ్య విరామం (ms)","bulkDelayHint": "1000–60000 ms (డిఫాల్ట్ 3000)",+ "bulkMediaKind": "ఇలా పంపండి",+ "bulkMediaHint": "అటాచ్మెంట్ ఉన్నప్పుడు సందేశం దాని క్యాప్షన్గా మారుతుంది. ఎంచుకున్న ఫైల్ అభ్యర్థనలోనే పంపబడుతుంది, కాబట్టి పెద్ద ఫైల్లను చాలా మంది గ్రహీతలకు పంపడానికి పబ్లిక్ మీడియా URL అవసరం.",+ "bulkMediaTooLarge": "ఈ ఫైల్ను {{count}} గ్రహీతలకు నేరుగా పంపడానికి ఇది చాలా పెద్దది. దానికి బదులుగా పబ్లిక్ మీడియా URLని ఉపయోగించండి లేదా తక్కువ మంది గ్రహీతలకు పంపండి.","send": "సందేశం పంపు","sending": "పంపుతోంది...","viewOnly": "చూడటానికి మాత్రమే",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 967d256b0..1803b1995 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "Alıcılar: {{count}}","bulkDelay": "Mesajlar Arası Gecikme (ms)","bulkDelayHint": "1000–60000 ms (varsayılan 3000)",+ "bulkMediaKind": "Gönderme biçimi",+ "bulkMediaHint": "Dosya eklendiğinde mesaj, dosyanın açıklaması olur. Seçilen dosya isteğin içinde gönderilir; bu yüzden çok sayıda alıcıya büyük dosya göndermek için herkese açık bir medya URL'si kullanın.",+ "bulkMediaTooLarge": "Bu dosya {{count}} alıcıya doğrudan gönderilemeyecek kadar büyük. Bunun yerine herkese açık bir medya URL'si kullanın veya daha az alıcıya gönderin.","send": "Mesajı Gönder","sending": "Gönderiliyor...","viewOnly": "Yalnızca Görüntüle",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex d67c61178..3f52fcb7d 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "接收者:{{count}}","bulkDelay": "消息间隔延迟(毫秒)","bulkDelayHint": "1000–60000 毫秒(默认 3000)",+ "bulkMediaKind": "发送为",+ "bulkMediaHint": "添加附件后,消息将作为附件的说明文字。所选文件会随请求一起发送,因此向大量接收者发送大文件时,请改用公开的媒体 URL。",+ "bulkMediaTooLarge": "此文件太大,无法直接发送给 {{count}} 位接收者。请改用公开的媒体 URL,或减少接收者数量。","send": "发送消息","sending": "正在发送...","viewOnly": "仅查看",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 494a7f688..c42b25d79 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -697,6 +697,9 @@"bulkRecipientsCount": "收件人:{{count}}","bulkDelay": "訊息之間的延遲(毫秒)","bulkDelayHint": "1000–60000 毫秒(預設 3000)",+ "bulkMediaKind": "傳送為",+ "bulkMediaHint": "加入附件後,訊息會成為附件的說明文字。所選檔案會隨請求一併傳送,因此向大量收件人傳送大型檔案時,請改用公開的媒體 URL。",+ "bulkMediaTooLarge": "此檔案太大,無法直接傳送給 {{count}} 位收件人。請改用公開的媒體 URL,或減少收件人數目。","send": "傳送訊息","sending": "正在傳送...","viewOnly": "僅檢視",diff --git a/dashboard/src/pages/MessageTester.css b/dashboard/src/pages/MessageTester.cssindex af95f77f4..454437367 100644--- a/dashboard/src/pages/MessageTester.css+++ b/dashboard/src/pages/MessageTester.css@@ -292,6 +292,14 @@border-color: var(--primary);}+.message-tester .toggle-group.bulk-media-kind button {+ flex: 1 1 0;+}++.message-tester .form-group .hint.error {+ color: var(--error-text);+}+/* Side-by-side pair (location latitude/longitude). */.message-tester .form-row {display: grid;diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 1930787f9..29cac24c3 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -13,6 +13,14 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useRole } from '../hooks/useRole';import { useSessionsQuery, useSessionGroupsQuery } from '../hooks/queries';import { parseBulkRecipients, BULK_MAX_RECIPIENTS, BULK_RECIPIENTS_FILE_MAX_BYTES } from '../utils/bulkRecipients';+import {+ BULK_MEDIA_KINDS,+ buildBulkMessages,+ mediaKindFromMime,+ mediaKindFromUrl,+ toBulkAttachment,+ type BulkMediaKind,+} from '../utils/bulkMedia';import { PageHeader } from '../components/PageHeader';import './MessageTester.css';@@ -83,6 +91,8 @@ const fallbackMime: Record<(typeof messageTypes)[number], string> = {// backend's MEDIA_DOWNLOAD_MAX_BYTES (default 50 MiB) stays authoritative for URL sends (fetched server-side).const MEDIA_UPLOAD_MAX_BYTES = 18 * 1024 * 1024;+const BULK_INLINE_MEDIA_MAX_BYTES = 24 * 1024 * 1024;+// Batch statuses that stop the progress polling (mirrors the backend BatchStatus enum).const TERMINAL_BATCH_STATUSES: readonly BatchStatus[] = ['completed', 'cancelled', 'failed'];@@ -133,6 +143,7 @@ export function MessageTester() {const [forwardMessageId, setForwardMessageId] = useState('');const [bulkRecipients, setBulkRecipients] = useState('');const [bulkDelay, setBulkDelay] = useState('');+ const [bulkMediaKind, setBulkMediaKind] = useState<BulkMediaKind>('document');const [isLoading, setIsLoading] = useState(false);const [response, setResponse] = useState<ApiResponse | null>(null);// Live bulk-batch progress, polled every ~2s while the batch runs (see startBatchPolling).@@ -253,9 +264,11 @@ export function MessageTester() {// readAsDataURL yields "data:<mime>;base64,<payload>"; the engine expects raw base64, so strip the prefix.const base64 = dataUrl.split(',')[1] ?? '';if (!base64) return;- setMediaFile({ base64, mimetype: file.type || fallbackMime[messageType], filename: file.name });+ const mimetype = file.type || fallbackMime[messageType];+ setMediaFile({ base64, mimetype, filename: file.name });setMediaUrl('');if (messageType === 'document') setContent(file.name);+ if (messageType === 'bulk') setBulkMediaKind(mediaKindFromMime(mimetype));};reader.onerror = () => {if (mediaReadSeq.current !== myRead) return;@@ -270,6 +283,11 @@ export function MessageTester() {const lat = parseFloat(latitude);const lng = parseFloat(longitude);const delayMs = bulkDelay.trim() === '' ? undefined : parseInt(bulkDelay, 10);+ const bulkAttachment = messageType === 'bulk' ? toBulkAttachment(bulkMediaKind, mediaFile, mediaUrl) : null;+ const bulkMediaTooLarge =+ messageType === 'bulk' &&+ !!mediaFile &&+ mediaFile.base64.length * bulkRecipientList.length > BULK_INLINE_MEDIA_MAX_BYTES;// Per-type required-field validation for the newer types; text/media keep their original behavior// (the backend stays the authoritative validator either way).@@ -286,7 +304,8 @@ export function MessageTester() {formValid = forwardTo.trim().length > 0 && forwardMessageId.trim().length > 0;} else if (messageType === 'bulk') {formValid =- content.trim().length > 0 &&+ (content.trim().length > 0 || bulkAttachment !== null) &&+ !bulkMediaTooLarge &&bulkRecipientList.length > 0 &&bulkRecipientList.length <= BULK_MAX_RECIPIENTS &&(delayMs === undefined || (!Number.isNaN(delayMs) && delayMs >= 1000 && delayMs <= 60000));@@ -330,11 +349,7 @@ export function MessageTester() {// Bulk is a batch, not a single send: 202 + batchId, then poll progress until terminal.if (messageType === 'bulk') {const batch = await messageApi.sendBulk(session, {- messages: bulkRecipientList.map(recipientChatId => ({- chatId: recipientChatId,- type: 'text' as const,- content: { text: content },- })),+ messages: buildBulkMessages(bulkRecipientList, content, bulkAttachment),...(delayMs !== undefined ? { options: { delayBetweenMessages: delayMs } } : {}),});batchSessionRef.current = session;@@ -453,6 +468,67 @@ export function MessageTester() {): 0;+ const optionalInBulk = messageType === 'bulk' ? ` (${t('common.optional')})` : '';+ const mediaSourceFields = (+ <>+ <div className="form-group">+ <label htmlFor="mt-3">+ {t('messageTester.mediaUrl')}+ {optionalInBulk}+ </label>+ <input+ id="mt-3"+ type="text"+ value={mediaUrl}+ onChange={e => {+ setMediaUrl(e.target.value);+ // Typing a URL supersedes the file: drop the picked file AND any read still+ // in flight (its late onload would otherwise re-clear this URL).+ mediaReadSeq.current += 1;+ if (mediaFile) setMediaFile(null);+ if (messageType === 'bulk') setBulkMediaKind(mediaKindFromUrl(e.target.value));+ }}+ placeholder="https://example.com/file.jpg"+ disabled={!!mediaFile}+ />+ </div>+ <div className="form-group">+ <label>+ {t('messageTester.uploadFile')}+ {optionalInBulk}+ </label>+ {mediaFile ? (+ <div className="file-selected">+ <span className="file-name" title={mediaFile.filename}>+ {mediaFile.filename}+ </span>+ <button type="button" className="remove-file-btn" onClick={clearMediaFile}>+ <X size={14} /> {t('messageTester.removeFile')}+ </button>+ </div>+ ) : (+ <button type="button" className="browse-btn" onClick={() => fileInputRef.current?.click()}>+ <Upload size={14} /> {t('messageTester.browse')}+ </button>+ )}+ <input+ ref={fileInputRef}+ type="file"+ style={{ display: 'none' }}+ accept={mediaAccept[messageType]}+ onChange={handleFileChange}+ />+ {messageType === 'bulk' && (+ <span className={bulkMediaTooLarge ? 'hint error' : 'hint'} role={bulkMediaTooLarge ? 'alert' : undefined}>+ {bulkMediaTooLarge+ ? t('messageTester.bulkMediaTooLarge', { count: bulkRecipientList.length })+ : t('messageTester.bulkMediaHint')}+ </span>+ )}+ </div>+ </>+ );+if (loadingSessions) {return (<div@@ -566,7 +642,10 @@ export function MessageTester() {onClick={() => {// A picked file's mimetype is bound to the category active at pick time, so dropping the// category would route stale bytes to the wrong send-${type} endpoint — clear it.- if (type !== messageType) clearMediaFile();+ if (type !== messageType) {+ clearMediaFile();+ if (type === 'bulk' || messageType === 'bulk') setMediaUrl('');+ }setMessageType(type);}}>@@ -591,47 +670,7 @@ export function MessageTester() {{isMediaMessageType && (<>- <div className="form-group">- <label htmlFor="mt-3">{t('messageTester.mediaUrl')}</label>- <input- id="mt-3"- type="text"- value={mediaUrl}- onChange={e => {- setMediaUrl(e.target.value);- // Typing a URL supersedes the file: drop the picked file AND any read still- // in flight (its late onload would otherwise re-clear this URL).- mediaReadSeq.current += 1;- if (mediaFile) setMediaFile(null);- }}- placeholder="https://example.com/file.jpg"- disabled={!!mediaFile}- />- </div>- <div className="form-group">- <label>{t('messageTester.uploadFile')}</label>- {mediaFile ? (- <div className="file-selected">- <span className="file-name" title={mediaFile.filename}>- {mediaFile.filename}- </span>- <button type="button" className="remove-file-btn" onClick={clearMediaFile}>- <X size={14} /> {t('messageTester.removeFile')}- </button>- </div>- ) : (- <button type="button" className="browse-btn" onClick={() => fileInputRef.current?.click()}>- <Upload size={14} /> {t('messageTester.browse')}- </button>- )}- <input- ref={fileInputRef}- type="file"- style={{ display: 'none' }}- accept={mediaAccept[messageType]}- onChange={handleFileChange}- />- </div>+ {mediaSourceFields}{messageType !== 'audio' && messageType !== 'sticker' && (<div className="form-group"><label htmlFor="mt-14">@@ -877,6 +916,31 @@ export function MessageTester() {rows={4}/></div>+ {mediaSourceFields}+ {bulkAttachment && (+ <div className="form-group">+ <span className="group-label" id="bulk-media-kind-label">+ {t('messageTester.bulkMediaKind')}+ </span>+ <div+ className="toggle-group toggle-group-wrap bulk-media-kind"+ role="group"+ aria-labelledby="bulk-media-kind-label"+ >+ {BULK_MEDIA_KINDS.map(kind => (+ <button+ key={kind}+ type="button"+ aria-pressed={bulkMediaKind === kind}+ className={bulkMediaKind === kind ? 'active' : ''}+ onClick={() => setBulkMediaKind(kind)}+ >+ {t(`messageTester.types.${kind}`)}+ </button>+ ))}+ </div>+ </div>+ )}<div className="form-group"><label htmlFor="mt-18">{t('messageTester.bulkDelay')} ({t('common.optional')})diff --git a/dashboard/src/utils/bulkMedia.test.ts b/dashboard/src/utils/bulkMedia.test.tsnew file mode 100644index 000000000..808556dd4--- /dev/null+++ b/dashboard/src/utils/bulkMedia.test.ts@@ -0,0 +1,90 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ buildBulkMessages,+ filenameFromUrl,+ mediaKindFromMime,+ mediaKindFromUrl,+ toBulkAttachment,+} from './bulkMedia.ts';++const file = { base64: 'QUJD', mimetype: 'application/pdf', filename: 'price list.pdf' };++test('maps a MIME type to the bulk media kind, defaulting to document', () => {+ assert.equal(mediaKindFromMime('image/jpeg'), 'image');+ assert.equal(mediaKindFromMime('VIDEO/MP4'), 'video');+ assert.equal(mediaKindFromMime('audio/mpeg'), 'audio');+ assert.equal(mediaKindFromMime('application/pdf'), 'document');+ assert.equal(mediaKindFromMime('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'), 'document');+ assert.equal(mediaKindFromMime(''), 'document');+});++test('guesses the kind from the URL file extension, ignoring the query string', () => {+ assert.equal(mediaKindFromUrl('https://cdn.example.com/a/photo.JPG'), 'image');+ assert.equal(mediaKindFromUrl('https://cdn.example.com/promo.mp4?token=abc'), 'video');+ assert.equal(mediaKindFromUrl('https://cdn.example.com/voice.ogg'), 'audio');+ assert.equal(mediaKindFromUrl('https://cdn.example.com/report.pdf'), 'document');+ assert.equal(mediaKindFromUrl('https://cdn.example.com/download'), 'document');+ assert.equal(mediaKindFromUrl('not a url'), 'document');+});++test('derives a decoded filename from the URL path', () => {+ assert.equal(filenameFromUrl('https://cdn.example.com/files/price%20list.pdf?x=1'), 'price list.pdf');+ assert.equal(filenameFromUrl('https://cdn.example.com/'), undefined);+ assert.equal(filenameFromUrl('relative/path.pdf'), undefined);+ assert.equal(filenameFromUrl('https://cdn.example.com/bad%E0%A4%A.pdf'), 'bad%E0%A4%A.pdf');+});++test('no file and a blank URL means no attachment', () => {+ assert.equal(toBulkAttachment('image', null, ' '), null);+});++test('a picked file is sent inline and wins over a URL', () => {+ assert.deepEqual(toBulkAttachment('image', { ...file, mimetype: 'image/png' }, 'https://x.test/a.png'), {+ kind: 'image',+ media: { base64: 'QUJD', mimetype: 'image/png' },+ });+});++test('a document keeps the picked filename', () => {+ assert.deepEqual(toBulkAttachment('document', file, ''), {+ kind: 'document',+ media: { base64: 'QUJD', mimetype: 'application/pdf', filename: 'price list.pdf' },+ });+});++test('a URL document takes its filename from the URL, other kinds carry none', () => {+ assert.deepEqual(toBulkAttachment('document', null, ' https://x.test/docs/menu.pdf '), {+ kind: 'document',+ media: { url: 'https://x.test/docs/menu.pdf', filename: 'menu.pdf' },+ });+ assert.deepEqual(toBulkAttachment('video', null, 'https://x.test/clip.mp4'), {+ kind: 'video',+ media: { url: 'https://x.test/clip.mp4' },+ });+});++test('without an attachment every recipient gets a text message', () => {+ assert.deepEqual(buildBulkMessages(['[email protected]', '[email protected]'], 'Hello', null), [+ { chatId: '[email protected]', type: 'text', content: { text: 'Hello' } },+ { chatId: '[email protected]', type: 'text', content: { text: 'Hello' } },+ ]);+});++test('with an attachment the text becomes the caption', () => {+ const attachment = { kind: 'video' as const, media: { url: 'https://x.test/clip.mp4' } };+ assert.deepEqual(buildBulkMessages(['[email protected]'], 'Watch this', attachment), [+ {+ chatId: '[email protected]',+ type: 'video',+ content: { caption: 'Watch this', video: { url: 'https://x.test/clip.mp4' } },+ },+ ]);+});++test('an attachment with blank text is sent without a caption', () => {+ const attachment = { kind: 'document' as const, media: { url: 'https://x.test/a.pdf', filename: 'a.pdf' } };+ assert.deepEqual(buildBulkMessages(['[email protected]'], ' ', attachment), [+ { chatId: '[email protected]', type: 'document', content: { document: { url: 'https://x.test/a.pdf', filename: 'a.pdf' } } },+ ]);+});diff --git a/dashboard/src/utils/bulkMedia.ts b/dashboard/src/utils/bulkMedia.tsnew file mode 100644index 000000000..3914f05dd--- /dev/null+++ b/dashboard/src/utils/bulkMedia.ts@@ -0,0 +1,83 @@+import type { BulkMediaPayload, BulkMessageItem } from '../services/api';++export type BulkMediaKind = 'image' | 'video' | 'audio' | 'document';++export const BULK_MEDIA_KINDS: readonly BulkMediaKind[] = ['image', 'video', 'audio', 'document'];++export interface BulkAttachment {+ kind: BulkMediaKind;+ media: BulkMediaPayload;+}++const KIND_BY_EXTENSION: Record<string, BulkMediaKind> = {+ jpg: 'image',+ jpeg: 'image',+ png: 'image',+ gif: 'image',+ webp: 'image',+ mp4: 'video',+ mov: 'video',+ '3gp': 'video',+ mkv: 'video',+ webm: 'video',+ mp3: 'audio',+ ogg: 'audio',+ opus: 'audio',+ m4a: 'audio',+ aac: 'audio',+ wav: 'audio',+};++export function mediaKindFromMime(mimetype: string): BulkMediaKind {+ const category = mimetype.split('/')[0]?.toLowerCase();+ return category === 'image' || category === 'video' || category === 'audio' ? category : 'document';+}++export function filenameFromUrl(url: string): string | undefined {+ let lastSegment: string | undefined;+ try {+ lastSegment = new URL(url).pathname.split('/').pop();+ } catch {+ return undefined;+ }+ if (!lastSegment) return undefined;+ try {+ return decodeURIComponent(lastSegment);+ } catch {+ return lastSegment;+ }+}++export function mediaKindFromUrl(url: string): BulkMediaKind {+ const filename = filenameFromUrl(url.trim());+ const extension = filename?.includes('.') ? filename.split('.').pop()?.toLowerCase() : undefined;+ return (extension && KIND_BY_EXTENSION[extension]) || 'document';+}++export function toBulkAttachment(+ kind: BulkMediaKind,+ file: { base64: string; mimetype: string; filename: string } | null,+ url: string,+): BulkAttachment | null {+ const trimmedUrl = url.trim();+ if (!file && !trimmedUrl) return null;+ const media: BulkMediaPayload = file ? { base64: file.base64, mimetype: file.mimetype } : { url: trimmedUrl };+ if (kind === 'document') {+ const filename = file ? file.filename : filenameFromUrl(trimmedUrl);+ if (filename) media.filename = filename;+ }+ return { kind, media };+}++export function buildBulkMessages(+ chatIds: readonly string[],+ text: string,+ attachment: BulkAttachment | null,+): BulkMessageItem[] {+ return chatIds.map(chatId => {+ if (!attachment) return { chatId, type: 'text', content: { text } };+ const content: BulkMessageItem['content'] = text.trim() ? { caption: text } : {};+ content[attachment.kind] = attachment.media;+ return { chatId, type: attachment.kind, content };+ });+}