astrabail 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/WAProto.proto +5479 -0
  3. package/WAProto/fix-imports.js +73 -0
  4. package/WAProto/index.d.ts +14017 -0
  5. package/WAProto/index.js +89351 -0
  6. package/WAProto/p.html +1 -0
  7. package/engine-requirements.js +7 -0
  8. package/lib/Defaults/astrabail-version.json +8 -0
  9. package/lib/Defaults/index.d.ts +74 -0
  10. package/lib/Defaults/index.js +166 -0
  11. package/lib/Defaults/phonenumber-mcc.json +223 -0
  12. package/lib/Defaults/update-wa-version.js +75 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.js +15 -0
  15. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  16. package/lib/Signal/Group/group-session-builder.js +66 -0
  17. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  18. package/lib/Signal/Group/group_cipher.js +85 -0
  19. package/lib/Signal/Group/index.d.ts +12 -0
  20. package/lib/Signal/Group/index.js +57 -0
  21. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  22. package/lib/Signal/Group/keyhelper.js +55 -0
  23. package/lib/Signal/Group/queue-job.js +57 -0
  24. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  25. package/lib/Signal/Group/sender-chain-key.js +29 -0
  26. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  27. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  28. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  29. package/lib/Signal/Group/sender-key-message.js +69 -0
  30. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  31. package/lib/Signal/Group/sender-key-name.js +51 -0
  32. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  33. package/lib/Signal/Group/sender-key-record.js +44 -0
  34. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  35. package/lib/Signal/Group/sender-key-state.js +87 -0
  36. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  37. package/lib/Signal/Group/sender-message-key.js +29 -0
  38. package/lib/Signal/libsignal.d.ts +5 -0
  39. package/lib/Signal/libsignal.js +478 -0
  40. package/lib/Signal/lid-mapping.d.ts +19 -0
  41. package/lib/Signal/lid-mapping.js +274 -0
  42. package/lib/Socket/Client/index.d.ts +3 -0
  43. package/lib/Socket/Client/index.js +18 -0
  44. package/lib/Socket/Client/types.d.ts +16 -0
  45. package/lib/Socket/Client/types.js +14 -0
  46. package/lib/Socket/Client/websocket.d.ts +13 -0
  47. package/lib/Socket/Client/websocket.js +60 -0
  48. package/lib/Socket/business.d.ts +202 -0
  49. package/lib/Socket/business.js +382 -0
  50. package/lib/Socket/chats.d.ts +111 -0
  51. package/lib/Socket/chats.js +1155 -0
  52. package/lib/Socket/communities.d.ts +258 -0
  53. package/lib/Socket/communities.js +438 -0
  54. package/lib/Socket/community.js +333 -0
  55. package/lib/Socket/groups.d.ts +150 -0
  56. package/lib/Socket/groups.js +470 -0
  57. package/lib/Socket/index.d.ts +245 -0
  58. package/lib/Socket/index.js +13 -0
  59. package/lib/Socket/messages-recv.d.ts +187 -0
  60. package/lib/Socket/messages-recv.js +1708 -0
  61. package/lib/Socket/messages-send.d.ts +183 -0
  62. package/lib/Socket/messages-send.js +1692 -0
  63. package/lib/Socket/mex.d.ts +3 -0
  64. package/lib/Socket/mex.js +45 -0
  65. package/lib/Socket/newsletter.d.ts +160 -0
  66. package/lib/Socket/newsletter.js +293 -0
  67. package/lib/Socket/socket.d.ts +55 -0
  68. package/lib/Socket/socket.js +947 -0
  69. package/lib/Socket/usync.js +70 -0
  70. package/lib/Store/index.js +20 -0
  71. package/lib/Store/make-cache-manager-store.js +83 -0
  72. package/lib/Store/make-in-memory-store.js +398 -0
  73. package/lib/Store/make-ordered-dictionary.js +81 -0
  74. package/lib/Store/object-repository.js +27 -0
  75. package/lib/Types/Auth.d.ts +116 -0
  76. package/lib/Types/Auth.js +2 -0
  77. package/lib/Types/Bussines.d.ts +25 -0
  78. package/lib/Types/Bussines.js +2 -0
  79. package/lib/Types/Call.d.ts +15 -0
  80. package/lib/Types/Call.js +2 -0
  81. package/lib/Types/Chat.d.ts +123 -0
  82. package/lib/Types/Chat.js +10 -0
  83. package/lib/Types/Contact.d.ts +24 -0
  84. package/lib/Types/Contact.js +2 -0
  85. package/lib/Types/Events.d.ts +237 -0
  86. package/lib/Types/Events.js +3 -0
  87. package/lib/Types/GroupMetadata.d.ts +67 -0
  88. package/lib/Types/GroupMetadata.js +2 -0
  89. package/lib/Types/Label.d.ts +47 -0
  90. package/lib/Types/Label.js +25 -0
  91. package/lib/Types/LabelAssociation.d.ts +30 -0
  92. package/lib/Types/LabelAssociation.js +7 -0
  93. package/lib/Types/Message.d.ts +305 -0
  94. package/lib/Types/Message.js +11 -0
  95. package/lib/Types/MexUpdates.js +11 -0
  96. package/lib/Types/Newsletter.d.ts +135 -0
  97. package/lib/Types/Newsletter.js +43 -0
  98. package/lib/Types/Product.d.ts +79 -0
  99. package/lib/Types/Product.js +2 -0
  100. package/lib/Types/Signal.d.ts +76 -0
  101. package/lib/Types/Signal.js +3 -0
  102. package/lib/Types/Socket.d.ts +133 -0
  103. package/lib/Types/Socket.js +3 -0
  104. package/lib/Types/State.d.ts +39 -0
  105. package/lib/Types/State.js +14 -0
  106. package/lib/Types/USync.d.ts +26 -0
  107. package/lib/Types/USync.js +3 -0
  108. package/lib/Types/index.d.ts +65 -0
  109. package/lib/Types/index.js +42 -0
  110. package/lib/Utils/astrabail-event-stream.js +3 -0
  111. package/lib/Utils/audioToBuffer.js +31 -0
  112. package/lib/Utils/auth-utils.d.ts +19 -0
  113. package/lib/Utils/auth-utils.js +298 -0
  114. package/lib/Utils/baileys-event-stream.js +60 -0
  115. package/lib/Utils/bridge-runtime.d.ts +1 -0
  116. package/lib/Utils/bridge-runtime.js +14 -0
  117. package/lib/Utils/browser-utils.d.ts +4 -0
  118. package/lib/Utils/browser-utils.js +44 -0
  119. package/lib/Utils/business.d.ts +23 -0
  120. package/lib/Utils/business.js +240 -0
  121. package/lib/Utils/chat-utils.d.ts +70 -0
  122. package/lib/Utils/chat-utils.js +825 -0
  123. package/lib/Utils/crypto.d.ts +37 -0
  124. package/lib/Utils/crypto.js +168 -0
  125. package/lib/Utils/decode-wa-message.d.ts +48 -0
  126. package/lib/Utils/decode-wa-message.js +287 -0
  127. package/lib/Utils/event-buffer.d.ts +34 -0
  128. package/lib/Utils/event-buffer.js +580 -0
  129. package/lib/Utils/generics.d.ts +91 -0
  130. package/lib/Utils/generics.js +483 -0
  131. package/lib/Utils/history.d.ts +22 -0
  132. package/lib/Utils/history.js +137 -0
  133. package/lib/Utils/identity-change-handler.d.ts +37 -0
  134. package/lib/Utils/identity-change-handler.js +54 -0
  135. package/lib/Utils/index.d.ts +22 -0
  136. package/lib/Utils/index.js +48 -0
  137. package/lib/Utils/link-preview.d.ts +21 -0
  138. package/lib/Utils/link-preview.js +121 -0
  139. package/lib/Utils/logger.d.ts +13 -0
  140. package/lib/Utils/logger.js +7 -0
  141. package/lib/Utils/lt-hash.d.ts +8 -0
  142. package/lib/Utils/lt-hash.js +10 -0
  143. package/lib/Utils/make-mutex.d.ts +9 -0
  144. package/lib/Utils/make-mutex.js +37 -0
  145. package/lib/Utils/message-retry-manager.d.ts +110 -0
  146. package/lib/Utils/message-retry-manager.js +226 -0
  147. package/lib/Utils/messages-media.d.ts +130 -0
  148. package/lib/Utils/messages-media.js +887 -0
  149. package/lib/Utils/messages-newsletter.d.ts +84 -0
  150. package/lib/Utils/messages-newsletter.js +295 -0
  151. package/lib/Utils/messages.d.ts +92 -0
  152. package/lib/Utils/messages.js +1752 -0
  153. package/lib/Utils/noise-handler.d.ts +20 -0
  154. package/lib/Utils/noise-handler.js +204 -0
  155. package/lib/Utils/pre-key-manager.d.ts +28 -0
  156. package/lib/Utils/pre-key-manager.js +112 -0
  157. package/lib/Utils/process-message.d.ts +60 -0
  158. package/lib/Utils/process-message.js +536 -0
  159. package/lib/Utils/reporting-utils.d.ts +11 -0
  160. package/lib/Utils/reporting-utils.js +262 -0
  161. package/lib/Utils/resolve-jid.d.ts +43 -0
  162. package/lib/Utils/resolve-jid.js +95 -0
  163. package/lib/Utils/rust-bridge-shim.d.ts +22 -0
  164. package/lib/Utils/rust-bridge-shim.js +70 -0
  165. package/lib/Utils/serial-task-queue.js +29 -0
  166. package/lib/Utils/signal.d.ts +34 -0
  167. package/lib/Utils/signal.js +170 -0
  168. package/lib/Utils/streamToBuffer.js +17 -0
  169. package/lib/Utils/sync-action-utils.d.ts +19 -0
  170. package/lib/Utils/sync-action-utils.js +52 -0
  171. package/lib/Utils/tc-token-utils.d.ts +12 -0
  172. package/lib/Utils/tc-token-utils.js +20 -0
  173. package/lib/Utils/use-mongo-file-auth-state.js +71 -0
  174. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  175. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  176. package/lib/Utils/use-single-file-auth-state.js +73 -0
  177. package/lib/Utils/validate-connection.d.ts +11 -0
  178. package/lib/Utils/validate-connection.js +206 -0
  179. package/lib/WABinary/constants.d.ts +28 -0
  180. package/lib/WABinary/constants.js +1303 -0
  181. package/lib/WABinary/decode.d.ts +7 -0
  182. package/lib/WABinary/decode.js +300 -0
  183. package/lib/WABinary/encode.d.ts +3 -0
  184. package/lib/WABinary/encode.js +256 -0
  185. package/lib/WABinary/generic-utils.d.ts +15 -0
  186. package/lib/WABinary/generic-utils.js +138 -0
  187. package/lib/WABinary/index.d.ts +6 -0
  188. package/lib/WABinary/index.js +25 -0
  189. package/lib/WABinary/jid-utils.d.ts +48 -0
  190. package/lib/WABinary/jid-utils.js +115 -0
  191. package/lib/WABinary/types.d.ts +19 -0
  192. package/lib/WABinary/types.js +36 -0
  193. package/lib/WAM/BinaryInfo.d.ts +9 -0
  194. package/lib/WAM/BinaryInfo.js +13 -0
  195. package/lib/WAM/constants.d.ts +40 -0
  196. package/lib/WAM/constants.js +22855 -0
  197. package/lib/WAM/encode.d.ts +3 -0
  198. package/lib/WAM/encode.js +153 -0
  199. package/lib/WAM/index.d.ts +4 -0
  200. package/lib/WAM/index.js +19 -0
  201. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  202. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  203. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  204. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  205. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  206. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  207. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  208. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +41 -0
  209. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  210. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +54 -0
  211. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  212. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +32 -0
  213. package/lib/WAUSync/Protocols/index.d.ts +5 -0
  214. package/lib/WAUSync/Protocols/index.js +22 -0
  215. package/lib/WAUSync/USyncQuery.d.ts +29 -0
  216. package/lib/WAUSync/USyncQuery.js +97 -0
  217. package/lib/WAUSync/USyncUser.d.ts +13 -0
  218. package/lib/WAUSync/USyncUser.js +26 -0
  219. package/lib/WAUSync/index.d.ts +4 -0
  220. package/lib/WAUSync/index.js +19 -0
  221. package/lib/index.d.ts +12 -0
  222. package/lib/index.js +124 -0
  223. package/package.json +120 -0
  224. package/readme.md +1956 -0
@@ -0,0 +1,1155 @@
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
+ exports.makeChatsSocket = void 0;
7
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
8
+ const boom_1 = require("@hapi/boom");
9
+ const index_js_1 = require("../../WAProto/index.js");
10
+ const index_js_2 = require("../Defaults/index.js");
11
+ const index_js_3 = require("../Types/index.js");
12
+ const State_js_1 = require("../Types/State.js");
13
+ const index_js_4 = require("../Utils/index.js");
14
+ const make_mutex_js_1 = require("../Utils/make-mutex.js");
15
+ const process_message_js_1 = __importDefault(require("../Utils/process-message.js"));
16
+ const tc_token_utils_js_1 = require("../Utils/tc-token-utils.js");
17
+ const index_js_5 = require("../WABinary/index.js");
18
+ const index_js_6 = require("../WAUSync/index.js");
19
+ const socket_js_1 = require("./socket.js");
20
+ const MAX_SYNC_ATTEMPTS = 2;
21
+ const makeChatsSocket = (config) => {
22
+ const { logger, markOnlineOnConnect, fireInitQueries, appStateMacVerification, shouldIgnoreJid, shouldSyncHistoryMessage, getMessage } = config;
23
+ const sock = (0, socket_js_1.makeSocket)(config);
24
+ const { ev, ws, authState, generateMessageTag, sendNode, query, signalRepository, onUnexpectedError, sendUnifiedSession } = sock;
25
+ let privacySettings;
26
+ let syncState = State_js_1.SyncState.Connecting;
27
+ /** this mutex ensures that messages are processed in order */
28
+ const messageMutex = (0, make_mutex_js_1.makeMutex)();
29
+ /** this mutex ensures that receipts are processed in order */
30
+ const receiptMutex = (0, make_mutex_js_1.makeMutex)();
31
+ /** this mutex ensures that app state patches are processed in order */
32
+ const appStatePatchMutex = (0, make_mutex_js_1.makeMutex)();
33
+ /** this mutex ensures that notifications are processed in order */
34
+ const notificationMutex = (0, make_mutex_js_1.makeMutex)();
35
+ // Timeout for AwaitingInitialSync state
36
+ let awaitingSyncTimeout;
37
+ const placeholderResendCache = config.placeholderResendCache ||
38
+ new node_cache_1.default({
39
+ stdTTL: index_js_2.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
40
+ useClones: false
41
+ });
42
+ if (!config.placeholderResendCache) {
43
+ config.placeholderResendCache = placeholderResendCache;
44
+ }
45
+ /** helper function to fetch the given app state sync key */
46
+ const getAppStateSyncKey = async (keyId) => {
47
+ const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
48
+ return key;
49
+ };
50
+ const fetchPrivacySettings = async (force = false) => {
51
+ if (!privacySettings || force) {
52
+ const { content } = await query({
53
+ tag: 'iq',
54
+ attrs: {
55
+ xmlns: 'privacy',
56
+ to: index_js_5.S_WHATSAPP_NET,
57
+ type: 'get'
58
+ },
59
+ content: [{ tag: 'privacy', attrs: {} }]
60
+ });
61
+ privacySettings = (0, index_js_5.reduceBinaryNodeToDictionary)(content?.[0], 'category');
62
+ }
63
+ return privacySettings;
64
+ };
65
+ /** helper function to run a privacy IQ query */
66
+ const privacyQuery = async (name, value) => {
67
+ await query({
68
+ tag: 'iq',
69
+ attrs: {
70
+ xmlns: 'privacy',
71
+ to: index_js_5.S_WHATSAPP_NET,
72
+ type: 'set'
73
+ },
74
+ content: [
75
+ {
76
+ tag: 'privacy',
77
+ attrs: {},
78
+ content: [
79
+ {
80
+ tag: 'category',
81
+ attrs: { name, value }
82
+ }
83
+ ]
84
+ }
85
+ ]
86
+ });
87
+ };
88
+ const updateMessagesPrivacy = async (value) => {
89
+ await privacyQuery('messages', value);
90
+ };
91
+ const updateCallPrivacy = async (value) => {
92
+ await privacyQuery('calladd', value);
93
+ };
94
+ const updateLastSeenPrivacy = async (value) => {
95
+ await privacyQuery('last', value);
96
+ };
97
+ const updateOnlinePrivacy = async (value) => {
98
+ await privacyQuery('online', value);
99
+ };
100
+ const updateProfilePicturePrivacy = async (value) => {
101
+ await privacyQuery('profile', value);
102
+ };
103
+ const updateStatusPrivacy = async (value) => {
104
+ await privacyQuery('status', value);
105
+ };
106
+ const updateReadReceiptsPrivacy = async (value) => {
107
+ await privacyQuery('readreceipts', value);
108
+ };
109
+ const updateGroupsAddPrivacy = async (value) => {
110
+ await privacyQuery('groupadd', value);
111
+ };
112
+ const updateDefaultDisappearingMode = async (duration) => {
113
+ await query({
114
+ tag: 'iq',
115
+ attrs: {
116
+ xmlns: 'disappearing_mode',
117
+ to: index_js_5.S_WHATSAPP_NET,
118
+ type: 'set'
119
+ },
120
+ content: [
121
+ {
122
+ tag: 'disappearing_mode',
123
+ attrs: {
124
+ duration: duration.toString()
125
+ }
126
+ }
127
+ ]
128
+ });
129
+ };
130
+ const getBotListV2 = async () => {
131
+ const resp = await query({
132
+ tag: 'iq',
133
+ attrs: {
134
+ xmlns: 'bot',
135
+ to: index_js_5.S_WHATSAPP_NET,
136
+ type: 'get'
137
+ },
138
+ content: [
139
+ {
140
+ tag: 'bot',
141
+ attrs: {
142
+ v: '2'
143
+ }
144
+ }
145
+ ]
146
+ });
147
+ const botNode = (0, index_js_5.getBinaryNodeChild)(resp, 'bot');
148
+ const botList = [];
149
+ for (const section of (0, index_js_5.getBinaryNodeChildren)(botNode, 'section')) {
150
+ if (section.attrs.type === 'all') {
151
+ for (const bot of (0, index_js_5.getBinaryNodeChildren)(section, 'bot')) {
152
+ botList.push({
153
+ jid: bot.attrs.jid,
154
+ personaId: bot.attrs['persona_id']
155
+ });
156
+ }
157
+ }
158
+ }
159
+ return botList;
160
+ };
161
+ const getLidUser = async (jid) => {
162
+ if (!jid)
163
+ throw new boom_1.Boom('Please input a jid user');
164
+ if (!jid.endsWith('@s.whatsapp.net') && !jid.endsWith('@lid')) {
165
+ throw new boom_1.Boom('Invalid JID: Not a user JID!');
166
+ }
167
+ const targetJid = jid.includes('@') ? jid : `${jid}@s.whatsapp.net`;
168
+ const usyncQuery = new index_js_6.USyncQuery();
169
+ usyncQuery.protocols.push({
170
+ name: 'lid',
171
+ getQueryElement: () => ({ tag: 'lid', attrs: {}, content: undefined }),
172
+ getUserElement: () => null,
173
+ parser: (node) => node.attrs.val
174
+ });
175
+ usyncQuery.users.push({ id: targetJid });
176
+ const result = await sock.executeUSyncQuery(usyncQuery);
177
+ if (result)
178
+ return result.list;
179
+ };
180
+ const fetchStatus = async (...jids) => {
181
+ const usyncQuery = new index_js_6.USyncQuery().withStatusProtocol();
182
+ for (const jid of jids) {
183
+ usyncQuery.withUser(new index_js_6.USyncUser().withId(jid));
184
+ }
185
+ const result = await sock.executeUSyncQuery(usyncQuery);
186
+ if (result) {
187
+ return result.list;
188
+ }
189
+ };
190
+ const fetchDisappearingDuration = async (...jids) => {
191
+ const usyncQuery = new index_js_6.USyncQuery().withDisappearingModeProtocol();
192
+ for (const jid of jids) {
193
+ usyncQuery.withUser(new index_js_6.USyncUser().withId(jid));
194
+ }
195
+ const result = await sock.executeUSyncQuery(usyncQuery);
196
+ if (result) {
197
+ return result.list;
198
+ }
199
+ };
200
+ /** update the profile picture for yourself or a group */
201
+ const updateProfilePicture = async (jid, content, dimensions) => {
202
+ let targetJid;
203
+ if (!jid) {
204
+ 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');
205
+ }
206
+ if ((0, index_js_5.jidNormalizedUser)(jid) !== (0, index_js_5.jidNormalizedUser)(authState.creds.me.id)) {
207
+ targetJid = (0, index_js_5.jidNormalizedUser)(jid); // in case it is someone other than us
208
+ }
209
+ else {
210
+ targetJid = undefined;
211
+ }
212
+ const { img } = await (0, index_js_4.generateProfilePicture)(content, dimensions);
213
+ await query({
214
+ tag: 'iq',
215
+ attrs: {
216
+ to: index_js_5.S_WHATSAPP_NET,
217
+ type: 'set',
218
+ xmlns: 'w:profile:picture',
219
+ ...(targetJid ? { target: targetJid } : {})
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 ((0, index_js_5.jidNormalizedUser)(jid) !== (0, index_js_5.jidNormalizedUser)(authState.creds.me.id)) {
237
+ targetJid = (0, index_js_5.jidNormalizedUser)(jid); // in case it is someone other than us
238
+ }
239
+ else {
240
+ targetJid = undefined;
241
+ }
242
+ await query({
243
+ tag: 'iq',
244
+ attrs: {
245
+ to: index_js_5.S_WHATSAPP_NET,
246
+ type: 'set',
247
+ xmlns: 'w:profile:picture',
248
+ ...(targetJid ? { target: targetJid } : {})
249
+ }
250
+ });
251
+ };
252
+ /** update the profile status for yourself */
253
+ const updateProfileStatus = async (status) => {
254
+ await query({
255
+ tag: 'iq',
256
+ attrs: {
257
+ to: index_js_5.S_WHATSAPP_NET,
258
+ type: 'set',
259
+ xmlns: 'status'
260
+ },
261
+ content: [
262
+ {
263
+ tag: 'status',
264
+ attrs: {},
265
+ content: Buffer.from(status, 'utf-8')
266
+ }
267
+ ]
268
+ });
269
+ };
270
+ const updateProfileName = async (name) => {
271
+ await chatModify({ pushNameSetting: name }, '');
272
+ };
273
+ const fetchBlocklist = async () => {
274
+ const result = await query({
275
+ tag: 'iq',
276
+ attrs: {
277
+ xmlns: 'blocklist',
278
+ to: index_js_5.S_WHATSAPP_NET,
279
+ type: 'get'
280
+ }
281
+ });
282
+ const listNode = (0, index_js_5.getBinaryNodeChild)(result, 'list');
283
+ return (0, index_js_5.getBinaryNodeChildren)(listNode, 'item').map(n => n.attrs.jid);
284
+ };
285
+ const updateBlockStatus = async (jid, action) => {
286
+ jid = (0, index_js_5.jidNormalizedUser)(jid);
287
+ // Jika input adalah LID, resolve ke PN dulu
288
+ if (jid.endsWith('@lid')) {
289
+ try {
290
+ const pn = await signalRepository?.lidMapping?.getPNForLID?.(jid).catch(() => null);
291
+ if (pn)
292
+ jid = (0, index_js_5.jidNormalizedUser)(pn);
293
+ }
294
+ catch { }
295
+ }
296
+ const dhash = String(Date.now());
297
+ const itemAttrs = {
298
+ dhash,
299
+ action,
300
+ jid, // selalu PN
301
+ };
302
+ // Block: tambah pn_jid juga
303
+ if (action === 'block') {
304
+ itemAttrs.pn_jid = jid;
305
+ }
306
+ await query({
307
+ tag: 'iq',
308
+ attrs: {
309
+ xmlns: 'blocklist',
310
+ to: index_js_5.S_WHATSAPP_NET,
311
+ type: 'set'
312
+ },
313
+ content: [
314
+ {
315
+ tag: 'item',
316
+ attrs: itemAttrs
317
+ }
318
+ ]
319
+ });
320
+ };
321
+ const getBusinessProfile = async (jid) => {
322
+ const results = await query({
323
+ tag: 'iq',
324
+ attrs: {
325
+ to: 's.whatsapp.net',
326
+ xmlns: 'w:biz',
327
+ type: 'get'
328
+ },
329
+ content: [
330
+ {
331
+ tag: 'business_profile',
332
+ attrs: { v: '244' },
333
+ content: [
334
+ {
335
+ tag: 'profile',
336
+ attrs: { jid }
337
+ }
338
+ ]
339
+ }
340
+ ]
341
+ });
342
+ const profileNode = (0, index_js_5.getBinaryNodeChild)(results, 'business_profile');
343
+ const profiles = (0, index_js_5.getBinaryNodeChild)(profileNode, 'profile');
344
+ if (profiles) {
345
+ const address = (0, index_js_5.getBinaryNodeChild)(profiles, 'address');
346
+ const description = (0, index_js_5.getBinaryNodeChild)(profiles, 'description');
347
+ const website = (0, index_js_5.getBinaryNodeChild)(profiles, 'website');
348
+ const email = (0, index_js_5.getBinaryNodeChild)(profiles, 'email');
349
+ const category = (0, index_js_5.getBinaryNodeChild)((0, index_js_5.getBinaryNodeChild)(profiles, 'categories'), 'category');
350
+ const businessHours = (0, index_js_5.getBinaryNodeChild)(profiles, 'business_hours');
351
+ const businessHoursConfig = businessHours
352
+ ? (0, index_js_5.getBinaryNodeChildren)(businessHours, 'business_hours_config')
353
+ : undefined;
354
+ const websiteStr = website?.content?.toString();
355
+ return {
356
+ wid: profiles.attrs?.jid,
357
+ address: address?.content?.toString(),
358
+ description: description?.content?.toString() || '',
359
+ website: websiteStr ? [websiteStr] : [],
360
+ email: email?.content?.toString(),
361
+ category: category?.content?.toString(),
362
+ business_hours: {
363
+ timezone: businessHours?.attrs?.timezone,
364
+ business_config: businessHoursConfig?.map(({ attrs }) => attrs)
365
+ }
366
+ };
367
+ }
368
+ };
369
+ const cleanDirtyBits = async (type, fromTimestamp) => {
370
+ logger.info({ fromTimestamp }, 'clean dirty bits ' + type);
371
+ await sendNode({
372
+ tag: 'iq',
373
+ attrs: {
374
+ to: index_js_5.S_WHATSAPP_NET,
375
+ type: 'set',
376
+ xmlns: 'urn:xmpp:whatsapp:dirty',
377
+ id: generateMessageTag()
378
+ },
379
+ content: [
380
+ {
381
+ tag: 'clean',
382
+ attrs: {
383
+ type,
384
+ ...(fromTimestamp ? { timestamp: fromTimestamp.toString() } : null)
385
+ }
386
+ }
387
+ ]
388
+ });
389
+ };
390
+ const newAppStateChunkHandler = (isInitialSync) => {
391
+ return {
392
+ onMutation(mutation) {
393
+ (0, index_js_4.processSyncAction)(mutation, ev, authState.creds.me, isInitialSync ? { accountSettings: authState.creds.accountSettings } : undefined, logger);
394
+ }
395
+ };
396
+ };
397
+ const resyncAppState = ev.createBufferedFunction(async (collections, isInitialSync) => {
398
+ const appStateSyncKeyCache = new Map();
399
+ const getCachedAppStateSyncKey = async (keyId) => {
400
+ if (appStateSyncKeyCache.has(keyId)) {
401
+ return appStateSyncKeyCache.get(keyId) ?? undefined;
402
+ }
403
+ const key = await getAppStateSyncKey(keyId);
404
+ appStateSyncKeyCache.set(keyId, key ?? null);
405
+ return key;
406
+ };
407
+ // we use this to determine which events to fire
408
+ // otherwise when we resync from scratch -- all notifications will fire
409
+ const initialVersionMap = {};
410
+ const globalMutationMap = {};
411
+ await authState.keys.transaction(async () => {
412
+ const collectionsToHandle = new Set(collections);
413
+ // in case something goes wrong -- ensure we don't enter a loop that cannot be exited from
414
+ const attemptsMap = {};
415
+ // keep executing till all collections are done
416
+ // sometimes a single patch request will not return all the patches (God knows why)
417
+ // so we fetch till they're all done (this is determined by the "has_more_patches" flag)
418
+ while (collectionsToHandle.size) {
419
+ const states = {};
420
+ const nodes = [];
421
+ for (const name of collectionsToHandle) {
422
+ const result = await authState.keys.get('app-state-sync-version', [name]);
423
+ let state = result[name];
424
+ if (state) {
425
+ if (typeof initialVersionMap[name] === 'undefined') {
426
+ initialVersionMap[name] = state.version;
427
+ }
428
+ }
429
+ else {
430
+ state = (0, index_js_4.newLTHashState)();
431
+ }
432
+ states[name] = state;
433
+ logger.info(`resyncing ${name} from v${state.version}`);
434
+ nodes.push({
435
+ tag: 'collection',
436
+ attrs: {
437
+ name,
438
+ version: state.version.toString(),
439
+ // return snapshot if being synced from scratch
440
+ return_snapshot: (!state.version).toString()
441
+ }
442
+ });
443
+ }
444
+ const result = await query({
445
+ tag: 'iq',
446
+ attrs: {
447
+ to: index_js_5.S_WHATSAPP_NET,
448
+ xmlns: 'w:sync:app:state',
449
+ type: 'set'
450
+ },
451
+ content: [
452
+ {
453
+ tag: 'sync',
454
+ attrs: {},
455
+ content: nodes
456
+ }
457
+ ]
458
+ });
459
+ // extract from binary node
460
+ const decoded = await (0, index_js_4.extractSyncdPatches)(result, config?.options);
461
+ for (const key in decoded) {
462
+ const name = key;
463
+ const { patches, hasMorePatches, snapshot } = decoded[name];
464
+ try {
465
+ if (snapshot) {
466
+ const { state: newState, mutationMap } = await (0, index_js_4.decodeSyncdSnapshot)(name, snapshot, getCachedAppStateSyncKey, initialVersionMap[name], appStateMacVerification.snapshot);
467
+ states[name] = newState;
468
+ Object.assign(globalMutationMap, mutationMap);
469
+ logger.info(`restored state of ${name} from snapshot to v${newState.version} with mutations`);
470
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
471
+ }
472
+ // only process if there are syncd patches
473
+ if (patches.length) {
474
+ const { state: newState, mutationMap } = await (0, index_js_4.decodePatches)(name, patches, states[name], getCachedAppStateSyncKey, config.options, initialVersionMap[name], logger, appStateMacVerification.patch);
475
+ await authState.keys.set({ 'app-state-sync-version': { [name]: newState } });
476
+ logger.info(`synced ${name} to v${newState.version}`);
477
+ initialVersionMap[name] = newState.version;
478
+ Object.assign(globalMutationMap, mutationMap);
479
+ }
480
+ if (hasMorePatches) {
481
+ logger.info(`${name} has more patches...`);
482
+ }
483
+ else {
484
+ // collection is done with sync
485
+ collectionsToHandle.delete(name);
486
+ }
487
+ }
488
+ catch (error) {
489
+ // if retry attempts overshoot
490
+ // or key not found
491
+ const isIrrecoverableError = attemptsMap[name] >= MAX_SYNC_ATTEMPTS ||
492
+ error.output?.statusCode === 404 ||
493
+ error.name === 'TypeError';
494
+ logger.info({ name, error: error.stack }, `failed to sync state from version${isIrrecoverableError ? '' : ', removing and trying from scratch'}`);
495
+ await authState.keys.set({ 'app-state-sync-version': { [name]: null } });
496
+ // increment number of retries
497
+ attemptsMap[name] = (attemptsMap[name] || 0) + 1;
498
+ if (isIrrecoverableError) {
499
+ // stop retrying
500
+ collectionsToHandle.delete(name);
501
+ }
502
+ }
503
+ }
504
+ }
505
+ }, authState?.creds?.me?.id || 'resync-app-state');
506
+ const { onMutation } = newAppStateChunkHandler(isInitialSync);
507
+ for (const key in globalMutationMap) {
508
+ onMutation(globalMutationMap[key]);
509
+ }
510
+ });
511
+ /**
512
+ * fetch the profile picture of a user/group
513
+ * type = "preview" for a low res picture
514
+ * type = "image for the high res picture"
515
+ */
516
+ const profilePictureUrl = async (jid, type = 'preview', timeoutMs) => {
517
+ const baseContent = [{ tag: 'picture', attrs: { type, query: 'url' } }];
518
+ const tcTokenContent = await (0, tc_token_utils_js_1.buildTcTokenFromJid)({ authState, jid, baseContent });
519
+ jid = (0, index_js_5.jidNormalizedUser)(jid);
520
+ const result = await query({
521
+ tag: 'iq',
522
+ attrs: {
523
+ target: jid,
524
+ to: index_js_5.S_WHATSAPP_NET,
525
+ type: 'get',
526
+ xmlns: 'w:profile:picture'
527
+ },
528
+ content: tcTokenContent
529
+ }, timeoutMs);
530
+ const child = (0, index_js_5.getBinaryNodeChild)(result, 'picture');
531
+ return child?.attrs?.url;
532
+ };
533
+ const createCallLink = async (type, event, timeoutMs) => {
534
+ const result = await query({
535
+ tag: 'call',
536
+ attrs: {
537
+ id: generateMessageTag(),
538
+ to: '@call'
539
+ },
540
+ content: [
541
+ {
542
+ tag: 'link_create',
543
+ attrs: { media: type },
544
+ content: event ? [{ tag: 'event', attrs: { start_time: String(event.startTime) } }] : undefined
545
+ }
546
+ ]
547
+ }, timeoutMs);
548
+ const child = (0, index_js_5.getBinaryNodeChild)(result, 'link_create');
549
+ return child?.attrs?.token;
550
+ };
551
+ const sendPresenceUpdate = async (type, toJid) => {
552
+ const me = authState.creds.me;
553
+ const isAvailableType = type === 'available';
554
+ if (isAvailableType || type === 'unavailable') {
555
+ if (!me.name) {
556
+ logger.warn('no name present, ignoring presence update request...');
557
+ return;
558
+ }
559
+ ev.emit('connection.update', { isOnline: isAvailableType });
560
+ if (isAvailableType) {
561
+ void sendUnifiedSession();
562
+ }
563
+ await sendNode({
564
+ tag: 'presence',
565
+ attrs: {
566
+ name: me.name.replace(/@/g, ''),
567
+ type
568
+ }
569
+ });
570
+ }
571
+ else {
572
+ const { server } = (0, index_js_5.jidDecode)(toJid);
573
+ const isLid = server === 'lid';
574
+ await sendNode({
575
+ tag: 'chatstate',
576
+ attrs: {
577
+ from: isLid ? me.lid : me.id,
578
+ to: toJid
579
+ },
580
+ content: [
581
+ {
582
+ tag: type === 'recording' ? 'composing' : type,
583
+ attrs: type === 'recording' ? { media: 'audio' } : {}
584
+ }
585
+ ]
586
+ });
587
+ }
588
+ };
589
+ /**
590
+ * @param toJid the jid to subscribe to
591
+ * @param tcToken token for subscription, use if present
592
+ */
593
+ const presenceSubscribe = async (toJid) => {
594
+ const tcTokenContent = await (0, tc_token_utils_js_1.buildTcTokenFromJid)({ authState, jid: toJid });
595
+ return sendNode({
596
+ tag: 'presence',
597
+ attrs: {
598
+ to: toJid,
599
+ id: generateMessageTag(),
600
+ type: 'subscribe'
601
+ },
602
+ content: tcTokenContent
603
+ });
604
+ };
605
+ const handlePresenceUpdate = ({ tag, attrs, content }) => {
606
+ let presence;
607
+ const jid = attrs.from;
608
+ const participant = attrs.participant || attrs.from;
609
+ if (shouldIgnoreJid(jid) && jid !== index_js_5.S_WHATSAPP_NET) {
610
+ return;
611
+ }
612
+ if (tag === 'presence') {
613
+ presence = {
614
+ lastKnownPresence: attrs.type === 'unavailable' ? 'unavailable' : 'available',
615
+ lastSeen: attrs.last && attrs.last !== 'deny' ? +attrs.last : undefined
616
+ };
617
+ }
618
+ else if (Array.isArray(content)) {
619
+ const [firstChild] = content;
620
+ let type = firstChild.tag;
621
+ if (type === 'paused') {
622
+ type = 'available';
623
+ }
624
+ if (firstChild.attrs?.media === 'audio') {
625
+ type = 'recording';
626
+ }
627
+ presence = { lastKnownPresence: type };
628
+ }
629
+ else {
630
+ logger.error({ tag, attrs, content }, 'recv invalid presence node');
631
+ }
632
+ if (presence) {
633
+ ev.emit('presence.update', { id: jid, presences: { [participant]: presence } });
634
+ }
635
+ };
636
+ const appPatch = async (patchCreate) => {
637
+ const name = patchCreate.type;
638
+ const myAppStateKeyId = authState.creds.myAppStateKeyId;
639
+ if (!myAppStateKeyId) {
640
+ throw new boom_1.Boom('App state key not present!', { statusCode: 400 });
641
+ }
642
+ let initial;
643
+ let encodeResult;
644
+ await appStatePatchMutex.mutex(async () => {
645
+ await authState.keys.transaction(async () => {
646
+ logger.debug({ patch: patchCreate }, 'applying app patch');
647
+ await resyncAppState([name], false);
648
+ const { [name]: currentSyncVersion } = await authState.keys.get('app-state-sync-version', [name]);
649
+ initial = currentSyncVersion || (0, index_js_4.newLTHashState)();
650
+ encodeResult = await (0, index_js_4.encodeSyncdPatch)(patchCreate, myAppStateKeyId, initial, getAppStateSyncKey);
651
+ const { patch, state } = encodeResult;
652
+ const node = {
653
+ tag: 'iq',
654
+ attrs: {
655
+ to: index_js_5.S_WHATSAPP_NET,
656
+ type: 'set',
657
+ xmlns: 'w:sync:app:state'
658
+ },
659
+ content: [
660
+ {
661
+ tag: 'sync',
662
+ attrs: {},
663
+ content: [
664
+ {
665
+ tag: 'collection',
666
+ attrs: {
667
+ name,
668
+ version: (state.version - 1).toString(),
669
+ return_snapshot: 'false'
670
+ },
671
+ content: [
672
+ {
673
+ tag: 'patch',
674
+ attrs: {},
675
+ content: index_js_1.proto.SyncdPatch.encode(patch).finish()
676
+ }
677
+ ]
678
+ }
679
+ ]
680
+ }
681
+ ]
682
+ };
683
+ await query(node);
684
+ await authState.keys.set({ 'app-state-sync-version': { [name]: state } });
685
+ }, authState?.creds?.me?.id || 'app-patch');
686
+ });
687
+ if (config.emitOwnEvents) {
688
+ const { onMutation } = newAppStateChunkHandler(false);
689
+ const { mutationMap } = await (0, index_js_4.decodePatches)(name, [{ ...encodeResult.patch, version: { version: encodeResult.state.version } }], initial, getAppStateSyncKey, config.options, undefined, logger);
690
+ for (const key in mutationMap) {
691
+ onMutation(mutationMap[key]);
692
+ }
693
+ }
694
+ };
695
+ /** sending non-abt props may fix QR scan fail if server expects */
696
+ const fetchProps = async () => {
697
+ //TODO: implement both protocol 1 and protocol 2 prop fetching, specially for abKey for WM
698
+ const resultNode = await query({
699
+ tag: 'iq',
700
+ attrs: {
701
+ to: index_js_5.S_WHATSAPP_NET,
702
+ xmlns: 'w',
703
+ type: 'get'
704
+ },
705
+ content: [
706
+ {
707
+ tag: 'props',
708
+ attrs: {
709
+ protocol: '2',
710
+ hash: authState?.creds?.lastPropHash || ''
711
+ }
712
+ }
713
+ ]
714
+ });
715
+ const propsNode = (0, index_js_5.getBinaryNodeChild)(resultNode, 'props');
716
+ let props = {};
717
+ if (propsNode) {
718
+ if (propsNode.attrs?.hash) {
719
+ // on some clients, the hash is returning as undefined
720
+ authState.creds.lastPropHash = propsNode?.attrs?.hash;
721
+ ev.emit('creds.update', authState.creds);
722
+ }
723
+ props = (0, index_js_5.reduceBinaryNodeToDictionary)(propsNode, 'prop');
724
+ }
725
+ logger.debug('fetched props');
726
+ return props;
727
+ };
728
+ /**
729
+ * modify a chat -- mark unread, read etc.
730
+ * lastMessages must be sorted in reverse chronologically
731
+ * requires the last messages till the last message received; required for archive & unread
732
+ */
733
+ const chatModify = (mod, jid) => {
734
+ const patch = (0, index_js_4.chatModificationToAppPatch)(mod, jid);
735
+ return appPatch(patch);
736
+ };
737
+ /**
738
+ * Enable/Disable link preview privacy, not related to baileys link preview generation
739
+ */
740
+ const updateDisableLinkPreviewsPrivacy = (isPreviewsDisabled) => {
741
+ return chatModify({
742
+ disableLinkPreviews: { isPreviewsDisabled }
743
+ }, '');
744
+ };
745
+ /**
746
+ * Star or Unstar a message
747
+ */
748
+ const star = (jid, messages, star) => {
749
+ return chatModify({
750
+ star: {
751
+ messages,
752
+ star
753
+ }
754
+ }, jid);
755
+ };
756
+ /**
757
+ * Add or Edit Contact
758
+ */
759
+ const addOrEditContact = (jid, contact) => {
760
+ return chatModify({
761
+ contact
762
+ }, jid);
763
+ };
764
+ /**
765
+ * Remove Contact
766
+ */
767
+ const removeContact = (jid) => {
768
+ return chatModify({
769
+ contact: null
770
+ }, jid);
771
+ };
772
+ /**
773
+ * Adds label
774
+ */
775
+ const addLabel = (jid, labels) => {
776
+ return chatModify({
777
+ addLabel: {
778
+ ...labels
779
+ }
780
+ }, jid);
781
+ };
782
+ /**
783
+ * Adds label for the chats
784
+ */
785
+ const addChatLabel = (jid, labelId) => {
786
+ return chatModify({
787
+ addChatLabel: {
788
+ labelId
789
+ }
790
+ }, jid);
791
+ };
792
+ /**
793
+ * Removes label for the chat
794
+ */
795
+ const removeChatLabel = (jid, labelId) => {
796
+ return chatModify({
797
+ removeChatLabel: {
798
+ labelId
799
+ }
800
+ }, jid);
801
+ };
802
+ /**
803
+ * Adds label for the message
804
+ */
805
+ const addMessageLabel = (jid, messageId, labelId) => {
806
+ return chatModify({
807
+ addMessageLabel: {
808
+ messageId,
809
+ labelId
810
+ }
811
+ }, jid);
812
+ };
813
+ /**
814
+ * Removes label for the message
815
+ */
816
+ const removeMessageLabel = (jid, messageId, labelId) => {
817
+ return chatModify({
818
+ removeMessageLabel: {
819
+ messageId,
820
+ labelId
821
+ }
822
+ }, jid);
823
+ };
824
+ /**
825
+ * Add or Edit Quick Reply
826
+ */
827
+ const addOrEditQuickReply = (quickReply) => {
828
+ return chatModify({
829
+ quickReply
830
+ }, '');
831
+ };
832
+ /**
833
+ * Remove Quick Reply
834
+ */
835
+ const removeQuickReply = (timestamp) => {
836
+ return chatModify({
837
+ quickReply: { timestamp, deleted: true }
838
+ }, '');
839
+ };
840
+ /**
841
+ * queries need to be fired on connection open
842
+ * help ensure parity with WA Web
843
+ * */
844
+ const executeInitQueries = async () => {
845
+ await Promise.all([fetchProps(), fetchBlocklist(), fetchPrivacySettings()]);
846
+ };
847
+ const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
848
+ // ── Auto-inject isAdmin, isBotAdmin, metadata ─────────────────────────
849
+ try {
850
+ const remoteJid = msg.key?.remoteJid || '';
851
+ const isGroup = remoteJid.endsWith('@g.us');
852
+ if (isGroup) {
853
+ const _normalizeJid = (jid) => {
854
+ if (!jid)
855
+ return null;
856
+ try {
857
+ return (0, index_js_5.jidNormalizedUser)(jid).split('@')[0];
858
+ }
859
+ catch {
860
+ return String(jid).split('@')[0];
861
+ }
862
+ };
863
+ // Fetch metadata (pakai cache jika tersedia)
864
+ let meta = null;
865
+ try {
866
+ meta = await sock.groupMetadata(remoteJid);
867
+ }
868
+ catch { }
869
+ if (meta && Array.isArray(meta.participants)) {
870
+ msg.metadata = meta;
871
+ const botJid = authState.creds?.me?.id;
872
+ const senderJid = msg.key.fromMe
873
+ ? authState.creds?.me?.id
874
+ : (msg.key.participant || remoteJid);
875
+ const senderNorm = _normalizeJid(senderJid);
876
+ const botNorm = _normalizeJid(botJid);
877
+ // isAdmin
878
+ msg.isAdmin = meta.participants.some(p => {
879
+ const pid = _normalizeJid(p.jid || p.id || p.lid);
880
+ return pid === senderNorm && (p.admin === 'admin' || p.admin === 'superadmin');
881
+ });
882
+ // isBotAdmin: via m.isBotAdmin jika sudah di-set
883
+ let isBotAdmin = typeof msg.isBotAdmin === 'boolean' ? msg.isBotAdmin : false;
884
+ // fallback via owner
885
+ if (!isBotAdmin) {
886
+ const owners = [meta.owner, meta.subjectOwner, meta.ownerPn]
887
+ .filter(Boolean).map(_normalizeJid);
888
+ if (owners.includes(botNorm))
889
+ isBotAdmin = true;
890
+ }
891
+ // fallback via participants
892
+ if (!isBotAdmin) {
893
+ isBotAdmin = meta.participants.some(p => {
894
+ const pid = _normalizeJid(p.jid || p.id || p.lid);
895
+ return pid === botNorm && (p.admin === 'admin' || p.admin === 'superadmin');
896
+ });
897
+ }
898
+ msg.isBotAdmin = isBotAdmin;
899
+ }
900
+ else {
901
+ msg.metadata = {};
902
+ msg.isAdmin = false;
903
+ msg.isBotAdmin = false;
904
+ }
905
+ }
906
+ else {
907
+ msg.metadata = {};
908
+ msg.isAdmin = false;
909
+ msg.isBotAdmin = false;
910
+ }
911
+ }
912
+ catch { }
913
+ // ─────────────────────────────────────────────────────────────────────
914
+ ev.emit('messages.upsert', { messages: [msg], type });
915
+ if (!!msg.pushName) {
916
+ let jid = msg.key.fromMe ? authState.creds.me.id : msg.key.participant || msg.key.remoteJid;
917
+ jid = (0, index_js_5.jidNormalizedUser)(jid);
918
+ if (!msg.key.fromMe) {
919
+ ev.emit('contacts.update', [{ id: jid, notify: msg.pushName, verifiedName: msg.verifiedBizName }]);
920
+ }
921
+ // update our pushname too
922
+ if (msg.key.fromMe && msg.pushName && authState.creds.me?.name !== msg.pushName) {
923
+ ev.emit('creds.update', { me: { ...authState.creds.me, name: msg.pushName } });
924
+ }
925
+ }
926
+ const historyMsg = (0, index_js_4.getHistoryMsg)(msg.message);
927
+ const shouldProcessHistoryMsg = historyMsg
928
+ ? shouldSyncHistoryMessage(historyMsg) &&
929
+ index_js_2.PROCESSABLE_HISTORY_TYPES.includes(historyMsg.syncType)
930
+ : false;
931
+ // State machine: decide on sync and flush
932
+ if (historyMsg && syncState === State_js_1.SyncState.AwaitingInitialSync) {
933
+ if (awaitingSyncTimeout) {
934
+ clearTimeout(awaitingSyncTimeout);
935
+ awaitingSyncTimeout = undefined;
936
+ }
937
+ if (shouldProcessHistoryMsg) {
938
+ syncState = State_js_1.SyncState.Syncing;
939
+ logger.info('Transitioned to Syncing state');
940
+ // Let doAppStateSync handle the final flush after it's done
941
+ }
942
+ else {
943
+ syncState = State_js_1.SyncState.Online;
944
+ logger.info('History sync skipped, transitioning to Online state and flushing buffer');
945
+ ev.flush();
946
+ }
947
+ }
948
+ const doAppStateSync = async () => {
949
+ if (syncState === State_js_1.SyncState.Syncing) {
950
+ logger.info('Doing app state sync');
951
+ await resyncAppState(index_js_3.ALL_WA_PATCH_NAMES, true);
952
+ // Sync is complete, go online and flush everything
953
+ syncState = State_js_1.SyncState.Online;
954
+ logger.info('App state sync complete, transitioning to Online state and flushing buffer');
955
+ ev.flush();
956
+ const accountSyncCounter = (authState.creds.accountSyncCounter || 0) + 1;
957
+ ev.emit('creds.update', { accountSyncCounter });
958
+ }
959
+ };
960
+ await Promise.all([
961
+ (async () => {
962
+ if (shouldProcessHistoryMsg) {
963
+ await doAppStateSync();
964
+ }
965
+ })(),
966
+ (0, process_message_js_1.default)(msg, {
967
+ signalRepository,
968
+ shouldProcessHistoryMsg,
969
+ placeholderResendCache,
970
+ ev,
971
+ creds: authState.creds,
972
+ keyStore: authState.keys,
973
+ logger,
974
+ options: config.options,
975
+ getMessage
976
+ })
977
+ ]);
978
+ // If the app state key arrives and we are waiting to sync, trigger the sync now.
979
+ if (msg.message?.protocolMessage?.appStateSyncKeyShare && syncState === State_js_1.SyncState.Syncing) {
980
+ logger.info('App state sync key arrived, triggering app state sync');
981
+ await doAppStateSync();
982
+ }
983
+ });
984
+ ws.on('CB:presence', handlePresenceUpdate);
985
+ ws.on('CB:chatstate', handlePresenceUpdate);
986
+ ws.on('CB:ib,,dirty', async (node) => {
987
+ const { attrs } = (0, index_js_5.getBinaryNodeChild)(node, 'dirty');
988
+ const type = attrs.type;
989
+ switch (type) {
990
+ case 'account_sync':
991
+ if (attrs.timestamp) {
992
+ let { lastAccountSyncTimestamp } = authState.creds;
993
+ if (lastAccountSyncTimestamp) {
994
+ await cleanDirtyBits('account_sync', lastAccountSyncTimestamp);
995
+ }
996
+ lastAccountSyncTimestamp = +attrs.timestamp;
997
+ ev.emit('creds.update', { lastAccountSyncTimestamp });
998
+ }
999
+ break;
1000
+ case 'groups':
1001
+ // handled in groups.ts
1002
+ break;
1003
+ default:
1004
+ logger.info({ node }, 'received unknown sync');
1005
+ break;
1006
+ }
1007
+ });
1008
+ ev.on('connection.update', ({ connection, receivedPendingNotifications }) => {
1009
+ if (connection === 'open') {
1010
+ if (fireInitQueries) {
1011
+ executeInitQueries().catch(error => onUnexpectedError(error, 'init queries'));
1012
+ }
1013
+ sendPresenceUpdate(markOnlineOnConnect ? 'available' : 'unavailable').catch(error => onUnexpectedError(error, 'presence update requests'));
1014
+ }
1015
+ if (!receivedPendingNotifications || syncState !== State_js_1.SyncState.Connecting) {
1016
+ return;
1017
+ }
1018
+ syncState = State_js_1.SyncState.AwaitingInitialSync;
1019
+ logger.info('Connection is now AwaitingInitialSync, buffering events');
1020
+ ev.buffer();
1021
+ const willSyncHistory = shouldSyncHistoryMessage(index_js_1.proto.Message.HistorySyncNotification.create({
1022
+ syncType: index_js_1.proto.HistorySync.HistorySyncType.RECENT
1023
+ }));
1024
+ if (!willSyncHistory) {
1025
+ logger.info('History sync is disabled by config, not waiting for notification. Transitioning to Online.');
1026
+ syncState = State_js_1.SyncState.Online;
1027
+ setTimeout(() => ev.flush(), 0);
1028
+ return;
1029
+ }
1030
+ logger.info('History sync is enabled, awaiting notification with a 20s timeout.');
1031
+ if (awaitingSyncTimeout) {
1032
+ clearTimeout(awaitingSyncTimeout);
1033
+ }
1034
+ awaitingSyncTimeout = setTimeout(() => {
1035
+ if (syncState === State_js_1.SyncState.AwaitingInitialSync) {
1036
+ // TODO: investigate
1037
+ logger.warn('Timeout in AwaitingInitialSync, forcing state to Online and flushing buffer');
1038
+ syncState = State_js_1.SyncState.Online;
1039
+ ev.flush();
1040
+ }
1041
+ }, 20000);
1042
+ });
1043
+ ev.on('lid-mapping.update', async ({ lid, pn }) => {
1044
+ try {
1045
+ await signalRepository.lidMapping.storeLIDPNMappings([{ lid, pn }]);
1046
+ }
1047
+ catch (error) {
1048
+ logger.warn({ lid, pn, error }, 'Failed to store LID-PN mapping');
1049
+ }
1050
+ });
1051
+ ev.on('groups.upsert', async (groups) => {
1052
+ try {
1053
+ const mappings = [];
1054
+ for (const group of groups) {
1055
+ for (const p of group.participants || []) {
1056
+ const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
1057
+ const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
1058
+ ? p.phoneNumber
1059
+ : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
1060
+ if (lidJid && pnJid) {
1061
+ mappings.push({ lid: lidJid, pn: pnJid });
1062
+ }
1063
+ }
1064
+ }
1065
+ if (mappings.length > 0) {
1066
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
1067
+ logger.debug({ count: mappings.length }, 'groups.upsert: stored LID-PN mappings from participants');
1068
+ }
1069
+ }
1070
+ catch (error) {
1071
+ logger.warn({ error }, 'groups.upsert: failed to store LID-PN mappings');
1072
+ }
1073
+ });
1074
+ ev.on('groups.update', async (updates) => {
1075
+ try {
1076
+ const mappings = [];
1077
+ for (const update of updates) {
1078
+ for (const p of update.participants || []) {
1079
+ const lidJid = p.id?.endsWith('@lid') ? p.id : p.lid;
1080
+ const pnJid = p.phoneNumber?.endsWith('@s.whatsapp.net')
1081
+ ? p.phoneNumber
1082
+ : p.id?.endsWith('@s.whatsapp.net') ? p.id : undefined;
1083
+ if (lidJid && pnJid) {
1084
+ mappings.push({ lid: lidJid, pn: pnJid });
1085
+ }
1086
+ }
1087
+ }
1088
+ if (mappings.length > 0) {
1089
+ await signalRepository.lidMapping.storeLIDPNMappings(mappings);
1090
+ logger.debug({ count: mappings.length }, 'groups.update: stored LID-PN mappings from participants');
1091
+ }
1092
+ }
1093
+ catch (error) {
1094
+ logger.warn({ error }, 'groups.update: failed to store LID-PN mappings');
1095
+ }
1096
+ });
1097
+ return {
1098
+ ...sock,
1099
+ createCallLink,
1100
+ getBotListV2,
1101
+ messageMutex,
1102
+ receiptMutex,
1103
+ appStatePatchMutex,
1104
+ notificationMutex,
1105
+ fetchPrivacySettings,
1106
+ upsertMessage,
1107
+ appPatch,
1108
+ sendPresenceUpdate,
1109
+ presenceSubscribe,
1110
+ profilePictureUrl,
1111
+ fetchBlocklist,
1112
+ fetchStatus,
1113
+ fetchDisappearingDuration,
1114
+ updateProfilePicture,
1115
+ removeProfilePicture,
1116
+ updateProfileStatus,
1117
+ updateProfileName,
1118
+ updateBlockStatus,
1119
+ updateDisableLinkPreviewsPrivacy,
1120
+ updateCallPrivacy,
1121
+ updateMessagesPrivacy,
1122
+ updateLastSeenPrivacy,
1123
+ updateOnlinePrivacy,
1124
+ updateProfilePicturePrivacy,
1125
+ updateStatusPrivacy,
1126
+ updateReadReceiptsPrivacy,
1127
+ updateGroupsAddPrivacy,
1128
+ updateDefaultDisappearingMode,
1129
+ getBusinessProfile,
1130
+ resyncAppState,
1131
+ chatModify,
1132
+ cleanDirtyBits,
1133
+ addOrEditContact,
1134
+ removeContact,
1135
+ addLabel,
1136
+ addChatLabel,
1137
+ removeChatLabel,
1138
+ addMessageLabel,
1139
+ removeMessageLabel,
1140
+ star,
1141
+ addOrEditQuickReply,
1142
+ removeQuickReply,
1143
+ clearMessage: (jid, key, timeStamp) => {
1144
+ return chatModify({
1145
+ delete: true,
1146
+ lastMessages: [{
1147
+ key: key,
1148
+ messageTimestamp: timeStamp
1149
+ }]
1150
+ }, jid);
1151
+ },
1152
+ getLidUser
1153
+ };
1154
+ };
1155
+ exports.makeChatsSocket = makeChatsSocket;