@badzz88/baileys 8.5.6 → 8.5.7

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 (279) hide show
  1. package/README.md +2 -2
  2. package/WAProto/WAProto.proto +75 -1256
  3. package/WAProto/fix-imports.js +79 -69
  4. package/WAProto/index.d.ts +71491 -15254
  5. package/WAProto/index.js +126432 -19810
  6. package/engine-requirements.js +4 -3
  7. package/lib/Defaults/index.js +187 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +92 -0
  10. package/lib/Signal/Group/group_cipher.js +89 -0
  11. package/lib/Signal/Group/index.js +136 -0
  12. package/lib/Signal/Group/keyhelper.js +73 -0
  13. package/lib/Signal/Group/sender-chain-key.js +32 -0
  14. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  15. package/lib/Signal/Group/sender-key-message.js +69 -0
  16. package/lib/Signal/Group/sender-key-name.js +50 -0
  17. package/lib/Signal/Group/sender-key-record.js +44 -0
  18. package/lib/Signal/Group/sender-key-state.js +97 -0
  19. package/lib/Signal/Group/sender-message-key.js +30 -0
  20. package/lib/Signal/libsignal.js +459 -0
  21. package/lib/Signal/lid-mapping.js +260 -0
  22. package/lib/Socket/Client/index.js +30 -0
  23. package/lib/Socket/Client/types.js +13 -0
  24. package/lib/Socket/Client/websocket.js +62 -0
  25. package/lib/Socket/aigroups.js +240 -0
  26. package/lib/Socket/business.js +422 -0
  27. package/lib/Socket/chats.js +1816 -0
  28. package/lib/Socket/communities.js +549 -0
  29. package/lib/Socket/graphql.js +656 -0
  30. package/lib/Socket/groups.js +764 -0
  31. package/lib/Socket/index.js +39 -0
  32. package/lib/Socket/interactive-handler.js +522 -0
  33. package/lib/Socket/interop.js +549 -0
  34. package/{src → lib}/Socket/luxu.js +120 -82
  35. package/lib/Socket/managed-account.js +183 -0
  36. package/lib/Socket/messages-recv.js +2442 -0
  37. package/lib/Socket/messages-send.js +1853 -0
  38. package/lib/Socket/mex.js +60 -0
  39. package/lib/Socket/newsletter.js +818 -0
  40. package/lib/Socket/privacy.js +449 -0
  41. package/lib/Socket/registration.js +427 -0
  42. package/lib/Socket/socket.js +1092 -0
  43. package/lib/Socket/text-router.js +83 -0
  44. package/lib/Socket/username.js +243 -0
  45. package/lib/Store/index.js +36 -0
  46. package/{src → lib}/Store/keyed-db.js +11 -21
  47. package/lib/Store/make-cache-manager-store.js +90 -0
  48. package/lib/Store/make-in-memory-store.js +604 -0
  49. package/lib/Store/make-ordered-dictionary.js +81 -0
  50. package/lib/Store/object-repository.js +29 -0
  51. package/lib/Types/Auth.js +38 -0
  52. package/lib/Types/Bussines.js +2 -0
  53. package/lib/Types/Call.js +2 -0
  54. package/lib/Types/Chat.js +4 -0
  55. package/lib/Types/Contact.js +2 -0
  56. package/lib/Types/Events.js +2 -0
  57. package/lib/Types/GroupMetadata.js +2 -0
  58. package/lib/Types/Label.js +27 -0
  59. package/lib/Types/LabelAssociation.js +9 -0
  60. package/lib/Types/Message.js +95 -0
  61. package/lib/Types/Mex.js +112 -0
  62. package/lib/Types/Newsletter.js +121 -0
  63. package/lib/Types/Product.js +2 -0
  64. package/lib/Types/Signal.js +2 -0
  65. package/lib/Types/Socket.js +2 -0
  66. package/lib/Types/State.js +70 -0
  67. package/lib/Types/USync.js +2 -0
  68. package/lib/Types/index.js +55 -0
  69. package/lib/Utils/auth-utils.js +306 -0
  70. package/lib/Utils/browser-utils.js +114 -0
  71. package/lib/Utils/business.js +247 -0
  72. package/lib/Utils/chat-utils.js +1208 -0
  73. package/lib/Utils/command-loader.d.ts +31 -0
  74. package/lib/Utils/command-loader.js +100 -0
  75. package/lib/Utils/companion-reg-client-utils.js +42 -0
  76. package/lib/Utils/consumer-application.js +107 -0
  77. package/lib/Utils/crypto.js +155 -0
  78. package/lib/Utils/curve25519-js.js +275 -0
  79. package/lib/Utils/decode-wa-message.js +560 -0
  80. package/lib/Utils/event-buffer.js +607 -0
  81. package/lib/Utils/generics.js +563 -0
  82. package/lib/Utils/group-history.js +60 -0
  83. package/lib/Utils/history.js +244 -0
  84. package/lib/Utils/identity-change-handler.js +52 -0
  85. package/lib/Utils/index.js +57 -0
  86. package/lib/Utils/jid-display-normalization.js +218 -0
  87. package/lib/Utils/link-preview.js +143 -0
  88. package/lib/Utils/logger.js +9 -0
  89. package/lib/Utils/lt-hash.js +39 -0
  90. package/lib/Utils/make-mutex.js +36 -0
  91. package/lib/Utils/message-composer.js +479 -0
  92. package/lib/Utils/message-retry-manager.js +270 -0
  93. package/lib/Utils/messages-media.js +896 -0
  94. package/lib/Utils/messages.js +2904 -0
  95. package/lib/Utils/meta-ai-msmsg.js +262 -0
  96. package/lib/Utils/native-bridge.js +82 -0
  97. package/lib/Utils/noise-handler.js +196 -0
  98. package/lib/Utils/offline-node-processor.js +42 -0
  99. package/lib/Utils/pre-key-manager.js +107 -0
  100. package/lib/Utils/process-message.js +1048 -0
  101. package/lib/Utils/reporting-utils.js +262 -0
  102. package/lib/Utils/session-pool.d.ts +16 -0
  103. package/lib/Utils/session-pool.js +94 -0
  104. package/lib/Utils/signal.js +224 -0
  105. package/lib/Utils/stanza-ack.js +40 -0
  106. package/lib/Utils/sticker.d.ts +17 -0
  107. package/lib/Utils/sticker.js +145 -0
  108. package/lib/Utils/sync-action-utils.js +54 -0
  109. package/lib/Utils/tc-token-utils.js +161 -0
  110. package/lib/Utils/use-multi-file-auth-state.js +121 -0
  111. package/lib/Utils/validate-connection.js +219 -0
  112. package/lib/Utils/view-once-cache.d.ts +9 -0
  113. package/lib/Utils/view-once-cache.js +79 -0
  114. package/lib/Utils/voip-rekey.js +22 -0
  115. package/lib/WABinary/constants.js +1304 -0
  116. package/lib/WABinary/decode.js +343 -0
  117. package/{src → lib}/WABinary/encode.js +12 -9
  118. package/lib/WABinary/generic-utils.js +240 -0
  119. package/lib/WABinary/index.js +33 -0
  120. package/lib/WABinary/jid-utils.js +361 -0
  121. package/lib/WABinary/types.js +2 -0
  122. package/lib/WAM/BinaryInfo.js +13 -0
  123. package/lib/WAM/constants.js +39486 -0
  124. package/lib/WAM/encode.js +142 -0
  125. package/lib/WAM/index.js +31 -0
  126. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +55 -0
  127. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +43 -0
  128. package/lib/WAUSync/Protocols/USyncContactProtocol.js +54 -0
  129. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  130. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  131. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +59 -0
  132. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +31 -0
  133. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +32 -0
  134. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  135. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +39 -0
  136. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  137. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +27 -0
  138. package/lib/WAUSync/Protocols/index.js +39 -0
  139. package/lib/WAUSync/USyncQuery.js +133 -0
  140. package/lib/WAUSync/USyncUser.js +50 -0
  141. package/lib/WAUSync/index.js +31 -0
  142. package/lib/antiban.js +4637 -0
  143. package/{src → lib}/index.js +49 -51
  144. package/package.json +4 -4
  145. package/src/Defaults/index.js +0 -186
  146. package/src/Signal/Group/ciphertext-message.js +0 -15
  147. package/src/Signal/Group/group-session-builder.js +0 -86
  148. package/src/Signal/Group/group_cipher.js +0 -82
  149. package/src/Signal/Group/index.js +0 -140
  150. package/src/Signal/Group/keyhelper.js +0 -77
  151. package/src/Signal/Group/sender-chain-key.js +0 -29
  152. package/src/Signal/Group/sender-key-distribution-message.js +0 -66
  153. package/src/Signal/Group/sender-key-message.js +0 -69
  154. package/src/Signal/Group/sender-key-name.js +0 -51
  155. package/src/Signal/Group/sender-key-record.js +0 -44
  156. package/src/Signal/Group/sender-key-state.js +0 -87
  157. package/src/Signal/Group/sender-message-key.js +0 -29
  158. package/src/Signal/libsignal.js +0 -455
  159. package/src/Signal/lid-mapping.js +0 -273
  160. package/src/Socket/Client/index.js +0 -31
  161. package/src/Socket/Client/types.js +0 -13
  162. package/src/Socket/Client/websocket.js +0 -61
  163. package/src/Socket/aigroups.js +0 -221
  164. package/src/Socket/business.js +0 -411
  165. package/src/Socket/chats.js +0 -1449
  166. package/src/Socket/communities.js +0 -463
  167. package/src/Socket/graphql.js +0 -523
  168. package/src/Socket/groups.js +0 -516
  169. package/src/Socket/index.js +0 -31
  170. package/src/Socket/interactive-handler.js +0 -527
  171. package/src/Socket/interop.js +0 -339
  172. package/src/Socket/managed-account.js +0 -98
  173. package/src/Socket/messages-recv.js +0 -2685
  174. package/src/Socket/messages-send.js +0 -2047
  175. package/src/Socket/mex.js +0 -57
  176. package/src/Socket/newsletter.js +0 -455
  177. package/src/Socket/privacy.js +0 -125
  178. package/src/Socket/registration.js +0 -236
  179. package/src/Socket/socket.js +0 -983
  180. package/src/Socket/text-router.js +0 -65
  181. package/src/Socket/username.js +0 -130
  182. package/src/Store/index.js +0 -33
  183. package/src/Store/make-cache-manager-store.js +0 -84
  184. package/src/Store/make-in-memory-store.js +0 -551
  185. package/src/Store/make-ordered-dictionary.js +0 -81
  186. package/src/Store/object-repository.js +0 -26
  187. package/src/Types/Auth.js +0 -31
  188. package/src/Types/Bussines.js +0 -2
  189. package/src/Types/Call.js +0 -2
  190. package/src/Types/Chat.js +0 -4
  191. package/src/Types/Contact.js +0 -2
  192. package/src/Types/Events.js +0 -2
  193. package/src/Types/GroupMetadata.js +0 -2
  194. package/src/Types/Label.js +0 -26
  195. package/src/Types/LabelAssociation.js +0 -8
  196. package/src/Types/Message.js +0 -93
  197. package/src/Types/Mex.js +0 -112
  198. package/src/Types/Newsletter.js +0 -109
  199. package/src/Types/Product.js +0 -2
  200. package/src/Types/Signal.js +0 -2
  201. package/src/Types/Socket.js +0 -2
  202. package/src/Types/State.js +0 -62
  203. package/src/Types/USync.js +0 -2
  204. package/src/Types/index.js +0 -56
  205. package/src/Utils/auth-utils.js +0 -254
  206. package/src/Utils/browser-utils.js +0 -112
  207. package/src/Utils/business.js +0 -240
  208. package/src/Utils/chat-utils.js +0 -1230
  209. package/src/Utils/command-loader.d.ts +0 -27
  210. package/src/Utils/command-loader.js +0 -89
  211. package/src/Utils/companion-reg-client-utils.js +0 -40
  212. package/src/Utils/consumer-application.js +0 -105
  213. package/src/Utils/crypto.js +0 -118
  214. package/src/Utils/curve25519-js.js +0 -242
  215. package/src/Utils/decode-wa-message.js +0 -529
  216. package/src/Utils/event-buffer.js +0 -580
  217. package/src/Utils/generics.js +0 -483
  218. package/src/Utils/group-history.js +0 -44
  219. package/src/Utils/history.js +0 -232
  220. package/src/Utils/identity-change-handler.js +0 -52
  221. package/src/Utils/index.js +0 -58
  222. package/src/Utils/jid-display-normalization.js +0 -195
  223. package/src/Utils/link-preview.js +0 -135
  224. package/src/Utils/logger.js +0 -8
  225. package/src/Utils/lt-hash.js +0 -25
  226. package/src/Utils/make-mutex.js +0 -36
  227. package/src/Utils/message-composer.js +0 -471
  228. package/src/Utils/message-retry-manager.js +0 -217
  229. package/src/Utils/messages-media.js +0 -843
  230. package/src/Utils/messages.js +0 -2817
  231. package/src/Utils/meta-ai-msmsg.js +0 -222
  232. package/src/Utils/native-bridge.js +0 -68
  233. package/src/Utils/noise-handler.js +0 -169
  234. package/src/Utils/offline-node-processor.js +0 -34
  235. package/src/Utils/pre-key-manager.js +0 -90
  236. package/src/Utils/process-message.js +0 -950
  237. package/src/Utils/reporting-utils.js +0 -261
  238. package/src/Utils/session-pool.d.ts +0 -14
  239. package/src/Utils/session-pool.js +0 -70
  240. package/src/Utils/signal.js +0 -217
  241. package/src/Utils/stanza-ack.js +0 -30
  242. package/src/Utils/sticker.d.ts +0 -13
  243. package/src/Utils/sticker.js +0 -123
  244. package/src/Utils/sync-action-utils.js +0 -45
  245. package/src/Utils/tc-token-utils.js +0 -158
  246. package/src/Utils/use-multi-file-auth-state.js +0 -111
  247. package/src/Utils/validate-connection.js +0 -209
  248. package/src/Utils/view-once-cache.d.ts +0 -12
  249. package/src/Utils/view-once-cache.js +0 -63
  250. package/src/Utils/voip-rekey.js +0 -22
  251. package/src/WABinary/constants.js +0 -1304
  252. package/src/WABinary/decode.js +0 -342
  253. package/src/WABinary/generic-utils.js +0 -238
  254. package/src/WABinary/index.js +0 -34
  255. package/src/WABinary/jid-utils.js +0 -351
  256. package/src/WABinary/types.js +0 -2
  257. package/src/WAM/BinaryInfo.js +0 -13
  258. package/src/WAM/constants.js +0 -39484
  259. package/src/WAM/encode.js +0 -149
  260. package/src/WAM/index.js +0 -32
  261. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +0 -53
  262. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +0 -44
  263. package/src/WAUSync/Protocols/USyncContactProtocol.js +0 -55
  264. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +0 -55
  265. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -31
  266. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +0 -54
  267. package/src/WAUSync/Protocols/USyncLIDProtocol.js +0 -32
  268. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +0 -473
  269. package/src/WAUSync/Protocols/USyncPictureProtocol.js +0 -34
  270. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +0 -29
  271. package/src/WAUSync/Protocols/USyncStatusProtocol.js +0 -42
  272. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -38
  273. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +0 -28
  274. package/src/WAUSync/Protocols/index.js +0 -40
  275. package/src/WAUSync/USyncQuery.js +0 -126
  276. package/src/WAUSync/USyncUser.js +0 -50
  277. package/src/WAUSync/index.js +0 -32
  278. package/src/antiban.js +0 -4152
  279. /package/{src → lib}/Defaults/phonenumber-mcc.json +0 -0
@@ -1,843 +0,0 @@
1
- 'use strict';
2
- var __createBinding = (this && this.__createBinding) ||
3
- (Object.create
4
- ? function (o, m, k, k2) {
5
- if (k2 === undefined)
6
- k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = {
10
- enumerable: true,
11
- get: function () {
12
- return m[k];
13
- }
14
- };
15
- }
16
- Object.defineProperty(o, k2, desc);
17
- }
18
- : function (o, m, k, k2) {
19
- if (k2 === undefined)
20
- k2 = k;
21
- o[k2] = m[k];
22
- });
23
- var __setModuleDefault = (this && this.__setModuleDefault) ||
24
- (Object.create
25
- ? function (o, v) {
26
- Object.defineProperty(o, 'default', { enumerable: true, value: v });
27
- }
28
- : function (o, v) {
29
- o['default'] = v;
30
- });
31
- var __importStar = (this && this.__importStar) ||
32
- (function () {
33
- var ownKeys = function (o) {
34
- ownKeys =
35
- Object.getOwnPropertyNames ||
36
- function (o) {
37
- var ar = [];
38
- for (var k in o)
39
- if (Object.prototype.hasOwnProperty.call(o, k))
40
- ar[ar.length] = k;
41
- return ar;
42
- };
43
- return ownKeys(o);
44
- };
45
- return function (mod) {
46
- if (mod && mod.__esModule)
47
- return mod;
48
- var result = {};
49
- if (mod != null)
50
- for (var k = ownKeys(mod), i = 0; i < k.length; i++)
51
- if (k[i] !== 'default')
52
- __createBinding(result, mod, k[i]);
53
- __setModuleDefault(result, mod);
54
- return result;
55
- };
56
- })();
57
- Object.defineProperty(exports, '__esModule', { value: true });
58
- exports.getStatusCodeForMediaRetry =
59
- exports.decryptMediaRetryData =
60
- exports.decodeMediaRetryNode =
61
- exports.encryptMediaRetryRequest =
62
- exports.getWAUploadToServer =
63
- exports.uploadWithNodeHttp =
64
- exports.downloadEncryptedContent =
65
- exports.downloadContentFromMessage =
66
- exports.getUrlFromDirectPath =
67
- exports.encryptedStream =
68
- exports.getHttpStream =
69
- exports.getStream =
70
- exports.toBuffer =
71
- exports.toReadable =
72
- exports.mediaMessageSHA256B64 =
73
- exports.generateProfilePicture =
74
- exports.encodeBase64EncodedStringForUpload =
75
- exports.extractImageThumb =
76
- exports.getRawMediaUploadData =
77
- exports.hkdfInfoKey =
78
- void 0;
79
- exports.getMediaKeys = getMediaKeys;
80
- exports.getAudioDuration = getAudioDuration;
81
- exports.getAudioWaveform = getAudioWaveform;
82
- exports.generateThumbnail = generateThumbnail;
83
- exports.extensionForMediaMessage = extensionForMediaMessage;
84
- const boom_1 = require('@hapi/boom');
85
- const child_process_1 = require('child_process');
86
- const Crypto = __importStar(require('crypto'));
87
- const events_1 = require('events');
88
- const fs_1 = require('fs');
89
- const os_1 = require('os');
90
- const path_1 = require('path');
91
- const stream_1 = require('stream');
92
- const url_1 = require('url');
93
- const index_js_1 = require('../../WAProto/index.js');
94
- const Defaults_1 = require('../Defaults');
95
- const WABinary_1 = require('../WABinary');
96
- const crypto_1 = require('./crypto');
97
- const generics_1 = require('./generics');
98
- const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
99
- const getImageProcessingLibrary = async () => {
100
- const [jimp, sharp] = await Promise.all([
101
- Promise.resolve()
102
- .then(() => __importStar(require('jimp')))
103
- .catch(() => { }),
104
- Promise.resolve()
105
- .then(() => __importStar(require('sharp')))
106
- .catch(() => { })
107
- ]);
108
- if (sharp) {
109
- return { sharp };
110
- }
111
- if (jimp) {
112
- return { jimp };
113
- }
114
- throw new boom_1.Boom('No image processing library available');
115
- };
116
- const hkdfInfoKey = type => {
117
- const hkdfInfo = Defaults_1.MEDIA_HKDF_KEY_MAPPING[type];
118
- return `WhatsApp ${hkdfInfo} Keys`;
119
- };
120
- exports.hkdfInfoKey = hkdfInfoKey;
121
- const getRawMediaUploadData = async (media, mediaType, logger) => {
122
- const { stream } = await (0, exports.getStream)(media);
123
- logger?.debug('got stream for raw upload');
124
- const hasher = Crypto.createHash('sha256');
125
- const filePath = (0, path_1.join)((0, os_1.tmpdir)(), mediaType + (0, generics_1.generateMessageIDV2)());
126
- const fileWriteStream = (0, fs_1.createWriteStream)(filePath);
127
- let fileLength = 0;
128
- try {
129
- for await (const data of stream) {
130
- fileLength += data.length;
131
- hasher.update(data);
132
- if (!fileWriteStream.write(data)) {
133
- await (0, events_1.once)(fileWriteStream, 'drain');
134
- }
135
- }
136
- fileWriteStream.end();
137
- await (0, events_1.once)(fileWriteStream, 'finish');
138
- stream.destroy();
139
- const fileSha256 = hasher.digest();
140
- logger?.debug('hashed data for raw upload');
141
- return {
142
- filePath: filePath,
143
- fileSha256,
144
- fileLength
145
- };
146
- }
147
- catch (error) {
148
- fileWriteStream.destroy();
149
- stream.destroy();
150
- try {
151
- await fs_1.promises.unlink(filePath);
152
- }
153
- catch {
154
- }
155
- throw error;
156
- }
157
- };
158
- exports.getRawMediaUploadData = getRawMediaUploadData;
159
- async function getMediaKeys(buffer, mediaType) {
160
- if (!buffer) {
161
- throw new boom_1.Boom('Cannot derive from empty media key');
162
- }
163
- if (typeof buffer === 'string') {
164
- buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
165
- }
166
- const expandedMediaKey = (0, crypto_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
167
- return {
168
- iv: expandedMediaKey.slice(0, 16),
169
- cipherKey: expandedMediaKey.slice(16, 48),
170
- macKey: expandedMediaKey.slice(48, 80)
171
- };
172
- }
173
- const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
174
- const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
175
- (0, child_process_1.exec)(cmd, err => {
176
- if (err) {
177
- reject(err);
178
- }
179
- else {
180
- resolve();
181
- }
182
- });
183
- });
184
- const extractImageThumb = async (bufferOrFilePath, width = 32) => {
185
- if (bufferOrFilePath instanceof stream_1.Readable) {
186
- bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
187
- }
188
- const lib = await getImageProcessingLibrary();
189
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
190
- const img = lib.sharp.default(bufferOrFilePath);
191
- const dimensions = await img.metadata();
192
- const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
193
- return {
194
- buffer,
195
- original: {
196
- width: dimensions.width,
197
- height: dimensions.height
198
- }
199
- };
200
- }
201
- else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
202
- const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
203
- const dimensions = {
204
- width: jimp.width,
205
- height: jimp.height
206
- };
207
- const buffer = await jimp
208
- .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
209
- .getBuffer('image/jpeg', { quality: 50 });
210
- return {
211
- buffer,
212
- original: dimensions
213
- };
214
- }
215
- else {
216
- throw new boom_1.Boom('No image processing library available');
217
- }
218
- };
219
- exports.extractImageThumb = extractImageThumb;
220
- const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
221
- exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
222
- const generateProfilePicture = async (mediaUpload, dimensions) => {
223
- let buffer;
224
- const { width: w = 640, height: h = 640 } = dimensions || {};
225
- if (Buffer.isBuffer(mediaUpload)) {
226
- buffer = mediaUpload;
227
- }
228
- else {
229
- const { stream } = await (0, exports.getStream)(mediaUpload);
230
- buffer = await (0, exports.toBuffer)(stream);
231
- }
232
- const lib = await getImageProcessingLibrary();
233
- let img;
234
- if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
235
- img = lib.sharp
236
- .default(buffer)
237
- .resize(w, h)
238
- .jpeg({
239
- quality: 50
240
- })
241
- .toBuffer();
242
- }
243
- else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
244
- const jimp = await lib.jimp.Jimp.read(buffer);
245
- const min = Math.min(jimp.width, jimp.height);
246
- const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
247
- img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
248
- }
249
- else {
250
- throw new boom_1.Boom('No image processing library available');
251
- }
252
- return {
253
- img: await img
254
- };
255
- };
256
- exports.generateProfilePicture = generateProfilePicture;
257
- const mediaMessageSHA256B64 = message => {
258
- const media = Object.values(message)[0];
259
- return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
260
- };
261
- exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
262
- async function getAudioDuration(buffer) {
263
- const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
264
- let metadata;
265
- const options = {
266
- duration: true
267
- };
268
- if (Buffer.isBuffer(buffer)) {
269
- metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
270
- }
271
- else if (typeof buffer === 'string') {
272
- metadata = await musicMetadata.parseFile(buffer, options);
273
- }
274
- else {
275
- metadata = await musicMetadata.parseStream(buffer, undefined, options);
276
- }
277
- return metadata.format.duration;
278
- }
279
- async function getAudioWaveform(buffer, logger) {
280
- try {
281
- const { default: decoder } = await Promise.resolve().then(() => __importStar(require('audio-decode')));
282
- let audioData;
283
- if (Buffer.isBuffer(buffer)) {
284
- audioData = buffer;
285
- }
286
- else if (typeof buffer === 'string') {
287
- const rStream = (0, fs_1.createReadStream)(buffer);
288
- audioData = await (0, exports.toBuffer)(rStream);
289
- }
290
- else {
291
- audioData = await (0, exports.toBuffer)(buffer);
292
- }
293
- const audioBuffer = await decoder(audioData);
294
- const rawData = audioBuffer.getChannelData(0);
295
- const samples = 64;
296
- const blockSize = Math.floor(rawData.length / samples);
297
- const filteredData = [];
298
- for (let i = 0; i < samples; i++) {
299
- const blockStart = blockSize * i;
300
- let sum = 0;
301
- for (let j = 0; j < blockSize; j++) {
302
- sum = sum + Math.abs(rawData[blockStart + j]);
303
- }
304
- filteredData.push(sum / blockSize);
305
- }
306
- const multiplier = Math.pow(Math.max(...filteredData), -1);
307
- const normalizedData = filteredData.map(n => n * multiplier);
308
- const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
309
- return waveform;
310
- }
311
- catch (e) {
312
- logger?.debug('Failed to generate waveform: ' + e);
313
- }
314
- }
315
- const toReadable = buffer => {
316
- const readable = new stream_1.Readable({ read: () => { } });
317
- readable.push(buffer);
318
- readable.push(null);
319
- return readable;
320
- };
321
- exports.toReadable = toReadable;
322
- const toBuffer = async (stream) => {
323
- const chunks = [];
324
- for await (const chunk of stream) {
325
- chunks.push(chunk);
326
- }
327
- stream.destroy();
328
- return Buffer.concat(chunks);
329
- };
330
- exports.toBuffer = toBuffer;
331
- const getStream = async (item, opts) => {
332
- if (Buffer.isBuffer(item)) {
333
- return { stream: (0, exports.toReadable)(item), type: 'buffer' };
334
- }
335
- if ('stream' in item) {
336
- return { stream: item.stream, type: 'readable' };
337
- }
338
- const urlStr = item.url.toString();
339
- if (urlStr.startsWith('data:')) {
340
- const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
341
- return { stream: (0, exports.toReadable)(buffer), type: 'buffer' };
342
- }
343
- if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
344
- return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
345
- }
346
- return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
347
- };
348
- exports.getStream = getStream;
349
- async function generateThumbnail(file, mediaType, options) {
350
- let thumbnail;
351
- let originalImageDimensions;
352
- if (mediaType === 'image') {
353
- const { buffer, original } = await (0, exports.extractImageThumb)(file);
354
- thumbnail = buffer.toString('base64');
355
- if (original.width && original.height) {
356
- originalImageDimensions = {
357
- width: original.width,
358
- height: original.height
359
- };
360
- }
361
- }
362
- else if (mediaType === 'video') {
363
- const imgFilename = (0, path_1.join)(getTmpFilesDirectory(), (0, generics_1.generateMessageIDV2)() + '.jpg');
364
- try {
365
- await extractVideoThumb(file, imgFilename, '00:00:00', { width: 32, height: 32 });
366
- const buff = await fs_1.promises.readFile(imgFilename);
367
- thumbnail = buff.toString('base64');
368
- await fs_1.promises.unlink(imgFilename);
369
- }
370
- catch (err) {
371
- options.logger?.debug('could not generate video thumb: ' + err);
372
- }
373
- }
374
- return {
375
- thumbnail,
376
- originalImageDimensions
377
- };
378
- }
379
- const getHttpStream = async (url, options = {}) => {
380
- const response = await fetch(url.toString(), {
381
- dispatcher: options.dispatcher,
382
- method: 'GET',
383
- headers: options.headers
384
- });
385
- if (!response.ok) {
386
- throw new boom_1.Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
387
- }
388
- return response.body instanceof stream_1.Readable ? response.body : stream_1.Readable.fromWeb(response.body);
389
- };
390
- exports.getHttpStream = getHttpStream;
391
- const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
392
- const { stream, type } = await (0, exports.getStream)(media, opts);
393
- logger?.debug('fetched media stream');
394
- const mediaKey = Crypto.randomBytes(32);
395
- const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
396
- const encFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-enc');
397
- const encFileWriteStream = (0, fs_1.createWriteStream)(encFilePath);
398
- let originalFileStream;
399
- let originalFilePath;
400
- if (saveOriginalFileIfRequired) {
401
- originalFilePath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_1.generateMessageIDV2)() + '-original');
402
- originalFileStream = (0, fs_1.createWriteStream)(originalFilePath);
403
- }
404
- let fileLength = 0;
405
- const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
406
- const hmac = Crypto.createHmac('sha256', macKey).update(iv);
407
- const sha256Plain = Crypto.createHash('sha256');
408
- const sha256Enc = Crypto.createHash('sha256');
409
- const onChunk = async (buff) => {
410
- sha256Enc.update(buff);
411
- hmac.update(buff);
412
- if (!encFileWriteStream.write(buff)) {
413
- await (0, events_1.once)(encFileWriteStream, 'drain');
414
- }
415
- };
416
- try {
417
- for await (const data of stream) {
418
- fileLength += data.length;
419
- if (type === 'remote' && opts?.maxContentLength && fileLength + data.length > opts.maxContentLength) {
420
- throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
421
- data: { media, type }
422
- });
423
- }
424
- if (originalFileStream) {
425
- if (!originalFileStream.write(data)) {
426
- await (0, events_1.once)(originalFileStream, 'drain');
427
- }
428
- }
429
- sha256Plain.update(data);
430
- await onChunk(aes.update(data));
431
- }
432
- await onChunk(aes.final());
433
- const mac = hmac.digest().slice(0, 10);
434
- sha256Enc.update(mac);
435
- const fileSha256 = sha256Plain.digest();
436
- const fileEncSha256 = sha256Enc.digest();
437
- encFileWriteStream.write(mac);
438
- const encFinishPromise = (0, events_1.once)(encFileWriteStream, 'finish');
439
- const originalFinishPromise = originalFileStream
440
- ? (0, events_1.once)(originalFileStream, 'finish')
441
- : Promise.resolve();
442
- encFileWriteStream.end();
443
- originalFileStream?.end?.();
444
- stream.destroy();
445
- await encFinishPromise;
446
- await originalFinishPromise;
447
- logger?.debug('encrypted data successfully');
448
- return {
449
- mediaKey,
450
- originalFilePath,
451
- encFilePath,
452
- mac,
453
- fileEncSha256,
454
- fileSha256,
455
- fileLength
456
- };
457
- }
458
- catch (error) {
459
- encFileWriteStream.destroy();
460
- originalFileStream?.destroy?.();
461
- aes.destroy();
462
- hmac.destroy();
463
- sha256Plain.destroy();
464
- sha256Enc.destroy();
465
- stream.destroy();
466
- try {
467
- await fs_1.promises.unlink(encFilePath);
468
- if (originalFilePath) {
469
- await fs_1.promises.unlink(originalFilePath);
470
- }
471
- }
472
- catch (err) {
473
- logger?.error({ err }, 'failed deleting tmp files');
474
- }
475
- throw error;
476
- }
477
- };
478
- exports.encryptedStream = encryptedStream;
479
- const DEF_HOST = 'mmg.whatsapp.net';
480
- const AES_CHUNK_SIZE = 16;
481
- const toSmallestChunkSize = num => {
482
- return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
483
- };
484
- const getUrlFromDirectPath = directPath => `https://${DEF_HOST}${directPath}`;
485
- exports.getUrlFromDirectPath = getUrlFromDirectPath;
486
- const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
487
- const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
488
- const downloadUrl = isValidMediaUrl ? url : (0, exports.getUrlFromDirectPath)(directPath);
489
- if (!downloadUrl) {
490
- throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
491
- }
492
- const keys = await getMediaKeys(mediaKey, type);
493
- return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
494
- };
495
- exports.downloadContentFromMessage = downloadContentFromMessage;
496
- const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
497
- let bytesFetched = 0;
498
- let startChunk = 0;
499
- let firstBlockIsIV = false;
500
- if (startByte) {
501
- const chunk = toSmallestChunkSize(startByte || 0);
502
- if (chunk) {
503
- startChunk = chunk - AES_CHUNK_SIZE;
504
- bytesFetched = chunk;
505
- firstBlockIsIV = true;
506
- }
507
- }
508
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
509
- const headersInit = options?.headers ? options.headers : undefined;
510
- const headers = {
511
- ...(headersInit ? (Array.isArray(headersInit) ? Object.fromEntries(headersInit) : headersInit) : {}),
512
- Origin: Defaults_1.DEFAULT_ORIGIN
513
- };
514
- if (startChunk || endChunk) {
515
- headers.Range = `bytes=${startChunk}-`;
516
- if (endChunk) {
517
- headers.Range += endChunk;
518
- }
519
- }
520
- const fetched = await (0, exports.getHttpStream)(downloadUrl, {
521
- ...(options || {}),
522
- headers
523
- });
524
- let remainingBytes = Buffer.from([]);
525
- let aes;
526
- const pushBytes = (bytes, push) => {
527
- if (startByte || endByte) {
528
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
529
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
530
- push(bytes.slice(start, end));
531
- bytesFetched += bytes.length;
532
- }
533
- else {
534
- push(bytes);
535
- }
536
- };
537
- const output = new stream_1.Transform({
538
- transform(chunk, _, callback) {
539
- let data = Buffer.concat([remainingBytes, chunk]);
540
- const decryptLength = toSmallestChunkSize(data.length);
541
- remainingBytes = data.slice(decryptLength);
542
- data = data.slice(0, decryptLength);
543
- if (!aes) {
544
- let ivValue = iv;
545
- if (firstBlockIsIV) {
546
- ivValue = data.slice(0, AES_CHUNK_SIZE);
547
- data = data.slice(AES_CHUNK_SIZE);
548
- }
549
- aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
550
- if (endByte) {
551
- aes.setAutoPadding(false);
552
- }
553
- }
554
- try {
555
- pushBytes(aes.update(data), b => this.push(b));
556
- callback();
557
- }
558
- catch (error) {
559
- callback(error);
560
- }
561
- },
562
- final(callback) {
563
- try {
564
- pushBytes(aes.final(), b => this.push(b));
565
- callback();
566
- }
567
- catch (error) {
568
- callback(error);
569
- }
570
- }
571
- });
572
- return fetched.pipe(output, { end: true });
573
- };
574
- exports.downloadEncryptedContent = downloadEncryptedContent;
575
- function extensionForMediaMessage(message) {
576
- const getExtension = mimetype => mimetype.split(';')[0]?.split('/')[1];
577
- const type = Object.keys(message)[0];
578
- let extension;
579
- if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
580
- extension = '.jpeg';
581
- }
582
- else {
583
- const messageContent = message[type];
584
- extension = getExtension(messageContent.mimetype);
585
- }
586
- return extension;
587
- }
588
- const isNodeRuntime = () => {
589
- return (typeof process !== 'undefined' &&
590
- process.versions?.node !== null &&
591
- typeof process.versions.bun === 'undefined' &&
592
- typeof globalThis.Deno === 'undefined');
593
- };
594
- const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
595
- if (redirectCount > 5) {
596
- throw new Error('Too many redirects');
597
- }
598
- const parsedUrl = new url_1.URL(url);
599
- const httpModule = parsedUrl.protocol === 'https:'
600
- ? await Promise.resolve().then(() => __importStar(require('https')))
601
- : await Promise.resolve().then(() => __importStar(require('http')));
602
- const fileStats = await fs_1.promises.stat(filePath);
603
- const fileSize = fileStats.size;
604
- return new Promise((resolve, reject) => {
605
- const req = httpModule.request({
606
- hostname: parsedUrl.hostname,
607
- port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
608
- path: parsedUrl.pathname + parsedUrl.search,
609
- method: 'POST',
610
- headers: {
611
- ...headers,
612
- 'Content-Length': fileSize
613
- },
614
- agent,
615
- timeout: timeoutMs
616
- }, res => {
617
- if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
618
- res.resume();
619
- const newUrl = new url_1.URL(res.headers.location, url).toString();
620
- resolve((0, exports.uploadWithNodeHttp)({
621
- url: newUrl,
622
- filePath,
623
- headers,
624
- timeoutMs,
625
- agent
626
- }, redirectCount + 1));
627
- return;
628
- }
629
- let body = '';
630
- res.on('data', chunk => (body += chunk));
631
- res.on('end', () => {
632
- try {
633
- const parsed = JSON.parse(body);
634
- if (parsed && typeof parsed === 'object') {
635
- Object.defineProperty(parsed, '__statusCode', { value: res.statusCode, enumerable: false });
636
- }
637
- resolve(parsed);
638
- }
639
- catch {
640
- resolve({ __statusCode: res.statusCode });
641
- }
642
- });
643
- });
644
- req.on('error', reject);
645
- req.on('timeout', () => {
646
- req.destroy();
647
- reject(new Error('Upload timeout'));
648
- });
649
- const stream = (0, fs_1.createReadStream)(filePath);
650
- stream.pipe(req);
651
- stream.on('error', err => {
652
- req.destroy();
653
- reject(err);
654
- });
655
- });
656
- };
657
- exports.uploadWithNodeHttp = uploadWithNodeHttp;
658
- const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
659
- const nodeStream = (0, fs_1.createReadStream)(filePath);
660
- const webStream = stream_1.Readable.toWeb(nodeStream);
661
- const response = await fetch(url, {
662
- dispatcher: agent,
663
- method: 'POST',
664
- body: webStream,
665
- headers,
666
- duplex: 'half',
667
- signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
668
- });
669
- try {
670
- const parsed = await response.json();
671
- if (parsed && typeof parsed === 'object') {
672
- Object.defineProperty(parsed, '__statusCode', { value: response.status, enumerable: false });
673
- }
674
- return parsed;
675
- }
676
- catch {
677
- return { __statusCode: response.status };
678
- }
679
- };
680
- const uploadMedia = async (params, logger) => {
681
- if (isNodeRuntime()) {
682
- logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
683
- return (0, exports.uploadWithNodeHttp)(params);
684
- }
685
- else {
686
- logger?.debug('Using web-standard Fetch API for upload');
687
- return uploadWithFetch(params);
688
- }
689
- };
690
- const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
691
- return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
692
- let uploadInfo = await refreshMediaConn(false);
693
- let urls;
694
- const hosts = [...customUploadHosts, ...uploadInfo.hosts];
695
- fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
696
- const customHeaders = (() => {
697
- const hdrs = options?.headers;
698
- if (!hdrs)
699
- return {};
700
- return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
701
- })();
702
- const headers = {
703
- ...customHeaders,
704
- 'Content-Type': 'application/octet-stream',
705
- Origin: Defaults_1.DEFAULT_ORIGIN
706
- };
707
- for (const { hostname } of hosts) {
708
- logger.debug(`uploading to "${hostname}"`);
709
- const auth = encodeURIComponent(uploadInfo.auth);
710
- const url = `https://${hostname}${Defaults_1.MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
711
- let result;
712
- const maxRateLimitRetries = 3;
713
- for (let attempt = 0; attempt <= maxRateLimitRetries; attempt++) {
714
- try {
715
- result = await uploadMedia({
716
- url,
717
- filePath,
718
- headers,
719
- timeoutMs,
720
- agent: fetchAgent
721
- }, logger);
722
- const isRateLimited = result?.__statusCode === 429 || result?.__statusCode === 503;
723
- if (isRateLimited && attempt < maxRateLimitRetries) {
724
- const backoffMs = Math.min(500 * 2 ** attempt, 8000) + Math.floor(Math.random() * 250);
725
- logger.warn({ hostname, attempt, backoffMs, statusCode: result.__statusCode }, 'media upload rate-limited, backing off before retry');
726
- await new Promise(resolve => setTimeout(resolve, backoffMs));
727
- continue;
728
- }
729
- if (result?.url || result?.direct_path) {
730
- urls = {
731
- mediaUrl: result.url,
732
- directPath: result.direct_path,
733
- meta_hmac: result.meta_hmac,
734
- fbid: result.fbid,
735
- ts: result.ts
736
- };
737
- }
738
- else {
739
- uploadInfo = await refreshMediaConn(true);
740
- throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
741
- }
742
- break;
743
- }
744
- catch (error) {
745
- const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
746
- logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
747
- break;
748
- }
749
- }
750
- if (urls)
751
- break;
752
- }
753
- if (!urls) {
754
- throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
755
- }
756
- return urls;
757
- };
758
- };
759
- exports.getWAUploadToServer = getWAUploadToServer;
760
- const getMediaRetryKey = mediaKey => {
761
- return (0, crypto_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
762
- };
763
- const encryptMediaRetryRequest = (key, mediaKey, meId) => {
764
- const recp = { stanzaId: key.id };
765
- const recpBuffer = index_js_1.proto.ServerErrorReceipt.encode(recp).finish();
766
- const iv = Crypto.randomBytes(12);
767
- const retryKey = getMediaRetryKey(mediaKey);
768
- const ciphertext = (0, crypto_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
769
- const req = {
770
- tag: 'receipt',
771
- attrs: {
772
- id: key.id,
773
- to: (0, WABinary_1.jidNormalizedUser)(meId),
774
- type: 'server-error'
775
- },
776
- content: [
777
- {
778
- tag: 'encrypt',
779
- attrs: {},
780
- content: [
781
- { tag: 'enc_p', attrs: {}, content: ciphertext },
782
- { tag: 'enc_iv', attrs: {}, content: iv }
783
- ]
784
- },
785
- {
786
- tag: 'rmr',
787
- attrs: {
788
- jid: key.remoteJid,
789
- from_me: (!!key.fromMe).toString(),
790
- participant: key.participant || undefined
791
- }
792
- }
793
- ]
794
- };
795
- return req;
796
- };
797
- exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
798
- const decodeMediaRetryNode = node => {
799
- const rmrNode = (0, WABinary_1.getBinaryNodeChild)(node, 'rmr');
800
- const event = {
801
- key: {
802
- id: node.attrs.id,
803
- remoteJid: rmrNode.attrs.jid,
804
- fromMe: rmrNode.attrs.from_me === 'true',
805
- participant: rmrNode.attrs.participant
806
- }
807
- };
808
- const errorNode = (0, WABinary_1.getBinaryNodeChild)(node, 'error');
809
- if (errorNode) {
810
- const errorCode = +errorNode.attrs.code;
811
- event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, {
812
- data: errorNode.attrs,
813
- statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode)
814
- });
815
- }
816
- else {
817
- const encryptedInfoNode = (0, WABinary_1.getBinaryNodeChild)(node, 'encrypt');
818
- const ciphertext = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
819
- const iv = (0, WABinary_1.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
820
- if (ciphertext && iv) {
821
- event.media = { ciphertext, iv };
822
- }
823
- else {
824
- event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
825
- }
826
- }
827
- return event;
828
- };
829
- exports.decodeMediaRetryNode = decodeMediaRetryNode;
830
- const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
831
- const retryKey = getMediaRetryKey(mediaKey);
832
- const plaintext = (0, crypto_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
833
- return index_js_1.proto.MediaRetryNotification.decode(plaintext);
834
- };
835
- exports.decryptMediaRetryData = decryptMediaRetryData;
836
- const getStatusCodeForMediaRetry = code => MEDIA_RETRY_STATUS_MAP[code];
837
- exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
838
- const MEDIA_RETRY_STATUS_MAP = {
839
- [index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
840
- [index_js_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
841
- [index_js_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
842
- [index_js_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
843
- };