phantom-baileys 0.0.8 → 0.1.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 (441) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +592 -0
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +81 -0
  6. package/WAProto/index.d.ts +5147 -41513
  7. package/WAProto/index.js +84008 -142014
  8. package/lib/Defaults/index.d.ts +29 -8
  9. package/lib/Defaults/index.d.ts.map +1 -0
  10. package/lib/Defaults/index.js +80 -60
  11. package/lib/Defaults/index.js.map +1 -0
  12. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  14. package/lib/Signal/Group/ciphertext-message.js +12 -0
  15. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  16. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  18. package/lib/Signal/Group/group-session-builder.js +30 -0
  19. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  20. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  21. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  22. package/lib/Signal/Group/group_cipher.js +82 -0
  23. package/lib/Signal/Group/group_cipher.js.map +1 -0
  24. package/lib/Signal/Group/index.d.ts +12 -0
  25. package/lib/Signal/Group/index.d.ts.map +1 -0
  26. package/lib/Signal/Group/index.js +12 -0
  27. package/lib/Signal/Group/index.js.map +1 -0
  28. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  29. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  30. package/lib/Signal/Group/keyhelper.js +18 -0
  31. package/lib/Signal/Group/keyhelper.js.map +1 -0
  32. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  34. package/lib/Signal/Group/sender-chain-key.js +26 -0
  35. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  36. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  40. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  42. package/lib/Signal/Group/sender-key-message.js +66 -0
  43. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  44. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  46. package/lib/Signal/Group/sender-key-name.js +48 -0
  47. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  48. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  50. package/lib/Signal/Group/sender-key-record.js +41 -0
  51. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  52. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  54. package/lib/Signal/Group/sender-key-state.js +84 -0
  55. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  56. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  58. package/{WASignalGroup/sender_message_key.js → lib/Signal/Group/sender-message-key.js} +3 -16
  59. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  60. package/lib/Signal/libsignal.d.ts +5 -3
  61. package/lib/Signal/libsignal.d.ts.map +1 -0
  62. package/lib/Signal/libsignal.js +331 -80
  63. package/lib/Signal/libsignal.js.map +1 -0
  64. package/lib/Signal/lid-mapping.d.ts +19 -0
  65. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  66. package/lib/Signal/lid-mapping.js +271 -0
  67. package/lib/Signal/lid-mapping.js.map +1 -0
  68. package/lib/Socket/Client/index.d.ts +3 -3
  69. package/lib/Socket/Client/index.d.ts.map +1 -0
  70. package/lib/Socket/Client/index.js +3 -19
  71. package/lib/Socket/Client/index.js.map +1 -0
  72. package/lib/Socket/Client/{abstract-socket-client.d.ts → types.d.ts} +4 -5
  73. package/lib/Socket/Client/types.d.ts.map +1 -0
  74. package/lib/Socket/Client/types.js +11 -0
  75. package/lib/Socket/Client/types.js.map +1 -0
  76. package/lib/Socket/Client/{web-socket-client.d.ts → websocket.d.ts} +3 -2
  77. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  78. package/lib/Socket/Client/websocket.js +54 -0
  79. package/lib/Socket/Client/websocket.js.map +1 -0
  80. package/lib/Socket/business.d.ts +184 -101
  81. package/lib/Socket/business.d.ts.map +1 -0
  82. package/lib/Socket/business.js +162 -43
  83. package/lib/Socket/business.js.map +1 -0
  84. package/lib/Socket/chats.d.ts +72 -42
  85. package/lib/Socket/chats.d.ts.map +1 -0
  86. package/lib/Socket/chats.js +340 -299
  87. package/lib/Socket/chats.js.map +1 -0
  88. package/lib/Socket/communities.d.ts +309 -0
  89. package/lib/Socket/communities.d.ts.map +1 -0
  90. package/lib/Socket/communities.js +431 -0
  91. package/lib/Socket/communities.js.map +1 -0
  92. package/lib/Socket/dugong.d.ts +79 -0
  93. package/lib/Socket/dugong.d.ts.map +1 -0
  94. package/lib/Socket/dugong.js +527 -0
  95. package/lib/Socket/dugong.js.map +1 -0
  96. package/lib/Socket/groups.d.ts +93 -58
  97. package/lib/Socket/groups.d.ts.map +1 -0
  98. package/lib/Socket/groups.js +96 -84
  99. package/lib/Socket/groups.js.map +1 -0
  100. package/lib/Socket/index.d.ts +232 -107
  101. package/lib/Socket/index.d.ts.map +1 -0
  102. package/lib/Socket/index.js +13 -10
  103. package/lib/Socket/index.js.map +1 -0
  104. package/lib/Socket/messages-recv.d.ts +170 -90
  105. package/lib/Socket/messages-recv.d.ts.map +1 -0
  106. package/lib/Socket/messages-recv.js +798 -462
  107. package/lib/Socket/messages-recv.js.map +1 -0
  108. package/lib/Socket/messages-send.d.ts +180 -99
  109. package/lib/Socket/messages-send.d.ts.map +1 -0
  110. package/lib/Socket/messages-send.js +833 -709
  111. package/lib/Socket/messages-send.js.map +1 -0
  112. package/lib/Socket/mex.d.ts +3 -0
  113. package/lib/Socket/mex.d.ts.map +1 -0
  114. package/lib/Socket/mex.js +42 -0
  115. package/lib/Socket/mex.js.map +1 -0
  116. package/lib/Socket/newsletter.d.ts +120 -75
  117. package/lib/Socket/newsletter.d.ts.map +1 -0
  118. package/lib/Socket/newsletter.js +227 -198
  119. package/lib/Socket/newsletter.js.map +1 -0
  120. package/lib/Socket/socket.d.ts +31 -20
  121. package/lib/Socket/socket.d.ts.map +1 -0
  122. package/lib/Socket/socket.js +508 -215
  123. package/lib/Socket/socket.js.map +1 -0
  124. package/lib/Types/Auth.d.ts +18 -11
  125. package/lib/Types/Auth.d.ts.map +1 -0
  126. package/lib/Types/Auth.js +2 -2
  127. package/lib/Types/Auth.js.map +1 -0
  128. package/lib/Types/Bussines.d.ts +25 -0
  129. package/lib/Types/Bussines.d.ts.map +1 -0
  130. package/lib/Types/Bussines.js +2 -0
  131. package/lib/Types/Bussines.js.map +1 -0
  132. package/lib/Types/Call.d.ts +2 -0
  133. package/lib/Types/Call.d.ts.map +1 -0
  134. package/lib/Types/Call.js +2 -2
  135. package/lib/Types/Call.js.map +1 -0
  136. package/lib/Types/Chat.d.ts +24 -8
  137. package/lib/Types/Chat.d.ts.map +1 -0
  138. package/lib/Types/Chat.js +8 -4
  139. package/lib/Types/Chat.js.map +1 -0
  140. package/lib/Types/Contact.d.ts +6 -1
  141. package/lib/Types/Contact.d.ts.map +1 -0
  142. package/lib/Types/Contact.js +2 -2
  143. package/lib/Types/Contact.js.map +1 -0
  144. package/lib/Types/Events.d.ts +82 -17
  145. package/lib/Types/Events.d.ts.map +1 -0
  146. package/lib/Types/Events.js +2 -2
  147. package/lib/Types/Events.js.map +1 -0
  148. package/lib/Types/GroupMetadata.d.ts +15 -3
  149. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  150. package/lib/Types/GroupMetadata.js +2 -2
  151. package/lib/Types/GroupMetadata.js.map +1 -0
  152. package/lib/Types/Label.d.ts +1 -0
  153. package/lib/Types/Label.d.ts.map +1 -0
  154. package/lib/Types/Label.js +3 -5
  155. package/lib/Types/Label.js.map +1 -0
  156. package/lib/Types/LabelAssociation.d.ts +1 -0
  157. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  158. package/lib/Types/LabelAssociation.js +3 -5
  159. package/lib/Types/LabelAssociation.js.map +1 -0
  160. package/lib/Types/Message.d.ts +77 -202
  161. package/lib/Types/Message.d.ts.map +1 -0
  162. package/lib/Types/Message.js +11 -9
  163. package/lib/Types/Message.js.map +1 -0
  164. package/lib/Types/Newsletter.d.ts +128 -85
  165. package/lib/Types/Newsletter.d.ts.map +1 -0
  166. package/lib/Types/Newsletter.js +25 -26
  167. package/lib/Types/Newsletter.js.map +1 -0
  168. package/lib/Types/Product.d.ts +2 -1
  169. package/lib/Types/Product.d.ts.map +1 -0
  170. package/lib/Types/Product.js +2 -2
  171. package/lib/Types/Product.js.map +1 -0
  172. package/lib/Types/Signal.d.ts +20 -1
  173. package/lib/Types/Signal.d.ts.map +1 -0
  174. package/lib/Types/Signal.js +2 -2
  175. package/lib/Types/Signal.js.map +1 -0
  176. package/lib/Types/Socket.d.ts +41 -24
  177. package/lib/Types/Socket.d.ts.map +1 -0
  178. package/lib/Types/Socket.js +3 -2
  179. package/lib/Types/Socket.js.map +1 -0
  180. package/lib/Types/State.d.ts +14 -2
  181. package/lib/Types/State.d.ts.map +1 -0
  182. package/lib/Types/State.js +13 -2
  183. package/lib/Types/State.js.map +1 -0
  184. package/lib/Types/USync.d.ts +3 -2
  185. package/lib/Types/USync.d.ts.map +1 -0
  186. package/lib/Types/USync.js +2 -2
  187. package/lib/Types/USync.js.map +1 -0
  188. package/lib/Types/index.d.ts +15 -16
  189. package/lib/Types/index.d.ts.map +1 -0
  190. package/lib/Types/index.js +15 -31
  191. package/lib/Types/index.js.map +1 -0
  192. package/lib/Utils/auth-utils.d.ts +7 -6
  193. package/lib/Utils/auth-utils.d.ts.map +1 -0
  194. package/lib/Utils/auth-utils.js +228 -165
  195. package/lib/Utils/auth-utils.js.map +1 -0
  196. package/lib/Utils/browser-utils.d.ts +4 -0
  197. package/lib/Utils/browser-utils.d.ts.map +1 -0
  198. package/lib/Utils/browser-utils.js +28 -0
  199. package/lib/Utils/browser-utils.js.map +1 -0
  200. package/lib/Utils/business.d.ts +4 -3
  201. package/lib/Utils/business.d.ts.map +1 -0
  202. package/lib/Utils/business.js +66 -69
  203. package/lib/Utils/business.js.map +1 -0
  204. package/lib/Utils/chat-utils.d.ts +16 -16
  205. package/lib/Utils/chat-utils.d.ts.map +1 -0
  206. package/lib/Utils/chat-utils.js +299 -232
  207. package/lib/Utils/chat-utils.js.map +1 -0
  208. package/lib/Utils/crypto.d.ts +18 -21
  209. package/lib/Utils/crypto.d.ts.map +1 -0
  210. package/lib/Utils/crypto.js +44 -125
  211. package/lib/Utils/crypto.js.map +1 -0
  212. package/lib/Utils/decode-wa-message.d.ts +20 -8
  213. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  214. package/lib/Utils/decode-wa-message.js +139 -90
  215. package/lib/Utils/decode-wa-message.js.map +1 -0
  216. package/lib/Utils/event-buffer.d.ts +7 -8
  217. package/lib/Utils/event-buffer.d.ts.map +1 -0
  218. package/lib/Utils/event-buffer.js +129 -72
  219. package/lib/Utils/event-buffer.js.map +1 -0
  220. package/lib/Utils/generics.d.ts +25 -22
  221. package/lib/Utils/generics.d.ts.map +1 -0
  222. package/lib/Utils/generics.js +157 -175
  223. package/lib/Utils/generics.js.map +1 -0
  224. package/lib/Utils/history.d.ts +14 -11
  225. package/lib/Utils/history.d.ts.map +1 -0
  226. package/lib/Utils/history.js +83 -46
  227. package/lib/Utils/history.js.map +1 -0
  228. package/lib/Utils/identity-change-handler.d.ts +37 -0
  229. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  230. package/lib/Utils/identity-change-handler.js +49 -0
  231. package/lib/Utils/identity-change-handler.js.map +1 -0
  232. package/lib/Utils/index.d.ts +22 -17
  233. package/lib/Utils/index.d.ts.map +1 -0
  234. package/lib/Utils/index.js +22 -33
  235. package/lib/Utils/index.js.map +1 -0
  236. package/lib/Utils/link-preview.d.ts +5 -5
  237. package/lib/Utils/link-preview.d.ts.map +1 -0
  238. package/lib/Utils/link-preview.js +14 -22
  239. package/lib/Utils/link-preview.js.map +1 -0
  240. package/lib/Utils/logger.d.ts +12 -1
  241. package/lib/Utils/logger.d.ts.map +1 -0
  242. package/lib/Utils/logger.js +3 -7
  243. package/lib/Utils/logger.js.map +1 -0
  244. package/lib/Utils/lt-hash.d.ts +8 -12
  245. package/lib/Utils/lt-hash.d.ts.map +1 -0
  246. package/lib/Utils/lt-hash.js +3 -46
  247. package/lib/Utils/lt-hash.js.map +1 -0
  248. package/lib/Utils/make-mutex.d.ts +2 -0
  249. package/lib/Utils/make-mutex.d.ts.map +1 -0
  250. package/lib/Utils/make-mutex.js +24 -34
  251. package/lib/Utils/make-mutex.js.map +1 -0
  252. package/lib/Utils/message-retry-manager.d.ts +110 -0
  253. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  254. package/lib/Utils/message-retry-manager.js +225 -0
  255. package/lib/Utils/message-retry-manager.js.map +1 -0
  256. package/lib/Utils/messages-media.d.ts +59 -42
  257. package/lib/Utils/messages-media.d.ts.map +1 -0
  258. package/lib/Utils/messages-media.js +411 -356
  259. package/lib/Utils/messages-media.js.map +1 -0
  260. package/lib/Utils/messages.d.ts +32 -18
  261. package/lib/Utils/messages.d.ts.map +1 -0
  262. package/lib/Utils/messages.js +412 -723
  263. package/lib/Utils/messages.js.map +1 -0
  264. package/lib/Utils/noise-handler.d.ts +13 -13
  265. package/lib/Utils/noise-handler.d.ts.map +1 -0
  266. package/lib/Utils/noise-handler.js +149 -108
  267. package/lib/Utils/noise-handler.js.map +1 -0
  268. package/lib/Utils/offline-node-processor.d.ts +17 -0
  269. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  270. package/lib/Utils/offline-node-processor.js +40 -0
  271. package/lib/Utils/offline-node-processor.js.map +1 -0
  272. package/lib/Utils/pre-key-manager.d.ts +28 -0
  273. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  274. package/lib/Utils/pre-key-manager.js +106 -0
  275. package/lib/Utils/pre-key-manager.js.map +1 -0
  276. package/lib/Utils/process-message.d.ts +30 -11
  277. package/lib/Utils/process-message.d.ts.map +1 -0
  278. package/lib/Utils/process-message.js +321 -166
  279. package/lib/Utils/process-message.js.map +1 -0
  280. package/lib/Utils/reporting-utils.d.ts +11 -0
  281. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  282. package/lib/Utils/reporting-utils.js +258 -0
  283. package/lib/Utils/reporting-utils.js.map +1 -0
  284. package/lib/Utils/rich-messages.d.ts +129 -0
  285. package/lib/Utils/rich-messages.d.ts.map +1 -0
  286. package/lib/Utils/rich-messages.js +455 -0
  287. package/lib/Utils/rich-messages.js.map +1 -0
  288. package/lib/Utils/signal.d.ts +7 -6
  289. package/lib/Utils/signal.d.ts.map +1 -0
  290. package/lib/Utils/signal.js +65 -65
  291. package/lib/Utils/signal.js.map +1 -0
  292. package/lib/Utils/stanza-ack.d.ts +11 -0
  293. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  294. package/lib/Utils/stanza-ack.js +38 -0
  295. package/lib/Utils/stanza-ack.js.map +1 -0
  296. package/lib/Utils/sync-action-utils.d.ts +19 -0
  297. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  298. package/lib/Utils/sync-action-utils.js +48 -0
  299. package/lib/Utils/sync-action-utils.js.map +1 -0
  300. package/lib/Utils/tc-token-utils.d.ts +12 -0
  301. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  302. package/lib/Utils/tc-token-utils.js +18 -0
  303. package/lib/Utils/tc-token-utils.js.map +1 -0
  304. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  305. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  306. package/lib/Utils/use-multi-file-auth-state.js +79 -253
  307. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  308. package/lib/Utils/validate-connection.d.ts +6 -6
  309. package/lib/Utils/validate-connection.d.ts.map +1 -0
  310. package/lib/Utils/validate-connection.js +111 -116
  311. package/lib/Utils/validate-connection.js.map +1 -0
  312. package/lib/WABinary/constants.d.ts +5 -4
  313. package/lib/WABinary/constants.d.ts.map +1 -0
  314. package/lib/WABinary/constants.js +1281 -20
  315. package/lib/WABinary/constants.js.map +1 -0
  316. package/lib/WABinary/decode.d.ts +4 -3
  317. package/lib/WABinary/decode.d.ts.map +1 -0
  318. package/lib/WABinary/decode.js +51 -53
  319. package/lib/WABinary/decode.js.map +1 -0
  320. package/lib/WABinary/encode.d.ts +2 -1
  321. package/lib/WABinary/encode.d.ts.map +1 -0
  322. package/lib/WABinary/encode.js +12 -44
  323. package/lib/WABinary/encode.js.map +1 -0
  324. package/lib/WABinary/generic-utils.d.ts +9 -6
  325. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  326. package/lib/WABinary/generic-utils.js +124 -43
  327. package/lib/WABinary/generic-utils.js.map +1 -0
  328. package/lib/WABinary/index.d.ts +6 -5
  329. package/lib/WABinary/index.d.ts.map +1 -0
  330. package/lib/WABinary/index.js +6 -21
  331. package/lib/WABinary/index.js.map +1 -0
  332. package/lib/WABinary/jid-utils.d.ts +24 -7
  333. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  334. package/lib/WABinary/jid-utils.js +74 -40
  335. package/lib/WABinary/jid-utils.js.map +1 -0
  336. package/lib/WABinary/types.d.ts +2 -1
  337. package/lib/WABinary/types.d.ts.map +1 -0
  338. package/lib/WABinary/types.js +2 -2
  339. package/lib/WABinary/types.js.map +1 -0
  340. package/lib/WAM/BinaryInfo.d.ts +2 -1
  341. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  342. package/lib/WAM/BinaryInfo.js +2 -5
  343. package/lib/WAM/BinaryInfo.js.map +1 -0
  344. package/lib/WAM/constants.d.ts +5 -3
  345. package/lib/WAM/constants.d.ts.map +1 -0
  346. package/lib/WAM/constants.js +19071 -11568
  347. package/lib/WAM/constants.js.map +1 -0
  348. package/lib/WAM/encode.d.ts +3 -2
  349. package/lib/WAM/encode.d.ts.map +1 -0
  350. package/lib/WAM/encode.js +17 -22
  351. package/lib/WAM/encode.js.map +1 -0
  352. package/lib/WAM/index.d.ts +4 -3
  353. package/lib/WAM/index.d.ts.map +1 -0
  354. package/lib/WAM/index.js +4 -19
  355. package/lib/WAM/index.js.map +1 -0
  356. package/lib/WAProto/fix-imports.d.ts +1 -0
  357. package/lib/WAProto/fix-imports.js +71 -0
  358. package/lib/WAProto/index.js +89345 -0
  359. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +4 -3
  360. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  361. package/lib/WAUSync/Protocols/USyncContactProtocol.js +8 -11
  362. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  363. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +3 -2
  364. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  365. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +11 -14
  366. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  367. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +3 -2
  368. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  369. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +9 -12
  370. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  371. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +3 -2
  372. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  373. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +9 -13
  374. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  375. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +4 -3
  376. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  377. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +20 -22
  378. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  379. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +5 -3
  380. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  381. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +13 -8
  382. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  383. package/lib/WAUSync/Protocols/index.d.ts +5 -4
  384. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  385. package/lib/WAUSync/Protocols/index.js +5 -20
  386. package/lib/WAUSync/Protocols/index.js.map +1 -0
  387. package/lib/WAUSync/USyncQuery.d.ts +5 -4
  388. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  389. package/lib/WAUSync/USyncQuery.js +40 -35
  390. package/lib/WAUSync/USyncQuery.js.map +1 -0
  391. package/lib/WAUSync/USyncUser.d.ts +7 -4
  392. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  393. package/lib/WAUSync/USyncUser.js +2 -5
  394. package/lib/WAUSync/USyncUser.js.map +1 -0
  395. package/lib/WAUSync/index.d.ts +4 -3
  396. package/lib/WAUSync/index.d.ts.map +1 -0
  397. package/lib/WAUSync/index.js +4 -19
  398. package/lib/WAUSync/index.js.map +1 -0
  399. package/lib/index.d.ts +13 -0
  400. package/lib/index.d.ts.map +1 -0
  401. package/lib/index.js +16 -31
  402. package/lib/index.js.map +1 -0
  403. package/package.json +34 -74
  404. package/Readme.md +0 -1
  405. package/WASignalGroup/GroupProtocol.js +0 -1697
  406. package/WASignalGroup/ciphertext_message.js +0 -16
  407. package/WASignalGroup/group_cipher.js +0 -120
  408. package/WASignalGroup/group_session_builder.js +0 -46
  409. package/WASignalGroup/index.js +0 -5
  410. package/WASignalGroup/keyhelper.js +0 -21
  411. package/WASignalGroup/protobufs.js +0 -3
  412. package/WASignalGroup/queue_job.js +0 -69
  413. package/WASignalGroup/sender_chain_key.js +0 -50
  414. package/WASignalGroup/sender_key_distribution_message.js +0 -78
  415. package/WASignalGroup/sender_key_message.js +0 -92
  416. package/WASignalGroup/sender_key_name.js +0 -70
  417. package/WASignalGroup/sender_key_record.js +0 -56
  418. package/WASignalGroup/sender_key_state.js +0 -129
  419. package/lib/Defaults/baileys-version.json +0 -3
  420. package/lib/Socket/Client/abstract-socket-client.js +0 -13
  421. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  422. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  423. package/lib/Socket/Client/web-socket-client.js +0 -62
  424. package/lib/Socket/registration.d.ts +0 -264
  425. package/lib/Socket/registration.js +0 -166
  426. package/lib/Socket/usync.d.ts +0 -37
  427. package/lib/Socket/usync.js +0 -70
  428. package/lib/Store/index.d.ts +0 -3
  429. package/lib/Store/index.js +0 -10
  430. package/lib/Store/make-cache-manager-store.d.ts +0 -14
  431. package/lib/Store/make-cache-manager-store.js +0 -83
  432. package/lib/Store/make-in-memory-store.d.ts +0 -118
  433. package/lib/Store/make-in-memory-store.js +0 -431
  434. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  435. package/lib/Store/make-ordered-dictionary.js +0 -81
  436. package/lib/Store/object-repository.d.ts +0 -10
  437. package/lib/Store/object-repository.js +0 -27
  438. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  439. package/lib/Utils/baileys-event-stream.js +0 -63
  440. package/lib/Utils/use-single-file-auth-state.d.ts +0 -12
  441. package/lib/Utils/use-single-file-auth-state.js +0 -75
@@ -1,65 +1,84 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
1
+ import NodeCache from "@cacheable/node-cache";
2
+ import { Boom } from "@hapi/boom";
3
+ import { proto } from "../../WAProto/index.js";
4
+ import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from "../Defaults/index.js";
5
+ import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, unixTimestampSeconds, } from "../Utils/index.js";
6
+ import { generateTableContent, generateListContent, generateCodeBlockContent, generateRichMessageContent, generateLatexContent, generateLatexImageContent, generateLatexInlineImageContent, generateUnifiedResponseContent, captureUnifiedResponse, } from "../Utils/rich-messages.js";
7
+ import { getUrlInfo } from "../Utils/link-preview.js";
8
+ import { makeKeyedMutex } from "../Utils/make-mutex.js";
9
+ import { getMessageReportingToken, shouldIncludeReportingToken, } from "../Utils/reporting-utils.js";
10
+ import { areJidsSameUser, getAdditionalNode, getBinaryNodeChild, getBinaryNodeChildren, isHostedLidUser, isHostedPnUser, isJidGroup, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, S_WHATSAPP_NET, } from "../WABinary/index.js";
11
+ import { USyncQuery, USyncUser } from "../WAUSync/index.js";
12
+ import { Dugong } from "./dugong.js";
13
+ import { makeNewsletterSocket } from "./newsletter.js";
14
+ const NATIVE_FLOW_BUTTON_MAP = {
15
+ review_and_pay: "order_details",
16
+ review_order: "order_status",
17
+ payment_info: "payment_info",
18
+ payment_status: "payment_status",
19
+ payment_method: "payment_method",
4
20
  };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.makeMessagesSocket = void 0;
7
- const boom_1 = require("@hapi/boom");
8
- const node_cache_1 = __importDefault(require("node-cache"));
9
- const WAProto_1 = require("../../WAProto");
10
- const Defaults_1 = require("../Defaults");
11
- const Types_1 = require("../Types");
12
- const Utils_1 = require("../Utils");
13
- const link_preview_1 = require("../Utils/link-preview");
14
- const WABinary_1 = require("../WABinary");
15
- const WAUSync_1 = require("../WAUSync");
16
- const newsletter_1 = require("./newsletter");
17
- var ListType = WAProto_1.proto.Message.ListMessage.ListType;
18
- const makeMessagesSocket = (config) => {
19
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, } = config;
20
- const sock = (0, newsletter_1.makeNewsletterSocket)(config);
21
- const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, generateMessageTag, sendNode, groupMetadata, groupQuery, newsletterWMexQuery, groupToggleEphemeral } = sock;
22
- const patchMessageRequiresBeforeSending = (msg, recipientJids) => {
23
- var _a, _b;
24
- if ((_b = (_a = msg === null || msg === void 0 ? void 0 : msg.deviceSentMessage) === null || _a === void 0 ? void 0 : _a.message) === null || _b === void 0 ? void 0 : _b.listMessage) {
25
- msg = JSON.parse(JSON.stringify(msg));
26
- msg.deviceSentMessage.message.listMessage.listType = WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT;
27
- }
28
- if (msg === null || msg === void 0 ? void 0 : msg.listMessage) {
29
- msg = JSON.parse(JSON.stringify(msg));
30
- msg.listMessage.listType = WAProto_1.proto.Message.ListMessage.ListType.SINGLE_SELECT;
31
- }
32
- return msg;
33
- };
34
- const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
35
- stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.USER_DEVICES,
36
- useClones: false
21
+ const getButtonType = (message) => {
22
+ const msg = normalizeMessageContent(message) || message;
23
+ if (msg?.buttonsMessage || msg?.listMessage)
24
+ return msg.listMessage ? "list" : "buttons";
25
+ const vm = msg?.viewOnceMessage?.message ||
26
+ msg?.viewOnceMessageV2?.message;
27
+ const im = vm?.interactiveMessage || msg?.interactiveMessage;
28
+ if (!im?.nativeFlowMessage)
29
+ return null;
30
+ const btnName = im.nativeFlowMessage?.buttons?.[0]?.name;
31
+ if (btnName && NATIVE_FLOW_BUTTON_MAP[btnName])
32
+ return NATIVE_FLOW_BUTTON_MAP[btnName];
33
+ return "interactive";
34
+ };
35
+ export const makeMessagesSocket = (config) => {
36
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount, } = config;
37
+ const sock = makeNewsletterSocket(config);
38
+ const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
39
+ const userDevicesCache = config.userDevicesCache ||
40
+ new NodeCache({
41
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES, // 5 minutes
42
+ useClones: false,
43
+ });
44
+ const peerSessionsCache = new NodeCache({
45
+ stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
46
+ useClones: false,
37
47
  });
48
+ // Initialize message retry manager if enabled
49
+ const messageRetryManager = enableRecentMessageCache
50
+ ? new MessageRetryManager(logger, maxMsgRetryCount)
51
+ : null;
52
+ // Prevent race conditions in Signal session encryption by user
53
+ const encryptionMutex = makeKeyedMutex();
38
54
  let mediaConn;
39
55
  const refreshMediaConn = async (forceGet = false) => {
40
56
  const media = await mediaConn;
41
- if (!media || forceGet || (new Date().getTime() - media.fetchDate.getTime()) > media.ttl * 1000) {
57
+ if (!media ||
58
+ forceGet ||
59
+ new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
42
60
  mediaConn = (async () => {
43
61
  const result = await query({
44
- tag: 'iq',
62
+ tag: "iq",
45
63
  attrs: {
46
- type: 'set',
47
- xmlns: 'w:m',
48
- to: WABinary_1.S_WHATSAPP_NET,
64
+ type: "set",
65
+ xmlns: "w:m",
66
+ to: S_WHATSAPP_NET,
49
67
  },
50
- content: [{ tag: 'media_conn', attrs: {} }]
68
+ content: [{ tag: "media_conn", attrs: {} }],
51
69
  });
52
- const mediaConnNode = (0, WABinary_1.getBinaryNodeChild)(result, 'media_conn');
70
+ const mediaConnNode = getBinaryNodeChild(result, "media_conn");
71
+ // TODO: explore full length of data that whatsapp provides
53
72
  const node = {
54
- hosts: (0, WABinary_1.getBinaryNodeChildren)(mediaConnNode, 'host').map(({ attrs }) => ({
73
+ hosts: getBinaryNodeChildren(mediaConnNode, "host").map(({ attrs }) => ({
55
74
  hostname: attrs.hostname,
56
75
  maxContentLengthBytes: +attrs.maxContentLengthBytes,
57
76
  })),
58
77
  auth: mediaConnNode.attrs.auth,
59
78
  ttl: +mediaConnNode.attrs.ttl,
60
- fetchDate: new Date()
79
+ fetchDate: new Date(),
61
80
  };
62
- logger.debug('fetched media conn');
81
+ logger.debug("fetched media conn");
63
82
  return node;
64
83
  })();
65
84
  }
@@ -70,17 +89,20 @@ const makeMessagesSocket = (config) => {
70
89
  * used for receipts of phone call, read, delivery etc.
71
90
  * */
72
91
  const sendReceipt = async (jid, participant, messageIds, type) => {
92
+ if (!messageIds || messageIds.length === 0) {
93
+ throw new Boom("missing ids in receipt");
94
+ }
73
95
  const node = {
74
- tag: 'receipt',
96
+ tag: "receipt",
75
97
  attrs: {
76
98
  id: messageIds[0],
77
99
  },
78
100
  };
79
- const isReadReceipt = type === 'read' || type === 'read-self';
101
+ const isReadReceipt = type === "read" || type === "read-self";
80
102
  if (isReadReceipt) {
81
- node.attrs.t = (0, Utils_1.unixTimestampSeconds)().toString();
103
+ node.attrs.t = unixTimestampSeconds().toString();
82
104
  }
83
- if (type === 'sender' && (0, WABinary_1.isJidUser)(jid)) {
105
+ if (type === "sender" && (isPnUser(jid) || isLidUser(jid))) {
84
106
  node.attrs.recipient = jid;
85
107
  node.attrs.to = participant;
86
108
  }
@@ -91,27 +113,27 @@ const makeMessagesSocket = (config) => {
91
113
  }
92
114
  }
93
115
  if (type) {
94
- node.attrs.type = (0, WABinary_1.isJidNewsLetter)(jid) ? 'read-self' : type;
116
+ node.attrs.type = type;
95
117
  }
96
118
  const remainingMessageIds = messageIds.slice(1);
97
119
  if (remainingMessageIds.length) {
98
120
  node.content = [
99
121
  {
100
- tag: 'list',
122
+ tag: "list",
101
123
  attrs: {},
102
- content: remainingMessageIds.map(id => ({
103
- tag: 'item',
104
- attrs: { id }
105
- }))
106
- }
124
+ content: remainingMessageIds.map((id) => ({
125
+ tag: "item",
126
+ attrs: { id },
127
+ })),
128
+ },
107
129
  ];
108
130
  }
109
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
131
+ logger.debug({ attrs: node.attrs, messageIds }, "sending receipt for messages");
110
132
  await sendNode(node);
111
133
  };
112
134
  /** Correctly bulk send receipts to multiple chats, participants */
113
135
  const sendReceipts = async (keys, type) => {
114
- const recps = (0, Utils_1.aggregateMessageKeysNotFromMe)(keys);
136
+ const recps = aggregateMessageKeysNotFromMe(keys);
115
137
  for (const { jid, participant, messageIds } of recps) {
116
138
  await sendReceipt(jid, participant, messageIds, type);
117
139
  }
@@ -120,63 +142,54 @@ const makeMessagesSocket = (config) => {
120
142
  const readMessages = async (keys) => {
121
143
  const privacySettings = await fetchPrivacySettings();
122
144
  // based on privacy settings, we have to change the read type
123
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
145
+ const readType = privacySettings.readreceipts === "all" ? "read" : "read-self";
124
146
  await sendReceipts(keys, readType);
125
147
  };
126
- const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
127
- var _a, _b, _c, _d;
128
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
129
- if ((0, WABinary_1.isJidNewsLetter)(jid)) {
130
- const node = await newsletterWMexQuery(undefined, Types_1.QueryIds.METADATA, {
131
- input: {
132
- key: jid,
133
- type: "JID",
134
- 'view_role': 'GUEST'
135
- },
136
- 'fetch_viewer_metadata': true,
137
- 'fetch_full_image': true,
138
- 'fetch_creation_time': true
139
- });
140
- const result = (_b = (_a = (0, WABinary_1.getBinaryNodeChild)(node, 'result')) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.toString();
141
- const metadataPath = JSON.parse(result).data[Types_1.XWAPaths.NEWSLETTER];
142
- const pictype = type === 'image' ? 'picture' : 'preview';
143
- const directPath = (_c = metadataPath === null || metadataPath === void 0 ? void 0 : metadataPath.thread_metadata[pictype]) === null || _c === void 0 ? void 0 : _c.direct_path;
144
- return directPath ? (0, Utils_1.getUrlFromDirectPath)(directPath) : null;
145
- }
146
- else {
147
- const result = await query({
148
- tag: 'iq',
149
- attrs: {
150
- target: jid,
151
- to: WABinary_1.S_WHATSAPP_NET,
152
- type: 'get',
153
- xmlns: 'w:profile:picture'
154
- },
155
- content: [
156
- { tag: 'picture', attrs: { type, query: 'url' } }
157
- ]
158
- }, timeoutMs);
159
- const child = (0, WABinary_1.getBinaryNodeChild)(result, 'picture');
160
- return (_d = child === null || child === void 0 ? void 0 : child.attrs) === null || _d === void 0 ? void 0 : _d.url;
161
- }
162
- };
163
148
  /** Fetch all the devices we've to send a message to */
164
149
  const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
165
- var _a;
166
150
  const deviceResults = [];
167
151
  if (!useCache) {
168
- logger.debug('not using cache for devices');
152
+ logger.debug("not using cache for devices");
169
153
  }
170
154
  const toFetch = [];
171
- jids = Array.from(new Set(jids));
172
- for (let jid of jids) {
173
- const user = (_a = (0, WABinary_1.jidDecode)(jid)) === null || _a === void 0 ? void 0 : _a.user;
174
- jid = (0, WABinary_1.jidNormalizedUser)(jid);
155
+ const jidsWithUser = jids
156
+ .map((jid) => {
157
+ const decoded = jidDecode(jid);
158
+ const user = decoded?.user;
159
+ const device = decoded?.device;
160
+ const isExplicitDevice = typeof device === "number" && device >= 0;
161
+ if (isExplicitDevice && user) {
162
+ deviceResults.push({
163
+ user,
164
+ device,
165
+ jid,
166
+ });
167
+ return null;
168
+ }
169
+ jid = jidNormalizedUser(jid);
170
+ return { jid, user };
171
+ })
172
+ .filter((jid) => jid !== null);
173
+ let mgetDevices;
174
+ if (useCache && userDevicesCache.mget) {
175
+ const usersToFetch = jidsWithUser
176
+ .map((j) => j?.user)
177
+ .filter(Boolean);
178
+ mgetDevices = await userDevicesCache.mget(usersToFetch);
179
+ }
180
+ for (const { jid, user } of jidsWithUser) {
175
181
  if (useCache) {
176
- const devices = userDevicesCache.get(user);
182
+ const devices = mgetDevices?.[user] ||
183
+ (userDevicesCache.mget
184
+ ? undefined
185
+ : (await userDevicesCache.get(user)));
177
186
  if (devices) {
178
- deviceResults.push(...devices);
179
- logger.trace({ user }, 'using cache for devices');
187
+ const devicesWithJid = devices.map((d) => ({
188
+ ...d,
189
+ jid: jidEncode(d.user, d.server, d.device),
190
+ }));
191
+ deviceResults.push(...devicesWithJid);
192
+ logger.trace({ user }, "using cache for devices");
180
193
  }
181
194
  else {
182
195
  toFetch.push(jid);
@@ -189,321 +202,594 @@ const makeMessagesSocket = (config) => {
189
202
  if (!toFetch.length) {
190
203
  return deviceResults;
191
204
  }
192
- const query = new WAUSync_1.USyncQuery()
193
- .withContext('message')
194
- .withDeviceProtocol();
205
+ const requestedLidUsers = new Set();
195
206
  for (const jid of toFetch) {
196
- query.withUser(new WAUSync_1.USyncUser().withId(jid));
207
+ if (isLidUser(jid) || isHostedLidUser(jid)) {
208
+ const user = jidDecode(jid)?.user;
209
+ if (user)
210
+ requestedLidUsers.add(user);
211
+ }
212
+ }
213
+ const query = new USyncQuery()
214
+ .withContext("message")
215
+ .withDeviceProtocol()
216
+ .withLIDProtocol();
217
+ for (const jid of toFetch) {
218
+ query.withUser(new USyncUser().withId(jid)); // todo: investigate - the idea here is that <user> should have an inline lid field with the lid being the pn equivalent
197
219
  }
198
220
  const result = await sock.executeUSyncQuery(query);
199
221
  if (result) {
200
- const extracted = (0, Utils_1.extractDeviceJids)(result === null || result === void 0 ? void 0 : result.list, authState.creds.me.id, ignoreZeroDevices);
222
+ // TODO: LID MAP this stuff (lid protocol will now return lid with devices)
223
+ const lidResults = result.list.filter((a) => !!a.lid);
224
+ if (lidResults.length > 0) {
225
+ logger.trace("Storing LID maps from device call");
226
+ await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map((a) => ({ lid: a.lid, pn: a.id })));
227
+ // Force-refresh sessions for newly mapped LIDs to align identity addressing
228
+ try {
229
+ const lids = lidResults.map((a) => a.lid);
230
+ if (lids.length) {
231
+ await assertSessions(lids, true);
232
+ }
233
+ }
234
+ catch (e) {
235
+ logger.warn({ e, count: lidResults.length }, "failed to assert sessions for newly mapped LIDs");
236
+ }
237
+ }
238
+ const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
201
239
  const deviceMap = {};
202
240
  for (const item of extracted) {
203
241
  deviceMap[item.user] = deviceMap[item.user] || [];
204
- deviceMap[item.user].push(item);
205
- deviceResults.push(item);
242
+ deviceMap[item.user]?.push(item);
243
+ }
244
+ // Process each user's devices as a group for bulk LID migration
245
+ for (const [user, userDevices] of Object.entries(deviceMap)) {
246
+ const isLidUser = requestedLidUsers.has(user);
247
+ // Process all devices for this user
248
+ for (const item of userDevices) {
249
+ const finalJid = isLidUser
250
+ ? jidEncode(user, item.server, item.device)
251
+ : jidEncode(item.user, item.server, item.device);
252
+ deviceResults.push({
253
+ ...item,
254
+ jid: finalJid,
255
+ });
256
+ logger.debug({
257
+ user: item.user,
258
+ device: item.device,
259
+ finalJid,
260
+ usedLid: isLidUser,
261
+ }, "Processed device with LID priority");
262
+ }
206
263
  }
207
- for (const key in deviceMap) {
208
- userDevicesCache.set(key, deviceMap[key]);
264
+ if (userDevicesCache.mset) {
265
+ // if the cache supports mset, we can set all devices in one go
266
+ await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
267
+ }
268
+ else {
269
+ for (const key in deviceMap) {
270
+ if (deviceMap[key])
271
+ await userDevicesCache.set(key, deviceMap[key]);
272
+ }
273
+ }
274
+ const userDeviceUpdates = {};
275
+ for (const [userId, devices] of Object.entries(deviceMap)) {
276
+ if (devices && devices.length > 0) {
277
+ userDeviceUpdates[userId] = devices.map((d) => d.device?.toString() || "0");
278
+ }
279
+ }
280
+ if (Object.keys(userDeviceUpdates).length > 0) {
281
+ try {
282
+ await authState.keys.set({ "device-list": userDeviceUpdates });
283
+ logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, "stored user device lists for bulk migration");
284
+ }
285
+ catch (error) {
286
+ logger.warn({ error }, "failed to store user device lists");
287
+ }
209
288
  }
210
289
  }
211
290
  return deviceResults;
212
291
  };
292
+ /**
293
+ * Update Member Label
294
+ */
295
+ const updateMemberLabel = (jid, memberLabel) => {
296
+ return relayMessage(jid, {
297
+ protocolMessage: {
298
+ type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
299
+ memberLabel: {
300
+ label: memberLabel?.slice(0, 30),
301
+ labelTimestamp: unixTimestampSeconds(),
302
+ },
303
+ },
304
+ }, {
305
+ additionalNodes: [
306
+ {
307
+ tag: "meta",
308
+ attrs: {
309
+ tag_reason: "user_update",
310
+ appdata: "member_tag",
311
+ },
312
+ content: undefined,
313
+ },
314
+ ],
315
+ });
316
+ };
213
317
  const assertSessions = async (jids, force) => {
214
318
  let didFetchNewSession = false;
215
- let jidsRequiringFetch = [];
216
- if (force) {
217
- jidsRequiringFetch = jids;
218
- }
219
- else {
220
- const addrs = jids.map(jid => (signalRepository
221
- .jidToSignalProtocolAddress(jid)));
222
- const sessions = await authState.keys.get('session', addrs);
223
- for (const jid of jids) {
224
- const signalId = signalRepository
225
- .jidToSignalProtocolAddress(jid);
226
- if (!sessions[signalId]) {
227
- jidsRequiringFetch.push(jid);
319
+ const uniqueJids = [...new Set(jids)]; // Deduplicate JIDs
320
+ const jidsRequiringFetch = [];
321
+ logger.debug({ jids }, "assertSessions call with jids");
322
+ // Check peerSessionsCache and validate sessions using libsignal loadSession
323
+ for (const jid of uniqueJids) {
324
+ const signalId = signalRepository.jidToSignalProtocolAddress(jid);
325
+ const cachedSession = peerSessionsCache.get(signalId);
326
+ if (cachedSession !== undefined) {
327
+ if (cachedSession && !force) {
328
+ continue; // Session exists in cache
329
+ }
330
+ }
331
+ else {
332
+ const sessionValidation = await signalRepository.validateSession(jid);
333
+ const hasSession = sessionValidation.exists;
334
+ peerSessionsCache.set(signalId, hasSession);
335
+ if (hasSession && !force) {
336
+ continue;
228
337
  }
229
338
  }
339
+ jidsRequiringFetch.push(jid);
230
340
  }
231
341
  if (jidsRequiringFetch.length) {
232
- logger.debug({ jidsRequiringFetch }, 'fetching sessions');
342
+ // LID if mapped, otherwise original
343
+ const wireJids = [
344
+ ...jidsRequiringFetch.filter((jid) => !!isLidUser(jid) || !!isHostedLidUser(jid)),
345
+ ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter((jid) => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map((a) => a.lid),
346
+ ];
347
+ logger.debug({ jidsRequiringFetch, wireJids }, "fetching sessions");
233
348
  const result = await query({
234
- tag: 'iq',
349
+ tag: "iq",
235
350
  attrs: {
236
- xmlns: 'encrypt',
237
- type: 'get',
238
- to: WABinary_1.S_WHATSAPP_NET,
351
+ xmlns: "encrypt",
352
+ type: "get",
353
+ to: S_WHATSAPP_NET,
239
354
  },
240
355
  content: [
241
356
  {
242
- tag: 'key',
357
+ tag: "key",
243
358
  attrs: {},
244
- content: jidsRequiringFetch.map(jid => ({
245
- tag: 'user',
246
- attrs: { jid },
247
- }))
248
- }
249
- ]
359
+ content: wireJids.map((jid) => {
360
+ const attrs = { jid };
361
+ if (force)
362
+ attrs.reason = "identity";
363
+ return { tag: "user", attrs };
364
+ }),
365
+ },
366
+ ],
250
367
  });
251
- await (0, Utils_1.parseAndInjectE2ESessions)(result, signalRepository);
368
+ await parseAndInjectE2ESessions(result, signalRepository);
252
369
  didFetchNewSession = true;
370
+ // Cache fetched sessions using wire JIDs
371
+ for (const wireJid of wireJids) {
372
+ const signalId = signalRepository.jidToSignalProtocolAddress(wireJid);
373
+ peerSessionsCache.set(signalId, true);
374
+ }
253
375
  }
254
376
  return didFetchNewSession;
255
377
  };
256
378
  const sendPeerDataOperationMessage = async (pdoMessage) => {
257
- var _a;
258
379
  //TODO: for later, abstract the logic to send a Peer Message instead of just PDO - useful for App State Key Resync with phone
259
- if (!((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id)) {
260
- throw new boom_1.Boom('Not authenticated');
380
+ if (!authState.creds.me?.id) {
381
+ throw new Boom("Not authenticated");
261
382
  }
262
383
  const protocolMessage = {
263
384
  protocolMessage: {
264
385
  peerDataOperationRequestMessage: pdoMessage,
265
- type: WAProto_1.proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
266
- }
386
+ type: proto.Message.ProtocolMessage.Type
387
+ .PEER_DATA_OPERATION_REQUEST_MESSAGE,
388
+ },
267
389
  };
268
- const meJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
390
+ const meJid = jidNormalizedUser(authState.creds.me.id);
269
391
  const msgId = await relayMessage(meJid, protocolMessage, {
270
392
  additionalAttributes: {
271
- category: 'peer',
272
- // eslint-disable-next-line camelcase
273
- push_priority: 'high_force',
393
+ category: "peer",
394
+ push_priority: "high_force",
274
395
  },
396
+ additionalNodes: [
397
+ {
398
+ tag: "meta",
399
+ attrs: { appdata: "default" },
400
+ },
401
+ ],
275
402
  });
276
403
  return msgId;
277
404
  };
278
- const createParticipantNodes = async (jids, message, extraAttrs) => {
279
- let patched = await patchMessageBeforeSending(message, jids);
280
- const requiredPatched = patchMessageRequiresBeforeSending(patched, jids);
281
- const bytes = (0, Utils_1.encodeWAMessage)(requiredPatched);
405
+ const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
406
+ if (!recipientJids.length) {
407
+ return { nodes: [], shouldIncludeDeviceIdentity: false };
408
+ }
409
+ const patched = await patchMessageBeforeSending(message, recipientJids);
410
+ const patchedMessages = Array.isArray(patched)
411
+ ? patched
412
+ : recipientJids.map((jid) => ({ recipientJid: jid, message: patched }));
282
413
  let shouldIncludeDeviceIdentity = false;
283
- const nodes = await Promise.all(jids.map(async (jid) => {
284
- const { type, ciphertext } = await signalRepository
285
- .encryptMessage({ jid, data: bytes });
286
- if (type === 'pkmsg') {
287
- shouldIncludeDeviceIdentity = true;
414
+ const meId = authState.creds.me.id;
415
+ const meLid = authState.creds.me?.lid;
416
+ const meLidUser = meLid ? jidDecode(meLid)?.user : null;
417
+ const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
418
+ try {
419
+ if (!jid)
420
+ return null;
421
+ let msgToEncrypt = patchedMessage;
422
+ if (dsmMessage) {
423
+ const { user: targetUser } = jidDecode(jid);
424
+ const { user: ownPnUser } = jidDecode(meId);
425
+ const ownLidUser = meLidUser;
426
+ const isOwnUser = targetUser === ownPnUser ||
427
+ (ownLidUser && targetUser === ownLidUser);
428
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
429
+ if (isOwnUser && !isExactSenderDevice) {
430
+ msgToEncrypt = dsmMessage;
431
+ logger.debug({ jid, targetUser }, "Using DSM for own device");
432
+ }
433
+ }
434
+ const bytes = encodeWAMessage(msgToEncrypt);
435
+ const mutexKey = jid;
436
+ const node = await encryptionMutex.mutex(mutexKey, async () => {
437
+ const { type, ciphertext } = await signalRepository.encryptMessage({
438
+ jid,
439
+ data: bytes,
440
+ });
441
+ if (type === "pkmsg") {
442
+ shouldIncludeDeviceIdentity = true;
443
+ }
444
+ return {
445
+ tag: "to",
446
+ attrs: { jid },
447
+ content: [
448
+ {
449
+ tag: "enc",
450
+ attrs: { v: "2", type, ...(extraAttrs || {}) },
451
+ content: ciphertext,
452
+ },
453
+ ],
454
+ };
455
+ });
456
+ return node;
288
457
  }
289
- const node = {
290
- tag: 'to',
291
- attrs: { jid },
292
- content: [{
293
- tag: 'enc',
294
- attrs: {
295
- v: '2',
296
- type,
297
- ...extraAttrs || {}
298
- },
299
- content: ciphertext
300
- }]
301
- };
302
- return node;
303
- }));
458
+ catch (err) {
459
+ logger.error({ jid, err }, "Failed to encrypt for recipient");
460
+ return null;
461
+ }
462
+ });
463
+ const nodes = (await Promise.all(encryptionPromises)).filter((node) => node !== null);
464
+ if (recipientJids.length > 0 && nodes.length === 0) {
465
+ throw new Boom("All encryptions failed", { statusCode: 500 });
466
+ }
304
467
  return { nodes, shouldIncludeDeviceIdentity };
305
- }; //apela
306
- const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, cachedGroupMetadata, useCachedGroupMetadata, statusJidList }) => {
468
+ };
469
+ const relayMessage = async (jid, message, { messageId: msgId, participant, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, statusJidList, }) => {
307
470
  const meId = authState.creds.me.id;
308
- let shouldIncludeDeviceIdentity = false;
309
- const { user, server } = (0, WABinary_1.jidDecode)(jid);
310
- const statusJid = 'status@broadcast';
311
- const isGroup = server === 'g.us';
471
+ const meLid = authState.creds.me?.lid;
472
+ const isRetryResend = Boolean(participant?.jid);
473
+ let shouldIncludeDeviceIdentity = isRetryResend;
474
+ const statusJid = "status@broadcast";
475
+ const { user, server } = jidDecode(jid);
476
+ const isGroup = server === "g.us";
312
477
  const isStatus = jid === statusJid;
313
- const isLid = server === 'lid';
314
- const isPrivate = server === 's.whatsapp.net';
315
- const isNewsletter = server === 'newsletter';
316
- msgId = msgId || (await config.generateMessageID() ?? (0, Utils_1.generateMessageID)());
478
+ const isLid = server === "lid";
479
+ const isNewsletter = server === "newsletter";
480
+ const isGroupOrStatus = isGroup || isStatus;
481
+ const finalJid = jid;
482
+ msgId = msgId || generateMessageIDV2(meId);
317
483
  useUserDevicesCache = useUserDevicesCache !== false;
318
484
  useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
319
485
  const participants = [];
320
- const destinationJid = (!isStatus) ? (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid;
486
+ const destinationJid = !isStatus ? finalJid : statusJid;
321
487
  const binaryNodeContent = [];
322
488
  const devices = [];
489
+ let reportingMessage;
323
490
  const meMsg = {
324
491
  deviceSentMessage: {
325
492
  destinationJid,
326
- message
327
- }
493
+ message,
494
+ },
495
+ messageContextInfo: message.messageContextInfo,
328
496
  };
329
497
  const extraAttrs = {};
330
498
  if (participant) {
331
- // when the retry request is not for a group
332
- // only send to the specific device that asked for a retry
333
- // otherwise the message is sent out to every device that should be a recipient
334
499
  if (!isGroup && !isStatus) {
335
- additionalAttributes = { ...additionalAttributes, 'device_fanout': 'false' };
500
+ additionalAttributes = {
501
+ ...additionalAttributes,
502
+ device_fanout: "false",
503
+ };
336
504
  }
337
- const { user, device } = (0, WABinary_1.jidDecode)(participant.jid);
338
- devices.push({ user, device });
505
+ const { user, device } = jidDecode(participant.jid);
506
+ devices.push({
507
+ user,
508
+ device,
509
+ jid: participant.jid,
510
+ });
339
511
  }
340
512
  await authState.keys.transaction(async () => {
341
- var _a, _b, _c, _d, _e, _f;
342
- const mediaType = getMediaType(message);
513
+ const mediaType = getMediaType(normalizeMessageContent(message) || message);
343
514
  if (mediaType) {
344
- extraAttrs['mediatype'] = mediaType;
515
+ extraAttrs["mediatype"] = mediaType;
345
516
  }
346
- if ((_a = (0, Utils_1.normalizeMessageContent)(message)) === null || _a === void 0 ? void 0 : _a.pinInChatMessage) {
347
- extraAttrs['decrypt-fail'] = 'hide';
517
+ if (isNewsletter) {
518
+ const patched = patchMessageBeforeSending
519
+ ? await patchMessageBeforeSending(message, [])
520
+ : message;
521
+ const bytes = encodeNewsletterMessage(patched);
522
+ binaryNodeContent.push({
523
+ tag: "plaintext",
524
+ attrs: extraAttrs || {},
525
+ content: bytes,
526
+ });
527
+ const stanza = {
528
+ tag: "message",
529
+ attrs: {
530
+ to: jid,
531
+ id: msgId,
532
+ type: getMessageType(message),
533
+ ...(additionalAttributes || {}),
534
+ },
535
+ content: binaryNodeContent,
536
+ };
537
+ logger.debug({ msgId }, `sending newsletter message to ${jid}`);
538
+ await sendNode(stanza);
539
+ return;
540
+ }
541
+ if (normalizeMessageContent(message)?.pinInChatMessage ||
542
+ normalizeMessageContent(message)?.reactionMessage) {
543
+ extraAttrs["decrypt-fail"] = "hide"; // todo: expand for reactions and other types
348
544
  }
349
- if (isGroup || isStatus) {
545
+ if (isGroupOrStatus && !isRetryResend) {
350
546
  const [groupData, senderKeyMap] = await Promise.all([
351
547
  (async () => {
352
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
353
- if (groupData && Array.isArray(groupData === null || groupData === void 0 ? void 0 : groupData.participants)) {
354
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
548
+ let groupData = useCachedGroupMetadata && cachedGroupMetadata
549
+ ? await cachedGroupMetadata(jid)
550
+ : undefined; // todo: should we rely on the cache specially if the cache is outdated and the metadata has new fields?
551
+ if (groupData && Array.isArray(groupData?.participants)) {
552
+ logger.trace({ jid, participants: groupData.participants.length }, "using cached group metadata");
355
553
  }
356
- if (!groupData && !isStatus) {
357
- groupData = await groupMetadata(jid);
554
+ else if (!isStatus) {
555
+ groupData = await groupMetadata(jid); // TODO: start storing group participant list + addr mode in Signal & stop relying on this
358
556
  }
359
557
  return groupData;
360
558
  })(),
361
559
  (async () => {
362
560
  if (!participant && !isStatus) {
363
- const result = await authState.keys.get('sender-key-memory', [jid]);
561
+ // what if sender memory is less accurate than the cached metadata
562
+ // on participant change in group, we should do sender memory manipulation
563
+ const result = await authState.keys.get("sender-key-memory", [
564
+ jid,
565
+ ]); // TODO: check out what if the sender key memory doesn't include the LID stuff now?
364
566
  return result[jid] || {};
365
567
  }
366
568
  return {};
367
- })()
569
+ })(),
368
570
  ]);
369
- if (!participant) {
370
- const participantsList = (groupData && !isStatus) ? groupData.participants.map(p => p.id) : [];
371
- if (isStatus && statusJidList) {
372
- participantsList.push(...statusJidList);
373
- }
374
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
375
- devices.push(...additionalDevices);
571
+ const participantsList = groupData
572
+ ? groupData.participants.map((p) => p.id)
573
+ : [];
574
+ if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
575
+ additionalAttributes = {
576
+ ...additionalAttributes,
577
+ expiration: groupData.ephemeralDuration.toString(),
578
+ };
376
579
  }
377
- const patched = await patchMessageBeforeSending(message, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', d.device)));
378
- const requiredPatched = patchMessageRequiresBeforeSending(patched, devices.map(d => (0, WABinary_1.jidEncode)(d.user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', d.device)));
379
- const bytes = (0, Utils_1.encodeWAMessage)(requiredPatched);
580
+ if (isStatus && statusJidList) {
581
+ participantsList.push(...statusJidList);
582
+ }
583
+ const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
584
+ devices.push(...additionalDevices);
585
+ if (isGroup) {
586
+ additionalAttributes = {
587
+ ...additionalAttributes,
588
+ addressing_mode: groupData?.addressingMode || "lid",
589
+ };
590
+ }
591
+ const patched = await patchMessageBeforeSending(message);
592
+ if (Array.isArray(patched)) {
593
+ throw new Boom("Per-jid patching is not supported in groups");
594
+ }
595
+ const bytes = encodeWAMessage(patched);
596
+ reportingMessage = patched;
597
+ const groupAddressingMode = additionalAttributes?.["addressing_mode"] ||
598
+ groupData?.addressingMode ||
599
+ "lid";
600
+ const groupSenderIdentity = groupAddressingMode === "lid" && meLid ? meLid : meId;
380
601
  const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
381
602
  group: destinationJid,
382
603
  data: bytes,
383
- meId,
604
+ meId: groupSenderIdentity,
384
605
  });
385
- const senderKeyJids = [];
386
- // ensure a connection is established with every device
387
- for (const { user, device } of devices) {
388
- const jid = (0, WABinary_1.jidEncode)(user, isLid ? 'lid' : 's.whatsapp.net', device);
389
- if (!senderKeyMap[jid] || !!participant) {
390
- senderKeyJids.push(jid);
391
- // store that this person has had the sender keys sent to them
392
- senderKeyMap[jid] = true;
606
+ const senderKeyRecipients = [];
607
+ for (const device of devices) {
608
+ const deviceJid = device.jid;
609
+ const hasKey = !!senderKeyMap[deviceJid];
610
+ if ((!hasKey || !!participant) &&
611
+ !isHostedLidUser(deviceJid) &&
612
+ !isHostedPnUser(deviceJid) &&
613
+ device.device !== 99) {
614
+ //todo: revamp all this logic
615
+ // the goal is to follow with what I said above for each group, and instead of a true false map of ids, we can set an array full of those the app has already sent pkmsgs
616
+ senderKeyRecipients.push(deviceJid);
617
+ senderKeyMap[deviceJid] = true;
393
618
  }
394
619
  }
395
- // if there are some participants with whom the session has not been established
396
- // if there are, we re-send the senderkey
397
- if (senderKeyJids.length) {
398
- logger.debug({ senderKeyJids }, 'sending new sender key');
620
+ if (senderKeyRecipients.length) {
621
+ logger.debug({ senderKeyJids: senderKeyRecipients }, "sending new sender key");
399
622
  const senderKeyMsg = {
400
623
  senderKeyDistributionMessage: {
401
624
  axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
402
- groupId: destinationJid
403
- }
625
+ groupId: destinationJid,
626
+ },
404
627
  };
405
- await assertSessions(senderKeyJids, false);
406
- const result = await createParticipantNodes(senderKeyJids, senderKeyMsg, mediaType ? { ...extraAttrs, mediatype: mediaType } : extraAttrs);
407
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
628
+ const senderKeySessionTargets = senderKeyRecipients;
629
+ await assertSessions(senderKeySessionTargets);
630
+ const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
631
+ shouldIncludeDeviceIdentity =
632
+ shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
408
633
  participants.push(...result.nodes);
409
634
  }
410
635
  binaryNodeContent.push({
411
- tag: 'enc',
412
- attrs: { v: '2', type: 'skmsg' },
413
- content: ciphertext
636
+ tag: "enc",
637
+ attrs: { v: "2", type: "skmsg", ...extraAttrs },
638
+ content: ciphertext,
414
639
  });
415
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
416
- }
417
- else if (isNewsletter) {
418
- // Message edit
419
- if ((_a = message.protocolMessage) === null || _a === void 0 ? void 0 : _a.editedMessage) {
420
- msgId = (_b = message.protocolMessage.key) === null || _b === void 0 ? void 0 : _b.id;
421
- message = message.protocolMessage.editedMessage;
422
- }
423
- // Message delete
424
- if (((_c = message.protocolMessage) === null || _c === void 0 ? void 0 : _c.type) === WAProto_1.proto.Message.ProtocolMessage.Type.REVOKE) {
425
- msgId = (_d = message.protocolMessage.key) === null || _d === void 0 ? void 0 : _d.id;
426
- message = {};
427
- }
428
- const patched = await patchMessageBeforeSending(message, []);
429
- const bytes = WAProto_1.proto.Message.encode(patched).finish();
430
- binaryNodeContent.push({
431
- tag: 'plaintext',
432
- attrs: mediaType ? { mediatype: mediaType } : {},
433
- content: bytes
640
+ await authState.keys.set({
641
+ "sender-key-memory": { [jid]: senderKeyMap },
434
642
  });
435
643
  }
436
644
  else {
437
- const { user: meUser, device: meDevice } = (0, WABinary_1.jidDecode)(meId);
645
+ // ADDRESSING CONSISTENCY: Match own identity to conversation context
646
+ // TODO: investigate if this is true
647
+ let ownId = meId;
648
+ if (isLid && meLid) {
649
+ ownId = meLid;
650
+ logger.debug({ to: jid, ownId }, "Using LID identity for @lid conversation");
651
+ }
652
+ else {
653
+ logger.debug({ to: jid, ownId }, "Using PN identity for @s.whatsapp.net conversation");
654
+ }
655
+ const { user: ownUser } = jidDecode(ownId);
438
656
  if (!participant) {
439
- devices.push({ user });
440
- // do not send message to self if the device is 0 (mobile)
441
- if (meDevice !== undefined && meDevice !== 0) {
442
- devices.push({ user: meUser });
657
+ const patchedForReporting = await patchMessageBeforeSending(message, [
658
+ jid,
659
+ ]);
660
+ reportingMessage = Array.isArray(patchedForReporting)
661
+ ? patchedForReporting.find((item) => item.recipientJid === jid) ||
662
+ patchedForReporting[0]
663
+ : patchedForReporting;
664
+ }
665
+ if (!isRetryResend) {
666
+ const targetUserServer = isLid ? "lid" : "s.whatsapp.net";
667
+ devices.push({
668
+ user,
669
+ device: 0,
670
+ jid: jidEncode(user, targetUserServer, 0), // rajeh, todo: this entire logic is convoluted and weird.
671
+ });
672
+ if (user !== ownUser) {
673
+ const ownUserServer = isLid ? "lid" : "s.whatsapp.net";
674
+ const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
675
+ devices.push({
676
+ user: ownUserForAddressing,
677
+ device: 0,
678
+ jid: jidEncode(ownUserForAddressing, ownUserServer, 0),
679
+ });
443
680
  }
444
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
445
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) !== 'peer') {
446
- const additionalDevices = await getUSyncDevices([meId, jid], !!useUserDevicesCache, true);
447
- devices.push(...additionalDevices);
681
+ if (additionalAttributes?.["category"] !== "peer") {
682
+ // Clear placeholders and enumerate actual devices
683
+ devices.length = 0;
684
+ // Use conversation-appropriate sender identity
685
+ const senderIdentity = isLid && meLid
686
+ ? jidEncode(jidDecode(meLid)?.user, "lid", undefined)
687
+ : jidEncode(jidDecode(meId)?.user, "s.whatsapp.net", undefined);
688
+ // Enumerate devices for sender and target with consistent addressing
689
+ const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
690
+ devices.push(...sessionDevices);
691
+ logger.debug({
692
+ deviceCount: devices.length,
693
+ devices: devices.map((d) => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`),
694
+ }, "Device enumeration complete with unified addressing");
448
695
  }
449
- devices.push(...additionalDevices);
450
696
  }
451
- const allJids = [];
452
- const meJids = [];
453
- const otherJids = [];
454
- for (const { user, device } of devices) {
455
- const isMe = user === meUser;
456
- const jid = (0, WABinary_1.jidEncode)(isMe && isLid ? ((_f = (_e = authState.creds) === null || _e === void 0 ? void 0 : _e.me) === null || _f === void 0 ? void 0 : _f.lid.split(':')[0]) || user : user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net', device);
697
+ const allRecipients = [];
698
+ const meRecipients = [];
699
+ const otherRecipients = [];
700
+ const { user: mePnUser } = jidDecode(meId);
701
+ const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
702
+ for (const { user, jid } of devices) {
703
+ const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
704
+ if (isExactSenderDevice) {
705
+ logger.debug({ jid, meId, meLid }, "Skipping exact sender device (whatsmeow pattern)");
706
+ continue;
707
+ }
708
+ // Check if this is our device (could match either PN or LID user)
709
+ const isMe = user === mePnUser || user === meLidUser;
457
710
  if (isMe) {
458
- meJids.push(jid);
711
+ meRecipients.push(jid);
459
712
  }
460
713
  else {
461
- otherJids.push(jid);
714
+ otherRecipients.push(jid);
462
715
  }
463
- allJids.push(jid);
716
+ allRecipients.push(jid);
464
717
  }
465
- await assertSessions(allJids, false);
466
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
467
- createParticipantNodes(meJids, meMsg, mediaType ? { ...extraAttrs, mediatype: mediaType } : extraAttrs),
468
- createParticipantNodes(otherJids, message, mediaType ? { ...extraAttrs, mediatype: mediaType } : extraAttrs)
718
+ await assertSessions(allRecipients);
719
+ const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 },] = await Promise.all([
720
+ // For own devices: use DSM if available (1:1 chats only)
721
+ createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
722
+ createParticipantNodes(otherRecipients, message, extraAttrs, meMsg),
469
723
  ]);
470
724
  participants.push(...meNodes);
471
725
  participants.push(...otherNodes);
726
+ if (meRecipients.length > 0 || otherRecipients.length > 0) {
727
+ extraAttrs["phash"] = generateParticipantHashV2([
728
+ ...meRecipients,
729
+ ...otherRecipients,
730
+ ]);
731
+ }
472
732
  shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
473
733
  }
734
+ if (isRetryResend) {
735
+ const isParticipantLid = isLidUser(participant.jid);
736
+ const isMe = areJidsSameUser(participant.jid, isParticipantLid ? meLid : meId);
737
+ const encodedMessageToSend = isMe
738
+ ? encodeWAMessage({
739
+ deviceSentMessage: {
740
+ destinationJid,
741
+ message,
742
+ },
743
+ })
744
+ : encodeWAMessage(message);
745
+ const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
746
+ data: encodedMessageToSend,
747
+ jid: participant.jid,
748
+ });
749
+ binaryNodeContent.push({
750
+ tag: "enc",
751
+ attrs: {
752
+ v: "2",
753
+ type,
754
+ count: participant.count.toString(),
755
+ },
756
+ content: encryptedContent,
757
+ });
758
+ }
474
759
  if (participants.length) {
475
- if ((additionalAttributes === null || additionalAttributes === void 0 ? void 0 : additionalAttributes['category']) === 'peer') {
476
- const peerNode = (_e = (_d = participants[0]) === null || _d === void 0 ? void 0 : _d.content) === null || _e === void 0 ? void 0 : _e[0];
760
+ if (additionalAttributes?.["category"] === "peer") {
761
+ const peerNode = participants[0]?.content?.[0];
477
762
  if (peerNode) {
478
763
  binaryNodeContent.push(peerNode); // push only enc
479
764
  }
480
765
  }
481
766
  else {
482
767
  binaryNodeContent.push({
483
- tag: 'participants',
768
+ tag: "participants",
484
769
  attrs: {},
485
- content: participants
770
+ content: participants,
486
771
  });
487
772
  }
488
773
  }
489
774
  const stanza = {
490
- tag: 'message',
775
+ tag: "message",
491
776
  attrs: {
492
777
  id: msgId,
493
- type: isNewsletter ? getTypeMessage(message) : 'text',
494
- ...(additionalAttributes || {})
778
+ to: destinationJid,
779
+ type: getMessageType(message),
780
+ ...(additionalAttributes || {}),
495
781
  },
496
- content: binaryNodeContent
782
+ content: binaryNodeContent,
497
783
  };
498
784
  // if the participant to send to is explicitly specified (generally retry recp)
499
785
  // ensure the message is only sent to that person
500
786
  // if a retry receipt is sent to everyone -- it'll fail decryption for everyone else who received the msg
501
787
  if (participant) {
502
- if ((0, WABinary_1.isJidGroup)(destinationJid)) {
788
+ if (isJidGroup(destinationJid)) {
503
789
  stanza.attrs.to = destinationJid;
504
790
  stanza.attrs.participant = participant.jid;
505
791
  }
506
- else if ((0, WABinary_1.areJidsSameUser)(participant.jid, meId)) {
792
+ else if (areJidsSameUser(participant.jid, meId)) {
507
793
  stanza.attrs.to = participant.jid;
508
794
  stanza.attrs.recipient = destinationJid;
509
795
  }
@@ -516,252 +802,161 @@ const makeMessagesSocket = (config) => {
516
802
  }
517
803
  if (shouldIncludeDeviceIdentity) {
518
804
  stanza.content.push({
519
- tag: 'device-identity',
805
+ tag: "device-identity",
520
806
  attrs: {},
521
- content: (0, Utils_1.encodeSignedDeviceIdentity)(authState.creds.account, true)
807
+ content: encodeSignedDeviceIdentity(authState.creds.account, true),
522
808
  });
523
- logger.debug({ jid }, 'adding device identity');
809
+ logger.debug({ jid }, "adding device identity");
524
810
  }
525
- if (additionalNodes && additionalNodes.length > 0) {
526
- stanza.content.push(...additionalNodes);
527
- }
528
- const inMsg = (0, Utils_1.normalizeMessageContent)(message) || null;
529
- const key = inMsg ? (0, Utils_1.getContentType)(inMsg) : null;
530
- if (!isNewsletter && (key === 'interactiveMessage' || key === 'buttonsMessage')) {
531
- const nativeNode = {
532
- tag: 'biz',
533
- attrs: {},
534
- content: [{
535
- tag: 'interactive',
536
- attrs: {
537
- type: 'native_flow',
538
- v: '1'
539
- },
540
- content: [{
541
- tag: 'native_flow',
542
- attrs: {
543
- name: 'quick_reply'
544
- }
545
- }]
546
- }]
547
- };
548
- const resultNativeNode = filterNativeNode(additionalNodes);
549
- if (resultNativeNode && additionalNodes && additionalNodes.length > 0) {
550
- stanza.content.push(...resultNativeNode);
551
- }
552
- else {
553
- stanza.content.push(nativeNode);
554
- }
555
- }/*
556
- if (isPrivate) {
557
- const botNode = {
558
- tag: 'bot',
559
- attrs: { biz_bot: '1' }
560
- };
561
- const resultBotNode = filterBotNode(additionalNodes);
562
- if (resultBotNode && additionalNodes && additionalNodes.length > 0) {
563
- stanza.content.push(...resultBotNode);
811
+ if (!isNewsletter &&
812
+ !isRetryResend &&
813
+ reportingMessage?.messageContextInfo?.messageSecret &&
814
+ shouldIncludeReportingToken(reportingMessage)) {
815
+ try {
816
+ const encoded = encodeWAMessage(reportingMessage);
817
+ const reportingKey = {
818
+ id: msgId,
819
+ fromMe: true,
820
+ remoteJid: destinationJid,
821
+ participant: participant?.jid,
822
+ };
823
+ const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
824
+ if (reportingNode) {
825
+ stanza.content.push(reportingNode);
826
+ logger.trace({ jid }, "added reporting token to message");
827
+ }
564
828
  }
565
- else {
566
- stanza.content.push(botNode);
829
+ catch (error) {
830
+ logger.warn({ jid, trace: error?.stack }, "failed to attach reporting token");
567
831
  }
568
- }*
569
- if (message && message.listMessage) {
832
+ }
833
+ const contactTcTokenData = !isGroup && !isRetryResend && !isStatus
834
+ ? await authState.keys.get("tctoken", [destinationJid])
835
+ : {};
836
+ const tcTokenBuffer = contactTcTokenData[destinationJid]?.token;
837
+ if (tcTokenBuffer) {
570
838
  stanza.content.push({
571
- tag: 'biz',
839
+ tag: "tctoken",
572
840
  attrs: {},
573
- content: [
574
- {
575
- tag: 'list',
576
- attrs: getButtonArgs(message)
577
- }
578
- ]
841
+ content: tcTokenBuffer,
579
842
  });
580
- logger.debug({ jid }, 'adding business node');
581
- }*/
843
+ }
844
+ if (additionalNodes && additionalNodes.length > 0) {
845
+ stanza.content.push(...additionalNodes);
846
+ }
582
847
  const buttonType = getButtonType(message);
583
- if (buttonType) {
584
- stanza.content.push({
585
- tag: 'biz',
586
- attrs: {},
587
- content: [
588
- {
589
- tag: buttonType,
590
- attrs: getButtonArgs(message),
591
- }
592
- ]
593
- });
594
- logger.debug({ jid }, 'adding business node');
848
+ if (buttonType && !isNewsletter && !isStatus) {
849
+ const bizNodes = getAdditionalNode(buttonType);
850
+ stanza.content.push(...bizNodes);
595
851
  }
596
852
  logger.debug({ msgId }, `sending message to ${participants.length} devices`);
597
853
  await sendNode(stanza);
598
- });
854
+ // Add message to retry cache if enabled
855
+ if (messageRetryManager && !participant) {
856
+ messageRetryManager.addRecentMessage(destinationJid, msgId, message);
857
+ }
858
+ }, meId);
599
859
  return msgId;
600
860
  };
601
- const filterNativeNode = (nodeContent) => {
602
- if (Array.isArray(nodeContent)) {
603
- return nodeContent.filter((item) => {
604
- var _a, _b, _c, _d, _e, _f, _g, _h;
605
- if (item.tag === 'biz' && ((_a = item === null || item === void 0 ? void 0 : item.content[0]) === null || _a === void 0 ? void 0 : _a.tag) === 'interactive' && ((_c = (_b = item === null || item === void 0 ? void 0 : item.content[0]) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c.type) === 'native_flow' && ((_e = (_d = item === null || item === void 0 ? void 0 : item.content[0]) === null || _d === void 0 ? void 0 : _d.content[0]) === null || _e === void 0 ? void 0 : _e.tag) === 'native_flow' && ((_h = (_g = (_f = item === null || item === void 0 ? void 0 : item.content[0]) === null || _f === void 0 ? void 0 : _f.content[0]) === null || _g === void 0 ? void 0 : _g.attrs) === null || _h === void 0 ? void 0 : _h.name) === 'quick_reply') {
606
- return false;
607
- }
608
- return true;
609
- });
861
+ const getMessageType = (message) => {
862
+ const normalizedMessage = normalizeMessageContent(message);
863
+ if (!normalizedMessage)
864
+ return "text";
865
+ if (normalizedMessage.reactionMessage ||
866
+ normalizedMessage.encReactionMessage) {
867
+ return "reaction";
610
868
  }
611
- else {
612
- return nodeContent;
869
+ if (normalizedMessage.pollCreationMessage ||
870
+ normalizedMessage.pollCreationMessageV2 ||
871
+ normalizedMessage.pollCreationMessageV3 ||
872
+ normalizedMessage.pollUpdateMessage) {
873
+ return "poll";
613
874
  }
614
- };
615
- const filterBotNode = (nodeContent) => {
616
- if (Array.isArray(nodeContent)) {
617
- return nodeContent.filter((item) => {
618
- if (item.tag === 'bot' && item.attrs.biz_bot === '1') {
619
- return false;
620
- }
621
- return true;
622
- });
875
+ if (normalizedMessage.eventMessage) {
876
+ return "event";
623
877
  }
624
- else {
625
- return nodeContent;
626
- }
627
- };
628
- const getTypeMessage = (msg) => {
629
- if (msg.viewOnceMessage) {
630
- return getTypeMessage(msg.viewOnceMessage.message);
631
- }
632
- else if (msg.viewOnceMessageV2) {
633
- return getTypeMessage(msg.viewOnceMessageV2.message);
634
- }
635
- else if (msg.viewOnceMessageV2Extension) {
636
- return getTypeMessage(msg.viewOnceMessageV2Extension.message);
637
- }
638
- else if (msg.ephemeralMessage) {
639
- return getTypeMessage(msg.ephemeralMessage.message);
640
- }
641
- else if (msg.documentWithCaptionMessage) {
642
- return getTypeMessage(msg.documentWithCaptionMessage.message);
643
- }
644
- else if (msg.reactionMessage) {
645
- return 'reaction';
646
- }
647
- else if (msg.pollCreationMessage || msg.pollCreationMessageV2 || msg.pollCreationMessageV3 || msg.pollUpdateMessage) {
648
- return 'poll';
649
- }
650
- else if (getMediaType(msg)) {
651
- return 'media';
652
- }
653
- else {
654
- return 'text';
878
+ if (getMediaType(normalizedMessage) !== "") {
879
+ return "media";
655
880
  }
881
+ return "text";
656
882
  };
657
883
  const getMediaType = (message) => {
658
884
  if (message.imageMessage) {
659
- return 'image';
885
+ return "image";
660
886
  }
661
887
  else if (message.videoMessage) {
662
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
888
+ return message.videoMessage.gifPlayback ? "gif" : "video";
663
889
  }
664
890
  else if (message.audioMessage) {
665
- return message.audioMessage.ptt ? 'ptt' : 'audio';
891
+ return message.audioMessage.ptt ? "ptt" : "audio";
666
892
  }
667
893
  else if (message.contactMessage) {
668
- return 'vcard';
894
+ return "vcard";
669
895
  }
670
896
  else if (message.documentMessage) {
671
- return 'document';
897
+ return "document";
672
898
  }
673
899
  else if (message.contactsArrayMessage) {
674
- return 'contact_array';
900
+ return "contact_array";
675
901
  }
676
902
  else if (message.liveLocationMessage) {
677
- return 'livelocation';
903
+ return "livelocation";
678
904
  }
679
905
  else if (message.stickerMessage) {
680
- return 'sticker';
906
+ return "sticker";
681
907
  }
682
908
  else if (message.listMessage) {
683
- return 'list';
909
+ return "list";
684
910
  }
685
911
  else if (message.listResponseMessage) {
686
- return 'list_response';
912
+ return "list_response";
687
913
  }
688
914
  else if (message.buttonsResponseMessage) {
689
- return 'buttons_response';
915
+ return "buttons_response";
690
916
  }
691
917
  else if (message.orderMessage) {
692
- return 'order';
918
+ return "order";
693
919
  }
694
920
  else if (message.productMessage) {
695
- return 'product';
921
+ return "product";
696
922
  }
697
923
  else if (message.interactiveResponseMessage) {
698
- return 'native_flow_response';
924
+ return "native_flow_response";
699
925
  }
700
926
  else if (message.groupInviteMessage) {
701
- return 'url';
702
- }
703
- };
704
- const getButtonType = (message) => {
705
- if (message.buttonsMessage) {
706
- return 'buttons';
707
- }
708
- else if (message.buttonsResponseMessage) {
709
- return 'buttons_response';
710
- }
711
- else if (message.interactiveResponseMessage) {
712
- return 'interactive_response';
713
- }
714
- else if (message.listMessage) {
715
- return 'list';
716
- }
717
- else if (message.listResponseMessage) {
718
- return 'list_response';
719
- }
720
- };
721
- const getButtonArgs = (message) => {
722
- if (message.templateMessage) {
723
- // TODO: Add attributes
724
- return {};
725
- }
726
- else if (message.listMessage) {
727
- const type = message.listMessage.listType;
728
- if (!type) {
729
- throw new boom_1.Boom('Expected list type inside message');
730
- }
731
- return { v: '2', type: ListType[type].toLowerCase() };
732
- }
733
- else {
734
- return {};
927
+ return "url";
735
928
  }
929
+ return "";
736
930
  };
737
931
  const getPrivacyTokens = async (jids) => {
738
- const t = (0, Utils_1.unixTimestampSeconds)().toString();
932
+ const t = unixTimestampSeconds().toString();
739
933
  const result = await query({
740
- tag: 'iq',
934
+ tag: "iq",
741
935
  attrs: {
742
- to: WABinary_1.S_WHATSAPP_NET,
743
- type: 'set',
744
- xmlns: 'privacy'
936
+ to: S_WHATSAPP_NET,
937
+ type: "set",
938
+ xmlns: "privacy",
745
939
  },
746
940
  content: [
747
941
  {
748
- tag: 'tokens',
942
+ tag: "tokens",
749
943
  attrs: {},
750
- content: jids.map(jid => ({
751
- tag: 'token',
944
+ content: jids.map((jid) => ({
945
+ tag: "token",
752
946
  attrs: {
753
- jid: (0, WABinary_1.jidNormalizedUser)(jid),
947
+ jid: jidNormalizedUser(jid),
754
948
  t,
755
- type: 'trusted_contact'
756
- }
757
- }))
758
- }
759
- ]
949
+ type: "trusted_contact",
950
+ },
951
+ })),
952
+ },
953
+ ],
760
954
  });
761
955
  return result;
762
956
  };
763
- const waUploadToServer = (0, Utils_1.getWAUploadToServer)(config, refreshMediaConn);
764
- const waitForMsgMediaUpdate = (0, Utils_1.bindWaitForEvent)(ev, 'messages.media-update');
957
+ const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
958
+ const changli = new Dugong(waUploadToServer, relayMessage, config, sock);
959
+ const waitForMsgMediaUpdate = bindWaitForEvent(ev, "messages.media-update");
765
960
  return {
766
961
  ...sock,
767
962
  getPrivacyTokens,
@@ -769,39 +964,44 @@ const makeMessagesSocket = (config) => {
769
964
  relayMessage,
770
965
  sendReceipt,
771
966
  sendReceipts,
772
- getButtonArgs,
967
+ changli,
773
968
  readMessages,
774
969
  refreshMediaConn,
775
- getUSyncDevices,
776
- sendPeerDataOperationMessage,
777
- createParticipantNodes,
778
- profilePictureUrl,
779
970
  waUploadToServer,
780
971
  fetchPrivacySettings,
972
+ sendPeerDataOperationMessage,
973
+ createParticipantNodes,
974
+ getUSyncDevices,
975
+ messageRetryManager,
976
+ updateMemberLabel,
781
977
  updateMediaMessage: async (message) => {
782
- const content = (0, Utils_1.assertMediaContent)(message.message);
978
+ const content = assertMediaContent(message.message);
783
979
  const mediaKey = content.mediaKey;
784
980
  const meId = authState.creds.me.id;
785
- const node = await (0, Utils_1.encryptMediaRetryRequest)(message.key, mediaKey, meId);
981
+ const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
786
982
  let error = undefined;
787
983
  await Promise.all([
788
984
  sendNode(node),
789
- waitForMsgMediaUpdate(async update => {
790
- const result = update.find(c => c.key.id === message.key.id);
985
+ waitForMsgMediaUpdate(async (update) => {
986
+ const result = update.find((c) => c.key.id === message.key.id);
791
987
  if (result) {
792
988
  if (result.error) {
793
989
  error = result.error;
794
990
  }
795
991
  else {
796
992
  try {
797
- const media = await (0, Utils_1.decryptMediaRetryData)(result.media, mediaKey, result.key.id);
798
- if (media && media.result !== WAProto_1.proto.MediaRetryNotification.ResultType.SUCCESS) {
799
- const resultStr = WAProto_1.proto.MediaRetryNotification.ResultType[media.result];
800
- throw new boom_1.Boom(`Media re-upload failed by device (${resultStr})`, { data: media, statusCode: (0, Utils_1.getStatusCodeForMediaRetry)(media.result) || 404 });
993
+ const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
994
+ if (media.result !==
995
+ proto.MediaRetryNotification.ResultType.SUCCESS) {
996
+ const resultStr = proto.MediaRetryNotification.ResultType[media.result];
997
+ throw new Boom(`Media re-upload failed by device (${resultStr})`, {
998
+ data: media,
999
+ statusCode: getStatusCodeForMediaRetry(media.result) || 404,
1000
+ });
801
1001
  }
802
1002
  content.directPath = media.directPath;
803
- content.url = (0, Utils_1.getUrlFromDirectPath)(content.directPath);
804
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1003
+ content.url = getUrlFromDirectPath(content.directPath);
1004
+ logger.debug({ directPath: media.directPath, key: result.key }, "media update successful");
805
1005
  }
806
1006
  catch (err) {
807
1007
  error = err;
@@ -809,279 +1009,203 @@ const makeMessagesSocket = (config) => {
809
1009
  }
810
1010
  return true;
811
1011
  }
812
- })
1012
+ }),
813
1013
  ]);
814
1014
  if (error) {
815
1015
  throw error;
816
1016
  }
817
- ev.emit('messages.update', [
818
- { key: message.key, update: { message: message.message } }
1017
+ ev.emit("messages.update", [
1018
+ { key: message.key, update: { message: message.message } },
819
1019
  ]);
820
1020
  return message;
821
1021
  },
822
- sendStatusMentions: async (content, jids = []) => {
823
- const userJid = (0, WABinary_1.jidNormalizedUser)(authState.creds.me.id);
824
- let allUsers = [];
825
- for (const id of jids) {
826
- const { user, server } = (0, WABinary_1.jidDecode)(id);
827
- const isGroup = server === 'g.us';
828
- const isPrivate = server === 's.whatsapp.net';
829
- if (isGroup) {
830
- let userId = await groupMetadata(id);
831
- let participant = await userId.participants;
832
- let users = await Promise.all(participant.map(u => (0, WABinary_1.jidNormalizedUser)(u.id)));
833
- allUsers = [...allUsers, ...users];
834
- }
835
- else if (isPrivate) {
836
- let users = await Promise.all(jids.map(id => id.replace(/\b\d{18}@.{4}\b/g, '')));
837
- allUsers = [...allUsers, ...users];
838
- }
839
- if (!allUsers.find(user => user.includes(userJid))) {
840
- allUsers.push(userJid);
841
- }
842
- }
843
- ;
844
- const getRandomHexColor = () => {
845
- return "#" + Math.floor(Math.random() * 16777215)
846
- .toString(16)
847
- .padStart(6, "0");
848
- };
849
- let mediaHandle;
850
- let msg = await (0, Utils_1.generateWAMessage)(WABinary_1.STORIES_JID, content, {
851
- logger,
852
- userJid,
853
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
854
- thumbnailWidth: linkPreviewImageThumbnailWidth,
855
- fetchOpts: {
856
- timeout: 3000,
857
- ...axiosOptions || {}
858
- },
859
- logger,
860
- uploadImage: generateHighQualityLinkPreview
861
- ? waUploadToServer
862
- : undefined
863
- }),
864
- upload: async (readStream, opts) => {
865
- const up = await waUploadToServer(readStream, { ...opts });
866
- mediaHandle = up.handle;
867
- return up;
868
- },
869
- mediaCache: config.mediaCache,
870
- options: config.options,
871
- backgroundColor: getRandomHexColor(),
872
- font: Math.floor(Math.random() * 9),
873
- });
874
- await relayMessage(WABinary_1.STORIES_JID, msg.message, {
875
- messageId: msg.key.id,
876
- statusJidList: allUsers,
877
- additionalNodes: [
878
- {
879
- tag: 'meta',
880
- attrs: {},
881
- content: [
882
- {
883
- tag: 'mentioned_users',
884
- attrs: {},
885
- content: jids.map(jid => ({
886
- tag: 'to',
887
- attrs: { jid },
888
- content: undefined,
889
- })),
890
- },
891
- ],
892
- },
893
- ],
894
- });
895
- jids.forEach(async (id) => {
896
- id = (0, WABinary_1.jidNormalizedUser)(id);
897
- const { user, server } = (0, WABinary_1.jidDecode)(id);
898
- const isPrivate = server === 's.whatsapp.net';
899
- let type = isPrivate
900
- ? 'statusMentionMessage'
901
- : 'groupStatusMentionMessage';
902
- await relayMessage(id, {
903
- [type]: {
904
- message: {
905
- protocolMessage: {
906
- key: msg.key,
907
- type: 25,
908
- },
909
- },
910
- },
911
- }, {});
912
- await (0, Utils_1.delay)(2500);
913
- });
914
- return msg;
1022
+ sendStatusMention: async (content, jids = []) => {
1023
+ return await changli.sendStatusWhatsApp(content, jids);
915
1024
  },
916
- sendAlbumMessage: async (jid, medias, options = {}) => {
917
- const userJid = authState.creds.me.id;
918
- for (const media of medias) {
919
- if (!media.image && !media.video)
920
- throw new TypeError(`medias[i] must have image or video property`);
921
- }
922
- if (medias.length < 2)
923
- throw new RangeError("Minimum 2 media");
924
- const time = options.delay || 500;
925
- delete options.delay;
926
- const album = await (0, Utils_1.generateWAMessageFromContent)(jid, {
927
- albumMessage: {
928
- expectedImageCount: medias.filter(media => media.image).length,
929
- expectedVideoCount: medias.filter(media => media.video).length,
930
- ...options
931
- }
932
- }, { userJid, ...options });
933
- await relayMessage(jid, album.message, { messageId: album.key.id });
934
- let mediaHandle;
935
- let msg;
936
- for (const i in medias) {
937
- const media = medias[i];
938
- if (media.image) {
939
- msg = await (0, Utils_1.generateWAMessage)(jid, {
940
- image: media.image,
941
- ...media,
942
- ...options
943
- }, {
944
- userJid,
945
- upload: async (readStream, opts) => {
946
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
947
- mediaHandle = up.handle;
948
- return up;
949
- },
950
- ...options,
951
- });
952
- }
953
- else if (media.video) {
954
- msg = await (0, Utils_1.generateWAMessage)(jid, {
955
- video: media.video,
956
- ...media,
957
- ...options
958
- }, {
959
- userJid,
960
- upload: async (readStream, opts) => {
961
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
962
- mediaHandle = up.handle;
963
- return up;
964
- },
965
- ...options,
966
- });
967
- }
968
- if (msg) {
969
- msg.message.messageContextInfo = {
970
- messageAssociation: {
971
- associationType: 1,
972
- parentMessageKey: album.key
973
- }
974
- };
975
- }
976
- await relayMessage(jid, msg.message, { messageId: msg.key.id });
977
- await (0, Utils_1.delay)(time);
978
- }
979
- return album;
1025
+ // Aku tau kamu pasti bakalan nyari ini, tapi gak papa deh
1026
+ // support changli terus yahh kawan kawan
1027
+ // @Zann
1028
+ sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1029
+ const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1030
+ await relayMessage(jid, message, { messageId });
1031
+ return { message, messageId };
1032
+ },
1033
+ sendList: async (jid, title, items, quoted, options = {}) => {
1034
+ const { message, messageId } = generateListContent(title, items, quoted, options);
1035
+ await relayMessage(jid, message, { messageId });
1036
+ return { message, messageId };
1037
+ },
1038
+ sendCodeBlock: async (jid, code, quoted, options = {}) => {
1039
+ const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1040
+ await relayMessage(jid, message, { messageId });
1041
+ return { message, messageId };
1042
+ },
1043
+ sendLatex: async (jid, quoted, options) => {
1044
+ const { message, messageId } = generateLatexContent(quoted, options);
1045
+ await relayMessage(jid, message, { messageId });
1046
+ return { message, messageId };
1047
+ },
1048
+ sendLatexImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1049
+ const { message, messageId } = await generateLatexImageContent(quoted, options, uploadFn, renderLatexToPng);
1050
+ await relayMessage(jid, message, { messageId });
1051
+ return { message, messageId };
1052
+ },
1053
+ sendLatexInlineImage: async (jid, quoted, options, renderLatexToPng, uploadFn) => {
1054
+ const { message, messageId } = await generateLatexInlineImageContent(quoted, options, uploadFn, renderLatexToPng);
1055
+ await relayMessage(jid, message, { messageId });
1056
+ return { message, messageId };
1057
+ },
1058
+ captureUnifiedResponse,
1059
+ sendUnifiedResponse: async (jid, quoted, captured) => {
1060
+ const { message, messageId } = generateUnifiedResponseContent(quoted, captured);
1061
+ await relayMessage(jid, message, { messageId });
1062
+ return { message, messageId };
1063
+ },
1064
+ sendRichMessage: async (jid, submessages, quoted, options = {}) => {
1065
+ const { message, messageId } = generateRichMessageContent(submessages, quoted);
1066
+ await relayMessage(jid, message, { messageId });
1067
+ return { message, messageId };
980
1068
  },
981
1069
  sendMessage: async (jid, content, options = {}) => {
982
- var _a, _b, _c;
983
1070
  const userJid = authState.creds.me.id;
984
- if (typeof content === 'object' &&
985
- 'disappearingMessagesInChat' in content &&
986
- typeof content['disappearingMessagesInChat'] !== 'undefined' &&
987
- (0, WABinary_1.isJidGroup)(jid)) {
1071
+ const { quoted } = options;
1072
+ const messageType = changli.detectType(content);
1073
+ if (typeof content === "object" &&
1074
+ "disappearingMessagesInChat" in content &&
1075
+ typeof content["disappearingMessagesInChat"] !== "undefined" &&
1076
+ isJidGroup(jid)) {
988
1077
  const { disappearingMessagesInChat } = content;
989
- const value = typeof disappearingMessagesInChat === 'boolean' ?
990
- (disappearingMessagesInChat ? Defaults_1.WA_DEFAULT_EPHEMERAL : 0) :
991
- disappearingMessagesInChat;
1078
+ const value = typeof disappearingMessagesInChat === "boolean"
1079
+ ? disappearingMessagesInChat
1080
+ ? WA_DEFAULT_EPHEMERAL
1081
+ : 0
1082
+ : disappearingMessagesInChat;
992
1083
  await groupToggleEphemeral(jid, value);
993
1084
  }
1085
+ else if (messageType) {
1086
+ switch (messageType) {
1087
+ case "PAYMENT": {
1088
+ const paymentContent = await changli.handlePayment(content, quoted);
1089
+ return await relayMessage(jid, paymentContent, {
1090
+ messageId: generateMessageIDV2(userJid),
1091
+ });
1092
+ }
1093
+ case "PRODUCT": {
1094
+ const productContent = await changli.handleProduct(content, jid, quoted);
1095
+ const productMsg = await generateWAMessageFromContent(jid, productContent, { quoted, userJid });
1096
+ return await relayMessage(jid, productMsg.message, {
1097
+ messageId: productMsg.key.id,
1098
+ });
1099
+ }
1100
+ case "INTERACTIVE": {
1101
+ const interactiveContent = await changli.handleInteractive(content, jid, quoted);
1102
+ const interactiveMsg = await generateWAMessageFromContent(jid, interactiveContent, { quoted, userJid });
1103
+ return await relayMessage(jid, interactiveMsg.message, {
1104
+ messageId: interactiveMsg.key.id,
1105
+ });
1106
+ }
1107
+ case "INTERACTIVE_BUTTONS": {
1108
+ const ibContent = await changli.handleInteractiveButtons(content, jid, quoted);
1109
+ const ibMsg = await generateWAMessageFromContent(jid, ibContent, { quoted, userJid });
1110
+ return await relayMessage(jid, ibMsg.message, {
1111
+ messageId: ibMsg.key.id,
1112
+ });
1113
+ }
1114
+ case "ALBUM":
1115
+ return await changli.handleAlbum(content, jid, quoted);
1116
+ case "EVENT":
1117
+ return await changli.handleEvent(content, jid, quoted);
1118
+ case "POLL_RESULT":
1119
+ return await changli.handlePollResult(content, jid, quoted);
1120
+ case "GROUP_STORY":
1121
+ return await changli.handleGroupStory(content, jid, quoted);
1122
+ }
1123
+ }
994
1124
  else {
995
1125
  let mediaHandle;
996
- const { server } = (0, WABinary_1.jidDecode)(jid);
997
- const isGroup = server === 'g.us';
998
- let eph;
999
- if (isGroup) {
1000
- const disappearingNode = await groupQuery(jid, 'get', [
1001
- {
1002
- tag: 'query',
1003
- attrs: { request: 'interactive' }
1004
- }
1005
- ]);
1006
- const group = (0, WABinary_1.getBinaryNodeChild)(disappearingNode, 'group');
1007
- const expiration = (0, WABinary_1.getBinaryNodeChild)(group, 'ephemeral');
1008
- eph = (_a = expiration === null || expiration === void 0 ? void 0 : expiration.attrs) === null || _a === void 0 ? void 0 : _a.expiration;
1009
- }
1010
- const fullMsg = await (0, Utils_1.generateWAMessage)(jid, content, {
1126
+ const fullMsg = await generateWAMessage(jid, content, {
1011
1127
  logger,
1012
1128
  userJid,
1013
- ephemeralExpiration: (options.ephemeralExpiration && options.ephemeralExpiration > 0) ? options.ephemeralExpiration : eph,
1014
- getUrlInfo: text => (0, link_preview_1.getUrlInfo)(text, {
1129
+ getUrlInfo: (text) => getUrlInfo(text, {
1015
1130
  thumbnailWidth: linkPreviewImageThumbnailWidth,
1016
1131
  fetchOpts: {
1017
1132
  timeout: 3000,
1018
- ...axiosOptions || {}
1133
+ ...(httpRequestOptions || {}),
1019
1134
  },
1020
1135
  logger,
1021
1136
  uploadImage: generateHighQualityLinkPreview
1022
1137
  ? waUploadToServer
1023
- : undefined
1138
+ : undefined,
1024
1139
  }),
1140
+ getProfilePicUrl: sock.profilePictureUrl,
1141
+ getCallLink: sock.createCallLink,
1025
1142
  upload: async (readStream, opts) => {
1026
- const up = await waUploadToServer(readStream, { ...opts, newsletter: (0, WABinary_1.isJidNewsLetter)(jid) });
1027
- mediaHandle = up.handle;
1143
+ const up = await waUploadToServer(readStream, {
1144
+ ...opts,
1145
+ newsletter: isJidNewsletter(jid),
1146
+ });
1028
1147
  return up;
1029
1148
  },
1030
1149
  mediaCache: config.mediaCache,
1031
1150
  options: config.options,
1032
- messageId: await config.generateMessageIDV2((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id) ?? (0, Utils_1.generateMessageIDV2)((_a = sock.user) === null || _a === void 0 ? void 0 : _a.id),
1151
+ messageId: generateMessageIDV2(sock.user?.id),
1033
1152
  ...options,
1034
1153
  });
1035
- const isAiMsg = 'ai' in content && !!content.ai;
1036
- const isPinMsg = 'pin' in content && !!content.pin;
1037
- const isKeepMsg = 'keep' in content && content.keep;
1038
- const isPollMsg = 'poll' in content && !!content.poll;
1039
- const isEditMsg = 'edit' in content && !!content.edit;
1040
- const isDeleteMsg = 'delete' in content && !!content.delete;
1154
+ const isEventMsg = "event" in content && !!content.event;
1155
+ const isDeleteMsg = "delete" in content && !!content.delete;
1156
+ const isEditMsg = "edit" in content && !!content.edit;
1157
+ const isPinMsg = "pin" in content && !!content.pin;
1158
+ const isPollMessage = "poll" in content && !!content.poll;
1159
+ const isAiMsg = "ai" in content && !!content.ai;
1041
1160
  const additionalAttributes = {};
1042
1161
  const additionalNodes = [];
1043
- // required for delete
1044
1162
  if (isDeleteMsg) {
1045
- // if the chat is a group, and I am not the author, then delete the message as an admin
1046
- if (((0, WABinary_1.isJidGroup)((_b = content.delete) === null || _b === void 0 ? void 0 : _b.remoteJid) && !((_c = content.delete) === null || _c === void 0 ? void 0 : _c.fromMe)) || (0, WABinary_1.isJidNewsLetter)(jid)) {
1047
- additionalAttributes.edit = '8';
1048
- }
1049
- else {
1050
- additionalAttributes.edit = '7';
1051
- }
1163
+ const fromMe = content.delete?.fromMe;
1164
+ const isGroup = isJidGroup(content.delete?.remoteJid);
1165
+ additionalAttributes.edit =
1166
+ (isGroup && !fromMe) || isJidNewsletter(jid) ? "8" : "7";
1052
1167
  }
1053
1168
  else if (isEditMsg) {
1054
- additionalAttributes.edit = (0, WABinary_1.isJidNewsLetter)(jid) ? '3' : '1';
1169
+ additionalAttributes.edit = isJidNewsletter(jid) ? "3" : "1";
1055
1170
  }
1056
1171
  else if (isPinMsg) {
1057
- additionalAttributes.edit = '2';
1172
+ additionalAttributes.edit = "2";
1058
1173
  }
1059
- else if (isAiMsg) {
1174
+ else if (isPollMessage) {
1060
1175
  additionalNodes.push({
1061
- attrs: {
1062
- biz_bot: '1'
1063
- },
1064
- tag: 'bot'
1176
+ tag: "meta",
1177
+ attrs: { polltype: "creation" },
1065
1178
  });
1066
- if (options.additionalNodes) {
1067
- additionalNodes.push(...options.additionalNodes);
1068
- }
1069
1179
  }
1070
- if (mediaHandle) {
1071
- additionalAttributes['media_id'] = mediaHandle;
1180
+ else if (isEventMsg) {
1181
+ additionalNodes.push({
1182
+ tag: "meta",
1183
+ attrs: { event_type: "creation" },
1184
+ });
1072
1185
  }
1073
- if ('cachedGroupMetadata' in options) {
1074
- console.warn('cachedGroupMetadata in sendMessage are deprecated, now cachedGroupMetadata is part of the socket config.');
1186
+ else if (isAiMsg) {
1187
+ additionalNodes.push({
1188
+ tag: "bot",
1189
+ attrs: { biz_bot: "1" },
1190
+ });
1075
1191
  }
1076
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, cachedGroupMetadata: options.cachedGroupMetadata, additionalNodes: isAiMsg ? additionalNodes : options.additionalNodes, additionalAttributes, statusJidList: options.statusJidList });
1192
+ await relayMessage(jid, fullMsg.message, {
1193
+ messageId: fullMsg.key.id,
1194
+ useCachedGroupMetadata: options.useCachedGroupMetadata,
1195
+ additionalAttributes,
1196
+ statusJidList: options.statusJidList,
1197
+ additionalNodes: isAiMsg
1198
+ ? additionalNodes
1199
+ : options.additionalNodes,
1200
+ });
1077
1201
  if (config.emitOwnEvents) {
1078
- process.nextTick(() => {
1079
- processingMutex.mutex(() => (upsertMessage(fullMsg, 'append')));
1202
+ process.nextTick(async () => {
1203
+ await messageMutex.mutex(() => upsertMessage(fullMsg, "append"));
1080
1204
  });
1081
1205
  }
1082
1206
  return fullMsg;
1083
1207
  }
1084
- }
1208
+ },
1085
1209
  };
1086
1210
  };
1087
- exports.makeMessagesSocket = makeMessagesSocket;
1211
+ //# sourceMappingURL=messages-send.js.map