astrabail 1.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 (224) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +89351 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +7 -0
  8. package/lib/Defaults/astrabail-version.json +8 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.js +166 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Defaults/update-wa-version.js +75 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  16. package/lib/Signal/Group/group-session-builder.js +66 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +85 -0
  19. package/lib/Signal/Group/index.d.ts +12 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  25. package/lib/Signal/Group/sender-chain-key.js +29 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  33. package/lib/Signal/Group/sender-key-record.js +44 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  35. package/lib/Signal/Group/sender-key-state.js +87 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +5 -0
  39. package/lib/Signal/libsignal.js +478 -0
  40. package/lib/Signal/lid-mapping.d.ts +19 -0
  41. package/lib/Signal/lid-mapping.js +274 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +18 -0
  44. package/lib/Socket/Client/types.d.ts +16 -0
  45. package/lib/Socket/Client/types.js +14 -0
  46. package/lib/Socket/Client/websocket.d.ts +13 -0
  47. package/lib/Socket/Client/websocket.js +60 -0
  48. package/lib/Socket/business.d.ts +202 -0
  49. package/lib/Socket/business.js +382 -0
  50. package/lib/Socket/chats.d.ts +111 -0
  51. package/lib/Socket/chats.js +1155 -0
  52. package/lib/Socket/communities.d.ts +258 -0
  53. package/lib/Socket/communities.js +438 -0
  54. package/lib/Socket/community.js +333 -0
  55. package/lib/Socket/groups.d.ts +150 -0
  56. package/lib/Socket/groups.js +470 -0
  57. package/lib/Socket/index.d.ts +245 -0
  58. package/lib/Socket/index.js +13 -0
  59. package/lib/Socket/messages-recv.d.ts +187 -0
  60. package/lib/Socket/messages-recv.js +1708 -0
  61. package/lib/Socket/messages-send.d.ts +183 -0
  62. package/lib/Socket/messages-send.js +1692 -0
  63. package/lib/Socket/mex.d.ts +3 -0
  64. package/lib/Socket/mex.js +45 -0
  65. package/lib/Socket/newsletter.d.ts +160 -0
  66. package/lib/Socket/newsletter.js +293 -0
  67. package/lib/Socket/socket.d.ts +55 -0
  68. package/lib/Socket/socket.js +947 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.js +20 -0
  71. package/lib/Store/make-cache-manager-store.js +83 -0
  72. package/lib/Store/make-in-memory-store.js +398 -0
  73. package/lib/Store/make-ordered-dictionary.js +81 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +116 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Bussines.d.ts +25 -0
  78. package/lib/Types/Bussines.js +2 -0
  79. package/lib/Types/Call.d.ts +15 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +123 -0
  82. package/lib/Types/Chat.js +10 -0
  83. package/lib/Types/Contact.d.ts +24 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +237 -0
  86. package/lib/Types/Events.js +3 -0
  87. package/lib/Types/GroupMetadata.d.ts +67 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +47 -0
  90. package/lib/Types/Label.js +25 -0
  91. package/lib/Types/LabelAssociation.d.ts +30 -0
  92. package/lib/Types/LabelAssociation.js +7 -0
  93. package/lib/Types/Message.d.ts +305 -0
  94. package/lib/Types/Message.js +11 -0
  95. package/lib/Types/MexUpdates.js +11 -0
  96. package/lib/Types/Newsletter.d.ts +135 -0
  97. package/lib/Types/Newsletter.js +43 -0
  98. package/lib/Types/Product.d.ts +79 -0
  99. package/lib/Types/Product.js +2 -0
  100. package/lib/Types/Signal.d.ts +76 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +133 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +39 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +65 -0
  109. package/lib/Types/index.js +42 -0
  110. package/lib/Utils/astrabail-event-stream.js +3 -0
  111. package/lib/Utils/audioToBuffer.js +31 -0
  112. package/lib/Utils/auth-utils.d.ts +19 -0
  113. package/lib/Utils/auth-utils.js +298 -0
  114. package/lib/Utils/baileys-event-stream.js +60 -0
  115. package/lib/Utils/bridge-runtime.d.ts +1 -0
  116. package/lib/Utils/bridge-runtime.js +14 -0
  117. package/lib/Utils/browser-utils.d.ts +4 -0
  118. package/lib/Utils/browser-utils.js +44 -0
  119. package/lib/Utils/business.d.ts +23 -0
  120. package/lib/Utils/business.js +240 -0
  121. package/lib/Utils/chat-utils.d.ts +70 -0
  122. package/lib/Utils/chat-utils.js +825 -0
  123. package/lib/Utils/crypto.d.ts +37 -0
  124. package/lib/Utils/crypto.js +168 -0
  125. package/lib/Utils/decode-wa-message.d.ts +48 -0
  126. package/lib/Utils/decode-wa-message.js +287 -0
  127. package/lib/Utils/event-buffer.d.ts +34 -0
  128. package/lib/Utils/event-buffer.js +580 -0
  129. package/lib/Utils/generics.d.ts +91 -0
  130. package/lib/Utils/generics.js +483 -0
  131. package/lib/Utils/history.d.ts +22 -0
  132. package/lib/Utils/history.js +137 -0
  133. package/lib/Utils/identity-change-handler.d.ts +37 -0
  134. package/lib/Utils/identity-change-handler.js +54 -0
  135. package/lib/Utils/index.d.ts +22 -0
  136. package/lib/Utils/index.js +48 -0
  137. package/lib/Utils/link-preview.d.ts +21 -0
  138. package/lib/Utils/link-preview.js +121 -0
  139. package/lib/Utils/logger.d.ts +13 -0
  140. package/lib/Utils/logger.js +7 -0
  141. package/lib/Utils/lt-hash.d.ts +8 -0
  142. package/lib/Utils/lt-hash.js +10 -0
  143. package/lib/Utils/make-mutex.d.ts +9 -0
  144. package/lib/Utils/make-mutex.js +37 -0
  145. package/lib/Utils/message-retry-manager.d.ts +110 -0
  146. package/lib/Utils/message-retry-manager.js +226 -0
  147. package/lib/Utils/messages-media.d.ts +130 -0
  148. package/lib/Utils/messages-media.js +887 -0
  149. package/lib/Utils/messages-newsletter.d.ts +84 -0
  150. package/lib/Utils/messages-newsletter.js +295 -0
  151. package/lib/Utils/messages.d.ts +92 -0
  152. package/lib/Utils/messages.js +1752 -0
  153. package/lib/Utils/noise-handler.d.ts +20 -0
  154. package/lib/Utils/noise-handler.js +204 -0
  155. package/lib/Utils/pre-key-manager.d.ts +28 -0
  156. package/lib/Utils/pre-key-manager.js +112 -0
  157. package/lib/Utils/process-message.d.ts +60 -0
  158. package/lib/Utils/process-message.js +536 -0
  159. package/lib/Utils/reporting-utils.d.ts +11 -0
  160. package/lib/Utils/reporting-utils.js +262 -0
  161. package/lib/Utils/resolve-jid.d.ts +43 -0
  162. package/lib/Utils/resolve-jid.js +95 -0
  163. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  164. package/lib/Utils/rust-bridge-shim.js +70 -0
  165. package/lib/Utils/serial-task-queue.js +29 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +170 -0
  168. package/lib/Utils/streamToBuffer.js +17 -0
  169. package/lib/Utils/sync-action-utils.d.ts +19 -0
  170. package/lib/Utils/sync-action-utils.js +52 -0
  171. package/lib/Utils/tc-token-utils.d.ts +12 -0
  172. package/lib/Utils/tc-token-utils.js +20 -0
  173. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  174. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  175. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  176. package/lib/Utils/use-single-file-auth-state.js +73 -0
  177. package/lib/Utils/validate-connection.d.ts +11 -0
  178. package/lib/Utils/validate-connection.js +206 -0
  179. package/lib/WABinary/constants.d.ts +28 -0
  180. package/lib/WABinary/constants.js +1303 -0
  181. package/lib/WABinary/decode.d.ts +7 -0
  182. package/lib/WABinary/decode.js +300 -0
  183. package/lib/WABinary/encode.d.ts +3 -0
  184. package/lib/WABinary/encode.js +256 -0
  185. package/lib/WABinary/generic-utils.d.ts +15 -0
  186. package/lib/WABinary/generic-utils.js +138 -0
  187. package/lib/WABinary/index.d.ts +6 -0
  188. package/lib/WABinary/index.js +25 -0
  189. package/lib/WABinary/jid-utils.d.ts +48 -0
  190. package/lib/WABinary/jid-utils.js +115 -0
  191. package/lib/WABinary/types.d.ts +19 -0
  192. package/lib/WABinary/types.js +36 -0
  193. package/lib/WAM/BinaryInfo.d.ts +9 -0
  194. package/lib/WAM/BinaryInfo.js +13 -0
  195. package/lib/WAM/constants.d.ts +40 -0
  196. package/lib/WAM/constants.js +22855 -0
  197. package/lib/WAM/encode.d.ts +3 -0
  198. package/lib/WAM/encode.js +153 -0
  199. package/lib/WAM/index.d.ts +4 -0
  200. package/lib/WAM/index.js +19 -0
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  203. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  204. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  205. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  206. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  207. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  208. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +41 -0
  209. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  210. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +54 -0
  211. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  212. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +32 -0
  213. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  214. package/lib/WAUSync/Protocols/index.js +22 -0
  215. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  216. package/lib/WAUSync/USyncQuery.js +97 -0
  217. package/lib/WAUSync/USyncUser.d.ts +13 -0
  218. package/lib/WAUSync/USyncUser.js +26 -0
  219. package/lib/WAUSync/index.d.ts +4 -0
  220. package/lib/WAUSync/index.js +19 -0
  221. package/lib/index.d.ts +12 -0
  222. package/lib/index.js +124 -0
  223. package/package.json +120 -0
  224. package/readme.md +1956 -0
@@ -0,0 +1,887 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.prepareStream = exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.uploadWithNodeHttp = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.getStream = exports.toBuffer = exports.toReadable = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.getRawMediaUploadData = exports.hkdfInfoKey = void 0;
37
+ exports.getMediaKeys = getMediaKeys;
38
+ exports.getAudioDuration = getAudioDuration;
39
+ exports.getAudioWaveform = getAudioWaveform;
40
+ exports.generateThumbnail = generateThumbnail;
41
+ exports.extensionForMediaMessage = extensionForMediaMessage;
42
+ const events_1 = require("events");
43
+ const boom_1 = require("@hapi/boom");
44
+ const Crypto = __importStar(require("crypto"));
45
+ const fs_1 = require("fs");
46
+ const os_1 = require("os");
47
+ const path_1 = require("path");
48
+ const stream_1 = require("stream");
49
+ const url_1 = require("url");
50
+ const index_js_1 = require("../../WAProto/index.js");
51
+ const index_js_2 = require("../Defaults/index.js");
52
+ const index_js_3 = require("../WABinary/index.js");
53
+ const crypto_js_1 = require("./crypto.js");
54
+ const generics_js_1 = require("./generics.js");
55
+ const getTmpFilesDirectory = () => (0, os_1.tmpdir)();
56
+ const getImageProcessingLibrary = async () => {
57
+ //@ts-ignore
58
+ const [jimp, sharp] = await Promise.all([Promise.resolve().then(() => __importStar(require('jimp'))).catch(() => { }), Promise.resolve().then(() => __importStar(require('sharp'))).catch(() => { })]);
59
+ if (sharp) {
60
+ return { sharp };
61
+ }
62
+ if (jimp) {
63
+ return { jimp };
64
+ }
65
+ throw new boom_1.Boom('No image processing library available');
66
+ };
67
+ const hkdfInfoKey = (type) => {
68
+ const hkdfInfo = index_js_2.MEDIA_HKDF_KEY_MAPPING[type];
69
+ return `WhatsApp ${hkdfInfo} Keys`;
70
+ };
71
+ exports.hkdfInfoKey = hkdfInfoKey;
72
+ const getRawMediaUploadData = async (media, mediaType, logger) => {
73
+ const { stream } = await (0, exports.getStream)(media);
74
+ const hasher = Crypto.createHash('sha256');
75
+ const filePath = (0, path_1.join)((0, os_1.tmpdir)(), mediaType + (0, generics_js_1.generateMessageIDV2)());
76
+ const fileWriteStream = (0, fs_1.createWriteStream)(filePath);
77
+ let fileLength = 0;
78
+ try {
79
+ for await (const data of stream) {
80
+ fileLength += data.length;
81
+ hasher.update(data);
82
+ if (!fileWriteStream.write(data)) {
83
+ await (0, events_1.once)(fileWriteStream, 'drain');
84
+ }
85
+ }
86
+ fileWriteStream.end();
87
+ await (0, events_1.once)(fileWriteStream, 'finish');
88
+ stream.destroy();
89
+ const fileSha256 = hasher.digest();
90
+ return {
91
+ filePath: filePath,
92
+ fileSha256,
93
+ fileLength
94
+ };
95
+ }
96
+ catch (error) {
97
+ fileWriteStream.destroy();
98
+ stream.destroy();
99
+ try {
100
+ await fs_1.promises.unlink(filePath);
101
+ }
102
+ catch {
103
+ //
104
+ }
105
+ throw error;
106
+ }
107
+ };
108
+ exports.getRawMediaUploadData = getRawMediaUploadData;
109
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
110
+ async function getMediaKeys(buffer, mediaType) {
111
+ if (!buffer) {
112
+ throw new boom_1.Boom('Cannot derive from empty media key');
113
+ }
114
+ if (typeof buffer === 'string') {
115
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
116
+ }
117
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
118
+ const expandedMediaKey = (0, crypto_js_1.hkdf)(buffer, 112, { info: (0, exports.hkdfInfoKey)(mediaType) });
119
+ return {
120
+ iv: expandedMediaKey.slice(0, 16),
121
+ cipherKey: expandedMediaKey.slice(16, 48),
122
+ macKey: expandedMediaKey.slice(48, 80)
123
+ };
124
+ }
125
+ const extractImageThumb = async (bufferOrFilePath, width = 32) => {
126
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
127
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
128
+ if (bufferOrFilePath instanceof stream_1.Readable) {
129
+ bufferOrFilePath = await (0, exports.toBuffer)(bufferOrFilePath);
130
+ }
131
+ const lib = await getImageProcessingLibrary();
132
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
133
+ const img = lib.sharp.default(bufferOrFilePath);
134
+ const dimensions = await img.metadata();
135
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
136
+ return {
137
+ buffer,
138
+ original: {
139
+ width: dimensions.width,
140
+ height: dimensions.height
141
+ }
142
+ };
143
+ }
144
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'object') {
145
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
146
+ const dimensions = {
147
+ width: jimp.width,
148
+ height: jimp.height
149
+ };
150
+ const buffer = await jimp
151
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
152
+ .getBuffer('image/jpeg', { quality: 50 });
153
+ return {
154
+ buffer,
155
+ original: dimensions
156
+ };
157
+ }
158
+ else {
159
+ throw new boom_1.Boom('No image processing library available');
160
+ }
161
+ };
162
+ exports.extractImageThumb = extractImageThumb;
163
+ const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
164
+ exports.encodeBase64EncodedStringForUpload = encodeBase64EncodedStringForUpload;
165
+ const generateProfilePicture = async (mediaUpload, dimensions) => {
166
+ let buffer;
167
+ const { width: w = 640, height: h = 640 } = dimensions || {};
168
+ if (Buffer.isBuffer(mediaUpload)) {
169
+ buffer = mediaUpload;
170
+ }
171
+ else {
172
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
173
+ const { stream } = await (0, exports.getStream)(mediaUpload);
174
+ // Convert the resulting stream to a buffer
175
+ buffer = await (0, exports.toBuffer)(stream);
176
+ }
177
+ const lib = await getImageProcessingLibrary();
178
+ let img;
179
+ if ('sharp' in lib && typeof lib.sharp?.default === 'function') {
180
+ img = lib.sharp
181
+ .default(buffer)
182
+ .resize(w, h)
183
+ .jpeg({
184
+ quality: 50
185
+ })
186
+ .toBuffer();
187
+ }
188
+ else if ('jimp' in lib && typeof lib.jimp?.Jimp === 'function') {
189
+ const jimp = await lib.jimp.Jimp.read(buffer);
190
+ const min = Math.min(jimp.width, jimp.height);
191
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
192
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 50 });
193
+ }
194
+ else {
195
+ throw new boom_1.Boom('No image processing library available');
196
+ }
197
+ return {
198
+ img: await img
199
+ };
200
+ };
201
+ exports.generateProfilePicture = generateProfilePicture;
202
+ /** gets the SHA256 of the given media message */
203
+ const mediaMessageSHA256B64 = (message) => {
204
+ const media = Object.values(message)[0];
205
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
206
+ };
207
+ exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
208
+ async function getAudioDuration(buffer, mimeType) {
209
+ const musicMetadata = await Promise.resolve().then(() => __importStar(require('music-metadata')));
210
+ let metadata;
211
+ const options = {
212
+ duration: true,
213
+ ...(mimeType ? { mimeType } : {})
214
+ };
215
+ if (Buffer.isBuffer(buffer)) {
216
+ metadata = await musicMetadata.parseBuffer(buffer, mimeType || undefined, options);
217
+ }
218
+ else if (typeof buffer === 'string') {
219
+ // parseFile tidak support mimeType langsung, tapi kita bisa baca sebagai buffer
220
+ // supaya mimeType hint bisa dipass — penting untuk m4a/aac yang nama filenya tanpa ekstensi
221
+ try {
222
+ metadata = await musicMetadata.parseFile(buffer, options);
223
+ }
224
+ catch (_) {
225
+ // fallback: baca file sebagai buffer lalu parse dengan mimeType
226
+ const { readFileSync } = await Promise.resolve().then(() => __importStar(require('fs')));
227
+ const buf = readFileSync(buffer);
228
+ metadata = await musicMetadata.parseBuffer(buf, mimeType || undefined, options);
229
+ }
230
+ }
231
+ else {
232
+ metadata = await musicMetadata.parseStream(buffer, mimeType || undefined, options);
233
+ }
234
+ const dur = metadata.format.duration;
235
+ // Jangan return NaN/undefined — WhatsApp akan tampilkan "Loading..." kalau seconds invalid
236
+ return (typeof dur === 'number' && !isNaN(dur) && isFinite(dur)) ? Math.round(dur) : 0;
237
+ }
238
+ /**
239
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
240
+ */
241
+ async function getAudioWaveform(buffer, logger) {
242
+ try {
243
+ // @ts-ignore
244
+ const { default: decoder } = await Promise.resolve().then(() => __importStar(require('audio-decode')));
245
+ let audioData;
246
+ if (Buffer.isBuffer(buffer)) {
247
+ audioData = buffer;
248
+ }
249
+ else if (typeof buffer === 'string') {
250
+ const rStream = (0, fs_1.createReadStream)(buffer);
251
+ audioData = await (0, exports.toBuffer)(rStream);
252
+ }
253
+ else {
254
+ audioData = await (0, exports.toBuffer)(buffer);
255
+ }
256
+ // Skip audio-decode for large buffers (> 3MB)
257
+ if (audioData.length > 3 * 1024 * 1024) {
258
+ return undefined;
259
+ }
260
+ const audioBuffer = await decoder(audioData);
261
+ const rawData = audioBuffer.getChannelData(0);
262
+ const samples = 64;
263
+ const blockSize = Math.floor(rawData.length / samples);
264
+ const filteredData = [];
265
+ for (let i = 0; i < samples; i++) {
266
+ const blockStart = blockSize * i;
267
+ let sum = 0;
268
+ for (let j = 0; j < blockSize; j++) {
269
+ sum = sum + Math.abs(rawData[blockStart + j]);
270
+ }
271
+ filteredData.push(sum / blockSize);
272
+ }
273
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
274
+ const normalizedData = filteredData.map(n => n * multiplier);
275
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
276
+ return waveform;
277
+ }
278
+ catch (e) {
279
+ }
280
+ }
281
+ const toReadable = (buffer) => {
282
+ const readable = new stream_1.Readable({ read: () => { }, highWaterMark: 64 * 1024 });
283
+ readable.push(buffer);
284
+ readable.push(null);
285
+ return readable;
286
+ };
287
+ exports.toReadable = toReadable;
288
+ const toBuffer = async (stream) => {
289
+ const chunks = [];
290
+ for await (const chunk of stream) {
291
+ chunks.push(chunk);
292
+ }
293
+ stream.destroy();
294
+ return Buffer.concat(chunks);
295
+ };
296
+ exports.toBuffer = toBuffer;
297
+ const getStream = async (item, opts) => {
298
+ if (item === undefined || item === null) {
299
+ throw new Error('Media input is undefined');
300
+ }
301
+ if (Buffer.isBuffer(item)) {
302
+ return { stream: (0, exports.toReadable)(item), type: 'buffer' };
303
+ }
304
+ if ('stream' in item) {
305
+ return { stream: item.stream, type: 'readable' };
306
+ }
307
+ const urlStr = item.url.toString();
308
+ if (urlStr.startsWith('data:')) {
309
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
310
+ return { stream: (0, exports.toReadable)(buffer), type: 'buffer' };
311
+ }
312
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
313
+ return { stream: await (0, exports.getHttpStream)(item.url, opts), type: 'remote' };
314
+ }
315
+ return { stream: (0, fs_1.createReadStream)(item.url), type: 'file' };
316
+ };
317
+ exports.getStream = getStream;
318
+ /** generates a thumbnail for a given media, if required */
319
+ async function generateThumbnail(file, mediaType, options) {
320
+ let thumbnail;
321
+ let originalImageDimensions;
322
+ if (mediaType === 'image') {
323
+ const { buffer, original } = await (0, exports.extractImageThumb)(file);
324
+ thumbnail = buffer.toString('base64');
325
+ if (original.width && original.height) {
326
+ originalImageDimensions = {
327
+ width: original.width,
328
+ height: original.height
329
+ };
330
+ }
331
+ }
332
+ else if (mediaType === 'video') {
333
+ // Video thumbnail generation skipped (ffmpeg removed)
334
+ }
335
+ return {
336
+ thumbnail,
337
+ originalImageDimensions
338
+ };
339
+ }
340
+ const getHttpStream = async (url, options = {}) => {
341
+ const response = await fetch(url.toString(), {
342
+ dispatcher: options.dispatcher,
343
+ method: 'GET',
344
+ headers: options.headers
345
+ });
346
+ if (!response.ok) {
347
+ throw new boom_1.Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
348
+ }
349
+ // @ts-ignore Node18+ Readable.fromWeb exists
350
+ return response.body instanceof stream_1.Readable ? response.body : stream_1.Readable.fromWeb(response.body);
351
+ };
352
+ exports.getHttpStream = getHttpStream;
353
+ const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
354
+ const { stream, type } = await (0, exports.getStream)(media, opts);
355
+ let finalStream = stream;
356
+ let opusConverted = false;
357
+ const mediaKey = Crypto.randomBytes(32);
358
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
359
+ const encWriteStream = new stream_1.Readable({ read: () => { }, highWaterMark: 64 * 1024 });
360
+ let bodyPath;
361
+ let writeStream;
362
+ let didSaveToTmpPath = false;
363
+ if (type === 'file') {
364
+ bodyPath = media.url?.toString?.() || media.url;
365
+ }
366
+ else if (saveOriginalFileIfRequired) {
367
+ bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_js_1.generateMessageIDV2)());
368
+ writeStream = (0, fs_1.createWriteStream)(bodyPath);
369
+ didSaveToTmpPath = true;
370
+ }
371
+ let fileLength = 0;
372
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
373
+ let hmac = Crypto.createHmac('sha256', macKey).update(iv);
374
+ let sha256Plain = Crypto.createHash('sha256');
375
+ let sha256Enc = Crypto.createHash('sha256');
376
+ const onChunk = (buff) => {
377
+ sha256Enc = sha256Enc.update(buff);
378
+ hmac = hmac.update(buff);
379
+ encWriteStream.push(buff);
380
+ };
381
+ try {
382
+ for await (const data of finalStream) {
383
+ fileLength += data.length;
384
+ if (type === 'remote' &&
385
+ opts?.maxContentLength &&
386
+ fileLength + data.length > opts.maxContentLength) {
387
+ throw new boom_1.Boom(`content length exceeded when encrypting "${type}"`, {
388
+ data: { media, type }
389
+ });
390
+ }
391
+ sha256Plain = sha256Plain.update(data);
392
+ if (writeStream) {
393
+ if (!writeStream.write(data)) {
394
+ await (0, events_1.once)(writeStream, 'drain');
395
+ }
396
+ }
397
+ onChunk(aes.update(data));
398
+ }
399
+ onChunk(aes.final());
400
+ const mac = hmac.digest().slice(0, 10);
401
+ sha256Enc = sha256Enc.update(mac);
402
+ const fileSha256 = sha256Plain.digest();
403
+ const fileEncSha256 = sha256Enc.digest();
404
+ encWriteStream.push(mac);
405
+ encWriteStream.push(null);
406
+ writeStream?.end();
407
+ if (writeStream)
408
+ await (0, events_1.once)(writeStream, 'finish');
409
+ finalStream.destroy();
410
+ return {
411
+ mediaKey,
412
+ encWriteStream,
413
+ bodyPath,
414
+ mac,
415
+ fileEncSha256,
416
+ fileSha256,
417
+ fileLength,
418
+ didSaveToTmpPath,
419
+ opusConverted
420
+ };
421
+ }
422
+ catch (error) {
423
+ encWriteStream.destroy();
424
+ writeStream?.destroy();
425
+ aes.destroy();
426
+ hmac.destroy();
427
+ sha256Plain.destroy();
428
+ sha256Enc.destroy();
429
+ stream.destroy();
430
+ if (didSaveToTmpPath) {
431
+ try {
432
+ await fs_1.promises.unlink(bodyPath);
433
+ }
434
+ catch (_) { }
435
+ }
436
+ throw error;
437
+ }
438
+ };
439
+ exports.encryptedStream = encryptedStream;
440
+ const DEF_HOST = 'mmg.whatsapp.net';
441
+ const AES_CHUNK_SIZE = 16;
442
+ const toSmallestChunkSize = (num) => {
443
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
444
+ };
445
+ const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
446
+ exports.getUrlFromDirectPath = getUrlFromDirectPath;
447
+ const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
448
+ const isValidMediaUrl = url?.startsWith('https://mmg.whatsapp.net/');
449
+ const downloadUrl = isValidMediaUrl ? url : (0, exports.getUrlFromDirectPath)(directPath);
450
+ if (!downloadUrl) {
451
+ throw new boom_1.Boom('No valid media URL or directPath present in message', { statusCode: 400 });
452
+ }
453
+ const keys = await getMediaKeys(mediaKey, type);
454
+ return (0, exports.downloadEncryptedContent)(downloadUrl, keys, opts);
455
+ };
456
+ exports.downloadContentFromMessage = downloadContentFromMessage;
457
+ /**
458
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
459
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
460
+ * */
461
+ const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
462
+ let bytesFetched = 0;
463
+ let startChunk = 0;
464
+ let firstBlockIsIV = false;
465
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
466
+ if (startByte) {
467
+ const chunk = toSmallestChunkSize(startByte || 0);
468
+ if (chunk) {
469
+ startChunk = chunk - AES_CHUNK_SIZE;
470
+ bytesFetched = chunk;
471
+ firstBlockIsIV = true;
472
+ }
473
+ }
474
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
475
+ const headersInit = options?.headers ? options.headers : undefined;
476
+ const headers = {
477
+ ...(headersInit
478
+ ? Array.isArray(headersInit)
479
+ ? Object.fromEntries(headersInit)
480
+ : headersInit
481
+ : {}),
482
+ Origin: index_js_2.DEFAULT_ORIGIN
483
+ };
484
+ if (startChunk || endChunk) {
485
+ headers.Range = `bytes=${startChunk}-`;
486
+ if (endChunk) {
487
+ headers.Range += endChunk;
488
+ }
489
+ }
490
+ // download the message
491
+ const fetched = await (0, exports.getHttpStream)(downloadUrl, {
492
+ ...(options || {}),
493
+ headers
494
+ });
495
+ let remainingBytes = Buffer.from([]);
496
+ let aes;
497
+ const pushBytes = (bytes, push) => {
498
+ if (startByte || endByte) {
499
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
500
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
501
+ push(bytes.slice(start, end));
502
+ bytesFetched += bytes.length;
503
+ }
504
+ else {
505
+ push(bytes);
506
+ }
507
+ };
508
+ const output = new stream_1.Transform({
509
+ transform(chunk, _, callback) {
510
+ let data = Buffer.concat([remainingBytes, chunk]);
511
+ const decryptLength = toSmallestChunkSize(data.length);
512
+ remainingBytes = data.slice(decryptLength);
513
+ data = data.slice(0, decryptLength);
514
+ if (!aes) {
515
+ let ivValue = iv;
516
+ if (firstBlockIsIV) {
517
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
518
+ data = data.slice(AES_CHUNK_SIZE);
519
+ }
520
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
521
+ // if an end byte that is not EOF is specified
522
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
523
+ if (endByte) {
524
+ aes.setAutoPadding(false);
525
+ }
526
+ }
527
+ try {
528
+ pushBytes(aes.update(data), b => this.push(b));
529
+ callback();
530
+ }
531
+ catch (error) {
532
+ callback(error);
533
+ }
534
+ },
535
+ final(callback) {
536
+ try {
537
+ pushBytes(aes.final(), b => this.push(b));
538
+ callback();
539
+ }
540
+ catch (error) {
541
+ callback(error);
542
+ }
543
+ }
544
+ });
545
+ return fetched.pipe(output, { end: true });
546
+ };
547
+ exports.downloadEncryptedContent = downloadEncryptedContent;
548
+ function extensionForMediaMessage(message) {
549
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
550
+ const type = Object.keys(message)[0];
551
+ let extension;
552
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
553
+ extension = '.jpeg';
554
+ }
555
+ else {
556
+ const messageContent = message[type];
557
+ extension = getExtension(messageContent.mimetype);
558
+ }
559
+ return extension;
560
+ }
561
+ const isNodeRuntime = () => {
562
+ return (typeof process !== 'undefined' &&
563
+ process.versions?.node !== null &&
564
+ typeof process.versions.bun === 'undefined' &&
565
+ typeof globalThis.Deno === 'undefined');
566
+ };
567
+ const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
568
+ if (redirectCount > 5) {
569
+ throw new Error('Too many redirects');
570
+ }
571
+ const parsedUrl = new url_1.URL(url);
572
+ const httpModule = parsedUrl.protocol === 'https:' ? await Promise.resolve().then(() => __importStar(require('https'))) : await Promise.resolve().then(() => __importStar(require('http')));
573
+ // Get file size for Content-Length header (required for Node.js streaming)
574
+ const fileStats = await fs_1.promises.stat(filePath);
575
+ const fileSize = fileStats.size;
576
+ return new Promise((resolve, reject) => {
577
+ const req = httpModule.request({
578
+ hostname: parsedUrl.hostname,
579
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
580
+ path: parsedUrl.pathname + parsedUrl.search,
581
+ method: 'POST',
582
+ headers: {
583
+ ...headers,
584
+ 'Content-Length': fileSize
585
+ },
586
+ agent,
587
+ timeout: timeoutMs
588
+ }, res => {
589
+ // Handle redirects (3xx)
590
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
591
+ res.resume(); // Consume response to free resources
592
+ const newUrl = new url_1.URL(res.headers.location, url).toString();
593
+ resolve((0, exports.uploadWithNodeHttp)({
594
+ url: newUrl,
595
+ filePath,
596
+ headers,
597
+ timeoutMs,
598
+ agent
599
+ }, redirectCount + 1));
600
+ return;
601
+ }
602
+ let body = '';
603
+ res.on('data', chunk => (body += chunk));
604
+ res.on('end', () => {
605
+ try {
606
+ resolve(JSON.parse(body));
607
+ }
608
+ catch {
609
+ resolve(undefined);
610
+ }
611
+ });
612
+ });
613
+ req.on('error', reject);
614
+ req.on('timeout', () => {
615
+ req.destroy();
616
+ reject(new Error('Upload timeout'));
617
+ });
618
+ const stream = (0, fs_1.createReadStream)(filePath);
619
+ stream.pipe(req);
620
+ stream.on('error', err => {
621
+ req.destroy();
622
+ reject(err);
623
+ });
624
+ });
625
+ };
626
+ exports.uploadWithNodeHttp = uploadWithNodeHttp;
627
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
628
+ // Convert Node.js Readable to Web ReadableStream
629
+ const nodeStream = (0, fs_1.createReadStream)(filePath);
630
+ const webStream = stream_1.Readable.toWeb(nodeStream);
631
+ const response = await fetch(url, {
632
+ dispatcher: agent,
633
+ method: 'POST',
634
+ body: webStream,
635
+ headers,
636
+ duplex: 'half',
637
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
638
+ });
639
+ try {
640
+ return (await response.json());
641
+ }
642
+ catch {
643
+ return undefined;
644
+ }
645
+ };
646
+ /**
647
+ * Uploads media to WhatsApp servers.
648
+ *
649
+ * ## Why we have two upload implementations:
650
+ *
651
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
652
+ * the entire request body in memory before sending, even when using streams.
653
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
654
+ * See: https://github.com/nodejs/undici/issues/4058
655
+ *
656
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
657
+ * buffering, so we can use the web-standard Fetch API there.
658
+ *
659
+ * ## Future considerations:
660
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
661
+ * across all runtimes. Monitor the GitHub issue for updates.
662
+ */
663
+ const uploadMedia = async (params, logger) => {
664
+ if (isNodeRuntime()) {
665
+ return (0, exports.uploadWithNodeHttp)(params);
666
+ }
667
+ else {
668
+ return uploadWithFetch(params);
669
+ }
670
+ };
671
+ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
672
+ return async (streamOrPath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
673
+ // send a query JSON to obtain the url & auth token to upload our media
674
+ let uploadInfo = await refreshMediaConn(false);
675
+ let urls;
676
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
677
+ fileEncSha256B64 = (0, exports.encodeBase64EncodedStringForUpload)(fileEncSha256B64);
678
+ // Prepare common headers
679
+ const customHeaders = (() => {
680
+ const hdrs = options?.headers;
681
+ if (!hdrs)
682
+ return {};
683
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
684
+ })();
685
+ const headers = {
686
+ ...customHeaders,
687
+ 'Content-Type': 'application/octet-stream',
688
+ Origin: index_js_2.DEFAULT_ORIGIN
689
+ };
690
+ // Collect buffer from Readable stream or read from file path
691
+ let reqBuffer;
692
+ if (Buffer.isBuffer(streamOrPath)) {
693
+ reqBuffer = streamOrPath;
694
+ }
695
+ else if (typeof streamOrPath === 'string') {
696
+ reqBuffer = await fs_1.promises.readFile(streamOrPath);
697
+ }
698
+ else {
699
+ // Readable stream
700
+ const chunks = [];
701
+ for await (const chunk of streamOrPath)
702
+ chunks.push(chunk);
703
+ reqBuffer = Buffer.concat(chunks);
704
+ }
705
+ // Newsletter uses different upload path
706
+ let mediaPath = index_js_2.MEDIA_PATH_MAP[mediaType];
707
+ if (newsletter) {
708
+ mediaPath = mediaPath?.replace('/mms/', '/newsletter/newsletter-');
709
+ }
710
+ for (const { hostname, maxContentLengthBytes } of hosts) {
711
+ const auth = encodeURIComponent(uploadInfo.auth);
712
+ const url = `https://${hostname}${mediaPath}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
713
+ let result;
714
+ try {
715
+ // Upload buffer directly like wiley (avoids file I/O issues)
716
+ const axios = (await Promise.resolve().then(() => __importStar(require('axios')))).default;
717
+ const body = await axios.post(url, reqBuffer, {
718
+ ...options,
719
+ headers: {
720
+ ...headers,
721
+ },
722
+ httpsAgent: fetchAgent,
723
+ timeout: timeoutMs,
724
+ responseType: 'json',
725
+ maxBodyLength: Infinity,
726
+ maxContentLength: Infinity,
727
+ });
728
+ result = body.data;
729
+ if (result?.url || result?.direct_path) {
730
+ urls = {
731
+ mediaUrl: result.url,
732
+ directPath: result.direct_path,
733
+ handle: result.handle,
734
+ meta_hmac: result.meta_hmac,
735
+ fbid: result.fbid,
736
+ ts: result.ts
737
+ };
738
+ break;
739
+ }
740
+ else {
741
+ uploadInfo = await refreshMediaConn(true);
742
+ throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
743
+ }
744
+ }
745
+ catch (error) {
746
+ const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
747
+ logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? '' : ', retrying...'}`);
748
+ }
749
+ }
750
+ if (!urls) {
751
+ throw new boom_1.Boom('Media upload failed on all hosts', { statusCode: 500 });
752
+ }
753
+ return urls;
754
+ };
755
+ };
756
+ exports.getWAUploadToServer = getWAUploadToServer;
757
+ const getMediaRetryKey = (mediaKey) => {
758
+ return (0, crypto_js_1.hkdf)(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
759
+ };
760
+ /**
761
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
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_js_1.aesEncryptGCM)(recpBuffer, retryKey, iv, Buffer.from(key.id));
769
+ const req = {
770
+ tag: 'receipt',
771
+ attrs: {
772
+ id: key.id,
773
+ to: (0, index_js_3.jidNormalizedUser)(meId),
774
+ type: 'server-error'
775
+ },
776
+ content: [
777
+ // this encrypt node is actually pretty useless
778
+ // the media is returned even without this node
779
+ // keeping it here to maintain parity with WA Web
780
+ {
781
+ tag: 'encrypt',
782
+ attrs: {},
783
+ content: [
784
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
785
+ { tag: 'enc_iv', attrs: {}, content: iv }
786
+ ]
787
+ },
788
+ {
789
+ tag: 'rmr',
790
+ attrs: {
791
+ jid: key.remoteJid,
792
+ from_me: (!!key.fromMe).toString(),
793
+ // @ts-ignore
794
+ participant: key.participant || undefined
795
+ }
796
+ }
797
+ ]
798
+ };
799
+ return req;
800
+ };
801
+ exports.encryptMediaRetryRequest = encryptMediaRetryRequest;
802
+ const decodeMediaRetryNode = (node) => {
803
+ const rmrNode = (0, index_js_3.getBinaryNodeChild)(node, 'rmr');
804
+ const event = {
805
+ key: {
806
+ id: node.attrs.id,
807
+ remoteJid: rmrNode.attrs.jid,
808
+ fromMe: rmrNode.attrs.from_me === 'true',
809
+ participant: rmrNode.attrs.participant
810
+ }
811
+ };
812
+ const errorNode = (0, index_js_3.getBinaryNodeChild)(node, 'error');
813
+ if (errorNode) {
814
+ const errorCode = +errorNode.attrs.code;
815
+ event.error = new boom_1.Boom(`Failed to re-upload media (${errorCode})`, {
816
+ data: errorNode.attrs,
817
+ statusCode: (0, exports.getStatusCodeForMediaRetry)(errorCode)
818
+ });
819
+ }
820
+ else {
821
+ const encryptedInfoNode = (0, index_js_3.getBinaryNodeChild)(node, 'encrypt');
822
+ const ciphertext = (0, index_js_3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_p');
823
+ const iv = (0, index_js_3.getBinaryNodeChildBuffer)(encryptedInfoNode, 'enc_iv');
824
+ if (ciphertext && iv) {
825
+ event.media = { ciphertext, iv };
826
+ }
827
+ else {
828
+ event.error = new boom_1.Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
829
+ }
830
+ }
831
+ return event;
832
+ };
833
+ exports.decodeMediaRetryNode = decodeMediaRetryNode;
834
+ const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
835
+ const retryKey = getMediaRetryKey(mediaKey);
836
+ const plaintext = (0, crypto_js_1.aesDecryptGCM)(ciphertext, retryKey, iv, Buffer.from(msgId));
837
+ return index_js_1.proto.MediaRetryNotification.decode(plaintext);
838
+ };
839
+ exports.decryptMediaRetryData = decryptMediaRetryData;
840
+ const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
841
+ exports.getStatusCodeForMediaRetry = getStatusCodeForMediaRetry;
842
+ const MEDIA_RETRY_STATUS_MAP = {
843
+ [index_js_1.proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
844
+ [index_js_1.proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
845
+ [index_js_1.proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
846
+ [index_js_1.proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
847
+ };
848
+ const prepareStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts, isPtt, forceOpus } = {}) => {
849
+ const { stream, type } = await (0, exports.getStream)(media, opts);
850
+ let buffer = await (0, exports.toBuffer)(stream);
851
+ let opusConverted = false;
852
+ let bodyPath;
853
+ let didSaveToTmpPath = false;
854
+ try {
855
+ if (type === 'file') {
856
+ bodyPath = media.url?.toString?.() || media.url;
857
+ }
858
+ else if (saveOriginalFileIfRequired) {
859
+ bodyPath = (0, path_1.join)(getTmpFilesDirectory(), mediaType + (0, generics_js_1.generateMessageIDV2)());
860
+ const { writeFileSync } = await Promise.resolve().then(() => __importStar(require('fs')));
861
+ writeFileSync(bodyPath, buffer);
862
+ didSaveToTmpPath = true;
863
+ }
864
+ const fileLength = buffer.length;
865
+ const fileSha256 = Crypto.createHash('sha256').update(buffer).digest();
866
+ return {
867
+ mediaKey: undefined,
868
+ encWriteStream: buffer,
869
+ fileLength,
870
+ fileSha256,
871
+ fileEncSha256: undefined,
872
+ bodyPath,
873
+ didSaveToTmpPath,
874
+ opusConverted
875
+ };
876
+ }
877
+ catch (error) {
878
+ if (didSaveToTmpPath && bodyPath) {
879
+ try {
880
+ await fs_1.promises.unlink(bodyPath);
881
+ }
882
+ catch (_) { }
883
+ }
884
+ throw error;
885
+ }
886
+ };
887
+ exports.prepareStream = prepareStream;