@neelegirl/baileys 1.4.3

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +77 -0
  3. package/WAProto/GenerateStatics.sh +4 -0
  4. package/WAProto/WAProto.proto +4451 -0
  5. package/WAProto/index.d.ts +51459 -0
  6. package/WAProto/index.js +158781 -0
  7. package/WASignalGroup/GroupProtocol.js +1697 -0
  8. package/WASignalGroup/ciphertext_message.js +16 -0
  9. package/WASignalGroup/group_cipher.js +120 -0
  10. package/WASignalGroup/group_session_builder.js +46 -0
  11. package/WASignalGroup/index.js +5 -0
  12. package/WASignalGroup/keyhelper.js +21 -0
  13. package/WASignalGroup/protobufs.js +3 -0
  14. package/WASignalGroup/queue_job.js +69 -0
  15. package/WASignalGroup/sender_chain_key.js +50 -0
  16. package/WASignalGroup/sender_key_distribution_message.js +78 -0
  17. package/WASignalGroup/sender_key_message.js +92 -0
  18. package/WASignalGroup/sender_key_name.js +70 -0
  19. package/WASignalGroup/sender_key_record.js +56 -0
  20. package/WASignalGroup/sender_key_state.js +129 -0
  21. package/WASignalGroup/sender_message_key.js +39 -0
  22. package/package.json +88 -0
  23. package/src/Defaults/baileys-version.json +3 -0
  24. package/src/Defaults/index.d.ts +68 -0
  25. package/src/Defaults/index.js +131 -0
  26. package/src/Defaults/phonenumber-mcc.json +223 -0
  27. package/src/Signal/libsignal.d.ts +4 -0
  28. package/src/Signal/libsignal.js +162 -0
  29. package/src/Socket/Client/index.d.ts +2 -0
  30. package/src/Socket/Client/index.js +22 -0
  31. package/src/Socket/Client/types.d.ts +16 -0
  32. package/src/Socket/Client/types.js +18 -0
  33. package/src/Socket/Client/websocket.d.ts +13 -0
  34. package/src/Socket/Client/websocket.js +62 -0
  35. package/src/Socket/business.d.ts +182 -0
  36. package/src/Socket/business.js +268 -0
  37. package/src/Socket/chats.d.ts +96 -0
  38. package/src/Socket/chats.js +1278 -0
  39. package/src/Socket/groups.d.ts +130 -0
  40. package/src/Socket/groups.js +337 -0
  41. package/src/Socket/index.d.ts +185 -0
  42. package/src/Socket/index.js +14 -0
  43. package/src/Socket/messages-recv.d.ts +171 -0
  44. package/src/Socket/messages-recv.js +1182 -0
  45. package/src/Socket/messages-send.d.ts +162 -0
  46. package/src/Socket/messages-send.js +1086 -0
  47. package/src/Socket/newsletter.d.ts +142 -0
  48. package/src/Socket/newsletter.js +256 -0
  49. package/src/Socket/socket.d.ts +45 -0
  50. package/src/Socket/socket.js +749 -0
  51. package/src/Socket/usync.d.ts +37 -0
  52. package/src/Socket/usync.js +83 -0
  53. package/src/Store/index.d.ts +4 -0
  54. package/src/Store/index.js +24 -0
  55. package/src/Store/make-cache-manager-store.d.ts +14 -0
  56. package/src/Store/make-cache-manager-store.js +90 -0
  57. package/src/Store/make-in-memory-store.d.ts +123 -0
  58. package/src/Store/make-in-memory-store.js +429 -0
  59. package/src/Store/make-ordered-dictionary.d.ts +12 -0
  60. package/src/Store/make-ordered-dictionary.js +86 -0
  61. package/src/Store/object-repository.d.ts +10 -0
  62. package/src/Store/object-repository.js +31 -0
  63. package/src/Types/Auth.d.ts +120 -0
  64. package/src/Types/Auth.js +3 -0
  65. package/src/Types/Call.d.ts +14 -0
  66. package/src/Types/Call.js +3 -0
  67. package/src/Types/Chat.d.ts +134 -0
  68. package/src/Types/Chat.js +9 -0
  69. package/src/Types/Contact.d.ts +25 -0
  70. package/src/Types/Contact.js +3 -0
  71. package/src/Types/Events.d.ts +212 -0
  72. package/src/Types/Events.js +3 -0
  73. package/src/Types/GroupMetadata.d.ts +64 -0
  74. package/src/Types/GroupMetadata.js +3 -0
  75. package/src/Types/Label.d.ts +48 -0
  76. package/src/Types/Label.js +31 -0
  77. package/src/Types/LabelAssociation.d.ts +35 -0
  78. package/src/Types/LabelAssociation.js +13 -0
  79. package/src/Types/Message.d.ts +459 -0
  80. package/src/Types/Message.js +13 -0
  81. package/src/Types/Newsletter.d.ts +107 -0
  82. package/src/Types/Newsletter.js +38 -0
  83. package/src/Types/Product.d.ts +92 -0
  84. package/src/Types/Product.js +3 -0
  85. package/src/Types/Signal.d.ts +68 -0
  86. package/src/Types/Signal.js +3 -0
  87. package/src/Types/Socket.d.ts +120 -0
  88. package/src/Types/Socket.js +3 -0
  89. package/src/Types/State.d.ts +29 -0
  90. package/src/Types/State.js +3 -0
  91. package/src/Types/USync.d.ts +26 -0
  92. package/src/Types/USync.js +3 -0
  93. package/src/Types/index.d.ts +78 -0
  94. package/src/Types/index.js +47 -0
  95. package/src/Utils/auth-utils.d.ts +21 -0
  96. package/src/Utils/auth-utils.js +205 -0
  97. package/src/Utils/baileys-event-stream.d.ts +18 -0
  98. package/src/Utils/baileys-event-stream.js +70 -0
  99. package/src/Utils/business.d.ts +29 -0
  100. package/src/Utils/business.js +247 -0
  101. package/src/Utils/chat-utils.d.ts +82 -0
  102. package/src/Utils/chat-utils.js +774 -0
  103. package/src/Utils/crypto.d.ts +56 -0
  104. package/src/Utils/crypto.js +179 -0
  105. package/src/Utils/decode-wa-message.d.ts +41 -0
  106. package/src/Utils/decode-wa-message.js +236 -0
  107. package/src/Utils/event-buffer.d.ts +39 -0
  108. package/src/Utils/event-buffer.js +548 -0
  109. package/src/Utils/generics.d.ts +129 -0
  110. package/src/Utils/generics.js +584 -0
  111. package/src/Utils/history.d.ts +23 -0
  112. package/src/Utils/history.js +100 -0
  113. package/src/Utils/index.d.ts +19 -0
  114. package/src/Utils/index.js +39 -0
  115. package/src/Utils/link-preview.d.ts +23 -0
  116. package/src/Utils/link-preview.js +120 -0
  117. package/src/Utils/logger.d.ts +13 -0
  118. package/src/Utils/logger.js +7 -0
  119. package/src/Utils/lt-hash.d.ts +14 -0
  120. package/src/Utils/lt-hash.js +58 -0
  121. package/src/Utils/make-mutex.d.ts +9 -0
  122. package/src/Utils/make-mutex.js +49 -0
  123. package/src/Utils/messages-media.d.ts +129 -0
  124. package/src/Utils/messages-media.js +782 -0
  125. package/src/Utils/messages.d.ts +103 -0
  126. package/src/Utils/messages.js +1536 -0
  127. package/src/Utils/noise-handler.d.ts +20 -0
  128. package/src/Utils/noise-handler.js +155 -0
  129. package/src/Utils/process-message.d.ts +49 -0
  130. package/src/Utils/process-message.js +387 -0
  131. package/src/Utils/signal.d.ts +42 -0
  132. package/src/Utils/signal.js +166 -0
  133. package/src/Utils/use-mongo-file-auth-state.d.ts +6 -0
  134. package/src/Utils/use-mongo-file-auth-state.js +84 -0
  135. package/src/Utils/use-multi-file-auth-state.d.ts +13 -0
  136. package/src/Utils/use-multi-file-auth-state.js +131 -0
  137. package/src/Utils/use-single-file-auth-state.d.ts +13 -0
  138. package/src/Utils/use-single-file-auth-state.js +80 -0
  139. package/src/Utils/validate-connection.d.ts +13 -0
  140. package/src/Utils/validate-connection.js +186 -0
  141. package/src/WABinary/constants.d.ts +30 -0
  142. package/src/WABinary/constants.js +53 -0
  143. package/src/WABinary/decode.d.ts +9 -0
  144. package/src/WABinary/decode.js +288 -0
  145. package/src/WABinary/encode.d.ts +3 -0
  146. package/src/WABinary/encode.js +256 -0
  147. package/src/WABinary/generic-utils.d.ts +28 -0
  148. package/src/WABinary/generic-utils.js +149 -0
  149. package/src/WABinary/index.d.ts +5 -0
  150. package/src/WABinary/index.js +25 -0
  151. package/src/WABinary/jid-utils.d.ts +53 -0
  152. package/src/WABinary/jid-utils.js +92 -0
  153. package/src/WABinary/types.d.ts +22 -0
  154. package/src/WABinary/types.js +3 -0
  155. package/src/WAM/BinaryInfo.d.ts +16 -0
  156. package/src/WAM/BinaryInfo.js +17 -0
  157. package/src/WAM/constants.d.ts +47 -0
  158. package/src/WAM/constants.js +15371 -0
  159. package/src/WAM/encode.d.ts +3 -0
  160. package/src/WAM/encode.js +165 -0
  161. package/src/WAM/index.d.ts +3 -0
  162. package/src/WAM/index.js +23 -0
  163. package/src/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +28 -0
  164. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +69 -0
  165. package/src/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  166. package/src/WAUSync/Protocols/USyncContactProtocol.js +36 -0
  167. package/src/WAUSync/Protocols/USyncDeviceProtocol.d.ts +26 -0
  168. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +62 -0
  169. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +14 -0
  170. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +35 -0
  171. package/src/WAUSync/Protocols/USyncLIDProtocol.d.ts +9 -0
  172. package/src/WAUSync/Protocols/USyncLIDProtocol.js +30 -0
  173. package/src/WAUSync/Protocols/USyncStatusProtocol.d.ts +14 -0
  174. package/src/WAUSync/Protocols/USyncStatusProtocol.js +46 -0
  175. package/src/WAUSync/Protocols/index.d.ts +6 -0
  176. package/src/WAUSync/Protocols/index.js +26 -0
  177. package/src/WAUSync/USyncQuery.d.ts +31 -0
  178. package/src/WAUSync/USyncQuery.js +92 -0
  179. package/src/WAUSync/USyncUser.d.ts +12 -0
  180. package/src/WAUSync/USyncUser.js +30 -0
  181. package/src/WAUSync/index.d.ts +3 -0
  182. package/src/WAUSync/index.js +23 -0
  183. package/src/index.d.ts +13 -0
  184. package/src/index.js +33 -0
@@ -0,0 +1,584 @@
1
+ "use strict"
2
+
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k
5
+ var desc = Object.getOwnPropertyDescriptor(m, k)
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k] } }
8
+ }
9
+ Object.defineProperty(o, k2, desc)
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k
12
+ o[k2] = m[k]
13
+ }))
14
+
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v })
17
+ }) : function(o, v) {
18
+ o["default"] = v
19
+ })
20
+
21
+ var __importStar = (this && this.__importStar) || function (mod) {
22
+ if (mod && mod.__esModule) return mod
23
+ var result = {}
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k)
25
+ __setModuleDefault(result, mod)
26
+ return result
27
+ }
28
+
29
+ var __importDefault = (this && this.__importDefault) || function (mod) {
30
+ return (mod && mod.__esModule) ? mod : { "default": mod }
31
+ }
32
+
33
+ Object.defineProperty(exports, "__esModule", { value: true })
34
+
35
+ const boom_1 = require("@hapi/boom")
36
+ const axios_1 = __importDefault(require("axios"))
37
+ const crypto_1 = require("crypto")
38
+ const os_1 = require("os")
39
+ const WAProto_1 = require("../../WAProto")
40
+ const baileys_version_json_1 = require("../Defaults/baileys-version.json")
41
+ const Types_1 = require("../Types")
42
+ const WABinary_1 = require("../WABinary")
43
+
44
+ const COMPANION_PLATFORM_MAP = {
45
+ 'Chrome': '49',
46
+ 'Edge': '50',
47
+ 'Firefox': '51',
48
+ 'Opera': '53',
49
+ 'Safari': '54',
50
+ 'Brave': '1.79.112',
51
+ 'Vivaldi': '6.2.3105.58',
52
+ 'Tor': '12.5.3',
53
+ 'Yandex': '23.7.1',
54
+ 'Falkon': '22.08.3',
55
+ 'Epiphany': '44.2'
56
+ }
57
+
58
+ const PLATFORM_MAP = {
59
+ 'aix': 'AIX',
60
+ 'darwin': 'Mac OS',
61
+ 'win32': 'Windows',
62
+ 'android': 'Android',
63
+ 'freebsd': 'FreeBSD',
64
+ 'openbsd': 'OpenBSD',
65
+ 'sunos': 'Solaris',
66
+ 'linux': 'Linux',
67
+ 'ubuntu': 'Ubuntu',
68
+ 'ios': 'iOS',
69
+ 'baileys': 'Baileys',
70
+ 'chromeos': 'Chrome OS',
71
+ 'tizen': 'Tizen',
72
+ 'watchos': 'watchOS',
73
+ 'wearos': 'Wear OS',
74
+ 'harmonyos': 'HarmonyOS',
75
+ 'kaios': 'KaiOS',
76
+ 'smarttv': 'Smart TV',
77
+ 'raspberrypi': 'Raspberry Pi OS',
78
+ 'symbian': 'Symbian',
79
+ 'blackberry': 'Blackberry OS',
80
+ 'windowsphone': 'Windows Phone'
81
+ }
82
+
83
+ const PLATFORM_VERSIONS = {
84
+ 'ubuntu': '22.04.4',
85
+ 'darwin': '14.4.1',
86
+ 'win32': '10.0.22631',
87
+ 'android': '14.0.0',
88
+ 'freebsd': '13.2',
89
+ 'openbsd': '7.3',
90
+ 'sunos': '11',
91
+ 'linux': '6.5',
92
+ 'ios': '18.2',
93
+ 'baileys': '6.5.0',
94
+ 'chromeos': '117.0.5938.132',
95
+ 'tizen': '6.5',
96
+ 'watchos': '10.1',
97
+ 'wearos': '4.1',
98
+ 'harmonyos': '4.0.0',
99
+ 'kaios': '3.1',
100
+ 'smarttv': '23.3.1',
101
+ 'raspberrypi': '11 (Bullseye)',
102
+ 'symbian': '3',
103
+ 'blackberry': '10.3.3',
104
+ 'windowsphone': '8.1'
105
+ }
106
+
107
+ const Browsers = {
108
+ ubuntu: (browser) => {
109
+ return [PLATFORM_MAP['ubuntu'], browser, PLATFORM_VERSIONS['ubuntu']]
110
+ },
111
+ macOS: (browser) => {
112
+ return [PLATFORM_MAP['darwin'], browser, PLATFORM_VERSIONS['darwin']]
113
+ },
114
+ windows: (browser) => {
115
+ return [PLATFORM_MAP['win32'], browser, PLATFORM_VERSIONS['win32']]
116
+ },
117
+ linux: (browser) => {
118
+ return [PLATFORM_MAP['linux'], browser, PLATFORM_VERSIONS['linux']]
119
+ },
120
+ solaris: (browser) => {
121
+ return [PLATFORM_MAP['sunos'], browser, PLATFORM_VERSIONS['sunos']]
122
+ },
123
+ baileys: (browser) => {
124
+ return [PLATFORM_MAP['baileys'], browser, PLATFORM_VERSIONS['baileys']]
125
+ },
126
+ android: (browser) => {
127
+ return [PLATFORM_MAP['android'], browser, PLATFORM_VERSIONS['android']]
128
+ },
129
+ iOS: (browser) => {
130
+ return [PLATFORM_MAP['ios'], browser, PLATFORM_VERSIONS['ios']]
131
+ },
132
+ kaiOS: (browser) => {
133
+ return [PLATFORM_MAP['kaios'], browser, PLATFORM_VERSIONS['kaios']]
134
+ },
135
+ chromeOS: (browser) => {
136
+ return [PLATFORM_MAP['chromeos'], browser, PLATFORM_VERSIONS['chromeos']]
137
+ },
138
+ appropriate: (browser) => {
139
+ const platform = os_1.platform()
140
+ const platformName = PLATFORM_MAP[platform] || 'Unknown OS'
141
+ return [platformName, browser, PLATFORM_VERSIONS[platform] || 'latest']
142
+ },
143
+ custom: (platform, browser, version) => {
144
+ const platformName = PLATFORM_MAP[platform.toLowerCase()] || platform
145
+ return [platformName, browser, version || PLATFORM_VERSIONS[platform] || 'latest']
146
+ }
147
+ }
148
+
149
+
150
+
151
+ const BufferJSON = {
152
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
153
+ replacer: (k, value) => {
154
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array || value?.type === 'Buffer') {
155
+ return { type: 'Buffer', data: Buffer.from(value?.data || value).toString('base64') }
156
+ }
157
+ return value
158
+ },
159
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
160
+ reviver: (_, value) => {
161
+ if (typeof value === 'object' && !!value && (value.buffer === true || value.type === 'Buffer')) {
162
+ const val = value.data || value.value
163
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val || [])
164
+ }
165
+ return value
166
+ }
167
+ }
168
+
169
+ const getPlatformId = (browser) => {
170
+ const platformType = WAProto_1.proto.DeviceProps.PlatformType[browser.toUpperCase()]
171
+ return platformType ? platformType.toString().charCodeAt(0).toString() : '49' //chrome
172
+ }
173
+
174
+ const getKeyAuthor = (key, meId = 'me') => {
175
+ return key?.fromMe ? meId : key?.participant || key?.remoteJid || ''
176
+ }
177
+
178
+ const writeRandomPadMax16 = (msg) => {
179
+ const pad = crypto_1.randomBytes(1)
180
+ pad[0] &= 0xf
181
+ if (!pad[0]) {
182
+ pad[0] = 0xf
183
+ }
184
+ return Buffer.concat([msg, Buffer.alloc(pad[0], pad[0])])
185
+ }
186
+
187
+ const unpadRandomMax16 = (e) => {
188
+ const t = new Uint8Array(e)
189
+ if (0 === t.length) {
190
+ throw new Error('unpadPkcs7 given empty bytes')
191
+ }
192
+ var r = t[t.length - 1]
193
+ if (r > t.length) {
194
+ throw new Error(`unpad given ${t.length} bytes, but pad is ${r}`)
195
+ }
196
+ return new Uint8Array(t.buffer, t.byteOffset, t.length - r)
197
+ }
198
+
199
+ const encodeWAMessage = (message) => {
200
+ return writeRandomPadMax16(WAProto_1.proto.Message.encode(message).finish())
201
+ }
202
+
203
+ const encodeNewsletterMessage = (message) => {
204
+ return WAProto_1.proto.Message.encode(message).finish()
205
+ }
206
+
207
+ const generateRegistrationId = () => {
208
+ return Uint16Array.from(crypto_1.randomBytes(2))[0] & 16383
209
+ }
210
+
211
+ const encodeBigEndian = (e, t = 4) => {
212
+ let r = e
213
+ const a = new Uint8Array(t)
214
+ for (let i = t - 1; i >= 0; i--) {
215
+ a[i] = 255 & r
216
+ r >>>= 8
217
+ }
218
+ return a
219
+ }
220
+
221
+ const toNumber = (t) => ((typeof t === 'object' && t) ? ('toNumber' in t ? t.toNumber() : t.low) : t || 0)
222
+
223
+ /** unix timestamp of a date in seconds */
224
+ const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
225
+
226
+ const debouncedTimeout = (intervalMs = 1000, task) => {
227
+ let timeout
228
+ return {
229
+ start: (newIntervalMs, newTask) => {
230
+ task = newTask || task
231
+ intervalMs = newIntervalMs || intervalMs
232
+ timeout && clearTimeout(timeout)
233
+ timeout = setTimeout(() => task?.(), intervalMs)
234
+ },
235
+ cancel: () => {
236
+ timeout && clearTimeout(timeout)
237
+ timeout = undefined
238
+ },
239
+ setTask: (newTask) => task = newTask,
240
+ setInterval: (newInterval) => intervalMs = newInterval
241
+ }
242
+ }
243
+
244
+ const delay = (ms) => {
245
+ return delayCancellable(ms).delay
246
+ }
247
+
248
+ const delayCancellable = (ms) => {
249
+ const stack = new Error().stack
250
+ let timeout
251
+ let reject
252
+ const delay = new Promise((resolve, _reject) => {
253
+ timeout = setTimeout(resolve, ms)
254
+ reject = _reject
255
+ })
256
+ const cancel = () => {
257
+ clearTimeout(timeout)
258
+ reject(new boom_1.Boom('Cancelled', {
259
+ statusCode: 500,
260
+ data: {
261
+ stack
262
+ }
263
+ }))
264
+ }
265
+ return { delay, cancel }
266
+ }
267
+
268
+ async function promiseTimeout(ms, promise) {
269
+ if (!ms) {
270
+ return new Promise(promise)
271
+ }
272
+ const stack = new Error().stack
273
+ // Create a promise that rejects in <ms> milliseconds
274
+ const { delay, cancel } = delayCancellable(ms)
275
+ const p = new Promise((resolve, reject) => {
276
+ delay.then(() => reject(new boom_1.Boom('Timed Out', {
277
+ statusCode: Types_1.DisconnectReason.timedOut,
278
+ data: {
279
+ stack
280
+ }
281
+ }))).catch(err => reject(err))
282
+ promise(resolve, reject)
283
+ }).finally(cancel)
284
+ return p
285
+ }
286
+
287
+ const generateMessageID = (userId) => {
288
+ const data = Buffer.alloc(8 + 20 + 16)
289
+ data.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000)))
290
+ if (userId) {
291
+ const id = WABinary_1.jidDecode(userId)
292
+ if (id?.user) {
293
+ data.write(id.user, 8)
294
+ data.write('@c.us', 8 + id.user.length)
295
+ }
296
+ }
297
+ const random = crypto_1.randomBytes(20)
298
+ random.copy(data, 28)
299
+ const sha = asciiDecode([ 83, 85, 75, 73 ])
300
+ const hash = crypto_1.createHash('sha256').update(data).digest()
301
+ return sha + hash.toString('hex').toUpperCase().substring(0, 16)
302
+ }
303
+
304
+ function bindWaitForEvent(ev, event) {
305
+ return async (check, timeoutMs) => {
306
+ let listener
307
+ let closeListener
308
+ await (promiseTimeout(timeoutMs, (resolve, reject) => {
309
+ closeListener = ({ connection, lastDisconnect }) => {
310
+ if (connection === 'close') {
311
+ reject((lastDisconnect?.error)
312
+ || new boom_1.Boom('Connection Closed', { statusCode: Types_1.DisconnectReason.connectionClosed }))
313
+ }
314
+ }
315
+ ev.on('connection.update', closeListener)
316
+ listener = async (update) => {
317
+ if (await check(update)) {
318
+ resolve()
319
+ }
320
+ }
321
+ ev.on(event, listener)
322
+ }).finally(() => {
323
+ ev.off(event, listener)
324
+ ev.off('connection.update', closeListener)
325
+ }))
326
+ }
327
+ }
328
+
329
+ const bindWaitForConnectionUpdate = (ev) => {
330
+ return bindWaitForEvent(ev, 'connection.update')
331
+ }
332
+
333
+ const printQRIfNecessaryListener = (ev, logger) => {
334
+ ev.on('connection.update', async ({ qr }) => {
335
+ if (qr) {
336
+ const QR = await Promise.resolve().then(() => __importStar(require('qrcode-terminal'))).then(m => m.default || m)
337
+ .catch(() => {
338
+ logger.error('QR code terminal not added as dependency')
339
+ })
340
+ QR?.generate(qr, { small: true })
341
+ }
342
+ })
343
+ }
344
+
345
+ /**
346
+ * utility that fetches latest baileys version from the master branch.
347
+ * Use to ensure your WA connection is always on the latest version
348
+ */
349
+ const fetchLatestBaileysVersion = async (options = {}) => {
350
+ const URL = 'https://raw.githubusercontent.com/Itsukichann/database/main/baileys-version.json'
351
+ try {
352
+ const result = await axios_1.default.get(URL, {
353
+ ...options,
354
+ responseType: 'json'
355
+ })
356
+ return {
357
+ version: result.data.version,
358
+ isLatest: true
359
+ }
360
+ }
361
+ catch (error) {
362
+ return {
363
+ version: baileys_version_json_1.version,
364
+ isLatest: false,
365
+ error
366
+ }
367
+ }
368
+ }
369
+
370
+ /**
371
+ * A utility that fetches the latest web version of whatsapp.
372
+ * Use to ensure your WA connection is always on the latest version
373
+ */
374
+ const fetchLatestWaWebVersion = async (options) => {
375
+ try {
376
+ const { data } = await axios_1.default.get('https://web.whatsapp.com/sw.js', {
377
+ ...options,
378
+ responseType: 'json'
379
+ })
380
+ const regex = /\\?"client_revision\\?":\s*(\d+)/
381
+ const match = data.match(regex)
382
+ if (!match?.match[1]) {
383
+ return {
384
+ version: baileys_version_json_1.version,
385
+ isLatest: false,
386
+ error: {
387
+ message: 'Could not find client revision in the fetched content'
388
+ }
389
+ }
390
+ }
391
+ const clientRevision = match[1]
392
+ return {
393
+ version: [2, 3000, +clientRevision],
394
+ isLatest: true
395
+ }
396
+ }
397
+ catch (error) {
398
+ return {
399
+ version: baileys_version_json_1.version,
400
+ isLatest: false,
401
+ error
402
+ }
403
+ }
404
+ }
405
+
406
+ /** unique message tag prefix for MD clients */
407
+ const generateMdTagPrefix = () => {
408
+ const bytes = crypto_1.randomBytes(4)
409
+ return `${bytes.readUInt16BE()}.${bytes.readUInt16BE(2)}-`
410
+ }
411
+
412
+ const STATUS_MAP = {
413
+ 'sender': WAProto_1.proto.WebMessageInfo.Status.SERVER_ACK,
414
+ 'played': WAProto_1.proto.WebMessageInfo.Status.PLAYED,
415
+ 'read': WAProto_1.proto.WebMessageInfo.Status.READ,
416
+ 'read-self': WAProto_1.proto.WebMessageInfo.Status.READ
417
+ }
418
+
419
+ /**
420
+ * Given a type of receipt, returns what the new status of the message should be
421
+ * @param type type from receipt
422
+ */
423
+ const getStatusFromReceiptType = (type) => {
424
+ const status = STATUS_MAP[type]
425
+ if (typeof type === 'undefined') {
426
+ return WAProto_1.proto.WebMessageInfo.Status.DELIVERY_ACK
427
+ }
428
+ return status
429
+ }
430
+
431
+ const CODE_MAP = {
432
+ conflict: Types_1.DisconnectReason.connectionReplaced
433
+ }
434
+
435
+ /**
436
+ * Stream errors generally provide a reason, map that to a baileys DisconnectReason
437
+ * @param reason the string reason given, eg. "conflict"
438
+ */
439
+ const getErrorCodeFromStreamError = (node) => {
440
+ const [reasonNode] = WABinary_1.getAllBinaryNodeChildren(node)
441
+ let reason = reasonNode?.tag || 'unknown'
442
+ const statusCode = +(node.attrs.code || CODE_MAP[reason] || Types_1.DisconnectReason.badSession)
443
+ if (statusCode === Types_1.DisconnectReason.restartRequired) {
444
+ reason = 'restart required'
445
+ }
446
+ return {
447
+ reason,
448
+ statusCode
449
+ }
450
+ }
451
+
452
+ const getCallStatusFromNode = ({ tag, attrs }) => {
453
+ let status
454
+ switch (tag) {
455
+ case 'offer':
456
+ case 'offer_notice':
457
+ status = 'offer'
458
+ break
459
+ case 'terminate':
460
+ if (attrs.reason === 'timeout') {
461
+ status = 'timeout'
462
+ }
463
+ else {
464
+ //fired when accepted/rejected/timeout/caller hangs up
465
+ status = 'terminate'
466
+ }
467
+ break
468
+ case 'reject':
469
+ status = 'reject'
470
+ break
471
+ case 'accept':
472
+ status = 'accept'
473
+ break
474
+ default:
475
+ status = 'ringing'
476
+ break
477
+ }
478
+ return status
479
+ }
480
+
481
+ const getCodeFromWSError = (error) => {
482
+ let statusCode = 500
483
+ if (error?.message?.includes('Unexpected server response: ')) {
484
+ const code = +(error?.message.slice('Unexpected server response: '.length))
485
+ if (!Number.isNaN(code) && code >= 400) {
486
+ statusCode = code
487
+ }
488
+ }
489
+ else if (error?.code?.startsWith('E') || error?.message?.includes('time out')) {
490
+ statusCode = 408
491
+ }
492
+ return statusCode
493
+ }
494
+
495
+ /**
496
+ * Is the given platform WA business
497
+ * @param platform AuthenticationCreds.platform
498
+ */
499
+ const isWABusinessPlatform = (platform) => {
500
+ return platform === 'smbi' || platform === 'smba'
501
+ }
502
+
503
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
504
+ function trimUndefined(obj) {
505
+ for (const key in obj) {
506
+ if (typeof obj[key] === 'undefined') {
507
+ delete obj[key]
508
+ }
509
+ }
510
+ return obj
511
+ }
512
+
513
+ function bytesToCrockford(buffer) {
514
+ let value = 0
515
+ let bitCount = 0
516
+ const crockford = []
517
+ for (const element of buffer) {
518
+ value = (value << 8) | (element & 0xff)
519
+ bitCount += 8
520
+ while (bitCount >= 5) {
521
+ crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value >>> (bitCount - 5)) & 31))
522
+ bitCount -= 5
523
+ }
524
+ }
525
+ if (bitCount > 0) {
526
+ crockford.push('123456789ABCDEFGHJKLMNPQRSTVWXYZ'.charAt((value << (5 - bitCount)) & 31))
527
+ }
528
+ return crockford.join('')
529
+ }
530
+
531
+ const toUnicodeEscape = (text) => {
532
+ return text.split("").map(char => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0")).join("")
533
+ }
534
+
535
+ const fromUnicodeEscape = (escapedText) => {
536
+ return escapedText.replace(/\\u[\dA-Fa-f]{4}/g, match => String.fromCharCode(parseInt(match.slice(2), 16)))
537
+ }
538
+
539
+ const asciiEncode = (text) => {
540
+ var encoded = text.split("").map(c => c.charCodeAt(0))
541
+ return encoded
542
+ }
543
+
544
+ const asciiDecode = (...codes) => {
545
+ var codeArray = Array.isArray(codes[0]) ? codes[0] : codes
546
+ return codeArray.map(c => String.fromCharCode(c)).join("")
547
+ }
548
+
549
+ module.exports = {
550
+ Browsers,
551
+ BufferJSON,
552
+ getPlatformId,
553
+ getKeyAuthor,
554
+ writeRandomPadMax16,
555
+ unpadRandomMax16,
556
+ encodeWAMessage,
557
+ encodeNewsletterMessage,
558
+ generateRegistrationId,
559
+ encodeBigEndian,
560
+ toNumber,
561
+ unixTimestampSeconds,
562
+ debouncedTimeout,
563
+ delay,
564
+ delayCancellable,
565
+ promiseTimeout,
566
+ generateMessageID,
567
+ bindWaitForEvent,
568
+ bindWaitForConnectionUpdate,
569
+ printQRIfNecessaryListener,
570
+ fetchLatestBaileysVersion,
571
+ fetchLatestWaWebVersion,
572
+ generateMdTagPrefix,
573
+ getStatusFromReceiptType,
574
+ getErrorCodeFromStreamError,
575
+ getCallStatusFromNode,
576
+ getCodeFromWSError,
577
+ isWABusinessPlatform,
578
+ trimUndefined,
579
+ bytesToCrockford,
580
+ toUnicodeEscape,
581
+ fromUnicodeEscape,
582
+ asciiEncode,
583
+ asciiDecode
584
+ }
@@ -0,0 +1,23 @@
1
+ import { AxiosRequestConfig } from 'axios'
2
+ import { proto } from '../../WAProto'
3
+ import { Chat, Contact } from '../Types'
4
+
5
+ export declare const downloadHistory: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<proto.HistorySync>
6
+
7
+ export declare const processHistoryMessage: (item: proto.IHistorySync) => {
8
+ chats: Chat[]
9
+ contacts: Contact[]
10
+ messages: proto.IWebMessageInfo[]
11
+ syncType: proto.HistorySync.HistorySyncType
12
+ progress: number | null | undefined
13
+ }
14
+
15
+ export declare const downloadAndProcessHistorySyncNotification: (msg: proto.Message.IHistorySyncNotification, options: AxiosRequestConfig<{}>) => Promise<{
16
+ chats: Chat[]
17
+ contacts: Contact[]
18
+ messages: proto.IWebMessageInfo[]
19
+ syncType: proto.HistorySync.HistorySyncType
20
+ progress: number | null | undefined
21
+ }>
22
+
23
+ export declare const getHistoryMsg: (message: proto.IMessage) => proto.Message.IHistorySyncNotification | null | undefined
@@ -0,0 +1,100 @@
1
+ "use strict"
2
+
3
+ Object.defineProperty(exports, "__esModule", { value: true })
4
+
5
+ const util_1 = require("util")
6
+ const zlib_1 = require("zlib")
7
+ const WAProto_1 = require("../../WAProto")
8
+ const Types_1 = require("../Types")
9
+ const WABinary_1 = require("../WABinary")
10
+ const generics_1 = require("./generics")
11
+ const messages_1 = require("./messages")
12
+ const messages_media_1 = require("./messages-media")
13
+ const inflatePromise = util_1.promisify(zlib_1.inflate)
14
+
15
+ const downloadHistory = async (msg, options) => {
16
+ const stream = await messages_media_1.downloadContentFromMessage(msg, 'md-msg-hist', { options })
17
+ const bufferArray = []
18
+ for await (const chunk of stream) {
19
+ bufferArray.push(chunk)
20
+ }
21
+ let buffer = Buffer.concat(bufferArray)
22
+ // decompress buffer
23
+ buffer = await inflatePromise(buffer)
24
+ const syncData = WAProto_1.proto.HistorySync.decode(buffer)
25
+ return syncData
26
+ }
27
+
28
+ const processHistoryMessage = (item) => {
29
+ const messages = []
30
+ const contacts = []
31
+ const chats = []
32
+ switch (item.syncType) {
33
+ case WAProto_1.proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
34
+ case WAProto_1.proto.HistorySync.HistorySyncType.RECENT:
35
+ case WAProto_1.proto.HistorySync.HistorySyncType.FULL:
36
+ case WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND:
37
+ for (const chat of item.conversations) {
38
+ contacts.push({ id: chat.id, name: chat.name || undefined })
39
+ const msgs = chat.messages || []
40
+ delete chat.messages
41
+ delete chat.archived
42
+ delete chat.muteEndTime
43
+ delete chat.pinned
44
+ for (const item of msgs) {
45
+ const message = item.message
46
+ messages.push(message)
47
+ if (!chat.messages?.length) {
48
+ // keep only the most recent message in the chat array
49
+ chat.messages = [{ message }]
50
+ }
51
+ if (!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
52
+ chat.lastMessageRecvTimestamp = generics_1.toNumber(message.messageTimestamp)
53
+ }
54
+ if (message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
55
+ || message.messageStubType === Types_1.WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
56
+ && message.messageStubParameters?.[0]) {
57
+ contacts.push({
58
+ id: message.key.participant || message.key.remoteJid,
59
+ verifiedName: message.messageStubParameters?.[0]
60
+ })
61
+ }
62
+ }
63
+ if (WABinary_1.isJidUser(chat.id) && chat.readOnly && chat.archived) {
64
+ delete chat.readOnly
65
+ }
66
+ chats.push({ ...chat })
67
+ }
68
+ break
69
+ case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
70
+ for (const c of item.pushnames) {
71
+ contacts.push({ id: c.id, notify: c.pushname })
72
+ }
73
+ break
74
+ }
75
+ return {
76
+ chats,
77
+ contacts,
78
+ messages,
79
+ syncType: item.syncType,
80
+ progress: item.progress
81
+ }
82
+ }
83
+
84
+ const downloadAndProcessHistorySyncNotification = async (msg, options) => {
85
+ const historyMsg = await downloadHistory(msg, options)
86
+ return processHistoryMessage(historyMsg)
87
+ }
88
+
89
+ const getHistoryMsg = (message) => {
90
+ const normalizedContent = !!message ? messages_1.normalizeMessageContent(message) : undefined
91
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification
92
+ return anyHistoryMsg
93
+ }
94
+
95
+ module.exports = {
96
+ downloadHistory,
97
+ processHistoryMessage,
98
+ downloadAndProcessHistorySyncNotification,
99
+ getHistoryMsg
100
+ }