wolfsocket 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +144 -144
  2. package/WAProto/WAProto.proto +10 -1
  3. package/WAProto/index.d.ts +26 -0
  4. package/WAProto/index.js +18415 -8908
  5. package/lib/Defaults/index.d.ts +6 -0
  6. package/lib/Defaults/index.d.ts.map +1 -1
  7. package/lib/Defaults/index.js +18 -1
  8. package/lib/Defaults/index.js.map +1 -1
  9. package/lib/Signal/lid-mapping.js +1 -1
  10. package/lib/Signal/lid-mapping.js.map +1 -1
  11. package/lib/Socket/business.d.ts +174 -6
  12. package/lib/Socket/business.d.ts.map +1 -1
  13. package/lib/Socket/channelPollVote.d.ts +44 -0
  14. package/lib/Socket/channelPollVote.d.ts.map +1 -0
  15. package/lib/Socket/channelPollVote.js +65 -0
  16. package/lib/Socket/channelPollVote.js.map +1 -0
  17. package/lib/Socket/channelSchedule.d.ts +229 -0
  18. package/lib/Socket/channelSchedule.d.ts.map +1 -0
  19. package/lib/Socket/channelSchedule.js +465 -0
  20. package/lib/Socket/channelSchedule.js.map +1 -0
  21. package/lib/Socket/channelStatus.d.ts +317 -0
  22. package/lib/Socket/channelStatus.d.ts.map +1 -0
  23. package/lib/Socket/channelStatus.js +479 -0
  24. package/lib/Socket/channelStatus.js.map +1 -0
  25. package/lib/Socket/chats.d.ts +30 -5
  26. package/lib/Socket/chats.d.ts.map +1 -1
  27. package/lib/Socket/chats.js +117 -2
  28. package/lib/Socket/chats.js.map +1 -1
  29. package/lib/Socket/communities.d.ts +176 -7
  30. package/lib/Socket/communities.d.ts.map +1 -1
  31. package/lib/Socket/communities.js +22 -6
  32. package/lib/Socket/communities.js.map +1 -1
  33. package/lib/Socket/groupHistory.d.ts +38 -0
  34. package/lib/Socket/groupHistory.d.ts.map +1 -0
  35. package/lib/Socket/groupHistory.js +88 -0
  36. package/lib/Socket/groupHistory.js.map +1 -0
  37. package/lib/Socket/groupStatus.d.ts +6 -0
  38. package/lib/Socket/groupStatus.d.ts.map +1 -1
  39. package/lib/Socket/groupStatus.js +19 -3
  40. package/lib/Socket/groupStatus.js.map +1 -1
  41. package/lib/Socket/groups.d.ts +11 -5
  42. package/lib/Socket/groups.d.ts.map +1 -1
  43. package/lib/Socket/groups.js +9 -2
  44. package/lib/Socket/groups.js.map +1 -1
  45. package/lib/Socket/index.d.ts +174 -6
  46. package/lib/Socket/index.d.ts.map +1 -1
  47. package/lib/Socket/messages-recv.d.ts +174 -6
  48. package/lib/Socket/messages-recv.d.ts.map +1 -1
  49. package/lib/Socket/messages-recv.js +152 -34
  50. package/lib/Socket/messages-recv.js.map +1 -1
  51. package/lib/Socket/messages-send.d.ts +211 -8
  52. package/lib/Socket/messages-send.d.ts.map +1 -1
  53. package/lib/Socket/messages-send.js +510 -133
  54. package/lib/Socket/messages-send.js.map +1 -1
  55. package/lib/Socket/newsletter.d.ts +11 -5
  56. package/lib/Socket/newsletter.d.ts.map +1 -1
  57. package/lib/Socket/newsletterDirectory.d.ts +201 -0
  58. package/lib/Socket/newsletterDirectory.d.ts.map +1 -0
  59. package/lib/Socket/newsletterDirectory.js +291 -0
  60. package/lib/Socket/newsletterDirectory.js.map +1 -0
  61. package/lib/Socket/payment.d.ts +37 -0
  62. package/lib/Socket/payment.d.ts.map +1 -0
  63. package/lib/Socket/payment.js +124 -0
  64. package/lib/Socket/payment.js.map +1 -0
  65. package/lib/Socket/report.d.ts +70 -0
  66. package/lib/Socket/report.d.ts.map +1 -0
  67. package/lib/Socket/report.js +265 -0
  68. package/lib/Socket/report.js.map +1 -0
  69. package/lib/Socket/socket.d.ts.map +1 -1
  70. package/lib/Socket/socket.js +17 -5
  71. package/lib/Socket/socket.js.map +1 -1
  72. package/lib/Socket/stickerPack.d.ts +29 -0
  73. package/lib/Socket/stickerPack.d.ts.map +1 -0
  74. package/lib/Socket/stickerPack.js +130 -0
  75. package/lib/Socket/stickerPack.js.map +1 -0
  76. package/lib/Socket/username.d.ts +55 -0
  77. package/lib/Socket/username.d.ts.map +1 -0
  78. package/lib/Socket/username.js +114 -0
  79. package/lib/Socket/username.js.map +1 -0
  80. package/lib/Types/ChannelStatus.d.ts +34 -0
  81. package/lib/Types/ChannelStatus.d.ts.map +1 -0
  82. package/lib/Types/ChannelStatus.js +2 -0
  83. package/lib/Types/ChannelStatus.js.map +1 -0
  84. package/lib/Types/Chat.d.ts +17 -0
  85. package/lib/Types/Chat.d.ts.map +1 -1
  86. package/lib/Types/Chat.js.map +1 -1
  87. package/lib/Types/Events.d.ts +4 -0
  88. package/lib/Types/Events.d.ts.map +1 -1
  89. package/lib/Types/GroupMetadata.d.ts +2 -0
  90. package/lib/Types/GroupMetadata.d.ts.map +1 -1
  91. package/lib/Types/Message.d.ts +123 -3
  92. package/lib/Types/Message.d.ts.map +1 -1
  93. package/lib/Types/Payment.d.ts +47 -0
  94. package/lib/Types/Payment.d.ts.map +1 -0
  95. package/lib/Types/Payment.js +2 -0
  96. package/lib/Types/Payment.js.map +1 -0
  97. package/lib/Types/Report.d.ts +219 -0
  98. package/lib/Types/Report.d.ts.map +1 -0
  99. package/lib/Types/Report.js +166 -0
  100. package/lib/Types/Report.js.map +1 -0
  101. package/lib/Types/StickerPack.d.ts +52 -0
  102. package/lib/Types/StickerPack.d.ts.map +1 -0
  103. package/lib/Types/StickerPack.js +2 -0
  104. package/lib/Types/StickerPack.js.map +1 -0
  105. package/lib/Types/Username.d.ts +19 -0
  106. package/lib/Types/Username.d.ts.map +1 -0
  107. package/lib/Types/Username.js +2 -0
  108. package/lib/Types/Username.js.map +1 -0
  109. package/lib/Types/index.d.ts +5 -0
  110. package/lib/Types/index.d.ts.map +1 -1
  111. package/lib/Types/index.js +5 -0
  112. package/lib/Types/index.js.map +1 -1
  113. package/lib/Utils/chat-utils.d.ts.map +1 -1
  114. package/lib/Utils/chat-utils.js +19 -1
  115. package/lib/Utils/chat-utils.js.map +1 -1
  116. package/lib/Utils/decode-wa-message.d.ts.map +1 -1
  117. package/lib/Utils/decode-wa-message.js +4 -1
  118. package/lib/Utils/decode-wa-message.js.map +1 -1
  119. package/lib/Utils/event-buffer.js +21 -1
  120. package/lib/Utils/event-buffer.js.map +1 -1
  121. package/lib/Utils/generics.js +1 -1
  122. package/lib/Utils/group-history.d.ts +37 -0
  123. package/lib/Utils/group-history.d.ts.map +1 -0
  124. package/lib/Utils/group-history.js +55 -0
  125. package/lib/Utils/group-history.js.map +1 -0
  126. package/lib/Utils/index.d.ts +3 -0
  127. package/lib/Utils/index.d.ts.map +1 -1
  128. package/lib/Utils/index.js +3 -0
  129. package/lib/Utils/index.js.map +1 -1
  130. package/lib/Utils/link-preview.d.ts.map +1 -1
  131. package/lib/Utils/link-preview.js +21 -7
  132. package/lib/Utils/link-preview.js.map +1 -1
  133. package/lib/Utils/message-retry-manager.d.ts +4 -0
  134. package/lib/Utils/message-retry-manager.d.ts.map +1 -1
  135. package/lib/Utils/message-retry-manager.js +11 -0
  136. package/lib/Utils/message-retry-manager.js.map +1 -1
  137. package/lib/Utils/messages-media.d.ts +25 -9
  138. package/lib/Utils/messages-media.d.ts.map +1 -1
  139. package/lib/Utils/messages-media.js +114 -27
  140. package/lib/Utils/messages-media.js.map +1 -1
  141. package/lib/Utils/messages.d.ts +89 -2
  142. package/lib/Utils/messages.d.ts.map +1 -1
  143. package/lib/Utils/messages.js +414 -15
  144. package/lib/Utils/messages.js.map +1 -1
  145. package/lib/Utils/offline-node-processor.d.ts +1 -1
  146. package/lib/Utils/offline-node-processor.d.ts.map +1 -1
  147. package/lib/Utils/process-message.d.ts +25 -0
  148. package/lib/Utils/process-message.d.ts.map +1 -1
  149. package/lib/Utils/process-message.js +60 -2
  150. package/lib/Utils/process-message.js.map +1 -1
  151. package/lib/Utils/reporting-utils.d.ts +7 -0
  152. package/lib/Utils/reporting-utils.d.ts.map +1 -1
  153. package/lib/Utils/reporting-utils.js +7 -0
  154. package/lib/Utils/reporting-utils.js.map +1 -1
  155. package/lib/Utils/sync-key-auto-resolve.d.ts +10 -0
  156. package/lib/Utils/sync-key-auto-resolve.d.ts.map +1 -0
  157. package/lib/Utils/sync-key-auto-resolve.js +33 -0
  158. package/lib/Utils/sync-key-auto-resolve.js.map +1 -0
  159. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -1
  160. package/lib/Utils/use-multi-file-auth-state.js +34 -2
  161. package/lib/Utils/use-multi-file-auth-state.js.map +1 -1
  162. package/lib/Utils/validate-connection.d.ts.map +1 -1
  163. package/lib/Utils/validate-connection.js +3 -2
  164. package/lib/Utils/validate-connection.js.map +1 -1
  165. package/lib/Utils/zip.d.ts +11 -0
  166. package/lib/Utils/zip.d.ts.map +1 -0
  167. package/lib/Utils/zip.js +88 -0
  168. package/lib/Utils/zip.js.map +1 -0
  169. package/lib/WABinary/generic-utils.d.ts +7 -0
  170. package/lib/WABinary/generic-utils.d.ts.map +1 -1
  171. package/lib/WABinary/generic-utils.js +88 -0
  172. package/lib/WABinary/generic-utils.js.map +1 -1
  173. package/package.json +3 -3
@@ -117,19 +117,22 @@ export const prepareWAMessageMedia = async (message, options) => {
117
117
  logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
118
118
  const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
119
119
  const fileSha256B64 = fileSha256.toString('base64');
120
- const { mediaUrl, directPath } = await options.upload(filePath, {
120
+ const { directPath, thumbnailDirectPath, thumbnailSha256 } = await options.upload(filePath, {
121
121
  fileEncSha256B64: fileSha256B64,
122
122
  mediaType: mediaType,
123
- timeoutMs: options.mediaUploadTimeoutMs
123
+ timeoutMs: options.mediaUploadTimeoutMs,
124
+ newsletter: true
124
125
  });
125
126
  await fs.unlink(filePath);
126
127
  const obj = WAProto.Message.fromObject({
127
128
  // todo: add more support here
128
129
  [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
129
- url: mediaUrl,
130
+ // url intentionally omitted — newsletters use directPath only
130
131
  directPath,
131
132
  fileSha256,
132
133
  fileLength,
134
+ thumbnailDirectPath,
135
+ thumbnailSha256: thumbnailSha256 ? Buffer.from(thumbnailSha256, 'base64') : undefined,
133
136
  ...uploadData,
134
137
  media: undefined
135
138
  })
@@ -286,8 +289,124 @@ export const hasNonNullishProperty = (message, key) => {
286
289
  function hasOptionalProperty(obj, key) {
287
290
  return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
288
291
  }
292
+ /**
293
+ * Build the native-flow button array for an interactiveMessage.
294
+ *
295
+ * Each entry of `nativeFlow` is either a shorthand button ({ id }, { copy },
296
+ * { url }, { call }, { sections }) or an already-shaped native-flow row
297
+ * which is passed through untouched.
298
+ *
299
+ * Optional top-level extras:
300
+ * - offerText (+ offerUrl, offerCode, offerExpiration) -> limited_time_offer
301
+ * - optionText (+ optionTitle) -> bottom_sheet
302
+ */
303
+ export const prepareNativeFlowButtons = (message) => {
304
+ const buttons = message.nativeFlow;
305
+ const isButtonsFieldArray = Array.isArray(buttons);
306
+ const correctedField = isButtonsFieldArray ? buttons : buttons.buttons;
307
+ const messageParamsJson = {};
308
+ if (hasOptionalProperty(message, 'offerText') && !!message.offerText) {
309
+ Object.assign(messageParamsJson, {
310
+ limited_time_offer: {
311
+ text: message.offerText,
312
+ url: message.offerUrl,
313
+ copy_code: message.offerCode,
314
+ expiration_time: message.offerExpiration
315
+ }
316
+ });
317
+ }
318
+ if (hasOptionalProperty(message, 'optionText') && !!message.optionText) {
319
+ Object.assign(messageParamsJson, {
320
+ bottom_sheet: {
321
+ in_thread_buttons_limit: 1,
322
+ divider_indices: Array.from({ length: correctedField.length }, (_, index) => index),
323
+ list_title: message.optionTitle || '📄 Select Options',
324
+ button_title: message.optionText
325
+ }
326
+ });
327
+ }
328
+ return {
329
+ buttons: correctedField.map(button => {
330
+ const shorthand = button;
331
+ const buttonText = shorthand.text || shorthand.buttonText;
332
+ const buttonIcon = shorthand.icon?.toUpperCase();
333
+ if (hasOptionalProperty(button, 'id') && !!button.id) {
334
+ return {
335
+ name: 'quick_reply',
336
+ buttonParamsJson: JSON.stringify({
337
+ display_text: buttonText || '👉🏻 Click',
338
+ id: button.id,
339
+ icon: buttonIcon
340
+ })
341
+ };
342
+ }
343
+ else if (hasOptionalProperty(button, 'copy') && !!button.copy) {
344
+ return {
345
+ name: 'cta_copy',
346
+ buttonParamsJson: JSON.stringify({
347
+ display_text: buttonText || '📋 Copy',
348
+ copy_code: button.copy,
349
+ icon: buttonIcon
350
+ })
351
+ };
352
+ }
353
+ else if (hasOptionalProperty(button, 'url') && !!button.url) {
354
+ return {
355
+ name: 'cta_url',
356
+ buttonParamsJson: JSON.stringify({
357
+ display_text: buttonText || '🌐 Visit',
358
+ url: button.url,
359
+ merchant_url: button.url,
360
+ webview_interaction: button.useWebview,
361
+ icon: buttonIcon
362
+ })
363
+ };
364
+ }
365
+ else if (hasOptionalProperty(button, 'call') && !!button.call) {
366
+ return {
367
+ name: 'cta_call',
368
+ buttonParamsJson: JSON.stringify({
369
+ display_text: buttonText || '📞 Call',
370
+ phone_number: button.call,
371
+ icon: buttonIcon
372
+ })
373
+ };
374
+ }
375
+ else if (hasOptionalProperty(button, 'sections') && !!button.sections) {
376
+ return {
377
+ name: 'single_select',
378
+ buttonParamsJson: JSON.stringify({
379
+ title: buttonText || '📋 Select',
380
+ sections: button.sections,
381
+ icon: buttonIcon
382
+ })
383
+ };
384
+ }
385
+ return button;
386
+ }),
387
+ messageParamsJson: JSON.stringify(messageParamsJson)
388
+ };
389
+ };
390
+ /** Media types that are valid at the top of an interactiveMessage header. */
391
+ export const hasValidInteractiveHeader = (message) => {
392
+ return !!(message.imageMessage ||
393
+ message.videoMessage ||
394
+ message.documentMessage ||
395
+ message.productMessage ||
396
+ message.locationMessage);
397
+ };
398
+ /**
399
+ * Determines whether a message needs a biz binary node on the outgoing stanza.
400
+ * Interactive shapes (buttons/list/template/native-flow) are rejected or
401
+ * rendered stripped without it.
402
+ */
403
+ export const shouldIncludeBizBinaryNode = (message) => {
404
+ return !!(message.buttonsMessage ||
405
+ message.listMessage ||
406
+ message.templateMessage ||
407
+ (message.interactiveMessage && message.interactiveMessage.nativeFlowMessage));
408
+ };
289
409
  export const generateWAMessageContent = async (message, options) => {
290
- var _a, _b;
291
410
  let m = {};
292
411
  if (hasNonNullishProperty(message, 'text')) {
293
412
  const extContent = { text: message.text };
@@ -447,31 +566,53 @@ export const generateWAMessageContent = async (message, options) => {
447
566
  m.eventMessage.location = message.event.location;
448
567
  }
449
568
  else if (hasNonNullishProperty(message, 'poll')) {
450
- (_a = message.poll).selectableCount || (_a.selectableCount = 0);
451
- (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
569
+ // `selectableOptionsCount` is the proto field name; `selectableCount` is the
570
+ // historic Baileys name. Accept both, with the proto name winning.
571
+ const selectableCount = message.poll.selectableOptionsCount ?? message.poll.selectableCount ?? 0;
572
+ const toAnnouncementGroup = message.poll.toAnnouncementGroup ?? false;
573
+ const pollType = message.poll.pollType ?? proto.Message.PollType.POLL;
452
574
  if (!Array.isArray(message.poll.values)) {
453
575
  throw new Boom('Invalid poll values', { statusCode: 400 });
454
576
  }
455
- if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
577
+ if (selectableCount < 0 || selectableCount > message.poll.values.length) {
456
578
  throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
457
579
  statusCode: 400
458
580
  });
459
581
  }
582
+ if (pollType === proto.Message.PollType.QUIZ) {
583
+ if (selectableCount !== 1) {
584
+ throw new Boom('quiz polls must allow exactly one selection', { statusCode: 400 });
585
+ }
586
+ if (!message.poll.correctAnswer) {
587
+ throw new Boom('quiz polls need a correctAnswer', { statusCode: 400 });
588
+ }
589
+ if (!message.poll.values.includes(message.poll.correctAnswer)) {
590
+ throw new Boom('quiz correctAnswer must be one of the poll values', { statusCode: 400 });
591
+ }
592
+ }
593
+ if (message.poll.endTime !== undefined && message.poll.endTime <= Date.now() / 1000) {
594
+ throw new Boom('poll endTime must be in the future', { statusCode: 400 });
595
+ }
460
596
  m.messageContextInfo = {
461
597
  // encKey
462
598
  messageSecret: message.poll.messageSecret || randomBytes(32)
463
599
  };
464
600
  const pollCreationMessage = {
465
601
  name: message.poll.name,
466
- selectableOptionsCount: message.poll.selectableCount,
467
- options: message.poll.values.map(optionName => ({ optionName }))
602
+ selectableOptionsCount: selectableCount,
603
+ options: message.poll.values.map(optionName => ({ optionName })),
604
+ pollType,
605
+ correctAnswer: message.poll.correctAnswer ? { optionName: message.poll.correctAnswer } : undefined,
606
+ endTime: message.poll.endTime,
607
+ hideParticipantName: message.poll.hideParticipantName,
608
+ allowAddOption: message.poll.allowAddOption
468
609
  };
469
- if (message.poll.toAnnouncementGroup) {
610
+ if (toAnnouncementGroup) {
470
611
  // poll v2 is for community announcement groups (single select and multiple)
471
612
  m.pollCreationMessageV2 = pollCreationMessage;
472
613
  }
473
614
  else {
474
- if (message.poll.selectableCount === 1) {
615
+ if (selectableCount === 1) {
475
616
  //poll v3 is for single select polls
476
617
  m.pollCreationMessageV3 = pollCreationMessage;
477
618
  }
@@ -481,6 +622,30 @@ export const generateWAMessageContent = async (message, options) => {
481
622
  }
482
623
  }
483
624
  }
625
+ else if (hasNonNullishProperty(message, 'pollAddOption')) {
626
+ // Add one option to an existing poll. The option hash is the same SHA-256
627
+ // of the option name the vote aggregation uses to match votes to options.
628
+ if (!message.pollAddOption.option) {
629
+ throw new Boom('pollAddOption needs an option', { statusCode: 400 });
630
+ }
631
+ m.pollAddOptionMessage = {
632
+ pollCreationMessageKey: message.pollAddOption.pollCreationMessageKey,
633
+ addOption: {
634
+ optionName: message.pollAddOption.option,
635
+ optionHash: sha256(Buffer.from(message.pollAddOption.option)).toString()
636
+ }
637
+ };
638
+ }
639
+ else if (hasNonNullishProperty(message, 'pollUpdateMessage')) {
640
+ // Manual poll vote update, with a pre-encrypted vote. Voting is usually
641
+ // handled internally; this is the raw passthrough for callers that
642
+ // encrypted the vote themselves.
643
+ m.pollUpdateMessage = message.pollUpdateMessage;
644
+ }
645
+ else if (hasNonNullishProperty(message, 'pollAddOptionMessage')) {
646
+ // Raw poll add-option message, with a pre-built option.
647
+ m.pollAddOptionMessage = message.pollAddOptionMessage;
648
+ }
484
649
  else if (hasNonNullishProperty(message, 'album')) {
485
650
  m.albumMessage = {
486
651
  expectedImageCount: message.album.expectedImageCount,
@@ -509,7 +674,98 @@ export const generateWAMessageContent = async (message, options) => {
509
674
  else {
510
675
  m = await prepareWAMessageMedia(message, options);
511
676
  }
512
- if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
677
+ // Interactive messages: native-flow buttons wrap the content built above
678
+ // (a text body, or a prepared media header). `interactiveButtons` is the
679
+ // gifted-btns-style alias for `nativeFlow`. This is a second stage, not
680
+ // another branch of the chain above: `{ text, nativeFlow }` must reach
681
+ // here, and the text branch above would swallow it first.
682
+ if ('nativeFlow' in message || 'interactiveButtons' in message) {
683
+ const flowButtons = message.nativeFlow ?? message.interactiveButtons;
684
+ if (!flowButtons) {
685
+ throw new Boom('nativeFlow buttons are required', { statusCode: 400 });
686
+ }
687
+ const flowMessage = { ...message, nativeFlow: flowButtons };
688
+ const interactiveMessage = {
689
+ nativeFlowMessage: prepareNativeFlowButtons(flowMessage)
690
+ };
691
+ if (hasOptionalProperty(message, 'bizJid')) {
692
+ interactiveMessage.collectionMessage = {
693
+ bizJid: message.bizJid,
694
+ id: message.id,
695
+ messageVersion: 1
696
+ };
697
+ }
698
+ else if (hasOptionalProperty(message, 'shopSurface')) {
699
+ interactiveMessage.shopStorefrontMessage = {
700
+ surface: message.shopSurface,
701
+ id: message.id,
702
+ messageVersion: 1
703
+ };
704
+ }
705
+ if (hasOptionalProperty(message, 'text')) {
706
+ interactiveMessage.body = { text: message.text };
707
+ }
708
+ else {
709
+ if (hasOptionalProperty(message, 'caption')) {
710
+ const isValidHeader = hasValidInteractiveHeader(m);
711
+ if (!isValidHeader) {
712
+ throw new Boom('Invalid media type for interactive message header', { statusCode: 400 });
713
+ }
714
+ interactiveMessage.header = {
715
+ title: message.title || '',
716
+ subtitle: message.subtitle || '',
717
+ hasMediaAttachment: isValidHeader
718
+ };
719
+ interactiveMessage.body = { text: message.caption };
720
+ }
721
+ // NOTE: the reference also sets interactiveMessage.jpegThumbnail
722
+ // from message.thumbnail, but neither proto defines that field on
723
+ // InteractiveMessage, so it is dropped on encode — omitted here.
724
+ if (interactiveMessage.header) {
725
+ Object.assign(interactiveMessage.header, m);
726
+ }
727
+ }
728
+ if (hasOptionalProperty(message, 'audioFooter')) {
729
+ const { audioMessage } = await prepareWAMessageMedia({ audio: message.audioFooter }, options);
730
+ interactiveMessage.footer = {
731
+ audioMessage,
732
+ hasMediaAttachment: true
733
+ };
734
+ }
735
+ else if (hasOptionalProperty(message, 'footer')) {
736
+ interactiveMessage.footer = { text: message.footer };
737
+ }
738
+ m = { interactiveMessage };
739
+ }
740
+ // View-once text (and media) in the V2 envelope: the official client sends
741
+ // viewOnceMessageV2 — or the voice-note-capable viewOnceMessageV2Extension —
742
+ // with the viewOnce flag on the inner message itself. The old v1 envelope is
743
+ // kept for plain `viewOnce`, which predates view-once text.
744
+ if ((hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) ||
745
+ (hasOptionalProperty(message, 'viewOnceV2Extension') && !!message.viewOnceV2Extension)) {
746
+ if (m.extendedTextMessage) {
747
+ m.extendedTextMessage.viewOnce = true;
748
+ }
749
+ else if (m.imageMessage) {
750
+ m.imageMessage.viewOnce = true;
751
+ }
752
+ else if (m.videoMessage) {
753
+ m.videoMessage.viewOnce = true;
754
+ }
755
+ else if (m.ptvMessage) {
756
+ m.ptvMessage.viewOnce = true;
757
+ }
758
+ else if (m.audioMessage) {
759
+ m.audioMessage.viewOnce = true;
760
+ }
761
+ if (hasOptionalProperty(message, 'viewOnceV2') && !!message.viewOnceV2) {
762
+ m = { viewOnceMessageV2: { message: m } };
763
+ }
764
+ else {
765
+ m = { viewOnceMessageV2Extension: { message: m } };
766
+ }
767
+ }
768
+ else if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
513
769
  m = { viewOnceMessage: { message: m } };
514
770
  }
515
771
  if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
@@ -681,6 +937,69 @@ export const normalizeMessageContent = (content) => {
681
937
  message?.groupStatusMessageV2);
682
938
  }
683
939
  };
940
+ /**
941
+ * Whether the outgoing content is view once media (image, video, round video or audio).
942
+ * WA Web tags these sends with a `<meta view_once="true"/>` stanza node.
943
+ * Looks through a disappearing message wrapper. View once wrappers around
944
+ * anything else (e.g. buttons wrapped so they render) don't count.
945
+ */
946
+ export const isViewOnceMessage = (content) => {
947
+ const inner = content?.ephemeralMessage?.message ?? content;
948
+ const wrapped = (inner?.viewOnceMessage || inner?.viewOnceMessageV2 || inner?.viewOnceMessageV2Extension)?.message;
949
+ return !!(wrapped?.imageMessage || wrapped?.videoMessage || wrapped?.ptvMessage || wrapped?.audioMessage);
950
+ };
951
+ const VIEW_ONCE_MEDIA = {
952
+ imageMessage: 'image',
953
+ videoMessage: 'video',
954
+ audioMessage: 'audio',
955
+ documentMessage: 'document',
956
+ ptvMessage: 'ptv'
957
+ };
958
+ /**
959
+ * Unwrap a message down to view once media, if it carries any.
960
+ *
961
+ * Peels disappearing-message wrappers and view once wrappers (V1, V2 and
962
+ * V2Extension, nested up to 5 deep) plus documentWithCaptionMessage, then
963
+ * returns the inner media message. Unlike `isViewOnceMessage` — which only
964
+ * looks one disappearing layer deep and only counts image/video/round-video/
965
+ * audio, because it drives the `<meta view_once>` tag on sends — this also
966
+ * counts document view once, and a bare media message carrying the `viewOnce`
967
+ * flag itself (e.g. a copy restored from a store, where the wrapper was
968
+ * already stripped).
969
+ *
970
+ * Returns undefined when the content holds no media at all.
971
+ */
972
+ export const extractViewOnceMedia = (content) => {
973
+ if (!content) {
974
+ return undefined;
975
+ }
976
+ // did the content arrive inside a view once wrapper at any depth?
977
+ const seenWrapper = (node, depth = 0) => {
978
+ if (!node || depth > 5) {
979
+ return false;
980
+ }
981
+ if (node.viewOnceMessage?.message || node.viewOnceMessageV2?.message || node.viewOnceMessageV2Extension?.message) {
982
+ return true;
983
+ }
984
+ return seenWrapper(node.ephemeralMessage?.message, depth + 1);
985
+ };
986
+ const wrapped = seenWrapper(content);
987
+ const inner = normalizeMessageContent(content);
988
+ if (!inner) {
989
+ return undefined;
990
+ }
991
+ const innerType = getContentType(inner);
992
+ if (!innerType) {
993
+ return undefined;
994
+ }
995
+ const mediaType = VIEW_ONCE_MEDIA[innerType];
996
+ if (!mediaType) {
997
+ return undefined;
998
+ }
999
+ const media = inner[innerType];
1000
+ const isViewOnce = wrapped || media?.viewOnce === true;
1001
+ return { media, mediaType, isViewOnce };
1002
+ };
684
1003
  /**
685
1004
  * Extract the true message content from a message
686
1005
  * Eg. extracts the inner message from a disappearing message/view once message
@@ -848,14 +1167,58 @@ export const aggregateMessageKeysNotFromMe = (keys) => {
848
1167
  return Object.values(keyMap);
849
1168
  };
850
1169
  const REUPLOAD_REQUIRED_STATUS = [410, 404];
1170
+ /**
1171
+ * When a media link's signature expires, in ms: its `oe` query parameter, in hex unix seconds.
1172
+ * Undefined unless the query carries exactly one `oe` and it is plain hex.
1173
+ */
1174
+ const mediaLinkExpiry = (link) => {
1175
+ let values;
1176
+ try {
1177
+ // a directPath has no host; the base only makes it parseable
1178
+ values = new URL(link, 'https://mmg.whatsapp.net').searchParams.getAll('oe');
1179
+ }
1180
+ catch {
1181
+ return undefined;
1182
+ }
1183
+ const [oe] = values;
1184
+ if (values.length !== 1 || !oe || !/^[0-9a-f]+$/i.test(oe)) {
1185
+ return undefined;
1186
+ }
1187
+ const expiry = parseInt(oe, 16) * 1000;
1188
+ return Number.isSafeInteger(expiry) ? expiry : undefined;
1189
+ };
1190
+ /**
1191
+ * Whether a 403 is worth a reupload: the link that failed carries an `oe` that has passed.
1192
+ * A conservative heuristic, not a documented contract: in a sample of 84 history-sync
1193
+ * downloads the media CDN answered 403 for all 34 links whose `oe` had passed and for none
1194
+ * of the 50 whose `oe` had not. It reads the local clock, so a clock that is off moves the line.
1195
+ * The link is the url getHttpStream reports on its error, or else the one
1196
+ * downloadContentFromMessage requests: the directPath when there is one, else the url.
1197
+ */
1198
+ const isExpiredLinkError = (error, message) => {
1199
+ let link = error?.data?.url;
1200
+ if (typeof link !== 'string' && !(link instanceof URL)) {
1201
+ const content = extractMessageContent(message.message);
1202
+ const contentType = content ? getContentType(content) : undefined;
1203
+ const media = (contentType && content?.[contentType]);
1204
+ link = media?.directPath || media?.url;
1205
+ }
1206
+ if (!link) {
1207
+ return false;
1208
+ }
1209
+ const expiry = mediaLinkExpiry(link.toString());
1210
+ return expiry !== undefined && expiry <= Date.now();
1211
+ };
851
1212
  /**
852
1213
  * Downloads the given message. Throws an error if it's not a media message
853
1214
  */
854
1215
  export const downloadMediaMessage = async (message, type, options, ctx) => {
855
1216
  const result = await downloadMsg().catch(async (error) => {
856
- if (ctx &&
857
- typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
858
- REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
1217
+ // the media download throws a Boom, which carries the HTTP status on output.statusCode, not on status
1218
+ const status = error?.output?.statusCode ?? error?.status;
1219
+ const expired = typeof status === 'number' &&
1220
+ (REUPLOAD_REQUIRED_STATUS.includes(status) || (status === 403 && isExpiredLinkError(error, message)));
1221
+ if (ctx && expired) {
859
1222
  ctx.logger.info({ key: message.key }, 'sending reupload media request...');
860
1223
  // request reupload
861
1224
  message = await ctx.reuploadRequest(message);
@@ -898,6 +1261,42 @@ export const downloadMediaMessage = async (message, type, options, ctx) => {
898
1261
  return stream;
899
1262
  }
900
1263
  };
1264
+ /**
1265
+ * Download a view once photo/video/voice note/document/round video.
1266
+ *
1267
+ * This is the one-call path bots need for view once recovery: it unwraps the
1268
+ * message, checks it really is view once media, and downloads it. It closes
1269
+ * two gaps over `downloadMediaMessage` alone:
1270
+ *
1271
+ * - a view once that arrived with a media key but no URL/directPath (the
1272
+ * sender's device has not served the file yet) is re-requested first via
1273
+ * `ctx.reuploadRequest` — `downloadMediaMessage` throws before it can
1274
+ * reupload when there is no URL at all, so without this the media is
1275
+ * unrecoverable even though the sender could still serve it.
1276
+ * - the view once check itself: `isViewOnceMessage` is the send-path check
1277
+ * (one disappearing layer, no documents), so recovery uses the wider
1278
+ * `extractViewOnceMedia` instead.
1279
+ *
1280
+ * Throws a Boom (400) when the message is not view once media, or when it
1281
+ * has no download URL and no `reuploadRequest` was supplied to ask the
1282
+ * sender's device to re-serve it. Expired links are still handled by
1283
+ * `downloadMediaMessage` itself, which reuploads and retries.
1284
+ */
1285
+ export const downloadViewOnceMessage = async (message, type, options, ctx) => {
1286
+ const extracted = extractViewOnceMedia(message.message);
1287
+ if (!extracted?.isViewOnce) {
1288
+ throw new Boom('message is not a view once media message', { statusCode: 400, data: message });
1289
+ }
1290
+ const { media } = extracted;
1291
+ if (!media.url && !media.directPath) {
1292
+ if (!media.mediaKey || !ctx?.reuploadRequest) {
1293
+ throw new Boom('view once media has no download URL; pass reuploadRequest (sock.updateMediaMessage) to ask the sender to re-serve it', { statusCode: 400, data: message });
1294
+ }
1295
+ ctx.logger.info({ key: message.key }, 'view once media has no URL, requesting re-upload...');
1296
+ message = await ctx.reuploadRequest(message);
1297
+ }
1298
+ return downloadMediaMessage(message, type, options, ctx);
1299
+ };
901
1300
  /** Checks whether the given message is a media message; if it is returns the inner content */
902
1301
  export const assertMediaContent = (content) => {
903
1302
  content = extractMessageContent(content);