@alannxd/baileys 6.0.5 → 6.0.6

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 (234) hide show
  1. package/WAProto/fix-import.js +29 -0
  2. package/WAProto/index.js +160 -201
  3. package/engine-requirements.js +1 -1
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +15 -37
  6. package/lib/Defaults/index.js +136 -119
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +0 -1
  9. package/lib/Signal/Group/ciphertext-message.js +5 -2
  10. package/lib/Signal/Group/group-session-builder.d.ts +3 -4
  11. package/lib/Signal/Group/group-session-builder.js +41 -7
  12. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  13. package/lib/Signal/Group/group_cipher.js +51 -37
  14. package/lib/Signal/Group/index.d.ts +11 -12
  15. package/lib/Signal/Group/index.js +57 -12
  16. package/lib/Signal/Group/keyhelper.d.ts +1 -2
  17. package/lib/Signal/Group/keyhelper.js +44 -7
  18. package/lib/Signal/Group/queue-job.d.ts +1 -0
  19. package/lib/Signal/Group/queue-job.js +57 -0
  20. package/lib/Signal/Group/sender-chain-key.d.ts +2 -3
  21. package/lib/Signal/Group/sender-chain-key.js +15 -7
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -2
  23. package/lib/Signal/Group/sender-key-distribution-message.js +11 -8
  24. package/lib/Signal/Group/sender-key-message.d.ts +1 -2
  25. package/lib/Signal/Group/sender-key-message.js +12 -9
  26. package/lib/Signal/Group/sender-key-name.d.ts +0 -1
  27. package/lib/Signal/Group/sender-key-name.js +5 -2
  28. package/lib/Signal/Group/sender-key-record.d.ts +2 -3
  29. package/lib/Signal/Group/sender-key-record.js +21 -9
  30. package/lib/Signal/Group/sender-key-state.d.ts +6 -7
  31. package/lib/Signal/Group/sender-key-state.js +42 -27
  32. package/lib/Signal/Group/sender-message-key.d.ts +0 -1
  33. package/lib/Signal/Group/sender-message-key.js +7 -4
  34. package/lib/Signal/libsignal.d.ts +3 -5
  35. package/lib/Signal/libsignal.js +90 -347
  36. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +5 -4
  37. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  38. package/lib/Socket/Client/index.d.ts +3 -3
  39. package/lib/Socket/Client/index.js +19 -3
  40. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  41. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  42. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +2 -3
  43. package/lib/Socket/Client/web-socket-client.js +62 -0
  44. package/lib/Socket/business.d.ts +108 -154
  45. package/lib/Socket/business.js +43 -162
  46. package/lib/Socket/chats.d.ts +239 -96
  47. package/lib/Socket/chats.js +427 -627
  48. package/lib/Socket/communities.d.ts +146 -239
  49. package/lib/Socket/communities.js +80 -90
  50. package/lib/Socket/groups.d.ts +57 -104
  51. package/lib/Socket/groups.js +161 -154
  52. package/lib/Socket/index.d.ts +115 -202
  53. package/lib/Socket/index.js +10 -11
  54. package/lib/Socket/luxu.d.ts +266 -22
  55. package/lib/Socket/luxu.js +465 -422
  56. package/lib/Socket/messages-recv.d.ts +84 -136
  57. package/lib/Socket/messages-recv.js +615 -1421
  58. package/lib/Socket/messages-send.d.ts +126 -142
  59. package/lib/Socket/messages-send.js +671 -878
  60. package/lib/Socket/newsletter.d.ts +85 -121
  61. package/lib/Socket/newsletter.js +272 -147
  62. package/lib/Socket/registration.d.ts +267 -0
  63. package/lib/Socket/registration.js +166 -0
  64. package/lib/Socket/socket.d.ts +19 -34
  65. package/lib/Socket/socket.js +313 -544
  66. package/lib/Socket/usync.d.ts +36 -0
  67. package/lib/Socket/usync.js +70 -0
  68. package/lib/Store/index.d.ts +3 -10
  69. package/lib/Store/index.js +10 -10
  70. package/lib/Store/make-cache-manager-store.d.ts +11 -17
  71. package/lib/Store/make-cache-manager-store.js +41 -43
  72. package/lib/Store/make-in-memory-store.d.ts +118 -39
  73. package/lib/Store/make-in-memory-store.js +341 -112
  74. package/lib/Store/make-ordered-dictionary.d.ts +10 -11
  75. package/lib/Store/make-ordered-dictionary.js +20 -14
  76. package/lib/Store/object-repository.d.ts +9 -10
  77. package/lib/Store/object-repository.js +6 -11
  78. package/lib/Types/Auth.d.ts +12 -19
  79. package/lib/Types/Auth.js +2 -2
  80. package/lib/Types/Call.d.ts +1 -3
  81. package/lib/Types/Call.js +2 -2
  82. package/lib/Types/Chat.d.ts +13 -35
  83. package/lib/Types/Chat.js +4 -8
  84. package/lib/Types/Contact.d.ts +1 -8
  85. package/lib/Types/Contact.js +2 -2
  86. package/lib/Types/Events.d.ts +17 -116
  87. package/lib/Types/Events.js +2 -2
  88. package/lib/Types/GroupMetadata.d.ts +5 -21
  89. package/lib/Types/GroupMetadata.js +2 -2
  90. package/lib/Types/Label.d.ts +0 -12
  91. package/lib/Types/Label.js +5 -3
  92. package/lib/Types/LabelAssociation.d.ts +0 -1
  93. package/lib/Types/LabelAssociation.js +5 -3
  94. package/lib/Types/Message.d.ts +58 -105
  95. package/lib/Types/Message.js +9 -11
  96. package/lib/Types/Newsletter.d.ts +103 -0
  97. package/lib/Types/Newsletter.js +38 -0
  98. package/lib/Types/Product.d.ts +1 -2
  99. package/lib/Types/Product.js +2 -2
  100. package/lib/Types/Signal.d.ts +2 -32
  101. package/lib/Types/Signal.js +2 -2
  102. package/lib/Types/Socket.d.ts +25 -50
  103. package/lib/Types/Socket.js +2 -3
  104. package/lib/Types/State.d.ts +2 -72
  105. package/lib/Types/State.js +2 -56
  106. package/lib/Types/USync.d.ts +2 -3
  107. package/lib/Types/USync.js +2 -2
  108. package/lib/Types/index.d.ts +14 -22
  109. package/lib/Types/index.js +31 -15
  110. package/lib/Utils/auth-utils.d.ts +6 -12
  111. package/lib/Utils/auth-utils.js +143 -239
  112. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  113. package/lib/Utils/baileys-event-stream.js +63 -0
  114. package/lib/Utils/business.d.ts +2 -3
  115. package/lib/Utils/business.js +69 -66
  116. package/lib/Utils/chat-utils.d.ts +23 -52
  117. package/lib/Utils/chat-utils.js +253 -396
  118. package/lib/Utils/crypto.d.ts +22 -18
  119. package/lib/Utils/crypto.js +90 -57
  120. package/lib/Utils/decode-wa-message.d.ts +8 -55
  121. package/lib/Utils/decode-wa-message.js +84 -203
  122. package/lib/Utils/event-buffer.d.ts +8 -9
  123. package/lib/Utils/event-buffer.js +77 -185
  124. package/lib/Utils/generics.d.ts +29 -28
  125. package/lib/Utils/generics.js +210 -180
  126. package/lib/Utils/history.d.ts +9 -18
  127. package/lib/Utils/history.js +55 -93
  128. package/lib/Utils/index.d.ts +17 -22
  129. package/lib/Utils/index.js +33 -22
  130. package/lib/Utils/link-preview.d.ts +5 -5
  131. package/lib/Utils/link-preview.js +24 -16
  132. package/lib/Utils/logger.d.ts +3 -11
  133. package/lib/Utils/logger.js +7 -3
  134. package/lib/Utils/lt-hash.d.ts +12 -8
  135. package/lib/Utils/lt-hash.js +46 -3
  136. package/lib/Utils/make-mutex.d.ts +2 -4
  137. package/lib/Utils/make-mutex.js +34 -24
  138. package/lib/Utils/messages-media.d.ts +44 -61
  139. package/lib/Utils/messages-media.js +482 -451
  140. package/lib/Utils/messages.d.ts +18 -32
  141. package/lib/Utils/messages.js +369 -458
  142. package/lib/Utils/noise-handler.d.ts +14 -13
  143. package/lib/Utils/noise-handler.js +99 -145
  144. package/lib/Utils/process-message.d.ts +12 -31
  145. package/lib/Utils/process-message.js +150 -459
  146. package/lib/Utils/signal.d.ts +5 -20
  147. package/lib/Utils/signal.js +72 -120
  148. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  149. package/lib/Utils/use-multi-file-auth-state.js +27 -29
  150. package/lib/Utils/validate-connection.d.ts +7 -7
  151. package/lib/Utils/validate-connection.js +99 -73
  152. package/lib/WABinary/constants.d.ts +27 -25
  153. package/lib/WABinary/constants.js +20 -1281
  154. package/lib/WABinary/decode.d.ts +5 -5
  155. package/lib/WABinary/decode.js +42 -52
  156. package/lib/WABinary/encode.d.ts +3 -3
  157. package/lib/WABinary/encode.js +155 -110
  158. package/lib/WABinary/generic-utils.d.ts +7 -8
  159. package/lib/WABinary/generic-utils.js +49 -48
  160. package/lib/WABinary/index.d.ts +5 -6
  161. package/lib/WABinary/index.js +21 -6
  162. package/lib/WABinary/jid-utils.d.ts +8 -25
  163. package/lib/WABinary/jid-utils.js +40 -74
  164. package/lib/WABinary/types.d.ts +1 -2
  165. package/lib/WABinary/types.js +2 -2
  166. package/lib/WAM/BinaryInfo.d.ts +11 -3
  167. package/lib/WAM/BinaryInfo.js +5 -2
  168. package/lib/WAM/constants.d.ts +3 -5
  169. package/lib/WAM/constants.js +11958 -19461
  170. package/lib/WAM/encode.d.ts +3 -3
  171. package/lib/WAM/encode.js +22 -17
  172. package/lib/WAM/index.d.ts +3 -4
  173. package/lib/WAM/index.js +19 -4
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  175. package/lib/WAUSync/Protocols/USyncContactProtocol.js +13 -33
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  177. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  179. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  181. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  183. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  185. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  186. package/lib/WAUSync/Protocols/index.d.ts +4 -6
  187. package/lib/WAUSync/Protocols/index.js +20 -6
  188. package/lib/WAUSync/USyncQuery.d.ts +4 -6
  189. package/lib/WAUSync/USyncQuery.js +35 -44
  190. package/lib/WAUSync/USyncUser.d.ts +5 -10
  191. package/lib/WAUSync/USyncUser.js +5 -10
  192. package/lib/WAUSync/index.js +19 -4
  193. package/lib/index.d.ts +9 -10
  194. package/lib/index.js +34 -12
  195. package/package.json +50 -83
  196. package/WAProto/GenerateStatics.sh +0 -3
  197. package/WAProto/WAProto.proto +0 -5479
  198. package/WAProto/fix-imports.js +0 -85
  199. package/WAProto/index.d.ts +0 -14017
  200. package/lib/Signal/lid-mapping.d.ts +0 -23
  201. package/lib/Signal/lid-mapping.js +0 -277
  202. package/lib/Socket/Client/types.js +0 -11
  203. package/lib/Socket/Client/websocket.js +0 -54
  204. package/lib/Socket/mex.d.ts +0 -3
  205. package/lib/Socket/mex.js +0 -42
  206. package/lib/Store/keyed-db.d.ts +0 -22
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Types/Bussines.d.ts +0 -25
  209. package/lib/Types/Bussines.js +0 -2
  210. package/lib/Types/Mex.d.ts +0 -141
  211. package/lib/Types/Mex.js +0 -37
  212. package/lib/Utils/browser-utils.d.ts +0 -4
  213. package/lib/Utils/browser-utils.js +0 -28
  214. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  215. package/lib/Utils/companion-reg-client-utils.js +0 -35
  216. package/lib/Utils/identity-change-handler.d.ts +0 -44
  217. package/lib/Utils/identity-change-handler.js +0 -50
  218. package/lib/Utils/message-retry-manager.d.ts +0 -115
  219. package/lib/Utils/message-retry-manager.js +0 -265
  220. package/lib/Utils/offline-node-processor.d.ts +0 -17
  221. package/lib/Utils/offline-node-processor.js +0 -40
  222. package/lib/Utils/pre-key-manager.d.ts +0 -28
  223. package/lib/Utils/pre-key-manager.js +0 -106
  224. package/lib/Utils/reporting-utils.d.ts +0 -11
  225. package/lib/Utils/reporting-utils.js +0 -258
  226. package/lib/Utils/stanza-ack.d.ts +0 -11
  227. package/lib/Utils/stanza-ack.js +0 -38
  228. package/lib/Utils/sync-action-utils.d.ts +0 -19
  229. package/lib/Utils/sync-action-utils.js +0 -49
  230. package/lib/Utils/tc-token-utils.d.ts +0 -37
  231. package/lib/Utils/tc-token-utils.js +0 -163
  232. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  233. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  234. package/lib/WAUSync/index.d.ts +0 -4
@@ -1,50 +1,56 @@
1
- import { Boom } from '@hapi/boom';
2
- import { randomBytes } from 'crypto';
3
- import { promises as fs } from 'fs';
4
- import {} from 'stream';
5
- import { proto } from '../../WAProto/index.js';
6
- import { CALL_AUDIO_PREFIX, CALL_VIDEO_PREFIX, MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
7
- import { WAMessageStatus, WAProto } from '../Types/index.js';
8
- import { isJidGroup, isJidNewsletter, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary/index.js';
9
- import { sha256 } from './crypto.js';
10
- import { generateMessageIDV2, getKeyAuthor, unixTimestampSeconds } from './generics.js';
11
- import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, getRawMediaUploadData } from './messages-media.js';
12
- import { shouldIncludeReportingToken } from './reporting-utils.js';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.assertMediaContent = exports.downloadMediaMessage = exports.aggregateMessageKeysNotFromMe = exports.getAggregateVotesInPollMessage = exports.updateMessageWithPollUpdate = exports.updateMessageWithReaction = exports.updateMessageWithReceipt = exports.getDevice = exports.extractMessageContent = exports.normalizeMessageContent = exports.getContentType = exports.generateWAMessage = exports.generateWAMessageFromContent = exports.generateWAMessageContent = exports.generateForwardMessageContent = exports.prepareDisappearingMessageSettingContent = exports.prepareWAMessageMedia = exports.generateLinkPreviewIfRequired = exports.extractUrlFromText = void 0;
7
+ const boom_1 = require("@hapi/boom");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const crypto_1 = require("crypto");
10
+ const fs_1 = require("fs");
11
+ const WAProto_1 = require("../../WAProto");
12
+ const Defaults_1 = require("../Defaults");
13
+ const Types_1 = require("../Types");
14
+ const WABinary_1 = require("../WABinary");
15
+ const crypto_2 = require("./crypto");
16
+ const generics_1 = require("./generics");
17
+ const messages_media_1 = require("./messages-media");
13
18
  const MIMETYPE_MAP = {
14
19
  image: 'image/jpeg',
15
20
  video: 'video/mp4',
16
21
  document: 'application/pdf',
17
22
  audio: 'audio/ogg; codecs=opus',
18
23
  sticker: 'image/webp',
19
- 'product-catalog-image': 'image/jpeg'
24
+ 'product-catalog-image': 'image/jpeg',
20
25
  };
21
26
  const MessageTypeProto = {
22
- image: WAProto.Message.ImageMessage,
23
- video: WAProto.Message.VideoMessage,
24
- audio: WAProto.Message.AudioMessage,
25
- sticker: WAProto.Message.StickerMessage,
26
- document: WAProto.Message.DocumentMessage
27
+ 'image': Types_1.WAProto.Message.ImageMessage,
28
+ 'video': Types_1.WAProto.Message.VideoMessage,
29
+ 'audio': Types_1.WAProto.Message.AudioMessage,
30
+ 'sticker': Types_1.WAProto.Message.StickerMessage,
31
+ 'document': Types_1.WAProto.Message.DocumentMessage,
27
32
  };
28
- const ButtonType = proto.Message.ButtonsMessage.HeaderType;
33
+ const ButtonType = WAProto_1.proto.Message.ButtonsMessage.HeaderType;
29
34
  /**
30
35
  * Uses a regex to test whether the string contains a URL, and returns the URL if it does.
31
36
  * @param text eg. hello https://google.com
32
37
  * @returns the URL, eg. https://google.com
33
38
  */
34
- export const extractUrlFromText = (text) => text.match(URL_REGEX)?.[0];
35
- export const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
36
- const url = extractUrlFromText(text);
39
+ const extractUrlFromText = (text) => { var _a; return (_a = text.match(Defaults_1.URL_REGEX)) === null || _a === void 0 ? void 0 : _a[0]; };
40
+ exports.extractUrlFromText = extractUrlFromText;
41
+ const generateLinkPreviewIfRequired = async (text, getUrlInfo, logger) => {
42
+ const url = (0, exports.extractUrlFromText)(text);
37
43
  if (!!getUrlInfo && url) {
38
44
  try {
39
45
  const urlInfo = await getUrlInfo(url);
40
46
  return urlInfo;
41
47
  }
42
- catch (error) {
43
- // ignore if fails
44
- logger?.warn({ trace: error.stack }, 'url generation failed');
48
+ catch (error) { // ignore if fails
49
+ logger === null || logger === void 0 ? void 0 : logger.warn({ trace: error.stack }, 'url generation failed');
45
50
  }
46
51
  }
47
52
  };
53
+ exports.generateLinkPreviewIfRequired = generateLinkPreviewIfRequired;
48
54
  const assertColor = async (color) => {
49
55
  let assertedColor;
50
56
  if (typeof color === 'number') {
@@ -59,150 +65,159 @@ const assertColor = async (color) => {
59
65
  return assertedColor;
60
66
  }
61
67
  };
62
- export const prepareWAMessageMedia = async (message, options) => {
68
+ const prepareWAMessageMedia = async (message, options) => {
63
69
  const logger = options.logger;
64
70
  let mediaType;
65
- for (const key of MEDIA_KEYS) {
71
+ for (const key of Defaults_1.MEDIA_KEYS) {
66
72
  if (key in message) {
67
73
  mediaType = key;
68
74
  }
69
75
  }
70
76
  if (!mediaType) {
71
- throw new Boom('Invalid media type', { statusCode: 400 });
77
+ throw new boom_1.Boom('Invalid media type', {
78
+ statusCode: 400
79
+ });
72
80
  }
81
+
73
82
  const uploadData = {
74
83
  ...message,
84
+ ...(message.annotations ? {
85
+ annotations: message.annotations
86
+ } : {
87
+ annotations: [
88
+ {
89
+ polygonVertices: [
90
+ {
91
+ x: 60.71664810180664,
92
+ y: -36.39784622192383
93
+ },
94
+ {
95
+ x: -16.710189819335938,
96
+ y: 49.263675689697266
97
+ },
98
+ {
99
+ x: -56.585853576660156,
100
+ y: 37.85963439941406
101
+ },
102
+ {
103
+ x: 20.840980529785156,
104
+ y: -47.80188751220703
105
+ }
106
+ ],
107
+ newsletter: {
108
+ newsletterJid: "120363420757607688@newsletter",
109
+ serverMessageId: 0,
110
+ newsletterName: "7eppeli - Information",
111
+ contentType: "UPDATE",
112
+ }
113
+ }
114
+ ]
115
+ }),
75
116
  media: message[mediaType]
76
117
  };
77
118
  delete uploadData[mediaType];
78
- // check if cacheable + generate cache key
79
119
  const cacheableKey = typeof uploadData.media === 'object' &&
80
- 'url' in uploadData.media &&
120
+ ('url' in uploadData.media) &&
81
121
  !!uploadData.media.url &&
82
- !!options.mediaCache &&
83
- mediaType + ':' + uploadData.media.url.toString();
122
+ !!options.mediaCache && (
123
+ mediaType + ':' + uploadData.media.url.toString());
124
+
84
125
  if (mediaType === 'document' && !uploadData.fileName) {
85
126
  uploadData.fileName = 'file';
86
127
  }
128
+
87
129
  if (!uploadData.mimetype) {
88
130
  uploadData.mimetype = MIMETYPE_MAP[mediaType];
89
131
  }
132
+
90
133
  if (cacheableKey) {
91
- const mediaBuff = await options.mediaCache.get(cacheableKey);
134
+ const mediaBuff = options.mediaCache.get(cacheableKey);
92
135
  if (mediaBuff) {
93
- logger?.debug({ cacheableKey }, 'got media cache hit');
94
- const obj = proto.Message.decode(mediaBuff);
136
+ logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'got media cache hit');
137
+ const obj = Types_1.WAProto.Message.decode(mediaBuff);
95
138
  const key = `${mediaType}Message`;
96
139
  Object.assign(obj[key], { ...uploadData, media: undefined });
97
140
  return obj;
98
141
  }
99
142
  }
100
- const isNewsletter = !!options.jid && isJidNewsletter(options.jid);
101
- if (isNewsletter) {
102
- logger?.info({ key: cacheableKey }, 'Preparing raw media for newsletter');
103
- const { filePath, fileSha256, fileLength } = await getRawMediaUploadData(uploadData.media, options.mediaTypeOverride || mediaType, logger);
104
- const fileSha256B64 = fileSha256.toString('base64');
105
- const { mediaUrl, directPath } = await options.upload(filePath, {
106
- fileEncSha256B64: fileSha256B64,
107
- mediaType: mediaType,
108
- timeoutMs: options.mediaUploadTimeoutMs
109
- });
110
- await fs.unlink(filePath);
111
- const obj = WAProto.Message.fromObject({
112
- // todo: add more support here
113
- [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
114
- url: mediaUrl,
115
- directPath,
116
- fileSha256,
117
- fileLength,
118
- ...uploadData,
119
- media: undefined
120
- })
121
- });
122
- if (uploadData.ptv) {
123
- obj.ptvMessage = obj.videoMessage;
124
- delete obj.videoMessage;
125
- }
126
- if (obj.stickerMessage) {
127
- obj.stickerMessage.stickerSentTs = Date.now();
128
- }
129
- if (cacheableKey) {
130
- logger?.debug({ cacheableKey }, 'set cache');
131
- await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
132
- }
133
- return obj;
134
- }
143
+
135
144
  const requiresDurationComputation = mediaType === 'audio' && typeof uploadData.seconds === 'undefined';
136
- const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') && typeof uploadData['jpegThumbnail'] === 'undefined';
137
- const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true && typeof uploadData.waveform === 'undefined';
145
+ const requiresThumbnailComputation = (mediaType === 'image' || mediaType === 'video') &&
146
+ (typeof uploadData['jpegThumbnail'] === 'undefined');
147
+ const requiresWaveformProcessing = mediaType === 'audio' && uploadData.ptt === true;
138
148
  const requiresAudioBackground = options.backgroundColor && mediaType === 'audio' && uploadData.ptt === true;
139
149
  const requiresOriginalForSomeProcessing = requiresDurationComputation || requiresThumbnailComputation;
140
- const { mediaKey, encFilePath, originalFilePath, fileEncSha256, fileSha256, fileLength } = await encryptedStream(uploadData.media, options.mediaTypeOverride || mediaType, {
150
+
151
+ const { mediaKey, encWriteStream, bodyPath, fileEncSha256, fileSha256, fileLength, didSaveToTmpPath, opusConverted } = await (options.newsletter ? messages_media_1.prepareStream : messages_media_1.encryptedStream)(uploadData.media, options.mediaTypeOverride || mediaType, {
141
152
  logger,
142
153
  saveOriginalFileIfRequired: requiresOriginalForSomeProcessing,
143
- opts: options.options
154
+ opts: options.options,
155
+ isPtt: uploadData.ptt,
156
+ forceOpus: (mediaType === "audio" && uploadData.mimetype && uploadData.mimetype.includes('opus'))
144
157
  });
145
- const fileEncSha256B64 = fileEncSha256.toString('base64');
146
- const [{ mediaUrl, directPath }] = await Promise.all([
158
+
159
+ if (mediaType === 'audio' && opusConverted) {
160
+ uploadData.mimetype = 'audio/ogg; codecs=opus';
161
+ }
162
+
163
+ const fileEncSha256B64 = (options.newsletter ? fileSha256 : fileEncSha256 !== null && fileEncSha256 !== void 0 ? fileEncSha256 : fileSha256).toString('base64');
164
+
165
+ const [{ mediaUrl, directPath, handle }] = await Promise.all([
147
166
  (async () => {
148
- const result = await options.upload(encFilePath, {
149
- fileEncSha256B64,
150
- mediaType,
151
- timeoutMs: options.mediaUploadTimeoutMs
152
- });
153
- logger?.debug({ mediaType, cacheableKey }, 'uploaded media');
167
+ const result = await options.upload(encWriteStream, { fileEncSha256B64, mediaType, timeoutMs: options.mediaUploadTimeoutMs });
168
+ logger === null || logger === void 0 ? void 0 : logger.debug({ mediaType, cacheableKey }, 'uploaded media');
154
169
  return result;
155
170
  })(),
156
171
  (async () => {
157
172
  try {
158
173
  if (requiresThumbnailComputation) {
159
- const { thumbnail, originalImageDimensions } = await generateThumbnail(originalFilePath, mediaType, options);
174
+ const { thumbnail, originalImageDimensions } = await (0, messages_media_1.generateThumbnail)(bodyPath, mediaType, options);
160
175
  uploadData.jpegThumbnail = thumbnail;
161
176
  if (!uploadData.width && originalImageDimensions) {
162
177
  uploadData.width = originalImageDimensions.width;
163
178
  uploadData.height = originalImageDimensions.height;
164
- logger?.debug('set dimensions');
179
+ logger === null || logger === void 0 ? void 0 : logger.debug('set dimensions');
165
180
  }
166
- logger?.debug('generated thumbnail');
181
+ logger === null || logger === void 0 ? void 0 : logger.debug('generated thumbnail');
167
182
  }
168
183
  if (requiresDurationComputation) {
169
- uploadData.seconds = await getAudioDuration(originalFilePath);
170
- logger?.debug('computed audio duration');
184
+ uploadData.seconds = await (0, messages_media_1.getAudioDuration)(bodyPath);
185
+ logger === null || logger === void 0 ? void 0 : logger.debug('computed audio duration');
171
186
  }
172
187
  if (requiresWaveformProcessing) {
173
- uploadData.waveform = await getAudioWaveform(originalFilePath, logger);
174
- logger?.debug('processed waveform');
188
+ uploadData.waveform = await (0, messages_media_1.getAudioWaveform)(bodyPath, logger);
189
+ logger === null || logger === void 0 ? void 0 : logger.debug('processed waveform');
175
190
  }
176
191
  if (requiresAudioBackground) {
177
192
  uploadData.backgroundArgb = await assertColor(options.backgroundColor);
178
- logger?.debug('computed backgroundColor audio status');
193
+ logger === null || logger === void 0 ? void 0 : logger.debug('computed backgroundColor audio status');
179
194
  }
180
195
  }
181
196
  catch (error) {
182
- logger?.warn({ trace: error.stack }, 'failed to obtain extra info');
197
+ logger === null || logger === void 0 ? void 0 : logger.warn({ trace: error.stack }, 'failed to obtain extra info');
183
198
  }
184
- })()
185
- ]).finally(async () => {
186
- try {
187
- await fs.unlink(encFilePath);
188
- if (originalFilePath) {
189
- await fs.unlink(originalFilePath);
190
- }
191
- logger?.debug('removed tmp files');
199
+ })(),
200
+ ])
201
+ .finally(async () => {
202
+ if (!Buffer.isBuffer(encWriteStream)) {
203
+ encWriteStream.destroy();
192
204
  }
193
- catch (error) {
194
- logger?.warn('failed to remove tmp file');
205
+
206
+ if (didSaveToTmpPath && bodyPath) {
207
+ await fs_1.promises.unlink(bodyPath);
208
+ logger === null || logger === void 0 ? void 0 : logger.debug('removed tmp files');
195
209
  }
196
210
  });
197
- const obj = WAProto.Message.fromObject({
211
+
212
+ const obj = Types_1.WAProto.Message.fromObject({
198
213
  [`${mediaType}Message`]: MessageTypeProto[mediaType].fromObject({
199
- url: mediaUrl,
214
+ url: handle ? undefined : mediaUrl,
200
215
  directPath,
201
- mediaKey,
202
- fileEncSha256,
216
+ mediaKey: mediaKey,
217
+ fileEncSha256: fileEncSha256,
203
218
  fileSha256,
204
219
  fileLength,
205
- mediaKeyTimestamp: unixTimestampSeconds(),
220
+ mediaKeyTimestamp: handle ? undefined : (0, generics_1.unixTimestampSeconds)(),
206
221
  ...uploadData,
207
222
  media: undefined
208
223
  })
@@ -211,76 +226,73 @@ export const prepareWAMessageMedia = async (message, options) => {
211
226
  obj.ptvMessage = obj.videoMessage;
212
227
  delete obj.videoMessage;
213
228
  }
229
+
214
230
  if (cacheableKey) {
215
- logger?.debug({ cacheableKey }, 'set cache');
216
- await options.mediaCache.set(cacheableKey, WAProto.Message.encode(obj).finish());
231
+ logger === null || logger === void 0 ? void 0 : logger.debug({ cacheableKey }, 'set cache');
232
+ options.mediaCache.set(cacheableKey, Types_1.WAProto.Message.encode(obj).finish());
217
233
  }
234
+
218
235
  return obj;
219
236
  };
220
- export const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
237
+ exports.prepareWAMessageMedia = prepareWAMessageMedia;
238
+ const prepareDisappearingMessageSettingContent = (ephemeralExpiration) => {
221
239
  ephemeralExpiration = ephemeralExpiration || 0;
222
240
  const content = {
223
241
  ephemeralMessage: {
224
242
  message: {
225
243
  protocolMessage: {
226
- type: WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
244
+ type: Types_1.WAProto.Message.ProtocolMessage.Type.EPHEMERAL_SETTING,
227
245
  ephemeralExpiration
228
246
  }
229
247
  }
230
248
  }
231
249
  };
232
- return WAProto.Message.fromObject(content);
250
+ return Types_1.WAProto.Message.fromObject(content);
233
251
  };
252
+ exports.prepareDisappearingMessageSettingContent = prepareDisappearingMessageSettingContent;
234
253
  /**
235
254
  * Generate forwarded message content like WA does
236
255
  * @param message the message to forward
237
256
  * @param options.forceForward will show the message as forwarded even if it is from you
238
257
  */
239
- export const generateForwardMessageContent = (message, forceForward) => {
258
+ const generateForwardMessageContent = (message, forceForward) => {
259
+ var _a;
240
260
  let content = message.message;
241
261
  if (!content) {
242
- throw new Boom('no content in message', { statusCode: 400 });
262
+ throw new boom_1.Boom('no content in message', { statusCode: 400 });
243
263
  }
244
264
  // hacky copy
245
- content = normalizeMessageContent(content);
246
- content = proto.Message.decode(proto.Message.encode(content).finish());
265
+ content = (0, exports.normalizeMessageContent)(content);
266
+ content = WAProto_1.proto.Message.decode(WAProto_1.proto.Message.encode(content).finish());
247
267
  let key = Object.keys(content)[0];
248
- let score = content?.[key]?.contextInfo?.forwardingScore || 0;
268
+ let score = ((_a = content[key].contextInfo) === null || _a === void 0 ? void 0 : _a.forwardingScore) || 0;
249
269
  score += message.key.fromMe && !forceForward ? 0 : 1;
250
270
  if (key === 'conversation') {
251
271
  content.extendedTextMessage = { text: content[key] };
252
272
  delete content.conversation;
253
273
  key = 'extendedTextMessage';
254
274
  }
255
- const key_ = content?.[key];
256
275
  if (score > 0) {
257
- key_.contextInfo = { forwardingScore: score, isForwarded: true };
276
+ content[key].contextInfo = { forwardingScore: score, isForwarded: true };
258
277
  }
259
278
  else {
260
- key_.contextInfo = {};
279
+ content[key].contextInfo = {};
261
280
  }
262
281
  return content;
263
282
  };
264
- export const hasNonNullishProperty = (message, key) => {
265
- return (typeof message === 'object' &&
266
- message !== null &&
267
- key in message &&
268
- message[key] !== null &&
269
- message[key] !== undefined);
270
- };
271
- function hasOptionalProperty(obj, key) {
272
- return typeof obj === 'object' && obj !== null && key in obj && obj[key] !== null;
273
- }
274
- export const generateWAMessageContent = async (message, options) => {
275
- var _a, _b;
283
+ exports.generateForwardMessageContent = generateForwardMessageContent;
284
+ const generateWAMessageContent = async (message, options) => {
285
+ var _a;
286
+ var _b;
276
287
  let m = {};
277
- if (hasNonNullishProperty(message, 'text')) {
288
+ if ('text' in message) {
278
289
  const extContent = { text: message.text };
279
290
  let urlInfo = message.linkPreview;
280
291
  if (typeof urlInfo === 'undefined') {
281
- urlInfo = await generateLinkPreviewIfRequired(message.text, options.getUrlInfo, options.logger);
292
+ urlInfo = await (0, exports.generateLinkPreviewIfRequired)(message.text, options.getUrlInfo, options.logger);
282
293
  }
283
294
  if (urlInfo) {
295
+ extContent.canonicalUrl = urlInfo['canonical-url'];
284
296
  extContent.matchedText = urlInfo['matched-text'];
285
297
  extContent.jpegThumbnail = urlInfo.jpegThumbnail;
286
298
  extContent.description = urlInfo.description;
@@ -305,296 +317,218 @@ export const generateWAMessageContent = async (message, options) => {
305
317
  }
306
318
  m.extendedTextMessage = extContent;
307
319
  }
308
- else if (hasNonNullishProperty(message, 'contacts')) {
320
+ else if ('contacts' in message) {
309
321
  const contactLen = message.contacts.contacts.length;
310
322
  if (!contactLen) {
311
- throw new Boom('require atleast 1 contact', { statusCode: 400 });
323
+ throw new boom_1.Boom('require atleast 1 contact', { statusCode: 400 });
312
324
  }
313
325
  if (contactLen === 1) {
314
- m.contactMessage = WAProto.Message.ContactMessage.create(message.contacts.contacts[0]);
326
+ m.contactMessage = Types_1.WAProto.Message.ContactMessage.fromObject(message.contacts.contacts[0]);
315
327
  }
316
328
  else {
317
- m.contactsArrayMessage = WAProto.Message.ContactsArrayMessage.create(message.contacts);
329
+ m.contactsArrayMessage = Types_1.WAProto.Message.ContactsArrayMessage.fromObject(message.contacts);
318
330
  }
319
331
  }
320
- else if (hasNonNullishProperty(message, 'buttons')) {
321
- const buttonsMessage = {
322
- buttons: message.buttons.map(b => ({ ...b, type: proto.Message.ButtonsMessage.Button.Type.RESPONSE }))
323
- };
324
- if ('text' in message) {
325
- buttonsMessage.contentText = message.text;
326
- buttonsMessage.headerType = ButtonType.EMPTY;
327
- }
328
- else {
329
- if ('caption' in message) {
330
- buttonsMessage.contentText = message.caption;
331
- }
332
- const contentType = getContentType(m);
333
- const type = contentType.replace('Message', '').toUpperCase();
334
- buttonsMessage.headerType = ButtonType[type];
335
- Object.assign(buttonsMessage, m);
336
- }
337
- if ('footer' in message && !!message.footer) {
338
- buttonsMessage.footerText = message.footer;
339
- }
340
- m = { buttonsMessage };
332
+ else if ('contact' in message) {
333
+ m.contactMessage = Types_1.WAProto.Message.ContactMessage.fromObject(message.contact);
341
334
  }
342
- else if (hasNonNullishProperty(message, 'location')) {
343
- m.locationMessage = WAProto.Message.LocationMessage.create(message.location);
335
+ else if ('location' in message) {
336
+ m.locationMessage = Types_1.WAProto.Message.LocationMessage.fromObject(message.location);
344
337
  }
345
- else if (hasNonNullishProperty(message, 'react')) {
338
+ else if ('react' in message) {
346
339
  if (!message.react.senderTimestampMs) {
347
340
  message.react.senderTimestampMs = Date.now();
348
341
  }
349
- m.reactionMessage = WAProto.Message.ReactionMessage.create(message.react);
342
+ m.reactionMessage = Types_1.WAProto.Message.ReactionMessage.fromObject(message.react);
350
343
  }
351
- else if (hasNonNullishProperty(message, 'delete')) {
344
+ else if ('delete' in message) {
352
345
  m.protocolMessage = {
353
346
  key: message.delete,
354
- type: WAProto.Message.ProtocolMessage.Type.REVOKE
347
+ type: Types_1.WAProto.Message.ProtocolMessage.Type.REVOKE
355
348
  };
356
349
  }
357
- else if (hasNonNullishProperty(message, 'forward')) {
358
- m = generateForwardMessageContent(message.forward, message.force);
359
- }
360
- else if (hasNonNullishProperty(message, 'disappearingMessagesInChat')) {
361
- const exp = typeof message.disappearingMessagesInChat === 'boolean'
362
- ? message.disappearingMessagesInChat
363
- ? WA_DEFAULT_EPHEMERAL
364
- : 0
365
- : message.disappearingMessagesInChat;
366
- m = prepareDisappearingMessageSettingContent(exp);
367
- }
368
- else if (hasNonNullishProperty(message, 'groupInvite')) {
369
- m.groupInviteMessage = {};
370
- m.groupInviteMessage.inviteCode = message.groupInvite.inviteCode;
371
- m.groupInviteMessage.inviteExpiration = message.groupInvite.inviteExpiration;
372
- m.groupInviteMessage.caption = message.groupInvite.text;
373
- m.groupInviteMessage.groupJid = message.groupInvite.jid;
374
- m.groupInviteMessage.groupName = message.groupInvite.subject;
375
- //TODO: use built-in interface and get disappearing mode info etc.
376
- //TODO: cache / use store!?
377
- if (options.getProfilePicUrl) {
378
- const pfpUrl = await options.getProfilePicUrl(message.groupInvite.jid, 'preview');
379
- if (pfpUrl) {
380
- const resp = await fetch(pfpUrl, { method: 'GET', dispatcher: options?.options?.dispatcher });
381
- if (resp.ok) {
382
- const buf = Buffer.from(await resp.arrayBuffer());
383
- m.groupInviteMessage.jpegThumbnail = buf;
384
- }
385
- }
386
- }
350
+ else if ('forward' in message) {
351
+ m = (0, exports.generateForwardMessageContent)(message.forward, message.force);
387
352
  }
388
- else if (hasNonNullishProperty(message, 'pin')) {
389
- m.pinInChatMessage = {};
390
- m.messageContextInfo = {};
391
- m.pinInChatMessage.key = message.pin;
392
- m.pinInChatMessage.type = message.type;
393
- m.pinInChatMessage.senderTimestampMs = Date.now();
394
- m.messageContextInfo.messageAddOnDurationInSecs = message.type === 1 ? message.time || 86400 : 0;
353
+ else if ('disappearingMessagesInChat' in message) {
354
+ const exp = typeof message.disappearingMessagesInChat === 'boolean' ?
355
+ (message.disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
356
+ message.disappearingMessagesInChat;
357
+ m = (0, exports.prepareDisappearingMessageSettingContent)(exp);
395
358
  }
396
- else if (hasNonNullishProperty(message, 'buttonReply')) {
359
+ else if ('buttonReply' in message) {
397
360
  switch (message.type) {
398
361
  case 'template':
399
362
  m.templateButtonReplyMessage = {
400
363
  selectedDisplayText: message.buttonReply.displayText,
401
364
  selectedId: message.buttonReply.id,
402
- selectedIndex: message.buttonReply.index
365
+ selectedIndex: message.buttonReply.index,
403
366
  };
404
367
  break;
405
368
  case 'plain':
406
369
  m.buttonsResponseMessage = {
407
370
  selectedButtonId: message.buttonReply.id,
408
371
  selectedDisplayText: message.buttonReply.displayText,
409
- type: proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT
372
+ type: WAProto_1.proto.Message.ButtonsResponseMessage.Type.DISPLAY_TEXT,
410
373
  };
411
374
  break;
412
375
  }
413
376
  }
414
- else if (hasOptionalProperty(message, 'ptv') && message.ptv) {
415
- const { videoMessage } = await prepareWAMessageMedia({ video: message.ptv }, options);
416
- m.ptvMessage = videoMessage;
417
- }
418
- else if (hasNonNullishProperty(message, 'product')) {
419
- const { imageMessage } = await prepareWAMessageMedia({ image: message.product.productImage }, options);
420
- m.productMessage = WAProto.Message.ProductMessage.create({
377
+ else if ('product' in message) {
378
+ const { imageMessage } = await (0, exports.prepareWAMessageMedia)({ image: message.product.productImage }, options);
379
+ m.productMessage = Types_1.WAProto.Message.ProductMessage.fromObject({
421
380
  ...message,
422
381
  product: {
423
382
  ...message.product,
424
- productImage: imageMessage
383
+ productImage: imageMessage,
425
384
  }
426
385
  });
427
386
  }
428
- else if (hasNonNullishProperty(message, 'listReply')) {
387
+ else if ('listReply' in message) {
429
388
  m.listResponseMessage = { ...message.listReply };
430
389
  }
431
- else if (hasNonNullishProperty(message, 'event')) {
432
- m.eventMessage = {};
433
- const startTime = Math.floor(message.event.startDate.getTime() / 1000);
434
- if (message.event.call && options.getCallLink) {
435
- const token = await options.getCallLink(message.event.call, { startTime });
436
- m.eventMessage.joinLink = (message.event.call === 'audio' ? CALL_AUDIO_PREFIX : CALL_VIDEO_PREFIX) + token;
437
- }
438
- m.messageContextInfo = {
439
- // encKey
440
- messageSecret: message.event.messageSecret || randomBytes(32)
441
- };
442
- m.eventMessage.name = message.event.name;
443
- m.eventMessage.description = message.event.description;
444
- m.eventMessage.startTime = startTime;
445
- m.eventMessage.endTime = message.event.endDate ? message.event.endDate.getTime() / 1000 : undefined;
446
- m.eventMessage.isCanceled = message.event.isCancelled ?? false;
447
- m.eventMessage.extraGuestsAllowed = message.event.extraGuestsAllowed;
448
- m.eventMessage.isScheduleCall = message.event.isScheduleCall ?? false;
449
- m.eventMessage.location = message.event.location;
450
- }
451
- else if (hasNonNullishProperty(message, 'poll')) {
452
- (_a = message.poll).selectableCount || (_a.selectableCount = 0);
453
- (_b = message.poll).toAnnouncementGroup || (_b.toAnnouncementGroup = false);
390
+ else if ('ptv' in message) {
391
+ const { videoMessage } = await prepareWAMessageMedia(
392
+ { video: message.ptv },
393
+ options
394
+ );
395
+ m.ptvMessage = videoMessage;
396
+ }
397
+ else if ('poll' in message) {
398
+ (_b = message.poll).selectableCount || (_b.selectableCount = 0);
454
399
  if (!Array.isArray(message.poll.values)) {
455
- throw new Boom('Invalid poll values', { statusCode: 400 });
400
+ throw new boom_1.Boom('Invalid poll values', { statusCode: 400 });
456
401
  }
457
- if (message.poll.selectableCount < 0 || message.poll.selectableCount > message.poll.values.length) {
458
- throw new Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, {
459
- statusCode: 400
460
- });
402
+ if (message.poll.selectableCount < 0
403
+ || message.poll.selectableCount > message.poll.values.length) {
404
+ throw new boom_1.Boom(`poll.selectableCount in poll should be >= 0 and <= ${message.poll.values.length}`, { statusCode: 400 });
461
405
  }
462
406
  m.messageContextInfo = {
463
407
  // encKey
464
- messageSecret: message.poll.messageSecret || randomBytes(32)
408
+ messageSecret: message.poll.messageSecret || (0, crypto_1.randomBytes)(32),
465
409
  };
466
- const pollCreationMessage = {
410
+ m.pollCreationMessage = {
467
411
  name: message.poll.name,
468
412
  selectableOptionsCount: message.poll.selectableCount,
469
- options: message.poll.values.map(optionName => ({ optionName }))
470
- };
471
- if (message.poll.toAnnouncementGroup) {
472
- // poll v2 is for community announcement groups (single select and multiple)
473
- m.pollCreationMessageV2 = pollCreationMessage;
474
- }
475
- else {
476
- if (message.poll.selectableCount === 1) {
477
- //poll v3 is for single select polls
478
- m.pollCreationMessageV3 = pollCreationMessage;
479
- }
480
- else {
481
- // poll for multiple choice polls
482
- m.pollCreationMessage = pollCreationMessage;
483
- }
484
- }
485
- }
486
- else if (hasNonNullishProperty(message, 'album')) {
487
- m.albumMessage = {
488
- expectedImageCount: message.album.expectedImageCount,
489
- expectedVideoCount: message.album.expectedVideoCount
413
+ options: message.poll.values.map(optionName => ({ optionName })),
414
+ pollType: message.poll.type,
415
+ correctAnswer: message.poll.answer
490
416
  };
491
417
  }
492
- else if (hasNonNullishProperty(message, 'sharePhoneNumber')) {
418
+ else if ('sharePhoneNumber' in message) {
493
419
  m.protocolMessage = {
494
- type: proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
420
+ type: WAProto_1.proto.Message.ProtocolMessage.Type.SHARE_PHONE_NUMBER
495
421
  };
496
422
  }
497
- else if (hasNonNullishProperty(message, 'requestPhoneNumber')) {
423
+ else if ('requestPhoneNumber' in message) {
498
424
  m.requestPhoneNumberMessage = {};
499
425
  }
500
- else if (hasNonNullishProperty(message, 'limitSharing')) {
501
- m.protocolMessage = {
502
- type: proto.Message.ProtocolMessage.Type.LIMIT_SHARING,
503
- limitSharing: {
504
- sharingLimited: message.limitSharing === true,
505
- trigger: 1,
506
- limitSharingSettingTimestamp: Date.now(),
507
- initiatedByMe: true
508
- }
509
- };
510
- }
511
426
  else {
512
- m = await prepareWAMessageMedia(message, options);
513
- }
514
- if (hasOptionalProperty(message, 'viewOnce') && !!message.viewOnce) {
515
- m = { viewOnceMessage: { message: m } };
427
+ m = await (0, exports.prepareWAMessageMedia)(message, options);
516
428
  }
517
- if ((hasOptionalProperty(message, 'mentions') && message.mentions?.length) ||
518
- (hasOptionalProperty(message, 'mentionAll') && message.mentionAll)) {
519
- const messageType = Object.keys(m)[0];
520
- const key = m[messageType];
521
- if (key && 'contextInfo' in key) {
522
- key.contextInfo = key.contextInfo || {};
523
- if (message.mentions?.length) {
524
- key.contextInfo.mentionedJid = message.mentions;
429
+ if ('buttons' in message && !!message.buttons) {
430
+ const buttonsMessage = {
431
+ buttons: message.buttons.map(b => ({ ...b, type: WAProto_1.proto.Message.ButtonsMessage.Button.Type.RESPONSE }))
432
+ };
433
+ if ('text' in message) {
434
+ buttonsMessage.contentText = message.text;
435
+ buttonsMessage.headerType = ButtonType.EMPTY;
436
+ }
437
+ else {
438
+ if ('caption' in message) {
439
+ buttonsMessage.contentText = message.caption;
525
440
  }
526
- if (message.mentionAll) {
527
- key.contextInfo.nonJidMentions = 1;
441
+ const type = Object.keys(m)[0].replace('Message', '').toUpperCase();
442
+ buttonsMessage.headerType = ButtonType[type];
443
+ Object.assign(buttonsMessage, m);
444
+ }
445
+ if ('footer' in message && !!message.footer) {
446
+ buttonsMessage.footerText = message.footer;
447
+ }
448
+ m = { buttonsMessage };
449
+ }
450
+ else if ('templateButtons' in message && !!message.templateButtons) {
451
+ const msg = {
452
+ hydratedButtons: message.templateButtons
453
+ };
454
+ if ('text' in message) {
455
+ msg.hydratedContentText = message.text;
456
+ }
457
+ else {
458
+ if ('caption' in message) {
459
+ msg.hydratedContentText = message.caption;
528
460
  }
461
+ Object.assign(msg, m);
529
462
  }
530
- else if (key) {
531
- key.contextInfo = {
532
- mentionedJid: message.mentions,
533
- nonJidMentions: message.mentionAll ? 1 : 0
534
- };
463
+ if ('footer' in message && !!message.footer) {
464
+ msg.hydratedFooterText = message.footer;
535
465
  }
466
+ m = {
467
+ templateMessage: {
468
+ fourRowTemplate: msg,
469
+ hydratedTemplate: msg
470
+ }
471
+ };
536
472
  }
537
- if (hasOptionalProperty(message, 'edit')) {
473
+ if ('sections' in message && !!message.sections) {
474
+ const listMessage = {
475
+ sections: message.sections,
476
+ buttonText: message.buttonText,
477
+ title: message.title,
478
+ footerText: message.footer,
479
+ description: message.text,
480
+ listType: WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT
481
+ };
482
+ m = { listMessage };
483
+ }
484
+ if ('viewOnce' in message && !!message.viewOnce) {
485
+ m = { viewOnceMessage: { message: m } };
486
+ }
487
+ if ('mentions' in message && ((_a = message.mentions) === null || _a === void 0 ? void 0 : _a.length)) {
488
+ const [messageType] = Object.keys(m);
489
+ m[messageType].contextInfo = m[messageType] || {};
490
+ m[messageType].contextInfo.mentionedJid = message.mentions;
491
+ }
492
+ if ('edit' in message) {
538
493
  m = {
539
494
  protocolMessage: {
540
495
  key: message.edit,
541
496
  editedMessage: m,
542
497
  timestampMs: Date.now(),
543
- type: WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
544
- }
545
- };
546
- }
547
- if (hasOptionalProperty(message, 'contextInfo') && !!message.contextInfo) {
548
- const messageType = Object.keys(m)[0];
549
- const key = m[messageType];
550
- if ('contextInfo' in key && !!key.contextInfo) {
551
- key.contextInfo = { ...key.contextInfo, ...message.contextInfo };
552
- }
553
- else if (key) {
554
- key.contextInfo = message.contextInfo;
555
- }
556
- }
557
- if (hasOptionalProperty(message, 'albumParentKey') && !!message.albumParentKey) {
558
- m.messageContextInfo = {
559
- ...m.messageContextInfo,
560
- messageAssociation: {
561
- associationType: WAProto.MessageAssociation.AssociationType.MEDIA_ALBUM,
562
- parentMessageKey: message.albumParentKey
498
+ type: Types_1.WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT
563
499
  }
564
500
  };
565
501
  }
566
- if (shouldIncludeReportingToken(m)) {
567
- m.messageContextInfo = m.messageContextInfo || {};
568
- if (!m.messageContextInfo.messageSecret) {
569
- m.messageContextInfo.messageSecret = randomBytes(32);
570
- }
502
+ if ('contextInfo' in message && !!message.contextInfo) {
503
+ const [messageType] = Object.keys(m);
504
+ m[messageType] = m[messageType] || {};
505
+ m[messageType].contextInfo = message.contextInfo;
571
506
  }
572
- return WAProto.Message.create(m);
507
+ return Types_1.WAProto.Message.fromObject(m);
573
508
  };
574
- export const generateWAMessageFromContent = (jid, message, options) => {
509
+ exports.generateWAMessageContent = generateWAMessageContent;
510
+ const generateWAMessageFromContent = (jid, message, options) => {
575
511
  // set timestamp to now
576
512
  // if not specified
577
513
  if (!options.timestamp) {
578
514
  options.timestamp = new Date();
579
515
  }
580
- const innerMessage = normalizeMessageContent(message);
581
- const key = getContentType(innerMessage);
582
- const timestamp = unixTimestampSeconds(options.timestamp);
516
+ const innerMessage = (0, exports.normalizeMessageContent)(message);
517
+ const key = (0, exports.getContentType)(innerMessage);
518
+ const timestamp = (0, generics_1.unixTimestampSeconds)(options.timestamp);
583
519
  const { quoted, userJid } = options;
584
- if (quoted && !isJidNewsletter(jid)) {
585
- const participant = quoted.key.fromMe
586
- ? userJid // TODO: Add support for LIDs
587
- : quoted.participant || quoted.key.participant || quoted.key.remoteJid;
588
- let quotedMsg = normalizeMessageContent(quoted.message);
589
- const msgType = getContentType(quotedMsg);
520
+ if (quoted && !(0, WABinary_1.isJidNewsLetter)(jid)) {
521
+ const participant = quoted.key.fromMe ? userJid : (quoted.participant || quoted.key.participant || quoted.key.remoteJid);
522
+ let quotedMsg = (0, exports.normalizeMessageContent)(quoted.message);
523
+ const msgType = (0, exports.getContentType)(quotedMsg);
590
524
  // strip any redundant properties
591
- quotedMsg = proto.Message.create({ [msgType]: quotedMsg[msgType] });
525
+ quotedMsg = WAProto_1.proto.Message.fromObject({ [msgType]: quotedMsg[msgType] });
592
526
  const quotedContent = quotedMsg[msgType];
593
527
  if (typeof quotedContent === 'object' && quotedContent && 'contextInfo' in quotedContent) {
594
528
  delete quotedContent.contextInfo;
595
529
  }
596
- const contextInfo = ('contextInfo' in innerMessage[key] && innerMessage[key]?.contextInfo) || {};
597
- contextInfo.participant = jidNormalizedUser(participant);
530
+ const contextInfo = innerMessage[key].contextInfo || {};
531
+ contextInfo.participant = (0, WABinary_1.jidNormalizedUser)(participant);
598
532
  contextInfo.stanzaId = quoted.key.id;
599
533
  contextInfo.quotedMessage = quotedMsg;
600
534
  // if a participant is quoted, then it must be a group
@@ -602,63 +536,62 @@ export const generateWAMessageFromContent = (jid, message, options) => {
602
536
  if (jid !== quoted.key.remoteJid) {
603
537
  contextInfo.remoteJid = quoted.key.remoteJid;
604
538
  }
605
- if (contextInfo && innerMessage[key]) {
606
- /* @ts-ignore */
607
- innerMessage[key].contextInfo = contextInfo;
608
- }
539
+ innerMessage[key].contextInfo = contextInfo;
609
540
  }
610
541
  if (
611
542
  // if we want to send a disappearing message
612
- !!options?.ephemeralExpiration &&
543
+ !!(options === null || options === void 0 ? void 0 : options.ephemeralExpiration) &&
613
544
  // and it's not a protocol message -- delete, toggle disappear message
614
545
  key !== 'protocolMessage' &&
615
546
  // already not converted to disappearing message
616
547
  key !== 'ephemeralMessage' &&
617
- // newsletters don't support ephemeral messages
618
- !isJidNewsletter(jid)) {
619
- /* @ts-ignore */
548
+ // newsletter not accept disappearing messages
549
+ !(0, WABinary_1.isJidNewsLetter)(jid)) {
620
550
  innerMessage[key].contextInfo = {
621
551
  ...(innerMessage[key].contextInfo || {}),
622
- expiration: options.ephemeralExpiration || WA_DEFAULT_EPHEMERAL
552
+ expiration: options.ephemeralExpiration || Defaults_1.WA_DEFAULT_EPHEMERAL,
623
553
  //ephemeralSettingTimestamp: options.ephemeralOptions.eph_setting_ts?.toString()
624
554
  };
625
555
  }
626
- message = WAProto.Message.create(message);
556
+ message = Types_1.WAProto.Message.fromObject(message);
627
557
  const messageJSON = {
628
558
  key: {
629
559
  remoteJid: jid,
630
560
  fromMe: true,
631
- id: options?.messageId || generateMessageIDV2()
561
+ id: (options === null || options === void 0 ? void 0 : options.messageId) || (0, generics_1.generateMessageID)(),
632
562
  },
633
563
  message: message,
634
564
  messageTimestamp: timestamp,
635
565
  messageStubParameters: [],
636
- participant: isJidGroup(jid) || isJidStatusBroadcast(jid) ? userJid : undefined, // TODO: Add support for LIDs
637
- status: WAMessageStatus.PENDING
566
+ participant: (0, WABinary_1.isJidGroup)(jid) || (0, WABinary_1.isJidStatusBroadcast)(jid) ? userJid : undefined,
567
+ status: Types_1.WAMessageStatus.PENDING
638
568
  };
639
- return WAProto.WebMessageInfo.fromObject(messageJSON);
569
+ return Types_1.WAProto.WebMessageInfo.fromObject(messageJSON);
640
570
  };
641
- export const generateWAMessage = async (jid, content, options) => {
571
+ exports.generateWAMessageFromContent = generateWAMessageFromContent;
572
+ const generateWAMessage = async (jid, content, options) => {
573
+ var _a;
642
574
  // ensure msg ID is with every log
643
- options.logger = options?.logger?.child({ msgId: options.messageId });
644
- // Pass jid in the options to generateWAMessageContent
645
- return generateWAMessageFromContent(jid, await generateWAMessageContent(content, { ...options, jid }), options);
575
+ options.logger = (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.child({ msgId: options.messageId });
576
+ return (0, exports.generateWAMessageFromContent)(jid, await (0, exports.generateWAMessageContent)(content, { newsletter: (0, WABinary_1.isJidNewsLetter)(jid), ...options }), options);
646
577
  };
578
+ exports.generateWAMessage = generateWAMessage;
647
579
  /** Get the key to access the true type of content */
648
- export const getContentType = (content) => {
580
+ const getContentType = (content) => {
649
581
  if (content) {
650
582
  const keys = Object.keys(content);
651
583
  const key = keys.find(k => (k === 'conversation' || k.includes('Message')) && k !== 'senderKeyDistributionMessage');
652
584
  return key;
653
585
  }
654
586
  };
587
+ exports.getContentType = getContentType;
655
588
  /**
656
589
  * Normalizes ephemeral, view once messages to regular message content
657
590
  * Eg. image messages in ephemeral messages, in view once messages etc.
658
591
  * @param content
659
592
  * @returns
660
593
  */
661
- export const normalizeMessageContent = (content) => {
594
+ const normalizeMessageContent = (content) => {
662
595
  if (!content) {
663
596
  return undefined;
664
597
  }
@@ -672,22 +605,21 @@ export const normalizeMessageContent = (content) => {
672
605
  }
673
606
  return content;
674
607
  function getFutureProofMessage(message) {
675
- return (message?.ephemeralMessage ||
676
- message?.viewOnceMessage ||
677
- message?.documentWithCaptionMessage ||
678
- message?.viewOnceMessageV2 ||
679
- message?.viewOnceMessageV2Extension ||
680
- message?.editedMessage ||
681
- message?.associatedChildMessage ||
682
- message?.groupStatusMessage ||
683
- message?.groupStatusMessageV2);
608
+ return ((message === null || message === void 0 ? void 0 : message.ephemeralMessage)
609
+ || (message === null || message === void 0 ? void 0 : message.viewOnceMessage)
610
+ || (message === null || message === void 0 ? void 0 : message.documentWithCaptionMessage)
611
+ || (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2)
612
+ || (message === null || message === void 0 ? void 0 : message.viewOnceMessageV2Extension)
613
+ || (message === null || message === void 0 ? void 0 : message.editedMessage));
684
614
  }
685
615
  };
616
+ exports.normalizeMessageContent = normalizeMessageContent;
686
617
  /**
687
618
  * Extract the true message content from a message
688
619
  * Eg. extracts the inner message from a disappearing message/view once message
689
620
  */
690
- export const extractMessageContent = (content) => {
621
+ const extractMessageContent = (content) => {
622
+ var _a, _b, _c, _d, _e, _f;
691
623
  const extractFromTemplateMessage = (msg) => {
692
624
  if (msg.imageMessage) {
693
625
  return { imageMessage: msg.imageMessage };
@@ -703,39 +635,35 @@ export const extractMessageContent = (content) => {
703
635
  }
704
636
  else {
705
637
  return {
706
- conversation: 'contentText' in msg ? msg.contentText : 'hydratedContentText' in msg ? msg.hydratedContentText : ''
638
+ conversation: 'contentText' in msg
639
+ ? msg.contentText
640
+ : ('hydratedContentText' in msg ? msg.hydratedContentText : '')
707
641
  };
708
642
  }
709
643
  };
710
- content = normalizeMessageContent(content);
711
- if (content?.buttonsMessage) {
644
+ content = (0, exports.normalizeMessageContent)(content);
645
+ if (content === null || content === void 0 ? void 0 : content.buttonsMessage) {
712
646
  return extractFromTemplateMessage(content.buttonsMessage);
713
647
  }
714
- if (content?.templateMessage?.hydratedFourRowTemplate) {
715
- return extractFromTemplateMessage(content?.templateMessage?.hydratedFourRowTemplate);
648
+ if ((_a = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _a === void 0 ? void 0 : _a.hydratedFourRowTemplate) {
649
+ return extractFromTemplateMessage((_b = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _b === void 0 ? void 0 : _b.hydratedFourRowTemplate);
716
650
  }
717
- if (content?.templateMessage?.hydratedTemplate) {
718
- return extractFromTemplateMessage(content?.templateMessage?.hydratedTemplate);
651
+ if ((_c = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _c === void 0 ? void 0 : _c.hydratedTemplate) {
652
+ return extractFromTemplateMessage((_d = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _d === void 0 ? void 0 : _d.hydratedTemplate);
719
653
  }
720
- if (content?.templateMessage?.fourRowTemplate) {
721
- return extractFromTemplateMessage(content?.templateMessage?.fourRowTemplate);
654
+ if ((_e = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _e === void 0 ? void 0 : _e.fourRowTemplate) {
655
+ return extractFromTemplateMessage((_f = content === null || content === void 0 ? void 0 : content.templateMessage) === null || _f === void 0 ? void 0 : _f.fourRowTemplate);
722
656
  }
723
657
  return content;
724
658
  };
659
+ exports.extractMessageContent = extractMessageContent;
725
660
  /**
726
661
  * Returns the device predicted by message ID
727
662
  */
728
- export const getDevice = (id) => /^3A.{18}$/.test(id)
729
- ? 'ios'
730
- : /^3E.{20}$/.test(id)
731
- ? 'web'
732
- : /^(.{21}|.{32})$/.test(id)
733
- ? 'android'
734
- : /^(3F|.{18}$)/.test(id)
735
- ? 'desktop'
736
- : 'wa bot';
663
+ const getDevice = (id) => /^3A.{18}$/.test(id) ? 'ios' : /^3E.{20}$/.test(id) ? 'web' : /^(.{21}|.{32})$/.test(id) ? 'android' : /^.{18}$/.test(id) ? 'desktop' : 'unknown';
664
+ exports.getDevice = getDevice;
737
665
  /** Upserts a receipt in the message */
738
- export const updateMessageWithReceipt = (msg, receipt) => {
666
+ const updateMessageWithReceipt = (msg, receipt) => {
739
667
  msg.userReceipt = msg.userReceipt || [];
740
668
  const recp = msg.userReceipt.find(m => m.userJid === receipt.userJid);
741
669
  if (recp) {
@@ -745,43 +673,41 @@ export const updateMessageWithReceipt = (msg, receipt) => {
745
673
  msg.userReceipt.push(receipt);
746
674
  }
747
675
  };
676
+ exports.updateMessageWithReceipt = updateMessageWithReceipt;
748
677
  /** Update the message with a new reaction */
749
- export const updateMessageWithReaction = (msg, reaction) => {
750
- const authorID = getKeyAuthor(reaction.key);
751
- const reactions = (msg.reactions || []).filter(r => getKeyAuthor(r.key) !== authorID);
752
- reaction.text = reaction.text || '';
753
- reactions.push(reaction);
678
+ const updateMessageWithReaction = (msg, reaction) => {
679
+ const authorID = (0, generics_1.getKeyAuthor)(reaction.key);
680
+ const reactions = (msg.reactions || [])
681
+ .filter(r => (0, generics_1.getKeyAuthor)(r.key) !== authorID);
682
+ if (reaction.text) {
683
+ reactions.push(reaction);
684
+ }
754
685
  msg.reactions = reactions;
755
686
  };
687
+ exports.updateMessageWithReaction = updateMessageWithReaction;
756
688
  /** Update the message with a new poll update */
757
- export const updateMessageWithPollUpdate = (msg, update) => {
758
- const authorID = getKeyAuthor(update.pollUpdateMessageKey);
759
- const reactions = (msg.pollUpdates || []).filter(r => getKeyAuthor(r.pollUpdateMessageKey) !== authorID);
760
- if (update.vote?.selectedOptions?.length) {
689
+ const updateMessageWithPollUpdate = (msg, update) => {
690
+ var _a, _b;
691
+ const authorID = (0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey);
692
+ const reactions = (msg.pollUpdates || [])
693
+ .filter(r => (0, generics_1.getKeyAuthor)(r.pollUpdateMessageKey) !== authorID);
694
+ if ((_b = (_a = update.vote) === null || _a === void 0 ? void 0 : _a.selectedOptions) === null || _b === void 0 ? void 0 : _b.length) {
761
695
  reactions.push(update);
762
696
  }
763
697
  msg.pollUpdates = reactions;
764
698
  };
765
- /** Update the message with a new event response */
766
- export const updateMessageWithEventResponse = (msg, update) => {
767
- const authorID = getKeyAuthor(update.eventResponseMessageKey);
768
- const responses = (msg.eventResponses || []).filter(r => getKeyAuthor(r.eventResponseMessageKey) !== authorID);
769
- responses.push(update);
770
- msg.eventResponses = responses;
771
- };
699
+ exports.updateMessageWithPollUpdate = updateMessageWithPollUpdate;
772
700
  /**
773
701
  * Aggregates all poll updates in a poll.
774
702
  * @param msg the poll creation message
775
703
  * @param meId your jid
776
704
  * @returns A list of options & their voters
777
705
  */
778
- export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
779
- const opts = message?.pollCreationMessage?.options ||
780
- message?.pollCreationMessageV2?.options ||
781
- message?.pollCreationMessageV3?.options ||
782
- [];
706
+ function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
707
+ var _a, _b, _c;
708
+ const opts = ((_a = message === null || message === void 0 ? void 0 : message.pollCreationMessage) === null || _a === void 0 ? void 0 : _a.options) || ((_b = message === null || message === void 0 ? void 0 : message.pollCreationMessageV2) === null || _b === void 0 ? void 0 : _b.options) || ((_c = message === null || message === void 0 ? void 0 : message.pollCreationMessageV3) === null || _c === void 0 ? void 0 : _c.options) || [];
783
709
  const voteHashMap = opts.reduce((acc, opt) => {
784
- const hash = sha256(Buffer.from(opt.optionName || '')).toString();
710
+ const hash = (0, crypto_2.sha256)(Buffer.from(opt.optionName || '')).toString();
785
711
  acc[hash] = {
786
712
  name: opt.optionName || '',
787
713
  voters: []
@@ -803,36 +729,14 @@ export function getAggregateVotesInPollMessage({ message, pollUpdates }, meId) {
803
729
  };
804
730
  data = voteHashMap[hash];
805
731
  }
806
- voteHashMap[hash].voters.push(getKeyAuthor(update.pollUpdateMessageKey, meId));
732
+ voteHashMap[hash].voters.push((0, generics_1.getKeyAuthor)(update.pollUpdateMessageKey, meId));
807
733
  }
808
734
  }
809
735
  return Object.values(voteHashMap);
810
736
  }
811
- /**
812
- * Aggregates all event responses in an event message.
813
- * @param msg the event creation message
814
- * @param meId your jid
815
- * @returns A list of response types & their responders
816
- */
817
- export function getAggregateResponsesInEventMessage({ eventResponses }, meId) {
818
- const responseTypes = ['GOING', 'NOT_GOING', 'MAYBE'];
819
- const responseMap = {};
820
- for (const type of responseTypes) {
821
- responseMap[type] = {
822
- response: type,
823
- responders: []
824
- };
825
- }
826
- for (const update of eventResponses || []) {
827
- const responseType = update.eventResponse || 'UNKNOWN';
828
- if (responseType !== 'UNKNOWN' && responseMap[responseType]) {
829
- responseMap[responseType].responders.push(getKeyAuthor(update.eventResponseMessageKey, meId));
830
- }
831
- }
832
- return Object.values(responseMap);
833
- }
737
+ exports.getAggregateVotesInPollMessage = getAggregateVotesInPollMessage;
834
738
  /** Given a list of message keys, aggregates them by chat & sender. Useful for sending read receipts in bulk */
835
- export const aggregateMessageKeysNotFromMe = (keys) => {
739
+ const aggregateMessageKeysNotFromMe = (keys) => {
836
740
  const keyMap = {};
837
741
  for (const { remoteJid, id, participant, fromMe } of keys) {
838
742
  if (!fromMe) {
@@ -849,34 +753,40 @@ export const aggregateMessageKeysNotFromMe = (keys) => {
849
753
  }
850
754
  return Object.values(keyMap);
851
755
  };
756
+ exports.aggregateMessageKeysNotFromMe = aggregateMessageKeysNotFromMe;
852
757
  const REUPLOAD_REQUIRED_STATUS = [410, 404];
853
758
  /**
854
759
  * Downloads the given message. Throws an error if it's not a media message
855
760
  */
856
- export const downloadMediaMessage = async (message, type, options, ctx) => {
857
- const result = await downloadMsg().catch(async (error) => {
858
- if (ctx &&
859
- typeof error?.status === 'number' && // treat errors with status as HTTP failures requiring reupload
860
- REUPLOAD_REQUIRED_STATUS.includes(error.status)) {
861
- ctx.logger.info({ key: message.key }, 'sending reupload media request...');
862
- // request reupload
863
- message = await ctx.reuploadRequest(message);
864
- const result = await downloadMsg();
865
- return result;
761
+ const downloadMediaMessage = async (message, type, options, ctx) => {
762
+ const result = await downloadMsg()
763
+ .catch(async (error) => {
764
+ var _a;
765
+ if (ctx) {
766
+ if (axios_1.default.isAxiosError(error)) {
767
+ // check if the message requires a reupload
768
+ if (REUPLOAD_REQUIRED_STATUS.includes((_a = error.response) === null || _a === void 0 ? void 0 : _a.status)) {
769
+ ctx.logger.info({ key: message.key }, 'sending reupload media request...');
770
+ // request reupload
771
+ message = await ctx.reuploadRequest(message);
772
+ const result = await downloadMsg();
773
+ return result;
774
+ }
775
+ }
866
776
  }
867
777
  throw error;
868
778
  });
869
779
  return result;
870
780
  async function downloadMsg() {
871
- const mContent = extractMessageContent(message.message);
781
+ const mContent = (0, exports.extractMessageContent)(message.message);
872
782
  if (!mContent) {
873
- throw new Boom('No message present', { statusCode: 400, data: message });
783
+ throw new boom_1.Boom('No message present', { statusCode: 400, data: message });
874
784
  }
875
- const contentType = getContentType(mContent);
876
- let mediaType = contentType?.replace('Message', '');
785
+ const contentType = (0, exports.getContentType)(mContent);
786
+ let mediaType = contentType === null || contentType === void 0 ? void 0 : contentType.replace('Message', '');
877
787
  const media = mContent[contentType];
878
788
  if (!media || typeof media !== 'object' || (!('url' in media) && !('thumbnailDirectPath' in media))) {
879
- throw new Boom(`"${contentType}" message is not a media message`);
789
+ throw new boom_1.Boom(`"${contentType}" message is not a media message`);
880
790
  }
881
791
  let download;
882
792
  if ('thumbnailDirectPath' in media && !('url' in media)) {
@@ -889,7 +799,7 @@ export const downloadMediaMessage = async (message, type, options, ctx) => {
889
799
  else {
890
800
  download = media;
891
801
  }
892
- const stream = await downloadContentFromMessage(download, mediaType, options);
802
+ const stream = await (0, messages_media_1.downloadContentFromMessage)(download, mediaType, options);
893
803
  if (type === 'buffer') {
894
804
  const bufferArray = [];
895
805
  for await (const chunk of stream) {
@@ -900,17 +810,18 @@ export const downloadMediaMessage = async (message, type, options, ctx) => {
900
810
  return stream;
901
811
  }
902
812
  };
813
+ exports.downloadMediaMessage = downloadMediaMessage;
903
814
  /** Checks whether the given message is a media message; if it is returns the inner content */
904
- export const assertMediaContent = (content) => {
905
- content = extractMessageContent(content);
906
- const mediaContent = content?.documentMessage ||
907
- content?.imageMessage ||
908
- content?.videoMessage ||
909
- content?.audioMessage ||
910
- content?.stickerMessage;
815
+ const assertMediaContent = (content) => {
816
+ content = (0, exports.extractMessageContent)(content);
817
+ const mediaContent = (content === null || content === void 0 ? void 0 : content.documentMessage)
818
+ || (content === null || content === void 0 ? void 0 : content.imageMessage)
819
+ || (content === null || content === void 0 ? void 0 : content.videoMessage)
820
+ || (content === null || content === void 0 ? void 0 : content.audioMessage)
821
+ || (content === null || content === void 0 ? void 0 : content.stickerMessage);
911
822
  if (!mediaContent) {
912
- throw new Boom('given message is not a media message', { statusCode: 400, data: content });
823
+ throw new boom_1.Boom('given message is not a media message', { statusCode: 400, data: content });
913
824
  }
914
825
  return mediaContent;
915
826
  };
916
- //# sourceMappingURL=messages.js.map
827
+ exports.assertMediaContent = assertMediaContent;