dcodeindra-baileyspro 2.3.9

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 (286) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2534 -0
  3. package/WAProto/Adv/Adv.d.ts +518 -0
  4. package/WAProto/Adv/Adv.js +1734 -0
  5. package/WAProto/Adv/Adv.proto +36 -0
  6. package/WAProto/BotMetadata/BotMetadata.d.ts +5745 -0
  7. package/WAProto/BotMetadata/BotMetadata.js +16291 -0
  8. package/WAProto/BotMetadata/BotMetadata.proto +463 -0
  9. package/WAProto/Cert/Cert.d.ts +497 -0
  10. package/WAProto/Cert/Cert.js +1503 -0
  11. package/WAProto/Cert/Cert.proto +28 -0
  12. package/WAProto/ChatLockSettings/ChatLockSettings.d.ts +391 -0
  13. package/WAProto/ChatLockSettings/ChatLockSettings.js +1155 -0
  14. package/WAProto/ChatLockSettings/ChatLockSettings.proto +7 -0
  15. package/WAProto/CompanionReg/CompanionReg.d.ts +1055 -0
  16. package/WAProto/CompanionReg/CompanionReg.js +3532 -0
  17. package/WAProto/CompanionReg/CompanionReg.proto +89 -0
  18. package/WAProto/DeviceCapabilities/DeviceCapabilities.d.ts +187 -0
  19. package/WAProto/DeviceCapabilities/DeviceCapabilities.js +520 -0
  20. package/WAProto/DeviceCapabilities/DeviceCapabilities.proto +14 -0
  21. package/WAProto/E2E/E2E.d.ts +28417 -0
  22. package/WAProto/E2E/E2E.js +98438 -0
  23. package/WAProto/E2E/E2E.proto +2289 -0
  24. package/WAProto/Ephemeral/Ephemeral.d.ts +95 -0
  25. package/WAProto/Ephemeral/Ephemeral.js +269 -0
  26. package/WAProto/Ephemeral/Ephemeral.proto +6 -0
  27. package/WAProto/HistorySync/HistorySync.d.ts +40728 -0
  28. package/WAProto/HistorySync/HistorySync.js +142980 -0
  29. package/WAProto/HistorySync/HistorySync.proto +207 -0
  30. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.d.ts +189 -0
  31. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.js +585 -0
  32. package/WAProto/LidMigrationSyncPayload/LidMigrationSyncPayload.proto +11 -0
  33. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.d.ts +461 -0
  34. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.js +1559 -0
  35. package/WAProto/MdStorageChatRowOpaqueData/MdStorageChatRowOpaqueData.proto +37 -0
  36. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.d.ts +29294 -0
  37. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.js +101732 -0
  38. package/WAProto/MdStorageMsgRowOpaqueData/MdStorageMsgRowOpaqueData.proto +76 -0
  39. package/WAProto/MmsRetry/MmsRetry.d.ts +200 -0
  40. package/WAProto/MmsRetry/MmsRetry.js +586 -0
  41. package/WAProto/MmsRetry/MmsRetry.proto +17 -0
  42. package/WAProto/Protocol/Protocol.d.ts +218 -0
  43. package/WAProto/Protocol/Protocol.js +701 -0
  44. package/WAProto/Protocol/Protocol.proto +20 -0
  45. package/WAProto/Reporting/Reporting.d.ts +301 -0
  46. package/WAProto/Reporting/Reporting.js +989 -0
  47. package/WAProto/Reporting/Reporting.proto +19 -0
  48. package/WAProto/ServerSync/ServerSync.d.ts +1050 -0
  49. package/WAProto/ServerSync/ServerSync.js +3176 -0
  50. package/WAProto/ServerSync/ServerSync.proto +59 -0
  51. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.d.ts +1507 -0
  52. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.js +4756 -0
  53. package/WAProto/SignalLocalStorageProtocol/SignalLocalStorageProtocol.proto +88 -0
  54. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.d.ts +617 -0
  55. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.js +1940 -0
  56. package/WAProto/SignalWhisperTextProtocol/SignalWhisperTextProtocol.proto +38 -0
  57. package/WAProto/StatusAttributions/StatusAttributions.d.ts +636 -0
  58. package/WAProto/StatusAttributions/StatusAttributions.js +2037 -0
  59. package/WAProto/StatusAttributions/StatusAttributions.proto +61 -0
  60. package/WAProto/SyncAction/SyncAction.d.ts +7227 -0
  61. package/WAProto/SyncAction/SyncAction.js +22271 -0
  62. package/WAProto/SyncAction/SyncAction.proto +423 -0
  63. package/WAProto/UserPassword/UserPassword.d.ts +298 -0
  64. package/WAProto/UserPassword/UserPassword.js +898 -0
  65. package/WAProto/UserPassword/UserPassword.proto +27 -0
  66. package/WAProto/VnameCert/VnameCert.d.ts +658 -0
  67. package/WAProto/VnameCert/VnameCert.js +2225 -0
  68. package/WAProto/VnameCert/VnameCert.proto +60 -0
  69. package/WAProto/Wa6/Wa6.d.ts +1613 -0
  70. package/WAProto/Wa6/Wa6.js +6299 -0
  71. package/WAProto/Wa6/Wa6.proto +229 -0
  72. package/WAProto/Web/Web.d.ts +31718 -0
  73. package/WAProto/Web/Web.js +113402 -0
  74. package/WAProto/Web/Web.proto +545 -0
  75. package/WAProto/index.d.ts +49 -0
  76. package/WAProto/index.js +28 -0
  77. package/WASignalGroup/GroupProtocol.js +1771 -0
  78. package/WASignalGroup/ciphertext_message.js +10 -0
  79. package/WASignalGroup/group_cipher.js +103 -0
  80. package/WASignalGroup/group_session_builder.js +39 -0
  81. package/WASignalGroup/index.js +5 -0
  82. package/WASignalGroup/keyhelper.js +17 -0
  83. package/WASignalGroup/protobufs.js +2 -0
  84. package/WASignalGroup/queue_job.js +64 -0
  85. package/WASignalGroup/sender_chain_key.js +38 -0
  86. package/WASignalGroup/sender_key_distribution_message.js +68 -0
  87. package/WASignalGroup/sender_key_message.js +79 -0
  88. package/WASignalGroup/sender_key_name.js +59 -0
  89. package/WASignalGroup/sender_key_record.js +47 -0
  90. package/WASignalGroup/sender_key_state.js +110 -0
  91. package/WASignalGroup/sender_message_key.js +30 -0
  92. package/check-node-version.js +10 -0
  93. package/lib/Defaults/baileys-version.json +3 -0
  94. package/lib/Defaults/index.d.ts +51 -0
  95. package/lib/Defaults/index.js +108 -0
  96. package/lib/Defaults/phonenumber-mcc.json +223 -0
  97. package/lib/Signal/Group/ciphertext-message.d.ts +9 -0
  98. package/lib/Signal/Group/ciphertext-message.js +19 -0
  99. package/lib/Signal/Group/group-session-builder.d.ts +17 -0
  100. package/lib/Signal/Group/group-session-builder.js +72 -0
  101. package/lib/Signal/Group/group_cipher.d.ts +19 -0
  102. package/lib/Signal/Group/group_cipher.js +99 -0
  103. package/lib/Signal/Group/index.d.ts +11 -0
  104. package/lib/Signal/Group/index.js +61 -0
  105. package/lib/Signal/Group/keyhelper.d.ts +16 -0
  106. package/lib/Signal/Group/keyhelper.js +66 -0
  107. package/lib/Signal/Group/queue-job.d.ts +1 -0
  108. package/lib/Signal/Group/queue-job.js +64 -0
  109. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  110. package/lib/Signal/Group/sender-chain-key.js +39 -0
  111. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  112. package/lib/Signal/Group/sender-key-distribution-message.js +71 -0
  113. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  114. package/lib/Signal/Group/sender-key-message.js +73 -0
  115. package/lib/Signal/Group/sender-key-name.d.ts +19 -0
  116. package/lib/Signal/Group/sender-key-name.js +59 -0
  117. package/lib/Signal/Group/sender-key-record.d.ts +32 -0
  118. package/lib/Signal/Group/sender-key-record.js +53 -0
  119. package/lib/Signal/Group/sender-key-record.ts +77 -0
  120. package/lib/Signal/Group/sender-key-state.d.ts +44 -0
  121. package/lib/Signal/Group/sender-key-state.js +104 -0
  122. package/lib/Signal/Group/sender-message-key.d.ts +11 -0
  123. package/lib/Signal/Group/sender-message-key.js +33 -0
  124. package/lib/Signal/libsignal.d.ts +3 -0
  125. package/lib/Signal/libsignal.js +153 -0
  126. package/lib/Socket/Client/index.d.ts +2 -0
  127. package/lib/Socket/Client/index.js +18 -0
  128. package/lib/Socket/Client/types.d.ts +15 -0
  129. package/lib/Socket/Client/types.js +14 -0
  130. package/lib/Socket/Client/websocket.d.ts +12 -0
  131. package/lib/Socket/Client/websocket.js +57 -0
  132. package/lib/Socket/business.d.ts +181 -0
  133. package/lib/Socket/business.js +259 -0
  134. package/lib/Socket/chats.d.ts +95 -0
  135. package/lib/Socket/chats.js +906 -0
  136. package/lib/Socket/community.d.ts +131 -0
  137. package/lib/Socket/community.js +369 -0
  138. package/lib/Socket/groups.d.ts +122 -0
  139. package/lib/Socket/groups.js +360 -0
  140. package/lib/Socket/index.d.ts +183 -0
  141. package/lib/Socket/index.js +10 -0
  142. package/lib/Socket/messages-recv.d.ts +170 -0
  143. package/lib/Socket/messages-recv.js +1074 -0
  144. package/lib/Socket/messages-send.d.ts +161 -0
  145. package/lib/Socket/messages-send.js +982 -0
  146. package/lib/Socket/newsletter.d.ts +140 -0
  147. package/lib/Socket/newsletter.js +242 -0
  148. package/lib/Socket/socket.d.ts +43 -0
  149. package/lib/Socket/socket.js +749 -0
  150. package/lib/Socket/usync.d.ts +36 -0
  151. package/lib/Socket/usync.js +71 -0
  152. package/lib/Store/index.d.ts +4 -0
  153. package/lib/Store/index.js +20 -0
  154. package/lib/Store/make-cache-manager-store.d.ts +13 -0
  155. package/lib/Store/make-cache-manager-store.js +77 -0
  156. package/lib/Store/make-in-memory-store.d.ts +117 -0
  157. package/lib/Store/make-in-memory-store.js +420 -0
  158. package/lib/Store/make-ordered-dictionary.d.ts +12 -0
  159. package/lib/Store/make-ordered-dictionary.js +83 -0
  160. package/lib/Store/object-repository.d.ts +10 -0
  161. package/lib/Store/object-repository.js +28 -0
  162. package/lib/Types/Auth.d.ts +103 -0
  163. package/lib/Types/Auth.js +2 -0
  164. package/lib/Types/Call.d.ts +13 -0
  165. package/lib/Types/Call.js +2 -0
  166. package/lib/Types/Chat.d.ts +115 -0
  167. package/lib/Types/Chat.js +6 -0
  168. package/lib/Types/Contact.d.ts +35 -0
  169. package/lib/Types/Contact.js +2 -0
  170. package/lib/Types/Events.d.ts +208 -0
  171. package/lib/Types/Events.js +2 -0
  172. package/lib/Types/GroupMetadata.d.ts +81 -0
  173. package/lib/Types/GroupMetadata.js +2 -0
  174. package/lib/Types/Label.d.ts +46 -0
  175. package/lib/Types/Label.js +28 -0
  176. package/lib/Types/LabelAssociation.d.ts +29 -0
  177. package/lib/Types/LabelAssociation.js +10 -0
  178. package/lib/Types/Message.d.ts +480 -0
  179. package/lib/Types/Message.js +9 -0
  180. package/lib/Types/MexUpdates.d.ts +9 -0
  181. package/lib/Types/MexUpdates.js +18 -0
  182. package/lib/Types/Newsletter.d.ts +92 -0
  183. package/lib/Types/Newsletter.js +33 -0
  184. package/lib/Types/Product.d.ts +78 -0
  185. package/lib/Types/Product.js +2 -0
  186. package/lib/Types/Signal.d.ts +57 -0
  187. package/lib/Types/Signal.js +2 -0
  188. package/lib/Types/Socket.d.ts +116 -0
  189. package/lib/Types/Socket.js +2 -0
  190. package/lib/Types/State.d.ts +27 -0
  191. package/lib/Types/State.js +2 -0
  192. package/lib/Types/USync.d.ts +25 -0
  193. package/lib/Types/USync.js +2 -0
  194. package/lib/Types/index.d.ts +70 -0
  195. package/lib/Types/index.js +42 -0
  196. package/lib/Utils/auth-utils.d.ts +18 -0
  197. package/lib/Utils/auth-utils.js +198 -0
  198. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  199. package/lib/Utils/baileys-event-stream.js +64 -0
  200. package/lib/Utils/business.d.ts +22 -0
  201. package/lib/Utils/business.js +243 -0
  202. package/lib/Utils/chat-utils.d.ts +72 -0
  203. package/lib/Utils/chat-utils.js +762 -0
  204. package/lib/Utils/crypto.d.ts +40 -0
  205. package/lib/Utils/crypto.js +150 -0
  206. package/lib/Utils/decode-wa-message.d.ts +252 -0
  207. package/lib/Utils/decode-wa-message.js +232 -0
  208. package/lib/Utils/event-buffer.d.ts +35 -0
  209. package/lib/Utils/event-buffer.js +539 -0
  210. package/lib/Utils/generics.d.ts +96 -0
  211. package/lib/Utils/generics.js +553 -0
  212. package/lib/Utils/history.d.ts +29 -0
  213. package/lib/Utils/history.js +109 -0
  214. package/lib/Utils/index.d.ts +19 -0
  215. package/lib/Utils/index.js +35 -0
  216. package/lib/Utils/link-preview.d.ts +21 -0
  217. package/lib/Utils/link-preview.js +112 -0
  218. package/lib/Utils/logger.d.ts +11 -0
  219. package/lib/Utils/logger.js +7 -0
  220. package/lib/Utils/lt-hash.d.ts +12 -0
  221. package/lib/Utils/lt-hash.js +53 -0
  222. package/lib/Utils/make-mutex.d.ts +7 -0
  223. package/lib/Utils/make-mutex.js +45 -0
  224. package/lib/Utils/messages-media.d.ts +104 -0
  225. package/lib/Utils/messages-media.js +751 -0
  226. package/lib/Utils/messages.d.ts +80 -0
  227. package/lib/Utils/messages.js +1741 -0
  228. package/lib/Utils/noise-handler.d.ts +19 -0
  229. package/lib/Utils/noise-handler.js +150 -0
  230. package/lib/Utils/process-message.d.ts +41 -0
  231. package/lib/Utils/process-message.js +391 -0
  232. package/lib/Utils/signal.d.ts +33 -0
  233. package/lib/Utils/signal.js +154 -0
  234. package/lib/Utils/use-mongo-file-auth-state.d.ts +5 -0
  235. package/lib/Utils/use-mongo-file-auth-state.js +75 -0
  236. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  237. package/lib/Utils/use-multi-file-auth-state.js +123 -0
  238. package/lib/Utils/use-single-file-auth-state.d.ts +12 -0
  239. package/lib/Utils/use-single-file-auth-state.js +75 -0
  240. package/lib/Utils/validate-connection.d.ts +10 -0
  241. package/lib/Utils/validate-connection.js +174 -0
  242. package/lib/WABinary/constants.d.ts +27 -0
  243. package/lib/WABinary/constants.js +45 -0
  244. package/lib/WABinary/decode.d.ts +6 -0
  245. package/lib/WABinary/decode.js +255 -0
  246. package/lib/WABinary/encode.d.ts +2 -0
  247. package/lib/WABinary/encode.js +243 -0
  248. package/lib/WABinary/generic-utils.d.ts +16 -0
  249. package/lib/WABinary/generic-utils.js +125 -0
  250. package/lib/WABinary/index.d.ts +5 -0
  251. package/lib/WABinary/index.js +21 -0
  252. package/lib/WABinary/jid-utils.d.ts +34 -0
  253. package/lib/WABinary/jid-utils.js +73 -0
  254. package/lib/WABinary/types.d.ts +18 -0
  255. package/lib/WABinary/types.js +2 -0
  256. package/lib/WAM/BinaryInfo.d.ts +16 -0
  257. package/lib/WAM/BinaryInfo.js +14 -0
  258. package/lib/WAM/constants.d.ts +39 -0
  259. package/lib/WAM/constants.js +15362 -0
  260. package/lib/WAM/encode.d.ts +2 -0
  261. package/lib/WAM/encode.js +156 -0
  262. package/lib/WAM/index.d.ts +3 -0
  263. package/lib/WAM/index.js +19 -0
  264. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.d.ts +25 -0
  265. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +60 -0
  266. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  267. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  268. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  269. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +58 -0
  270. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  271. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  272. package/lib/WAUSync/Protocols/USyncLIDProtocol.d.ts +8 -0
  273. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +26 -0
  274. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  275. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  276. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  277. package/lib/WAUSync/Protocols/index.js +22 -0
  278. package/lib/WAUSync/USyncQuery.d.ts +28 -0
  279. package/lib/WAUSync/USyncQuery.js +88 -0
  280. package/lib/WAUSync/USyncUser.d.ts +12 -0
  281. package/lib/WAUSync/USyncUser.js +27 -0
  282. package/lib/WAUSync/index.d.ts +3 -0
  283. package/lib/WAUSync/index.js +19 -0
  284. package/lib/index.d.ts +13 -0
  285. package/lib/index.js +45 -0
  286. package/package.json +63 -0
@@ -0,0 +1,906 @@
1
+ "use strict"
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod }
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true })
6
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"))
7
+ const boom_1 = require("@hapi/boom")
8
+ const WAProto_1 = require("../../WAProto")
9
+ const Defaults_1 = require("../Defaults")
10
+ const Types_1 = require("../Types")
11
+ const Utils_1 = require("../Utils")
12
+ const make_mutex_1 = require("../Utils/make-mutex")
13
+ const WABinary_1 = require("../WABinary")
14
+ const WAUSync_1 = require("../WAUSync")
15
+ const usync_1 = require("./usync")
16
+ const MAX_SYNC_ATTEMPTS = 2
17
+ const makeChatsSocket = (config) => {
18
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, } = config
19
+ const sock = usync_1.makeUSyncSocket(config)
20
+ const { ev, ws, authState, generateMessageTag, sendNode, query, onUnexpectedError, groupFetchAllParticipating } = sock
21
+ let privacySettings
22
+ let needToFlushWithAppStateSync = false
23
+ let pendingAppStateSync = false
24
+ /** this mutex ensures that the notifications (receipts, messages etc.) are processed in order */
25
+ const processingMutex = make_mutex_1.makeMutex()
26
+ const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
27
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
28
+ useClones: false
29
+ })
30
+ if (!config.placeholderResendCache) {
31
+ config.placeholderResendCache = placeholderResendCache
32
+ }
33
+ /** helper function to fetch the given app state sync key */
34
+ const getAppStateSyncKey = async (keyId) => {
35
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId])
36
+ return key
37
+ }
38
+ const fetchPrivacySettings = async (force = false) => {
39
+ if (!privacySettings || force) {
40
+ const { content } = await query({
41
+ tag: 'iq',
42
+ attrs: {
43
+ xmlns: 'privacy',
44
+ to: WABinary_1.S_WHATSAPP_NET,
45
+ type: 'get'
46
+ },
47
+ content: [
48
+ { tag: 'privacy', attrs: {} }
49
+ ]
50
+ })
51
+ privacySettings = WABinary_1.reduceBinaryNodeToDictionary(content?.[0], 'category')
52
+ }
53
+ return privacySettings
54
+ }
55
+ /** helper function to run a privacy IQ query */
56
+ const privacyQuery = async (name, value) => {
57
+ await query({
58
+ tag: 'iq',
59
+ attrs: {
60
+ xmlns: 'privacy',
61
+ to: WABinary_1.S_WHATSAPP_NET,
62
+ type: 'set'
63
+ },
64
+ content: [{
65
+ tag: 'privacy',
66
+ attrs: {},
67
+ content: [
68
+ {
69
+ tag: 'category',
70
+ attrs: { name, value }
71
+ }
72
+ ]
73
+ }]
74
+ })
75
+ }
76
+ const updateMessagesPrivacy = async (value) => {
77
+ await privacyQuery('messages', value)
78
+ }
79
+ const updateCallPrivacy = async (value) => {
80
+ await privacyQuery('calladd', value)
81
+ }
82
+ const updateLastSeenPrivacy = async (value) => {
83
+ await privacyQuery('last', value)
84
+ }
85
+ const updateOnlinePrivacy = async (value) => {
86
+ await privacyQuery('online', value)
87
+ }
88
+ const updateProfilePicturePrivacy = async (value) => {
89
+ await privacyQuery('profile', value)
90
+ }
91
+ const updateStatusPrivacy = async (value) => {
92
+ await privacyQuery('status', value)
93
+ }
94
+ const updateReadReceiptsPrivacy = async (value) => {
95
+ await privacyQuery('readreceipts', value)
96
+ }
97
+ const updateGroupsAddPrivacy = async (value) => {
98
+ await privacyQuery('groupadd', value)
99
+ }
100
+ const updateDefaultDisappearingMode = async (duration) => {
101
+ await query({
102
+ tag: 'iq',
103
+ attrs: {
104
+ xmlns: 'disappearing_mode',
105
+ to: WABinary_1.S_WHATSAPP_NET,
106
+ type: 'set'
107
+ },
108
+ content: [{
109
+ tag: 'disappearing_mode',
110
+ attrs: {
111
+ duration: duration.toString()
112
+ }
113
+ }]
114
+ })
115
+ }
116
+ const getBotListV2 = async () => {
117
+ const resp = await query({
118
+ tag: 'iq',
119
+ attrs: {
120
+ xmlns: 'bot',
121
+ to: WABinary_1.S_WHATSAPP_NET,
122
+ type: 'get'
123
+ },
124
+ content: [{
125
+ tag: 'bot',
126
+ attrs: {
127
+ v: '2'
128
+ }
129
+ }]
130
+ })
131
+ const botNode = WABinary_1.getBinaryNodeChild(resp, 'bot')
132
+ const botList = []
133
+ for(const section of WABinary_1.getBinaryNodeChildren(botNode, 'section')) {
134
+ if(section.attrs.type === 'all') {
135
+ for(const bot of WABinary_1.getBinaryNodeChildren(section, 'bot')) {
136
+ botList.push({
137
+ jid: bot.attrs.jid,
138
+ personaId: bot.attrs['persona_id']
139
+ })
140
+ }
141
+ }
142
+ }
143
+ return botList
144
+ }
145
+ const getLidUser = async (jid) => {
146
+ if (!jid) {
147
+ throw new boom_1.Boom('Please input a jid user')
148
+ }
149
+ if (!WABinary_1.isJidUser(jid)) {
150
+ throw new boom_1.Boom('Invalid JID: Not a user JID!')
151
+ }
152
+ const targetJid = WABinary_1.jidNormalizedUser(jid)
153
+ const usyncQuery = new WAUSync_1.USyncQuery()
154
+ usyncQuery.protocols.push({
155
+ name: 'lid',
156
+ getQueryElement: () => ({
157
+ tag: 'lid',
158
+ attrs: {},
159
+ content: undefined
160
+ }),
161
+ getUserElement: () => null,
162
+ parser: (node) => node.attrs.val
163
+ })
164
+ usyncQuery.users.push({
165
+ id: targetJid
166
+ })
167
+ const result = await sock.executeUSyncQuery(usyncQuery)
168
+ if (result) {
169
+ return result.list
170
+ }
171
+ }
172
+ const onWhatsApp = async (...jids) => {
173
+ const usyncQuery = new WAUSync_1.USyncQuery().withContactProtocol().withLIDProtocol()
174
+ for (const jid of jids) {
175
+ const phone = `+${jid.replace('+', '').split('@')[0].split(':')[0]}`
176
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withPhone(phone))
177
+ }
178
+ const results = await sock.executeUSyncQuery(usyncQuery)
179
+ if (results) {
180
+ return results.list.filter((a) => !!a.contact).map(({ contact, id, lid }) => ({ jid: id, exists: contact, lid }))
181
+ }
182
+ }
183
+ const fetchStatus = async (...jids) => {
184
+ const usyncQuery = new WAUSync_1.USyncQuery().withStatusProtocol()
185
+ for (const jid of jids) {
186
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
187
+ }
188
+ const result = await sock.executeUSyncQuery(usyncQuery)
189
+ if (result) {
190
+ return result.list
191
+ }
192
+ }
193
+ const fetchDisappearingDuration = async (...jids) => {
194
+ const usyncQuery = new WAUSync_1.USyncQuery().withDisappearingModeProtocol()
195
+ for (const jid of jids) {
196
+ usyncQuery.withUser(new WAUSync_1.USyncUser().withId(jid))
197
+ }
198
+ const result = await sock.executeUSyncQuery(usyncQuery)
199
+ if (result) {
200
+ return result.list
201
+ }
202
+ }
203
+ /** update the profile picture for yourself or a group */
204
+ const updateProfilePicture = async (jid, content) => {
205
+ let targetJid
206
+ if (!jid) {
207
+ throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
208
+ }
209
+ if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
210
+ targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
211
+ }
212
+ const { img } = await Utils_1.generateProfilePicture(content)
213
+ await query({
214
+ tag: 'iq',
215
+ attrs: {
216
+ target: targetJid,
217
+ to: WABinary_1.S_WHATSAPP_NET,
218
+ type: 'set',
219
+ xmlns: 'w:profile:picture'
220
+ },
221
+ content: [
222
+ {
223
+ tag: 'picture',
224
+ attrs: { type: 'image' },
225
+ content: img
226
+ }
227
+ ]
228
+ })
229
+ }
230
+ /** remove the profile picture for yourself or a group */
231
+ const removeProfilePicture = async (jid) => {
232
+ let targetJid
233
+ if (!jid) {
234
+ throw new boom_1.Boom('Illegal no-jid profile update. Please specify either your ID or the ID of the chat you wish to update')
235
+ }
236
+ if (WABinary_1.jidNormalizedUser(jid) !== WABinary_1.jidNormalizedUser(authState.creds.me.id)) {
237
+ targetJid = WABinary_1.jidNormalizedUser(jid) // in case it is someone other than us
238
+ }
239
+ await query({
240
+ tag: 'iq',
241
+ attrs: {
242
+ target: targetJid,
243
+ to: WABinary_1.S_WHATSAPP_NET,
244
+ type: 'set',
245
+ xmlns: 'w:profile:picture'
246
+ }
247
+ })
248
+ }
249
+ /** update the profile status for yourself */
250
+ const updateProfileStatus = async (status) => {
251
+ await query({
252
+ tag: 'iq',
253
+ attrs: {
254
+ to: WABinary_1.S_WHATSAPP_NET,
255
+ type: 'set',
256
+ xmlns: 'status'
257
+ },
258
+ content: [
259
+ {
260
+ tag: 'status',
261
+ attrs: {},
262
+ content: Buffer.from(status, 'utf-8')
263
+ }
264
+ ]
265
+ })
266
+ }
267
+ const updateProfileName = async (name) => {
268
+ await chatModify({ pushNameSetting: name }, '')
269
+ }
270
+ const fetchBlocklist = async () => {
271
+ const result = await query({
272
+ tag: 'iq',
273
+ attrs: {
274
+ xmlns: 'blocklist',
275
+ to: WABinary_1.S_WHATSAPP_NET,
276
+ type: 'get'
277
+ }
278
+ })
279
+ const listNode = WABinary_1.getBinaryNodeChild(result, 'list')
280
+ return WABinary_1.getBinaryNodeChildren(listNode, 'item').map((n) => n.attrs.jid)
281
+ }
282
+ const updateBlockStatus = async (jid, action) => {
283
+ await query({
284
+ tag: 'iq',
285
+ attrs: {
286
+ xmlns: 'blocklist',
287
+ to: WABinary_1.S_WHATSAPP_NET,
288
+ type: 'set'
289
+ },
290
+ content: [
291
+ {
292
+ tag: 'item',
293
+ attrs: {
294
+ action,
295
+ jid
296
+ }
297
+ }
298
+ ]
299
+ })
300
+ }
301
+ const getBusinessProfile = async (jid) => {
302
+ const results = await query({
303
+ tag: 'iq',
304
+ attrs: {
305
+ to: 's.whatsapp.net',
306
+ xmlns: 'w:biz',
307
+ type: 'get'
308
+ },
309
+ content: [{
310
+ tag: 'business_profile',
311
+ attrs: { v: '244' },
312
+ content: [{
313
+ tag: 'profile',
314
+ attrs: { jid }
315
+ }]
316
+ }]
317
+ })
318
+ const profileNode = WABinary_1.getBinaryNodeChild(results, 'business_profile')
319
+ const profiles = WABinary_1.getBinaryNodeChild(profileNode, 'profile')
320
+ if (profiles) {
321
+ const address = WABinary_1.getBinaryNodeChild(profiles, 'address')
322
+ const description = WABinary_1.getBinaryNodeChild(profiles, 'description')
323
+ const website = WABinary_1.getBinaryNodeChild(profiles, 'website')
324
+ const email = WABinary_1.getBinaryNodeChild(profiles, 'email')
325
+ const category = WABinary_1.getBinaryNodeChild(WABinary_1.getBinaryNodeChild(profiles, 'categories'), 'category')
326
+ const businessHours = WABinary_1.getBinaryNodeChild(profiles, 'business_hours')
327
+ const businessHoursConfig = businessHours
328
+ ? WABinary_1.getBinaryNodeChildren(businessHours, 'business_hours_config')
329
+ : undefined
330
+ const websiteStr = website?.content?.toString()
331
+ return {
332
+ wid: profiles?.attrs?.jid,
333
+ address: address?.content?.toString(),
334
+ description: description?.content?.toString() || '',
335
+ website: websiteStr ? [websiteStr] : [],
336
+ email: email?.content?.toString(),
337
+ category: category?.content?.toString(),
338
+ 'business_hours': {
339
+ timezone: businessHours?.attrs?.timezone,
340
+ 'business_config': businessHoursConfig?.map(({ attrs }) => attrs)
341
+ }
342
+ }
343
+ }
344
+ }
345
+ const cleanDirtyBits = async (type, fromTimestamp) => {
346
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type)
347
+ await sendNode({
348
+ tag: 'iq',
349
+ attrs: {
350
+ to: WABinary_1.S_WHATSAPP_NET,
351
+ type: 'set',
352
+ xmlns: 'urn:xmpp:whatsapp:dirty',
353
+ id: generateMessageTag(),
354
+ },
355
+ content: [
356
+ {
357
+ tag: 'clean',
358
+ attrs: {
359
+ type,
360
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null),
361
+ }
362
+ }
363
+ ]
364
+ })
365
+ }
366
+ const newAppStateChunkHandler = (isInitialSync) => {
367
+ return {
368
+ onMutation(mutation) {
369
+ Utils_1.processSyncAction(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger)
370
+ }
371
+ }
372
+ }
373
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
374
+ // we use this to determine which events to fire
375
+ // otherwise when we resync from scratch -- all notifications will fire
376
+ const initialVersionMap = {}
377
+ const globalMutationMap = {}
378
+ await authState.keys.transaction(async () => {
379
+ const collectionsToHandle = new Set(collections)
380
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
381
+ const attemptsMap = {}
382
+ // keep executing till all collections are done
383
+ // sometimes a single patch request will not return all the patches (God knows why)
384
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
385
+ while (collectionsToHandle.size) {
386
+ const states = {}
387
+ const nodes = []
388
+ for (const name of collectionsToHandle) {
389
+ const result = await authState.keys.get('app-state-sync-version', [name])
390
+ let state = result[name]
391
+ if (state) {
392
+ if (typeof initialVersionMap[name] === 'undefined') {
393
+ initialVersionMap[name] = state.version
394
+ }
395
+ }
396
+ else {
397
+ state = Utils_1.newLTHashState()
398
+ }
399
+ states[name] = state
400
+ logger.info(`resyncing ${name} from v${state.version}`)
401
+ nodes.push({
402
+ tag: 'collection',
403
+ attrs: {
404
+ name,
405
+ version: state.version.toString(),
406
+ // return snapshot if being synced from scratch
407
+ 'return_snapshot': (!state.version).toString()
408
+ }
409
+ })
410
+ }
411
+ const result = await query({
412
+ tag: 'iq',
413
+ attrs: {
414
+ to: WABinary_1.S_WHATSAPP_NET,
415
+ xmlns: 'w:sync:app:state',
416
+ type: 'set'
417
+ },
418
+ content: [
419
+ {
420
+ tag: 'sync',
421
+ attrs: {},
422
+ content: nodes
423
+ }
424
+ ]
425
+ })
426
+ // extract from binary node
427
+ const decoded = await Utils_1.extractSyncdPatches(result, config?.options)
428
+ for (const key in decoded) {
429
+ const name = key
430
+ const { patches, hasMorePatches, snapshot } = decoded[name]
431
+ try {
432
+ if (snapshot) {
433
+ const { state: newState, mutationMap } = await Utils_1.decodeSyncdSnapshot(name, snapshot, getAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot)
434
+ states[name] = newState
435
+ Object.assign(globalMutationMap, mutationMap)
436
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`)
437
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
438
+ }
439
+ // only process if there are syncd patches
440
+ if (patches.length) {
441
+ const { state: newState, mutationMap } = await Utils_1.decodePatches(name, patches, states[name], getAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch)
442
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } })
443
+ logger.info(`synced ${name} to v${newState.version}`)
444
+ initialVersionMap[name] = newState.version
445
+ Object.assign(globalMutationMap, mutationMap)
446
+ }
447
+ if (hasMorePatches) {
448
+ logger.info(`${name} has more patches...`)
449
+ }
450
+ else { // collection is done with sync
451
+ collectionsToHandle.delete(name)
452
+ }
453
+ }
454
+ catch (error) {
455
+ // if retry attempts overshoot
456
+ // or key not found
457
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS
458
+ || error.output?.statusCode === 404
459
+ || error.name === 'TypeError'
460
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`)
461
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } })
462
+ // increment number of retries
463
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1
464
+ if (isIrrecoverableError) {
465
+ // stop retrying
466
+ collectionsToHandle.delete(name)
467
+ }
468
+ }
469
+ }
470
+ }
471
+ })
472
+ const { onMutation } = newAppStateChunkHandler(isInitialSync)
473
+ for (const key in globalMutationMap) {
474
+ onMutation(globalMutationMap[key])
475
+ }
476
+ })
477
+ const sendPresenceUpdate = async (type, toJid) => {
478
+ const me = authState.creds.me
479
+ if (type === 'available' || type === 'unavailable') {
480
+ if (!me.name) {
481
+ logger.warn('no name present, ignoring presence update request...')
482
+ return
483
+ }
484
+ ev.emit('connection.update', { isOnline: type === 'available' })
485
+ await sendNode({
486
+ tag: 'presence',
487
+ attrs: {
488
+ name: me.name,
489
+ type
490
+ }
491
+ })
492
+ }
493
+ else {
494
+ await sendNode({
495
+ tag: 'chatstate',
496
+ attrs: {
497
+ from: me.id,
498
+ to: toJid,
499
+ },
500
+ content: [
501
+ {
502
+ tag: type === 'recording' ? 'composing' : type,
503
+ attrs: type === 'recording' ? { media: 'audio' } : {}
504
+ }
505
+ ]
506
+ })
507
+ }
508
+ }
509
+ /**
510
+ * @param toJid the jid to subscribe to
511
+ * @param tcToken token for subscription, use if present
512
+ */
513
+ const presenceSubscribe = (toJid, tcToken) => (sendNode({
514
+ tag: 'presence',
515
+ attrs: {
516
+ to: toJid,
517
+ id: generateMessageTag(),
518
+ type: 'subscribe'
519
+ },
520
+ content: tcToken
521
+ ? [
522
+ {
523
+ tag: 'tctoken',
524
+ attrs: {},
525
+ content: tcToken
526
+ }
527
+ ]
528
+ : undefined
529
+ }))
530
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
531
+ let presence
532
+ const jid = attrs.from
533
+ const participant = attrs.participant || attrs.from
534
+ if (shouldIgnoreJid(jid) && jid !== '@s.whatsapp.net') {
535
+ return
536
+ }
537
+ if (tag === 'presence') {
538
+ presence = {
539
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
540
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
541
+ }
542
+ }
543
+ else if (Array.isArray(content)) {
544
+ const [firstChild] = content
545
+ let type = firstChild.tag
546
+ if (type === 'paused') {
547
+ type = 'available'
548
+ }
549
+ if (firstChild.attrs?.media === 'audio') {
550
+ type = 'recording'
551
+ }
552
+ presence = { lastKnownPresence: type }
553
+ }
554
+ else {
555
+ logger.error({ tag, attrs, content }, 'recv invalid presence node')
556
+ }
557
+ if (presence) {
558
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } })
559
+ }
560
+ }
561
+ const appPatch = async (patchCreate) => {
562
+ const name = patchCreate.type
563
+ const myAppStateKeyId = authState.creds.myAppStateKeyId
564
+ if (!myAppStateKeyId) {
565
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 })
566
+ }
567
+ let initial
568
+ let encodeResult
569
+ await processingMutex.mutex(async () => {
570
+ await authState.keys.transaction(async () => {
571
+ logger.debug({ patch: patchCreate }, 'applying app patch')
572
+ await resyncAppState([name], false)
573
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name])
574
+ initial = currentSyncVersion || Utils_1.newLTHashState()
575
+ encodeResult = await Utils_1.encodeSyncdPatch(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey)
576
+ const { patch, state } = encodeResult
577
+ const node = {
578
+ tag: 'iq',
579
+ attrs: {
580
+ to: WABinary_1.S_WHATSAPP_NET,
581
+ type: 'set',
582
+ xmlns: 'w:sync:app:state'
583
+ },
584
+ content: [
585
+ {
586
+ tag: 'sync',
587
+ attrs: {},
588
+ content: [
589
+ {
590
+ tag: 'collection',
591
+ attrs: {
592
+ name,
593
+ version: (state.version - 1).toString(),
594
+ 'return_snapshot': 'false'
595
+ },
596
+ content: [
597
+ {
598
+ tag: 'patch',
599
+ attrs: {},
600
+ content: WAProto_1.proto.SyncdPatch.encode(patch).finish()
601
+ }
602
+ ]
603
+ }
604
+ ]
605
+ }
606
+ ]
607
+ }
608
+ await query(node)
609
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } })
610
+ })
611
+ })
612
+ if (config.emitOwnEvents) {
613
+ const { onMutation } = newAppStateChunkHandler(false)
614
+ const { mutationMap } = await Utils_1.decodePatches(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version }, }], initial, getAppStateSyncKey, config.options, undefined, logger)
615
+ for (const key in mutationMap) {
616
+ onMutation(mutationMap[key])
617
+ }
618
+ }
619
+ }
620
+ /** sending non-abt props may fix QR scan fail if server expects */
621
+ const fetchProps = async () => {
622
+ const resultNode = await query({
623
+ tag: 'iq',
624
+ attrs: {
625
+ to: WABinary_1.S_WHATSAPP_NET,
626
+ xmlns: 'w',
627
+ type: 'get',
628
+ },
629
+ content: [
630
+ { tag: 'props', attrs: {
631
+ protocol: '2',
632
+ hash: authState?.creds?.lastPropHash || ''
633
+ } }
634
+ ]
635
+ })
636
+ const propsNode = WABinary_1.getBinaryNodeChild(resultNode, 'props')
637
+ let props = {}
638
+ if (propsNode) {
639
+ if (propsNode.attrs?.hash) { // on some clients, the hash is returning as undefined
640
+ authState.creds.lastPropHash = propsNode?.attrs?.hash
641
+ ev.emit('creds.update', authState.creds)
642
+ }
643
+ props = WABinary_1.reduceBinaryNodeToDictionary(propsNode, 'prop')
644
+ }
645
+ logger.debug('fetched props')
646
+ return props
647
+ }
648
+ /**
649
+ * modify a chat -- mark unread, read etc.
650
+ * lastMessages must be sorted in reverse chronologically
651
+ * requires the last messages till the last message received required for archive & unread
652
+ */
653
+ const chatModify = (mod, jid) => {
654
+ const patch = Utils_1.chatModificationToAppPatch(mod, jid)
655
+ return appPatch(patch)
656
+ }
657
+ /**
658
+ * Star or Unstar a message
659
+ */
660
+ const star = (jid, messages, star) => {
661
+ return chatModify({
662
+ star: {
663
+ messages,
664
+ star
665
+ }
666
+ }, jid)
667
+ }
668
+ /**
669
+ * Add Or Edit Contact
670
+ */
671
+ const addOrEditContact = (jid, contact) => {
672
+ return chatModify({
673
+ contact
674
+ }, jid)
675
+ }
676
+ /**
677
+ * Remove Contact
678
+ */
679
+ const removeContact = (jid) => {
680
+ return chatModify({
681
+ contact: null
682
+ }, jid)
683
+ }
684
+ /**
685
+ * Adds label
686
+ */
687
+ const addLabel = (jid, labels) => {
688
+ return chatModify({
689
+ addLabel: {
690
+ ...labels
691
+ }
692
+ }, jid)
693
+ }
694
+ /**
695
+ * Adds label for the chats
696
+ */
697
+ const addChatLabel = (jid, labelId) => {
698
+ return chatModify({
699
+ addChatLabel: {
700
+ labelId
701
+ }
702
+ }, jid)
703
+ }
704
+ /**
705
+ * Removes label for the chat
706
+ */
707
+ const removeChatLabel = (jid, labelId) => {
708
+ return chatModify({
709
+ removeChatLabel: {
710
+ labelId
711
+ }
712
+ }, jid)
713
+ }
714
+ /**
715
+ * Adds label for the message
716
+ */
717
+ const addMessageLabel = (jid, messageId, labelId) => {
718
+ return chatModify({
719
+ addMessageLabel: {
720
+ messageId,
721
+ labelId
722
+ }
723
+ }, jid)
724
+ }
725
+ /**
726
+ * Removes label for the message
727
+ */
728
+ const removeMessageLabel = (jid, messageId, labelId) => {
729
+ return chatModify({
730
+ removeMessageLabel: {
731
+ messageId,
732
+ labelId
733
+ }
734
+ }, jid)
735
+ }
736
+ /**
737
+ * Removes Chats
738
+ */
739
+ const clearMessage = (jid, key, timeStamp) => {
740
+ return chatModify({
741
+ delete: true,
742
+ lastMessages: [{
743
+ key: key,
744
+ messageTimestamp: timeStamp
745
+ }],
746
+ }, jid)
747
+ }
748
+ /**
749
+ * queries need to be fired on connection open
750
+ * help ensure parity with WA Web
751
+ * */
752
+ const executeInitQueries = async () => {
753
+ await Promise.all([
754
+ fetchProps(),
755
+ fetchBlocklist(),
756
+ fetchPrivacySettings(),
757
+ ])
758
+ }
759
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
760
+ ev.emit('messages.upsert', { messages: [msg], type })
761
+ if (!!msg.pushName) {
762
+ let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid)
763
+ jid = WABinary_1.jidNormalizedUser(jid)
764
+ if (!msg.key.fromMe) {
765
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }])
766
+ }
767
+ // update our pushname too
768
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
769
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } })
770
+ }
771
+ }
772
+ const historyMsg = Utils_1.getHistoryMsg(msg.message)
773
+ const shouldProcessHistoryMsg = historyMsg
774
+ ? (shouldSyncHistoryMessage(historyMsg)
775
+ && Defaults_1.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType))
776
+ : false
777
+ if (historyMsg && !authState.creds.myAppStateKeyId) {
778
+ logger.warn('skipping app state sync, as myAppStateKeyId is not set')
779
+ pendingAppStateSync = true
780
+ }
781
+ await Promise.all([
782
+ (async () => {
783
+ if (historyMsg
784
+ && authState.creds.myAppStateKeyId) {
785
+ pendingAppStateSync = false
786
+ await doAppStateSync()
787
+ }
788
+ })(),
789
+ Utils_1.processMessage(msg, {
790
+ shouldProcessHistoryMsg,
791
+ placeholderResendCache,
792
+ ev,
793
+ creds: authState.creds,
794
+ keyStore: authState.keys,
795
+ logger,
796
+ options: config.options,
797
+ getMessage: config.getMessage,
798
+ })
799
+ ])
800
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare
801
+ && pendingAppStateSync) {
802
+ await doAppStateSync()
803
+ pendingAppStateSync = false
804
+ }
805
+ async function doAppStateSync() {
806
+ if (!authState.creds.accountSyncCounter) {
807
+ logger.info('doing initial app state sync')
808
+ await resyncAppState(Types_1.ALL_WA_PATCH_NAMES, true)
809
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1
810
+ ev.emit('creds.update', { accountSyncCounter })
811
+ if (needToFlushWithAppStateSync) {
812
+ logger.debug('flushing with app state sync')
813
+ ev.flush()
814
+ }
815
+ }
816
+ }
817
+ })
818
+ ws.on('CB:presence', handlePresenceUpdate)
819
+ ws.on('CB:chatstate', handlePresenceUpdate)
820
+ ws.on('CB:ib,,dirty', async (node) => {
821
+ const { attrs } = WABinary_1.getBinaryNodeChild(node, 'dirty')
822
+ const type = attrs.type
823
+ switch (type) {
824
+ case 'account_sync':
825
+ if (attrs.timestamp) {
826
+ let { lastAccountSyncTimestamp } = authState.creds
827
+ if (lastAccountSyncTimestamp) {
828
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp)
829
+ }
830
+ lastAccountSyncTimestamp = +attrs.timestamp
831
+ ev.emit('creds.update', { lastAccountSyncTimestamp })
832
+ }
833
+ break
834
+ case 'groups':
835
+ await groupFetchAllParticipating()
836
+ await cleanDirtyBits('groups')
837
+ break
838
+ default:
839
+ logger.info({ node }, 'received unknown sync')
840
+ break
841
+ }
842
+ })
843
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
844
+ if (connection === 'open') {
845
+ if (fireInitQueries) {
846
+ executeInitQueries()
847
+ .catch(error => onUnexpectedError(error, 'init queries'))
848
+ }
849
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable')
850
+ .catch(error => onUnexpectedError(error, 'presence update requests'))
851
+ }
852
+ if (receivedPendingNotifications && // if we don't have the app state key
853
+ // we keep buffering events until we finally have
854
+ // the key and can sync the messages
855
+ // todo scrutinize
856
+ !authState.creds?.myAppStateKeyId) {
857
+ ev.buffer()
858
+ needToFlushWithAppStateSync = true
859
+ }
860
+ })
861
+ return {
862
+ ...sock,
863
+ star,
864
+ addOrEditContact,
865
+ removeContact,
866
+ processingMutex,
867
+ fetchPrivacySettings,
868
+ upsertMessage,
869
+ appPatch,
870
+ sendPresenceUpdate,
871
+ presenceSubscribe,
872
+ getBotListV2,
873
+ getLidUser,
874
+ onWhatsApp,
875
+ fetchBlocklist,
876
+ fetchStatus,
877
+ fetchDisappearingDuration,
878
+ updateProfilePicture,
879
+ removeProfilePicture,
880
+ updateProfileStatus,
881
+ updateProfileName,
882
+ updateBlockStatus,
883
+ updateCallPrivacy,
884
+ updateMessagesPrivacy,
885
+ updateLastSeenPrivacy,
886
+ updateOnlinePrivacy,
887
+ updateProfilePicturePrivacy,
888
+ updateStatusPrivacy,
889
+ updateReadReceiptsPrivacy,
890
+ updateGroupsAddPrivacy,
891
+ updateDefaultDisappearingMode,
892
+ getBusinessProfile,
893
+ resyncAppState,
894
+ chatModify,
895
+ cleanDirtyBits,
896
+ addLabel,
897
+ addChatLabel,
898
+ removeChatLabel,
899
+ addMessageLabel,
900
+ removeMessageLabel,
901
+ clearMessage
902
+ }
903
+ }
904
+ module.exports = {
905
+ makeChatsSocket
906
+ }