bridge_helpers.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. import path from 'path';
  2. import { mkdirSync, writeFileSync } from 'fs';
  3. import { randomBytes } from 'crypto';
  4. import { format } from 'util';
  5. export const MIME_MAP = {
  6. jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png',
  7. webp: 'image/webp', gif: 'image/gif',
  8. mp4: 'video/mp4', mov: 'video/quicktime', avi: 'video/x-msvideo',
  9. mkv: 'video/x-matroska', '3gp': 'video/3gpp',
  10. pdf: 'application/pdf',
  11. doc: 'application/msword',
  12. docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  13. xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  14. };
  15. export function normalizeWhatsAppId(value) {
  16. if (!value) return '';
  17. // Baileys reports the bot's own ids device-qualified (`<user>:<device>@lid`), while
  18. // inbound mentionedJid / contextInfo.participant are not. Drop the suffix so both
  19. // forms compare equal; the old `':' -> '@'` swap produced `<user>@<device>@lid`,
  20. // which never matched and silently broke @mention / reply-to-bot gating in groups.
  21. return String(value).replace(/:\d+(?=@)/, '').replace(/:\d+$/, '');
  22. }
  23. function unwrapMessageEnvelopes(content) {
  24. let cur = content;
  25. // Envelopes nest (ephemeral wrapping viewOnce wrapping the payload); peel
  26. // until an inner message is reached so nested quotes resolve too.
  27. for (let i = 0; i < 8 && cur; i++) {
  28. const next =
  29. cur.ephemeralMessage?.message ??
  30. cur.viewOnceMessage?.message ??
  31. cur.viewOnceMessageV2?.message ??
  32. cur.documentWithCaptionMessage?.message;
  33. if (next === undefined) break;
  34. cur = next;
  35. }
  36. return cur;
  37. }
  38. export function getMessageContent(msg) {
  39. const raw = msg?.message || {};
  40. const content = unwrapMessageEnvelopes(raw);
  41. // A peeled envelope returns its inner message immediately: the payload
  42. // shape (template/buttons/list/etc.) applies to unenveloped messages.
  43. if (content !== raw) return content;
  44. if (content.templateMessage?.hydratedTemplate) return content.templateMessage.hydratedTemplate;
  45. if (content.buttonsMessage) return content.buttonsMessage;
  46. if (content.listMessage) return content.listMessage;
  47. return content;
  48. }
  49. export function getContextInfo(messageContent) {
  50. if (!messageContent || typeof messageContent !== 'object') return {};
  51. for (const value of Object.values(messageContent)) {
  52. if (value && typeof value === 'object' && value.contextInfo) {
  53. return value.contextInfo;
  54. }
  55. }
  56. return {};
  57. }
  58. export function createBoundedMessageStore(limit = 512) {
  59. const byId = new Map();
  60. function remember(msg) {
  61. const id = msg?.key?.id;
  62. if (!id) return;
  63. byId.delete(id);
  64. byId.set(id, msg);
  65. while (byId.size > limit) {
  66. const oldest = byId.keys().next().value;
  67. byId.delete(oldest);
  68. }
  69. }
  70. function get(id) {
  71. if (!id || !byId.has(id)) return null;
  72. const msg = byId.get(id);
  73. byId.delete(id);
  74. byId.set(id, msg);
  75. return msg;
  76. }
  77. return { remember, get };
  78. }
  79. /**
  80. * Bounded cache of the already-downloaded media (and plain text) for
  81. * recently seen inbound messages, keyed by "chatId:messageId".
  82. *
  83. * When a user replies to an earlier message, Baileys' contextInfo.quotedMessage
  84. * only carries a thumbnail-sized stub for media (or nothing at all for an
  85. * uncaptioned attachment) — never a way to re-fetch the full original file.
  86. * Without this cache, replying to a photo/video/document/voice note with no
  87. * caption gives the agent no text and no media reference: it looks like the
  88. * message never had an attachment. Since extractBridgeEvent already downloads
  89. * and caches the media for every inbound message as it arrives, remembering
  90. * that outcome here lets a later reply resolve the original file path.
  91. */
  92. export function createQuotedMediaCache(limit = 512) {
  93. const byKey = new Map();
  94. function key(chatId, messageId) {
  95. return `${chatId || ''}:${messageId || ''}`;
  96. }
  97. function remember(chatId, messageId, payload) {
  98. if (!messageId) return;
  99. const k = key(chatId, messageId);
  100. byKey.delete(k);
  101. byKey.set(k, payload);
  102. while (byKey.size > limit) {
  103. const oldest = byKey.keys().next().value;
  104. byKey.delete(oldest);
  105. }
  106. }
  107. function get(chatId, messageId) {
  108. if (!messageId) return null;
  109. return byKey.get(key(chatId, messageId)) || null;
  110. }
  111. return { remember, get };
  112. }
  113. export function pollCreationMessageSecret(pollCreation) {
  114. return pollCreation?.message?.messageContextInfo?.messageSecret
  115. || pollCreation?.messageContextInfo?.messageSecret
  116. || null;
  117. }
  118. function uniqueStrings(values) {
  119. const seen = new Set();
  120. const out = [];
  121. for (const value of values || []) {
  122. const text = String(value || '').trim();
  123. if (!text || seen.has(text)) continue;
  124. seen.add(text);
  125. out.push(text);
  126. }
  127. return out;
  128. }
  129. export function pollUpdateForAggregation({
  130. pollUpdateMessage,
  131. pollUpdateMessageKey,
  132. pollCreation,
  133. decryptPollVote,
  134. getKeyAuthor,
  135. meId = 'me',
  136. pollCreatorJids = [],
  137. voterJids = [],
  138. }) {
  139. if (!pollUpdateMessage) return null;
  140. const updateKey = pollUpdateMessage.pollUpdateMessageKey
  141. || pollUpdateMessageKey
  142. || pollUpdateMessage.key;
  143. if (!updateKey) return null;
  144. if (pollUpdateMessage.vote?.selectedOptions) {
  145. return {
  146. pollUpdateMessageKey: updateKey,
  147. vote: pollUpdateMessage.vote,
  148. senderTimestampMs: pollUpdateMessage.senderTimestampMs,
  149. };
  150. }
  151. const creationKey = pollUpdateMessage.pollCreationMessageKey;
  152. const secret = pollCreationMessageSecret(pollCreation);
  153. if (
  154. !creationKey?.id
  155. || !secret
  156. || !pollUpdateMessage.vote?.encPayload
  157. || !pollUpdateMessage.vote?.encIv
  158. || typeof decryptPollVote !== 'function'
  159. || typeof getKeyAuthor !== 'function'
  160. ) {
  161. return null;
  162. }
  163. // Baileys poll decryption keys include both creator and voter JIDs. On
  164. // WhatsApp LID chats, the poll creator can be the linked-device LID even
  165. // when sock.user.id is the classic @s.whatsapp.net JID. Try the exact
  166. // candidates the live bridge knows before falling back to the generic helper.
  167. const creatorCandidates = uniqueStrings([
  168. ...pollCreatorJids,
  169. getKeyAuthor(creationKey, meId),
  170. ]);
  171. const voterCandidates = uniqueStrings([
  172. ...voterJids,
  173. getKeyAuthor(updateKey, meId),
  174. ]);
  175. let lastError = null;
  176. for (const pollCreatorJid of creatorCandidates) {
  177. for (const voterJid of voterCandidates) {
  178. try {
  179. const vote = decryptPollVote(pollUpdateMessage.vote, {
  180. pollCreatorJid,
  181. pollMsgId: creationKey.id,
  182. pollEncKey: secret,
  183. voterJid,
  184. });
  185. return {
  186. pollUpdateMessageKey: updateKey,
  187. vote,
  188. senderTimestampMs: pollUpdateMessage.senderTimestampMs,
  189. };
  190. } catch (err) {
  191. lastError = err;
  192. }
  193. }
  194. }
  195. if (lastError) throw lastError;
  196. return null;
  197. }
  198. export function addMentions(payload, mentions) {
  199. if (payload && Array.isArray(mentions) && mentions.length > 0) {
  200. payload.mentions = mentions;
  201. }
  202. return payload;
  203. }
  204. export function buildTextSendPayload(text, { replyTo, messageStore, mentions } = {}) {
  205. const content = addMentions({ text }, mentions);
  206. const options = {};
  207. const quoted = messageStore?.get(replyTo);
  208. if (quoted?.key && quoted?.message) {
  209. // Baileys expects quoted messages as sendMessage options, not inside the
  210. // message content payload. Keeping this split avoids silently sending a
  211. // literal/ignored `quoted` field instead of a native WhatsApp reply.
  212. options.quoted = quoted;
  213. }
  214. return { content, options };
  215. }
  216. export function buildLocationPayload({ latitude, longitude, name, address } = {}) {
  217. const lat = Number(latitude);
  218. const lon = Number(longitude);
  219. if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
  220. throw new Error('latitude and longitude must be numbers');
  221. }
  222. if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
  223. throw new Error('latitude/longitude out of range');
  224. }
  225. const location = {
  226. degreesLatitude: lat,
  227. degreesLongitude: lon,
  228. };
  229. if (name) location.name = String(name);
  230. if (address) location.address = String(address);
  231. return { location };
  232. }
  233. function textFromQuotedMessage(quotedMessage) {
  234. const content = unwrapMessageEnvelopes(quotedMessage);
  235. if (!content) return '';
  236. if (content.conversation) return content.conversation;
  237. if (content.extendedTextMessage?.text) return content.extendedTextMessage.text;
  238. if (content.imageMessage?.caption) return content.imageMessage.caption;
  239. if (content.videoMessage?.caption) return content.videoMessage.caption;
  240. if (content.documentMessage?.caption) return content.documentMessage.caption;
  241. if (content.documentMessage?.fileName) return `[Document: ${content.documentMessage.fileName}]`;
  242. if (content.locationMessage) return formatLocationText(content.locationMessage, false);
  243. if (content.contactMessage) return formatContactText(content.contactMessage);
  244. if (content.pollCreationMessage) return formatPollText(content.pollCreationMessage);
  245. return '';
  246. }
  247. function mediaExtForMime(mime, fallback) {
  248. const normalized = String(mime || '').split(';', 1)[0].toLowerCase();
  249. const extMap = {
  250. 'image/jpeg': '.jpg',
  251. 'image/png': '.png',
  252. 'image/webp': '.webp',
  253. 'image/gif': '.gif',
  254. 'video/mp4': '.mp4',
  255. 'video/quicktime': '.mov',
  256. 'video/x-matroska': '.mkv',
  257. 'audio/ogg': '.ogg',
  258. 'audio/mp4': '.m4a',
  259. 'audio/mpeg': '.mp3',
  260. 'application/pdf': '.pdf',
  261. };
  262. return extMap[normalized] || fallback;
  263. }
  264. function defaultWriteMediaFile({ buffer, dir, prefix, ext, fileName }) {
  265. mkdirSync(dir, { recursive: true });
  266. let safeName = fileName ? `_${path.basename(fileName).replace(/[^a-zA-Z0-9._-]/g, '_')}` : '';
  267. if (safeName && ext && !path.extname(safeName)) {
  268. safeName = `${safeName}${ext}`;
  269. }
  270. const filePath = path.join(dir, `${prefix}_${randomBytes(6).toString('hex')}${safeName || ext}`);
  271. writeFileSync(filePath, buffer);
  272. return filePath;
  273. }
  274. function formatLocationText(location, isLive) {
  275. const name = location.name || location.address || '';
  276. const lat = location.degreesLatitude ?? location.latitude;
  277. const lng = location.degreesLongitude ?? location.longitude;
  278. const kind = isLive ? 'Live location' : 'Location';
  279. const coords = lat !== undefined && lng !== undefined ? `${lat},${lng}` : '';
  280. return `[${kind}: ${[name, coords].filter(Boolean).join(' ')}]`;
  281. }
  282. function locationMetadata(location, isLive) {
  283. return {
  284. name: location.name || '',
  285. address: location.address || '',
  286. latitude: location.degreesLatitude ?? location.latitude ?? null,
  287. longitude: location.degreesLongitude ?? location.longitude ?? null,
  288. isLive,
  289. };
  290. }
  291. function formatContactText(contact) {
  292. const name = contact.displayName || contact.vcard?.match(/FN:(.+)/)?.[1] || 'unknown';
  293. const phone = contact.vcard?.match(/TEL[^:]*:(.+)/)?.[1] || '';
  294. return `[Contact: ${[name, phone].filter(Boolean).join(' ')}]`;
  295. }
  296. function formatContactsText(contacts) {
  297. const names = contacts.map(c => c.displayName).filter(Boolean);
  298. return `[Contacts: ${names.join(', ') || contacts.length}]`;
  299. }
  300. function formatReactionText(reaction) {
  301. const emoji = reaction.text || '';
  302. const target = reaction.key?.id || '';
  303. return `[Reaction: ${emoji}${target ? ` to ${target}` : ''}]`;
  304. }
  305. function pollOptions(poll) {
  306. return (poll.options || [])
  307. .map(option => option.optionName || option.name)
  308. .filter(Boolean);
  309. }
  310. function formatPollText(poll) {
  311. const question = poll.name || poll.title || 'poll';
  312. const options = pollOptions(poll);
  313. return `[Poll: ${question}${options.length ? ` Options: ${options.join(', ')}` : ''}]`;
  314. }
  315. function formatPollUpdateText(update) {
  316. const target = update.pollCreationMessageKey?.id || update.key?.id || '';
  317. return `[Poll update${target ? `: ${target}` : ''}]`;
  318. }
  319. /**
  320. * Append a visible note for media that failed to download, so the agent knows
  321. * something was sent rather than silently losing the attachment. Returns
  322. * `content` unchanged when nothing failed. (Port of nanoclaw#2895.)
  323. */
  324. export function appendMediaFailureNote(content, failures) {
  325. if (!failures || failures.length === 0) return content;
  326. const note = failures.map((t) => `[${t} could not be downloaded]`).join(' ');
  327. return content ? `${content}\n${note}` : note;
  328. }
  329. export async function extractBridgeEvent({
  330. msg,
  331. chatId,
  332. senderId,
  333. senderNumber,
  334. botIds = [],
  335. isGroup = false,
  336. downloadMedia,
  337. writeMediaFile,
  338. cacheDirs = {},
  339. lookupQuotedMedia,
  340. }) {
  341. const messageContent = getMessageContent(msg);
  342. const contextInfo = getContextInfo(messageContent);
  343. const mentionedIds = Array.from(new Set((contextInfo?.mentionedJid || []).map(normalizeWhatsAppId).filter(Boolean)));
  344. const quotedMessageId = contextInfo?.stanzaId || null;
  345. const quotedParticipant = normalizeWhatsAppId(contextInfo?.participant || '') || null;
  346. const quotedRemoteJid = normalizeWhatsAppId(contextInfo?.remoteJid || '') || null;
  347. const hasQuotedMessage = !!contextInfo?.quotedMessage;
  348. let quotedText = textFromQuotedMessage(contextInfo?.quotedMessage);
  349. let quotedMediaUrls = [];
  350. let quotedMediaType = '';
  351. // contextInfo.quotedMessage only ever carries a thumbnail-sized stub for
  352. // media (or nothing for an uncaptioned attachment) — never a way to
  353. // re-fetch the original file. Resolve the quoted message's already-cached
  354. // media (downloaded when it first arrived) via lookupQuotedMedia so a
  355. // reply to an uncaptioned photo/video/document/voice note still gives the
  356. // agent the original file, not just silence.
  357. if (quotedMessageId && typeof lookupQuotedMedia === 'function') {
  358. const original = lookupQuotedMedia(quotedRemoteJid || chatId, quotedMessageId);
  359. if (original) {
  360. if (original.hasMedia && original.mediaUrls?.length) {
  361. quotedMediaUrls = original.mediaUrls;
  362. quotedMediaType = original.mediaType || '';
  363. if (!quotedText) {
  364. quotedText = {
  365. image: 'sent an image',
  366. video: 'sent a video',
  367. gif: 'sent a GIF',
  368. audio: 'sent an audio message',
  369. ptt: 'sent a voice message',
  370. document: 'sent a document',
  371. sticker: 'sent a sticker',
  372. }[original.mediaType] || 'sent media';
  373. }
  374. } else if (original.body && !quotedText) {
  375. quotedText = original.body;
  376. }
  377. }
  378. }
  379. let body = '';
  380. let hasMedia = false;
  381. let mediaType = '';
  382. let mime = '';
  383. let fileName = '';
  384. let nativeType = '';
  385. const mediaUrls = [];
  386. const nativeMetadata = {};
  387. const mediaFailures = [];
  388. const saveMedia = async ({ mediaMessage, dir, prefix, fallbackExt, fileName: name, type }) => {
  389. if (!downloadMedia) return;
  390. try {
  391. const buf = await downloadMedia(msg);
  392. const ext = mediaExtForMime(mediaMessage?.mimetype, fallbackExt);
  393. const writer = writeMediaFile || defaultWriteMediaFile;
  394. const saved = await writer({ buffer: buf, dir, prefix, ext, fileName: name });
  395. if (saved) mediaUrls.push(saved);
  396. } catch (err) {
  397. // A failed CDN fetch (expired media URL, transient network error) must
  398. // never reject out of extractBridgeEvent — that would drop this message
  399. // AND every remaining message in the same upsert batch. Record the
  400. // failure so the agent is told media was sent instead of losing it
  401. // silently. (Port of nanoclaw#2895's never-silently-drop guarantee; the
  402. // reuploadRequest recovery half is already wired in bridge.js.)
  403. mediaFailures.push(type || 'media');
  404. try {
  405. console.warn(`[bridge] failed to download inbound ${type || 'media'}:`, err?.message || err);
  406. } catch {}
  407. }
  408. };
  409. if (messageContent.conversation) {
  410. body = messageContent.conversation;
  411. nativeType = 'conversation';
  412. } else if (messageContent.extendedTextMessage?.text) {
  413. body = messageContent.extendedTextMessage.text;
  414. nativeType = 'extendedTextMessage';
  415. } else if (messageContent.imageMessage) {
  416. const item = messageContent.imageMessage;
  417. body = item.caption || '';
  418. hasMedia = true;
  419. mediaType = 'image';
  420. nativeType = 'imageMessage';
  421. mime = item.mimetype || 'image/jpeg';
  422. await saveMedia({ mediaMessage: item, dir: cacheDirs.image, prefix: 'img', fallbackExt: '.jpg', type: 'image' });
  423. } else if (messageContent.videoMessage) {
  424. const item = messageContent.videoMessage;
  425. body = item.caption || '';
  426. hasMedia = true;
  427. mediaType = item.gifPlayback ? 'gif' : 'video';
  428. nativeType = 'videoMessage';
  429. mime = item.mimetype || 'video/mp4';
  430. nativeMetadata.video = { gifPlayback: !!item.gifPlayback };
  431. await saveMedia({ mediaMessage: item, dir: cacheDirs.document, prefix: 'vid', fallbackExt: '.mp4', type: mediaType });
  432. } else if (messageContent.audioMessage || messageContent.pttMessage) {
  433. const item = messageContent.pttMessage || messageContent.audioMessage;
  434. hasMedia = true;
  435. mediaType = item.ptt || messageContent.pttMessage ? 'ptt' : 'audio';
  436. nativeType = messageContent.pttMessage ? 'pttMessage' : 'audioMessage';
  437. mime = item.mimetype || 'audio/ogg';
  438. nativeMetadata.audio = { ptt: mediaType === 'ptt' };
  439. await saveMedia({ mediaMessage: item, dir: cacheDirs.audio, prefix: 'aud', fallbackExt: '.ogg', type: 'audio' });
  440. } else if (messageContent.documentMessage) {
  441. const item = messageContent.documentMessage;
  442. body = item.caption || '';
  443. hasMedia = true;
  444. mediaType = 'document';
  445. nativeType = 'documentMessage';
  446. mime = item.mimetype || 'application/octet-stream';
  447. fileName = item.fileName || 'document';
  448. await saveMedia({ mediaMessage: item, dir: cacheDirs.document, prefix: 'doc', fallbackExt: '.bin', fileName, type: 'document' });
  449. } else if (messageContent.stickerMessage) {
  450. hasMedia = true;
  451. mediaType = 'sticker';
  452. nativeType = 'stickerMessage';
  453. mime = messageContent.stickerMessage.mimetype || 'image/webp';
  454. body = '[Sticker]';
  455. nativeMetadata.sticker = {
  456. animated: !!messageContent.stickerMessage.isAnimated,
  457. mimetype: mime,
  458. };
  459. await saveMedia({ mediaMessage: messageContent.stickerMessage, dir: cacheDirs.image, prefix: 'sticker', fallbackExt: '.webp', type: 'sticker' });
  460. } else if (messageContent.locationMessage || messageContent.liveLocationMessage) {
  461. const isLive = !!messageContent.liveLocationMessage;
  462. const item = messageContent.liveLocationMessage || messageContent.locationMessage;
  463. mediaType = isLive ? 'live_location' : 'location';
  464. nativeType = isLive ? 'liveLocationMessage' : 'locationMessage';
  465. body = formatLocationText(item, isLive);
  466. nativeMetadata.location = locationMetadata(item, isLive);
  467. } else if (messageContent.contactMessage) {
  468. mediaType = 'contact';
  469. nativeType = 'contactMessage';
  470. body = formatContactText(messageContent.contactMessage);
  471. nativeMetadata.contact = {
  472. displayName: messageContent.contactMessage.displayName || '',
  473. vcard: messageContent.contactMessage.vcard || '',
  474. };
  475. } else if (messageContent.contactsArrayMessage) {
  476. const contacts = messageContent.contactsArrayMessage.contacts || [];
  477. mediaType = 'contacts';
  478. nativeType = 'contactsArrayMessage';
  479. body = formatContactsText(contacts);
  480. nativeMetadata.contacts = contacts.map(contact => ({
  481. displayName: contact.displayName || '',
  482. vcard: contact.vcard || '',
  483. }));
  484. } else if (messageContent.reactionMessage) {
  485. mediaType = 'reaction';
  486. nativeType = 'reactionMessage';
  487. body = formatReactionText(messageContent.reactionMessage);
  488. nativeMetadata.reaction = {
  489. text: messageContent.reactionMessage.text || '',
  490. messageId: messageContent.reactionMessage.key?.id || '',
  491. remoteJid: normalizeWhatsAppId(messageContent.reactionMessage.key?.remoteJid || ''),
  492. participant: normalizeWhatsAppId(messageContent.reactionMessage.key?.participant || ''),
  493. };
  494. } else if (messageContent.pollCreationMessage || messageContent.pollCreationMessageV2 || messageContent.pollCreationMessageV3) {
  495. const item = messageContent.pollCreationMessage || messageContent.pollCreationMessageV2 || messageContent.pollCreationMessageV3;
  496. mediaType = 'poll';
  497. nativeType = messageContent.pollCreationMessage ? 'pollCreationMessage' : messageContent.pollCreationMessageV2 ? 'pollCreationMessageV2' : 'pollCreationMessageV3';
  498. body = formatPollText(item);
  499. nativeMetadata.poll = {
  500. question: item.name || item.title || '',
  501. options: pollOptions(item),
  502. selectableCount: item.selectableOptionsCount || item.selectableCount || 1,
  503. };
  504. } else if (messageContent.pollUpdateMessage) {
  505. mediaType = 'poll_update';
  506. nativeType = 'pollUpdateMessage';
  507. body = formatPollUpdateText(messageContent.pollUpdateMessage);
  508. nativeMetadata.pollUpdate = messageContent.pollUpdateMessage;
  509. }
  510. // Surface failed downloads to the agent instead of silently losing the
  511. // attachment. Applied before the generic "[<type> received]" fallback so an
  512. // uncaptioned message whose download failed reads "[image could not be
  513. // downloaded]" rather than claiming the media arrived.
  514. body = appendMediaFailureNote(body, mediaFailures);
  515. if (hasMedia && !body) {
  516. body = `[${mediaType} received]`;
  517. }
  518. return {
  519. messageId: msg.key.id,
  520. chatId,
  521. senderId,
  522. senderName: msg.pushName || senderNumber,
  523. chatName: isGroup ? (chatId.split('@')[0]) : (msg.pushName || senderNumber),
  524. isGroup,
  525. body,
  526. hasMedia,
  527. mediaType,
  528. mime,
  529. fileName,
  530. nativeType,
  531. nativeMetadata,
  532. mediaUrls,
  533. mentionedIds,
  534. quotedMessageId,
  535. quotedParticipant,
  536. quotedRemoteJid,
  537. quotedText,
  538. quotedMediaUrls,
  539. quotedMediaType,
  540. hasQuotedMessage,
  541. botIds,
  542. readReceiptKey: {
  543. remoteJid: msg.key.remoteJid || chatId,
  544. id: msg.key.id,
  545. participant: msg.key.participant || senderId,
  546. fromMe: Boolean(msg.key.fromMe),
  547. },
  548. timestamp: msg.messageTimestamp,
  549. };
  550. }
  551. export function inferMediaType(ext) {
  552. if (['jpg', 'jpeg', 'png', 'webp', 'gif'].includes(ext)) return 'image';
  553. if (['mp4', 'mov', 'avi', 'mkv', '3gp'].includes(ext)) return 'video';
  554. if (['ogg', 'opus', 'mp3', 'wav', 'm4a'].includes(ext)) return 'audio';
  555. return 'document';
  556. }
  557. export function inboundReadReceiptKeys({ key, enabled }) {
  558. if (!enabled || !key || key.fromMe || !key.id || !key.remoteJid) return [];
  559. // Preserve participant for group messages: Baileys needs the original key.
  560. return [key];
  561. }
  562. // proto.WebMessageInfo.Status values (Baileys). PENDING is our own local state, never a receipt.
  563. const DELIVERY_STATUS_NAMES = { 0: 'error', 2: 'server_ack', 3: 'delivered', 4: 'read', 5: 'played' };
  564. const RECEIPT_TIMESTAMP_STATUS = [
  565. ['playedTimestamp', 'played'], ['readTimestamp', 'read'], ['receiptTimestamp', 'delivered'],
  566. ];
  567. /**
  568. * Delivery/read status of a message Hermes sent, as a queue event for the adapter to log.
  569. * `messages.update` carries `update.status` for 1:1 chats; `message-receipt.update` carries a
  570. * per-recipient `receipt` for groups. Returns null for anything that is not a status change of
  571. * one of our own sends (`isOwnSend(id)`), so human messages on the linked phone are never logged.
  572. */
  573. export function deliveryStatusEvent({ key, update, receipt, isOwnSend }) {
  574. if (!key?.fromMe || !key.id || !isOwnSend(key.id)) return null;
  575. let status;
  576. let at;
  577. let recipientId = '';
  578. if (receipt) {
  579. const hit = RECEIPT_TIMESTAMP_STATUS.find(([field]) => receipt[field]);
  580. if (!hit) return null;
  581. [, status] = hit;
  582. at = Number(receipt[hit[0]]) || 0;
  583. recipientId = normalizeWhatsAppId(receipt.userJid || '');
  584. } else {
  585. status = DELIVERY_STATUS_NAMES[update?.status];
  586. if (!status) return null;
  587. at = Number(update.messageTimestamp) || 0;
  588. }
  589. const event = {
  590. event: 'delivery_status',
  591. messageId: key.id,
  592. chatId: normalizeWhatsAppId(key.remoteJid || ''),
  593. status,
  594. timestamp: at || Math.floor(Date.now() / 1000),
  595. };
  596. if (recipientId) event.recipientId = recipientId;
  597. const error = status === 'error' ? update?.messageStubParameters?.[0] : undefined;
  598. if (error) event.error = String(error);
  599. return event;
  600. }
  601. export function mediaPayloadForFile({ buffer, filePath, mediaType, caption, fileName }) {
  602. const ext = filePath.toLowerCase().split('.').pop();
  603. const type = mediaType || inferMediaType(ext);
  604. if (type === 'image' && ext === 'gif') {
  605. // Pure helper fallback: do not lie and label raw GIF bytes as mp4.
  606. // The live bridge tries ffmpeg conversion to WhatsApp gifPlayback video
  607. // before it falls back to this regular image payload.
  608. return { image: buffer, caption: caption || undefined, mimetype: MIME_MAP[ext] || 'image/gif' };
  609. }
  610. switch (type) {
  611. case 'image':
  612. return { image: buffer, caption: caption || undefined, mimetype: MIME_MAP[ext] || 'image/jpeg' };
  613. case 'video':
  614. return { video: buffer, caption: caption || undefined, mimetype: MIME_MAP[ext] || 'video/mp4' };
  615. case 'document':
  616. return {
  617. document: buffer,
  618. fileName: fileName || path.basename(filePath),
  619. caption: caption || undefined,
  620. mimetype: MIME_MAP[ext] || 'application/octet-stream',
  621. };
  622. default:
  623. return null;
  624. }
  625. }
  626. export function buildPollPayload({ question, options, selectableCount = 1 }) {
  627. const cleanQuestion = String(question || '').trim();
  628. const cleanOptions = (options || []).map(option => String(option || '').trim()).filter(Boolean);
  629. if (!cleanQuestion) throw new Error('question is required');
  630. if (cleanOptions.length < 2) throw new Error('at least two poll options are required');
  631. if (cleanOptions.length > 12) throw new Error('at most 12 poll options are supported');
  632. const count = Math.max(1, Math.min(Number(selectableCount) || 1, cleanOptions.length));
  633. return {
  634. poll: {
  635. name: cleanQuestion,
  636. values: cleanOptions,
  637. selectableCount: count,
  638. messageSecret: randomBytes(32),
  639. },
  640. };
  641. }
  642. export function pollCreationMessageFromPayload(payload) {
  643. const poll = payload?.poll;
  644. if (!poll) return null;
  645. const values = Array.isArray(poll.values) ? poll.values : [];
  646. const options = values.map(value => String(value || '').trim()).filter(Boolean);
  647. if (!poll.name || options.length < 2) return null;
  648. const selectableOptionsCount = Math.max(1, Math.min(Number(poll.selectableCount) || 1, options.length));
  649. const message = {};
  650. if (poll.messageSecret) {
  651. message.messageContextInfo = { messageSecret: poll.messageSecret };
  652. }
  653. message[selectableOptionsCount === 1 ? 'pollCreationMessageV3' : 'pollCreationMessage'] = {
  654. name: String(poll.name),
  655. options: options.map(optionName => ({ optionName })),
  656. selectableOptionsCount,
  657. };
  658. return message;
  659. }
  660. /**
  661. * Reconnect scheduling guard. startSocket() awaits network I/O before it
  662. * creates a socket or registers event handlers, so a bare
  663. * `setTimeout(startSocket, ...)` has two unrecoverable failure modes: a
  664. * rejection is unhandled (crashes the process on modern Node), and a hang
  665. * leaves the bridge permanently disconnected with nothing left to retry.
  666. * Every (re)connect must go through the scheduler this returns.
  667. */
  668. export function createReconnectScheduler(startFn, {
  669. retryDelayMs = 5000,
  670. log = console.log,
  671. setTimeoutFn = setTimeout,
  672. } = {}) {
  673. function scheduleReconnect(delayMs) {
  674. setTimeoutFn(() => {
  675. Promise.resolve()
  676. .then(startFn)
  677. .catch((err) => {
  678. log(`⚠️ Reconnect failed (${err?.message || err}). Retrying in ${Math.round(retryDelayMs / 1000)}s...`);
  679. scheduleReconnect(retryDelayMs);
  680. });
  681. }, delayMs);
  682. }
  683. return scheduleReconnect;
  684. }
  685. /**
  686. * Version resolution guard. fetchLatestBaileysVersion() is a plain fetch to
  687. * raw.githubusercontent.com with no AbortSignal; a stalled connection can
  688. * pend forever and wedge the reconnect path (the scheduler above cannot
  689. * retry past an await that never settles). Bound the fetch and fall back to
  690. * the last known-good version, or the Baileys default before first success.
  691. */
  692. export function createVersionResolver(fetchVersionFn, {
  693. timeoutMs = 15000,
  694. log = console.log,
  695. } = {}) {
  696. let cachedVersion = null;
  697. return async function resolveVersion() {
  698. let timer = null;
  699. try {
  700. const { version } = await Promise.race([
  701. fetchVersionFn(),
  702. new Promise((_, reject) => {
  703. timer = setTimeout(() => reject(new Error('version fetch timed out')), timeoutMs);
  704. }),
  705. ]);
  706. cachedVersion = version;
  707. } catch (err) {
  708. log(`⚠️ Baileys version fetch failed (${err?.message || err}); using ${cachedVersion ? 'cached version' : 'library default'}.`);
  709. } finally {
  710. if (timer) clearTimeout(timer);
  711. }
  712. return cachedVersion;
  713. };
  714. }
  715. const pad = (value, width = 2) => String(value).padStart(width, '0');
  716. /** `2026-09-28 13:18:46,062` in local time: the asctime shape every file in logs/ uses. */
  717. export function formatLogStamp(date) {
  718. const day = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
  719. const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  720. return `${day} ${time},${pad(date.getMilliseconds(), 3)}`;
  721. }
  722. /**
  723. * Stamp every console.log/warn/error line. The adapter captures stdout/stderr
  724. * verbatim into bridge.log, which otherwise cannot be sequenced (#97021).
  725. */
  726. export function installConsoleStamps(target = console) {
  727. for (const method of ['log', 'warn', 'error']) {
  728. const original = target[method].bind(target);
  729. target[method] = (...args) => {
  730. const text = format(...args);
  731. original('%s', text ? `${formatLogStamp(new Date())} ${text}` : text);
  732. };
  733. }
  734. }
  735. /** Machine-read JSON event lines bypass the console stamp so line parsers see bare JSON. */
  736. export function writeJsonLine(payload, stream = process.stdout) {
  737. stream.write(`${JSON.stringify(payload)}\n`);
  738. }