@yannajah/baileys 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/LICENSE +23 -0
  2. package/LICENSE.jexkcode +21 -0
  3. package/README.md +41 -2
  4. package/THIRD_PARTY_NOTICES.md +15 -0
  5. package/WAProto/index.d.ts +16922 -0
  6. package/WAProto/index.js +122451 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/baileys-version.json +3 -0
  9. package/lib/Defaults/index.js +156 -0
  10. package/lib/Defaults/phonenumber-mcc.json +223 -0
  11. package/lib/Signal/Group/ciphertext-message.js +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +64 -0
  13. package/lib/Signal/Group/group_cipher.js +96 -0
  14. package/lib/Signal/Group/index.js +57 -0
  15. package/lib/Signal/Group/keyhelper.js +55 -0
  16. package/lib/Signal/Group/queue-job.js +57 -0
  17. package/lib/Signal/Group/sender-chain-key.js +34 -0
  18. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  19. package/lib/Signal/Group/sender-key-message.js +69 -0
  20. package/lib/Signal/Group/sender-key-name.js +51 -0
  21. package/lib/Signal/Group/sender-key-record.js +53 -0
  22. package/lib/Signal/Group/sender-key-state.js +99 -0
  23. package/lib/Signal/Group/sender-message-key.js +29 -0
  24. package/lib/Signal/libsignal.js +174 -0
  25. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  26. package/lib/Socket/Client/index.js +19 -0
  27. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  28. package/lib/Socket/Client/web-socket-client.js +87 -0
  29. package/lib/Socket/business.js +260 -0
  30. package/lib/Socket/chats.js +1002 -0
  31. package/lib/Socket/clutch-handler.d.ts +27 -0
  32. package/lib/Socket/clutch-handler.js +880 -0
  33. package/lib/Socket/groups.js +317 -0
  34. package/lib/Socket/index.js +97 -0
  35. package/lib/Socket/messages-recv.js +1154 -0
  36. package/lib/Socket/messages-send.js +946 -0
  37. package/lib/Socket/newsletter.js +411 -0
  38. package/lib/Socket/registration.js +166 -0
  39. package/lib/Socket/socket.js +688 -0
  40. package/lib/Socket/usync.js +70 -0
  41. package/lib/Store/index.js +10 -0
  42. package/lib/Store/make-cache-manager-store.js +83 -0
  43. package/lib/Store/make-in-memory-store.js +457 -0
  44. package/lib/Store/make-ordered-dictionary.js +81 -0
  45. package/lib/Store/object-repository.js +27 -0
  46. package/lib/Types/Auth.js +2 -0
  47. package/lib/Types/Call.js +2 -0
  48. package/lib/Types/Chat.js +4 -0
  49. package/lib/Types/Contact.js +2 -0
  50. package/lib/Types/Events.js +2 -0
  51. package/lib/Types/GroupMetadata.js +2 -0
  52. package/lib/Types/Label.js +27 -0
  53. package/lib/Types/LabelAssociation.js +9 -0
  54. package/lib/Types/Message.js +10 -0
  55. package/lib/Types/Mex.d.ts +2 -0
  56. package/lib/Types/Mex.js +98 -0
  57. package/lib/Types/Newsletter.js +41 -0
  58. package/lib/Types/Product.js +2 -0
  59. package/lib/Types/Signal.js +2 -0
  60. package/lib/Types/Socket.js +2 -0
  61. package/lib/Types/State.js +2 -0
  62. package/lib/Types/USync.js +2 -0
  63. package/lib/Types/index.js +43 -0
  64. package/lib/Utils/MessageBuilder.d.ts +215 -0
  65. package/lib/Utils/MessageBuilder.js +4001 -0
  66. package/lib/Utils/a2ui.d.ts +202 -0
  67. package/lib/Utils/a2ui.js +770 -0
  68. package/lib/Utils/auth-utils.js +206 -0
  69. package/lib/Utils/baileys-event-stream.js +63 -0
  70. package/lib/Utils/bot-signature.d.ts +22 -0
  71. package/lib/Utils/bot-signature.js +125 -0
  72. package/lib/Utils/business.js +234 -0
  73. package/lib/Utils/channel-manager.d.ts +39 -0
  74. package/lib/Utils/channel-manager.js +312 -0
  75. package/lib/Utils/chat-utils.js +729 -0
  76. package/lib/Utils/crypto.js +151 -0
  77. package/lib/Utils/decode-wa-message.js +198 -0
  78. package/lib/Utils/event-buffer.js +514 -0
  79. package/lib/Utils/extras.d.ts +449 -0
  80. package/lib/Utils/extras.js +1377 -0
  81. package/lib/Utils/generics.js +574 -0
  82. package/lib/Utils/history.js +96 -0
  83. package/lib/Utils/html-app.d.ts +39 -0
  84. package/lib/Utils/html-app.js +307 -0
  85. package/lib/Utils/index.d.ts +23 -0
  86. package/lib/Utils/index.js +51 -0
  87. package/lib/Utils/link-preview.js +93 -0
  88. package/lib/Utils/logger.js +7 -0
  89. package/lib/Utils/lt-hash.js +51 -0
  90. package/lib/Utils/make-mutex.js +43 -0
  91. package/lib/Utils/message-retry-manager.d.ts +42 -0
  92. package/lib/Utils/message-retry-manager.js +309 -0
  93. package/lib/Utils/messages-media.js +861 -0
  94. package/lib/Utils/messages.js +1085 -0
  95. package/lib/Utils/metaai.d.ts +438 -0
  96. package/lib/Utils/metaai.js +911 -0
  97. package/lib/Utils/mini-app.d.ts +93 -0
  98. package/lib/Utils/mini-app.js +453 -0
  99. package/lib/Utils/modern-messages.d.ts +150 -0
  100. package/lib/Utils/modern-messages.js +498 -0
  101. package/lib/Utils/native-flow.d.ts +14 -0
  102. package/lib/Utils/native-flow.js +122 -0
  103. package/lib/Utils/newsletter-status.d.ts +163 -0
  104. package/lib/Utils/newsletter-status.js +695 -0
  105. package/lib/Utils/noise-handler.js +155 -0
  106. package/lib/Utils/payment-messages.d.ts +59 -0
  107. package/lib/Utils/payment-messages.js +164 -0
  108. package/lib/Utils/process-message.js +334 -0
  109. package/lib/Utils/reporting-utils.d.ts +12 -0
  110. package/lib/Utils/reporting-utils.js +271 -0
  111. package/lib/Utils/scheduled-message.d.ts +82 -0
  112. package/lib/Utils/scheduled-message.js +126 -0
  113. package/lib/Utils/signal.js +153 -0
  114. package/lib/Utils/spr.d.ts +26 -0
  115. package/lib/Utils/spr.js +525 -0
  116. package/lib/Utils/status-stickers.d.ts +78 -0
  117. package/lib/Utils/status-stickers.js +275 -0
  118. package/lib/Utils/telegram-adapter.d.ts +28 -0
  119. package/lib/Utils/telegram-adapter.js +285 -0
  120. package/lib/Utils/use-multi-file-auth-state.js +153 -0
  121. package/lib/Utils/validate-connection.js +235 -0
  122. package/lib/WABinary/constants.js +40 -0
  123. package/lib/WABinary/decode.js +252 -0
  124. package/lib/WABinary/encode.js +265 -0
  125. package/lib/WABinary/generic-utils.js +178 -0
  126. package/lib/WABinary/index.js +21 -0
  127. package/lib/WABinary/jid-utils.js +81 -0
  128. package/lib/WABinary/types.js +2 -0
  129. package/lib/WAM/BinaryInfo.js +13 -0
  130. package/lib/WAM/constants.js +15350 -0
  131. package/lib/WAM/encode.js +155 -0
  132. package/lib/WAM/index.js +19 -0
  133. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  134. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  135. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  136. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  137. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  138. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  139. package/lib/WAUSync/Protocols/index.js +20 -0
  140. package/lib/WAUSync/USyncQuery.js +89 -0
  141. package/lib/WAUSync/USyncUser.js +26 -0
  142. package/lib/WAUSync/index.js +19 -0
  143. package/lib/index.d.ts +20 -0
  144. package/lib/index.js +99 -0
  145. package/package.json +110 -4
@@ -0,0 +1,880 @@
1
+ const WAProto = require('../../WAProto').proto;
2
+ const crypto = require('crypto');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const Utils_1 = require("../Utils");
6
+ const WABinary_1 = require("../WABinary");
7
+
8
+ class ClutchHandler {
9
+ constructor(utils, waUploadToServer, relayMessageFn, config, sock) {
10
+ this.utils = utils;
11
+ this.relayMessage = relayMessageFn;
12
+ this.waUploadToServer = waUploadToServer;
13
+ this.config = config;
14
+ this.sock = sock;
15
+
16
+ this.bail = {
17
+ generateWAMessageContent: this.utils.generateWAMessageContent || Utils_1.generateWAMessageContent,
18
+ generateMessageID: Utils_1.generateMessageID,
19
+ getContentType: (msg) => Object.keys(msg.message || {})[0]
20
+ };
21
+
22
+ this.contactCache = new Map();
23
+ const cachePath = path.join(process.cwd(), 'contacts-cache.json');
24
+ try {
25
+ if (fs.existsSync(cachePath)) {
26
+ const data = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
27
+ for (const [key, val] of Object.entries(data)) {
28
+ this.contactCache.set(key, val);
29
+ }
30
+ }
31
+ } catch (err) {
32
+ console.error('[ClutchHandler] Failed to load contact cache:', err);
33
+ }
34
+
35
+ this.saveTimeout = null;
36
+ this.saveCache = () => {
37
+ if (this.saveTimeout) clearTimeout(this.saveTimeout);
38
+ this.saveTimeout = setTimeout(() => {
39
+ try {
40
+ const obj = {};
41
+ for (const [key, val] of this.contactCache.entries()) {
42
+ obj[key] = val;
43
+ }
44
+ // fs.writeFileSync(cachePath, JSON.stringify(obj, null, 2));
45
+ } catch (err) {
46
+ console.error('[ClutchHandler] Failed to save contact cache:', err);
47
+ }
48
+ }, 3000);
49
+ };
50
+
51
+ if (this.sock && this.sock.ev) {
52
+ this.sock.ev.on('contacts.upsert', (contacts) => {
53
+ let changed = false;
54
+ for (const contact of contacts) {
55
+ if (contact.id) {
56
+ this.contactCache.set(contact.id, contact);
57
+ changed = true;
58
+ }
59
+ }
60
+ if (changed) this.saveCache();
61
+ });
62
+ this.sock.ev.on('contacts.update', (updates) => {
63
+ let changed = false;
64
+ for (const update of updates) {
65
+ if (update.id) {
66
+ const current = this.contactCache.get(update.id) || {};
67
+ this.contactCache.set(update.id, { ...current, ...update });
68
+ changed = true;
69
+ }
70
+ }
71
+ if (changed) this.saveCache();
72
+ });
73
+ this.sock.ev.on('messaging-history.set', ({ contacts }) => {
74
+ if (contacts) {
75
+ let changed = false;
76
+ for (const contact of contacts) {
77
+ if (contact.id) {
78
+ this.contactCache.set(contact.id, contact);
79
+ changed = true;
80
+ }
81
+ }
82
+ if (changed) this.saveCache();
83
+ }
84
+ });
85
+ this.sock.ev.on('messages.upsert', ({ messages }) => {
86
+ let changed = false;
87
+ for (const msg of messages) {
88
+ if (msg.pushName) {
89
+ const jid = WABinary_1.jidNormalizedUser(msg.key.fromMe ? (this.sock.authState?.creds?.me?.id || '') : (msg.key.participant || msg.key.remoteJid));
90
+ if (jid) {
91
+ const current = this.contactCache.get(jid) || {};
92
+ this.contactCache.set(jid, {
93
+ ...current,
94
+ id: jid,
95
+ notify: msg.pushName,
96
+ name: current.name || msg.pushName
97
+ });
98
+ changed = true;
99
+ }
100
+ }
101
+ }
102
+ if (changed) this.saveCache();
103
+ });
104
+ }
105
+ }
106
+
107
+ detectType(content) {
108
+ if (!content || typeof content !== 'object') return null;
109
+ if (content.requestPaymentMessage) return 'PAYMENT';
110
+ if (content.productMessage) return 'PRODUCT';
111
+ if (content.interactiveMessage || content.carouselMessage || content.cards) return 'INTERACTIVE';
112
+ if (content.buttonsMessage) return 'BUTTONS';
113
+ if (content.albumMessage) return 'ALBUM';
114
+ if (content.eventMessage) return 'EVENT';
115
+ if (content.pollResultMessage) return 'POLL_RESULT';
116
+ if (content.groupStatusMessage) return 'GROUP_STORY';
117
+ if (content.flowMessage) return 'FLOW';
118
+ return null;
119
+ }
120
+
121
+ async getName(jid) {
122
+ if (!jid) return 'Unknown';
123
+ const normalizedJid = WABinary_1.jidNormalizedUser(jid);
124
+
125
+ // 1. Cek jika JID kita sendiri
126
+ const myJid = this.sock.authState?.creds?.me?.id ? WABinary_1.jidNormalizedUser(this.sock.authState.creds.me.id) : null;
127
+ if (myJid && normalizedJid === myJid) {
128
+ return this.sock.authState.creds.me.name || "Saya";
129
+ }
130
+
131
+ // 2. Cek cache lokal ClutchHandler
132
+ const cached = this.contactCache.get(normalizedJid);
133
+ if (cached) {
134
+ const name = cached.name || cached.verifiedName || cached.notify;
135
+ if (name) return name;
136
+ }
137
+
138
+ // 3. Cek jika itu JID grup
139
+ if (WABinary_1.isJidGroup(normalizedJid)) {
140
+ try {
141
+ const groupMetadata = await this.sock.groupMetadata(normalizedJid);
142
+ if (groupMetadata && groupMetadata.subject) {
143
+ const current = this.contactCache.get(normalizedJid) || {};
144
+ if (current.name !== groupMetadata.subject) {
145
+ this.contactCache.set(normalizedJid, {
146
+ ...current,
147
+ id: normalizedJid,
148
+ name: groupMetadata.subject,
149
+ notify: groupMetadata.subject
150
+ });
151
+ this.saveCache();
152
+ }
153
+ return groupMetadata.subject;
154
+ }
155
+ } catch (err) {
156
+ // Silently ignore
157
+ }
158
+ }
159
+
160
+ // 4. Fallback ke nomor telepon saja
161
+ return normalizedJid.split('@')[0];
162
+ }
163
+
164
+ async handlePayment(content, quoted) {
165
+ const data = content.requestPaymentMessage;
166
+ let notes = {};
167
+
168
+ try {
169
+ if (data.sticker?.stickerMessage) {
170
+ notes = {
171
+ stickerMessage: {
172
+ ...data.sticker.stickerMessage,
173
+ contextInfo: {
174
+ stanzaId: quoted?.key?.id,
175
+ participant: quoted?.key?.participant || content.sender,
176
+ quotedMessage: quoted?.message
177
+ }
178
+ }
179
+ };
180
+ } else if (data.note) {
181
+ notes = {
182
+ extendedTextMessage: {
183
+ text: data.note,
184
+ contextInfo: {
185
+ stanzaId: quoted?.key?.id,
186
+ participant: quoted?.key?.participant || content.sender,
187
+ quotedMessage: quoted?.message
188
+ }
189
+ }
190
+ };
191
+ }
192
+ } catch (err) {
193
+ if (this.config.logger) {
194
+ this.config.logger.error(`Error handling notes in payment: ${err}`);
195
+ }
196
+ }
197
+
198
+ return {
199
+ requestPaymentMessage: WAProto.Message.RequestPaymentMessage.fromObject({
200
+ expiryTimestamp: data.expiry || 0,
201
+ amount1000: data.amount || 0,
202
+ currencyCodeIso4217: data.currency || "IDR",
203
+ requestFrom: data.from || "0@s.whatsapp.net",
204
+ noteMessage: notes,
205
+ background: data.background ?? {
206
+ id: "DEFAULT",
207
+ placeholderArgb: 0xFFF0F0F0
208
+ }
209
+ })
210
+ };
211
+ }
212
+
213
+ async handleProduct(content, jid, quoted) {
214
+ const {
215
+ title,
216
+ description,
217
+ thumbnail,
218
+ productId,
219
+ retailerId,
220
+ url,
221
+ body = "",
222
+ footer = "",
223
+ buttons = [],
224
+ priceAmount1000 = null,
225
+ currencyCode = "IDR",
226
+ businessOwnerJid = "0@s.whatsapp.net"
227
+ } = content.productMessage;
228
+
229
+ let productImage;
230
+
231
+ try {
232
+ if (Buffer.isBuffer(thumbnail)) {
233
+ const { imageMessage } = await this.utils.generateWAMessageContent(
234
+ { image: thumbnail },
235
+ { upload: this.waUploadToServer }
236
+ );
237
+ productImage = imageMessage;
238
+ } else if (typeof thumbnail === 'object' && thumbnail.url) {
239
+ const { imageMessage } = await this.utils.generateWAMessageContent(
240
+ { image: { url: thumbnail.url }},
241
+ { upload: this.waUploadToServer }
242
+ );
243
+ productImage = imageMessage;
244
+ }
245
+ } catch (err) {
246
+ if (this.config.logger) {
247
+ this.config.logger.error(`Error preparing product image: ${err}`);
248
+ }
249
+ }
250
+
251
+ return {
252
+ viewOnceMessage: {
253
+ message: {
254
+ interactiveMessage: {
255
+ body: { text: body },
256
+ footer: { text: footer },
257
+ header: {
258
+ title,
259
+ hasMediaAttachment: true,
260
+ productMessage: {
261
+ product: {
262
+ productImage,
263
+ productId,
264
+ title,
265
+ description,
266
+ currencyCode,
267
+ priceAmount1000,
268
+ retailerId,
269
+ url,
270
+ productImageCount: 1
271
+ },
272
+ businessOwnerJid
273
+ }
274
+ },
275
+ nativeFlowMessage: { buttons }
276
+ }
277
+ }
278
+ }
279
+ };
280
+ }
281
+
282
+ async handleInteractive(content, jid, quoted) {
283
+ if (content.interactiveMessage?.carouselMessage) {
284
+ return content;
285
+ }
286
+ if (content.carouselMessage) {
287
+ return {
288
+ interactiveMessage: {
289
+ header: content.header || { hasMediaAttachment: false },
290
+ body: content.body || { text: content.text || content.caption || "" },
291
+ footer: content.footer || { text: "" },
292
+ contextInfo: content.contextInfo || {},
293
+ carouselMessage: content.carouselMessage
294
+ }
295
+ };
296
+ }
297
+ if (Array.isArray(content.cards)) {
298
+ return {
299
+ interactiveMessage: {
300
+ header: { hasMediaAttachment: false },
301
+ body: { text: content.text || content.caption || "" },
302
+ footer: { text: content.footer || "" },
303
+ contextInfo: content.contextInfo || {},
304
+ carouselMessage: {
305
+ cards: content.cards
306
+ }
307
+ }
308
+ };
309
+ }
310
+
311
+ const iMsg = content.interactiveMessage || content;
312
+ const {
313
+ title,
314
+ footer,
315
+ thumbnail,
316
+ image,
317
+ video,
318
+ document,
319
+ mimetype,
320
+ fileName,
321
+ jpegThumbnail,
322
+ contextInfo,
323
+ externalAdReply,
324
+ buttons = [],
325
+ nativeFlowMessage,
326
+ carouselMessage,
327
+ header
328
+ } = iMsg;
329
+
330
+ let media = null;
331
+ let mediaType = null;
332
+
333
+ try {
334
+ if (thumbnail) {
335
+ media = await this.utils.prepareWAMessageMedia(
336
+ { image: { url: thumbnail } },
337
+ { upload: this.waUploadToServer }
338
+ );
339
+ mediaType = 'image';
340
+ } else if (image) {
341
+ if (typeof image === 'object' && image.url) {
342
+ media = await this.utils.prepareWAMessageMedia(
343
+ { image: { url: image.url } },
344
+ { upload: this.waUploadToServer }
345
+ );
346
+ } else {
347
+ media = await this.utils.prepareWAMessageMedia(
348
+ { image: image },
349
+ { upload: this.waUploadToServer }
350
+ );
351
+ }
352
+ mediaType = 'image';
353
+ } else if (video) {
354
+ if (typeof video === 'object' && video.url) {
355
+ media = await this.utils.prepareWAMessageMedia(
356
+ { video: { url: video.url } },
357
+ { upload: this.waUploadToServer }
358
+ );
359
+ } else {
360
+ media = await this.utils.prepareWAMessageMedia(
361
+ { video: video },
362
+ { upload: this.waUploadToServer }
363
+ );
364
+ }
365
+ mediaType = 'video';
366
+ } else if (document) {
367
+ let documentPayload = {
368
+ document: document
369
+ };
370
+ if (jpegThumbnail) {
371
+ if (typeof jpegThumbnail === 'object' && jpegThumbnail.url) {
372
+ documentPayload.jpegThumbnail = { url: jpegThumbnail.url };
373
+ } else {
374
+ documentPayload.jpegThumbnail = jpegThumbnail;
375
+ }
376
+ }
377
+
378
+ media = await this.utils.prepareWAMessageMedia(
379
+ documentPayload,
380
+ { upload: this.waUploadToServer }
381
+ );
382
+ if (fileName) {
383
+ media.documentMessage.fileName = fileName;
384
+ }
385
+ if (mimetype) {
386
+ media.documentMessage.mimetype = mimetype;
387
+ }
388
+ mediaType = 'document';
389
+ }
390
+ } catch (err) {
391
+ if (this.config.logger) {
392
+ this.config.logger.error(`Error preparing interactive media: ${err}`);
393
+ }
394
+ }
395
+
396
+ let interactiveMessage = {
397
+ body: { text: title || iMsg.text || "" },
398
+ footer: { text: footer || "" }
399
+ };
400
+ if (carouselMessage) {
401
+ interactiveMessage.carouselMessage = carouselMessage;
402
+ } else if (buttons && buttons.length > 0) {
403
+ interactiveMessage.nativeFlowMessage = {
404
+ buttons: buttons
405
+ };
406
+ if (nativeFlowMessage) {
407
+ interactiveMessage.nativeFlowMessage = {
408
+ ...interactiveMessage.nativeFlowMessage,
409
+ ...nativeFlowMessage
410
+ };
411
+ }
412
+ } else if (nativeFlowMessage) {
413
+ interactiveMessage.nativeFlowMessage = nativeFlowMessage;
414
+ }
415
+
416
+ if (media) {
417
+ interactiveMessage.header = {
418
+ title: header || "",
419
+ hasMediaAttachment: true,
420
+ ...media
421
+ };
422
+ } else {
423
+ interactiveMessage.header = {
424
+ title: header || "",
425
+ hasMediaAttachment: false
426
+ };
427
+ }
428
+
429
+ let finalContextInfo = {};
430
+ if (contextInfo) {
431
+ finalContextInfo = {
432
+ mentionedJid: contextInfo.mentionedJid || [],
433
+ forwardingScore: contextInfo.forwardingScore || 0,
434
+ isForwarded: contextInfo.isForwarded || false,
435
+ ...contextInfo
436
+ };
437
+ }
438
+
439
+ if (externalAdReply) {
440
+ finalContextInfo.externalAdReply = {
441
+ title: externalAdReply.title || "",
442
+ body: externalAdReply.body || "",
443
+ mediaType: externalAdReply.mediaType || 1,
444
+ thumbnailUrl: externalAdReply.thumbnailUrl || "",
445
+ mediaUrl: externalAdReply.mediaUrl || "",
446
+ sourceUrl: externalAdReply.sourceUrl || "",
447
+ showAdAttribution: externalAdReply.showAdAttribution || false,
448
+ renderLargerThumbnail: externalAdReply.renderLargerThumbnail || false,
449
+ ...externalAdReply
450
+ };
451
+ }
452
+
453
+ if (Object.keys(finalContextInfo).length > 0) {
454
+ interactiveMessage.contextInfo = finalContextInfo;
455
+ }
456
+ return {
457
+ interactiveMessage: interactiveMessage
458
+ };
459
+ }
460
+
461
+ async handleAlbum(content, jid, quoted) {
462
+ const array = content.albumMessage;
463
+ const albumOptions = content.albumOptions || {};
464
+ const album = await this.utils.generateWAMessageFromContent(jid, {
465
+ messageContextInfo: {
466
+ messageSecret: crypto.randomBytes(32),
467
+ },
468
+ albumMessage: {
469
+ expectedImageCount: array.filter((a) => a.hasOwnProperty("image")).length,
470
+ expectedVideoCount: array.filter((a) => a.hasOwnProperty("video")).length,
471
+ },
472
+ }, {
473
+ userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
474
+ quoted,
475
+ upload: this.waUploadToServer
476
+ });
477
+
478
+ await this.relayMessage(jid, album.message, {
479
+ messageId: album.key.id,
480
+ });
481
+
482
+ for (let content of array) {
483
+ const img = await this.utils.generateWAMessage(jid, content, {
484
+ upload: this.waUploadToServer,
485
+ });
486
+
487
+ img.message.messageContextInfo = {
488
+ messageSecret: crypto.randomBytes(32),
489
+ messageAssociation: {
490
+ associationType: 1,
491
+ parentMessageKey: album.key,
492
+ },
493
+ participant: "0@s.whatsapp.net",
494
+ remoteJid: "status@broadcast",
495
+ forwardingScore: 99999,
496
+ isForwarded: true,
497
+ mentionedJid: [jid],
498
+ starred: true,
499
+ labels: ["Y", "Important"],
500
+ isHighlighted: true,
501
+ businessMessageForwardInfo: {
502
+ businessOwnerJid: jid,
503
+ },
504
+ dataSharingContext: {
505
+ showMmDisclosure: true,
506
+ },
507
+ };
508
+
509
+ if (albumOptions.newsletterJid) {
510
+ img.message.forwardedNewsletterMessageInfo = {
511
+ newsletterJid: albumOptions.newsletterJid,
512
+ serverMessageId: albumOptions.serverMessageId || 1,
513
+ newsletterName: albumOptions.newsletterName || `WhatsApp`,
514
+ contentType: albumOptions.contentType || 1,
515
+ timestamp: new Date().toISOString(),
516
+ senderName: albumOptions.senderName || "Who know",
517
+ content: albumOptions.content || "Text Message",
518
+ priority: "high",
519
+ status: "sent",
520
+ };
521
+ }
522
+
523
+ img.message.disappearingMode = {
524
+ initiator: 3,
525
+ trigger: 4,
526
+ initiatorDeviceJid: jid,
527
+ initiatedByExternalService: true,
528
+ initiatedByUserDevice: true,
529
+ initiatedBySystem: true,
530
+ initiatedByServer: true,
531
+ initiatedByAdmin: true,
532
+ initiatedByUser: true,
533
+ initiatedByApp: true,
534
+ initiatedByBot: true,
535
+ initiatedByMe: true,
536
+ };
537
+
538
+ await this.relayMessage(jid, img.message, {
539
+ messageId: img.key.id,
540
+ quoted: {
541
+ key: {
542
+ remoteJid: album.key.remoteJid,
543
+ id: album.key.id,
544
+ fromMe: true,
545
+ participant: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
546
+ },
547
+ message: album.message,
548
+ },
549
+ });
550
+ }
551
+ return album;
552
+ }
553
+
554
+ async handleEvent(content, jid, quoted) {
555
+ const eventData = content.eventMessage;
556
+
557
+ const msg = await this.utils.generateWAMessageFromContent(jid, {
558
+ viewOnceMessage: {
559
+ message: {
560
+ messageContextInfo: {
561
+ deviceListMetadata: {},
562
+ deviceListMetadataVersion: 2,
563
+ messageSecret: crypto.randomBytes(32),
564
+ supportPayload: JSON.stringify({
565
+ version: 2,
566
+ is_ai_message: true,
567
+ should_show_system_message: true,
568
+ ticket_id: crypto.randomBytes(16).toString('hex')
569
+ })
570
+ },
571
+ eventMessage: {
572
+ contextInfo: {
573
+ mentionedJid: [jid],
574
+ participant: jid,
575
+ remoteJid: "status@broadcast",
576
+ forwardedNewsletterMessageInfo: eventData.newsletterJid ? {
577
+ newsletterName: eventData.newsletterName || "WhatsApp",
578
+ newsletterJid: eventData.newsletterJid,
579
+ serverMessageId: eventData.serverMessageId || 1
580
+ } : undefined
581
+ },
582
+ isCanceled: eventData.isCanceled || false,
583
+ name: eventData.name,
584
+ description: eventData.description,
585
+ location: eventData.location || {
586
+ degreesLatitude: 0,
587
+ degreesLongitude: 0,
588
+ name: "Location"
589
+ },
590
+ joinLink: eventData.joinLink || '',
591
+ startTime: typeof eventData.startTime === 'string' ? parseInt(eventData.startTime) : eventData.startTime || Date.now(),
592
+ endTime: typeof eventData.endTime === 'string' ? parseInt(eventData.endTime) : eventData.endTime || Date.now() + 3600000,
593
+ extraGuestsAllowed: eventData.extraGuestsAllowed !== false
594
+ }
595
+ }
596
+ }
597
+ }, { quoted });
598
+
599
+ await this.relayMessage(jid, msg.message, {
600
+ messageId: msg.key.id
601
+ });
602
+ return msg;
603
+ }
604
+
605
+ async handlePollResult(content, jid, quoted) {
606
+ const pollData = content.pollResultMessage;
607
+
608
+ const msg = await this.utils.generateWAMessageFromContent(jid, {
609
+ pollResultSnapshotMessage: {
610
+ name: pollData.name,
611
+ pollVotes: pollData.pollVotes.map(vote => ({
612
+ optionName: vote.optionName,
613
+ optionVoteCount: typeof vote.optionVoteCount === 'number'
614
+ ? vote.optionVoteCount.toString()
615
+ : vote.optionVoteCount
616
+ }))
617
+ }
618
+ }, {
619
+ userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
620
+ quoted
621
+ });
622
+
623
+ await this.relayMessage(jid, msg.message, {
624
+ messageId: msg.key.id
625
+ });
626
+
627
+ return msg;
628
+ }
629
+
630
+ async handleGroupStory(content, jid, quoted) {
631
+ const storyData = content.groupStatusMessage;
632
+ let waMsgContent;
633
+
634
+ if (storyData.message) {
635
+ waMsgContent = storyData;
636
+ } else {
637
+ if (typeof this.bail?.generateWAMessageContent === "function") {
638
+ waMsgContent = await this.bail.generateWAMessageContent(storyData, {
639
+ upload: this.waUploadToServer
640
+ });
641
+ } else if (typeof this.utils?.generateWAMessageContent === "function") {
642
+ waMsgContent = await this.utils.generateWAMessageContent(storyData, {
643
+ upload: this.waUploadToServer
644
+ });
645
+ } else if (typeof this.utils?.prepareMessageContent === "function") {
646
+ waMsgContent = await this.utils.prepareMessageContent(storyData, {
647
+ upload: this.waUploadToServer
648
+ });
649
+ } else {
650
+ waMsgContent = await Utils_1.generateWAMessageContent(storyData, {
651
+ upload: this.waUploadToServer
652
+ });
653
+ }
654
+ }
655
+
656
+ let msg = {
657
+ message: {
658
+ groupStatusMessageV2: {
659
+ message: waMsgContent.message || waMsgContent
660
+ }
661
+ }
662
+ };
663
+
664
+ return await this.relayMessage(jid, msg.message, {
665
+ messageId: this.bail.generateMessageID()
666
+ });
667
+ }
668
+
669
+ async handleFlow(content, jid, quoted) {
670
+ const {
671
+ title,
672
+ body,
673
+ footer,
674
+ flowId,
675
+ flowToken = crypto.randomBytes(16).toString('hex'),
676
+ buttonText = "Open Flow",
677
+ screen = "UNION",
678
+ params = {},
679
+ contextInfo
680
+ } = content.flowMessage;
681
+
682
+ const buttonParamsJson = JSON.stringify({
683
+ flow_token: flowToken,
684
+ flow_id: flowId,
685
+ flow_cta: buttonText,
686
+ flow_action: "navigate",
687
+ flow_action_payload: {
688
+ screen: screen,
689
+ data: params
690
+ }
691
+ });
692
+
693
+ let interactiveMessage = {
694
+ body: { text: body || "" },
695
+ footer: { text: footer || "" },
696
+ header: {
697
+ title: title || "",
698
+ hasMediaAttachment: false
699
+ },
700
+ nativeFlowMessage: {
701
+ buttons: [
702
+ {
703
+ name: "flow",
704
+ buttonParamsJson: buttonParamsJson
705
+ }
706
+ ]
707
+ }
708
+ };
709
+
710
+ if (contextInfo) {
711
+ interactiveMessage.contextInfo = contextInfo;
712
+ }
713
+
714
+ return {
715
+ interactiveMessage: interactiveMessage
716
+ };
717
+ }
718
+
719
+ async sendStatusWhatsApp(content, jids = []) {
720
+ const userJid = WABinary_1.jidNormalizedUser(this.sock.authState.creds.me.id);
721
+ let allUsers = new Set();
722
+ allUsers.add(userJid);
723
+
724
+ for (const id of jids) {
725
+ const isGroup = WABinary_1.isJidGroup(id);
726
+ const isPrivate = WABinary_1.isJidUser(id);
727
+
728
+ if (isGroup) {
729
+ try {
730
+ const metadata = await this.sock.groupMetadata(id);
731
+ const participants = metadata.participants.map(p => WABinary_1.jidNormalizedUser(p.id));
732
+ participants.forEach(jid => allUsers.add(jid));
733
+ } catch (error) {
734
+ if (this.config.logger) {
735
+ this.config.logger.error(`Error getting metadata for group ${id}: ${error}`);
736
+ }
737
+ }
738
+ } else if (isPrivate) {
739
+ allUsers.add(WABinary_1.jidNormalizedUser(id));
740
+ }
741
+ }
742
+
743
+ const uniqueUsers = Array.from(allUsers);
744
+ const getRandomHexColor = () => "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0");
745
+
746
+ const isMedia = content.image || content.video || content.audio;
747
+ const isAudio = !!content.audio;
748
+
749
+ const messageContent = { ...content };
750
+
751
+ if (isMedia && !isAudio) {
752
+ if (messageContent.text) {
753
+ messageContent.caption = messageContent.text;
754
+ delete messageContent.text;
755
+ }
756
+ delete messageContent.ptt;
757
+ delete messageContent.font;
758
+ delete messageContent.backgroundColor;
759
+ delete messageContent.textColor;
760
+ }
761
+
762
+ if (isAudio) {
763
+ delete messageContent.text;
764
+ delete messageContent.caption;
765
+ delete messageContent.font;
766
+ delete messageContent.textColor;
767
+ }
768
+
769
+ const font = !isMedia ? (content.font || Math.floor(Math.random() * 9)) : undefined;
770
+ const textColor = !isMedia ? (content.textColor || getRandomHexColor()) : undefined;
771
+ const backgroundColor = (!isMedia || isAudio) ? (content.backgroundColor || getRandomHexColor()) : undefined;
772
+ const ptt = isAudio ? (typeof content.ptt === 'boolean' ? content.ptt : true) : undefined;
773
+
774
+ let msg;
775
+ let mediaHandle;
776
+
777
+ try {
778
+ const link_preview_1 = require("../Utils/link-preview");
779
+
780
+ msg = await Utils_1.generateWAMessage(WABinary_1.STORIES_JID, messageContent, {
781
+ logger: this.config.logger,
782
+ userJid,
783
+ getUrlInfo: text => link_preview_1.getUrlInfo(text, {
784
+ thumbnailWidth: this.config.linkPreviewImageThumbnailWidth,
785
+ fetchOpts: { timeout: 3000, ...this.config.options || {} },
786
+ logger: this.config.logger,
787
+ uploadImage: this.config.generateHighQualityLinkPreview ? this.waUploadToServer : undefined
788
+ }),
789
+ upload: async (encFilePath, opts) => {
790
+ const up = await this.waUploadToServer(encFilePath, { ...opts });
791
+ mediaHandle = up.handle;
792
+ return up;
793
+ },
794
+ mediaCache: this.config.mediaCache,
795
+ options: this.config.options,
796
+ font,
797
+ textColor,
798
+ backgroundColor,
799
+ ptt
800
+ });
801
+ } catch (error) {
802
+ if (this.config.logger) {
803
+ this.config.logger.error(`Error generating message: ${error}`);
804
+ }
805
+ throw error;
806
+ }
807
+
808
+ await this.relayMessage(WABinary_1.STORIES_JID, msg.message, {
809
+ messageId: msg.key.id,
810
+ statusJidList: uniqueUsers,
811
+ additionalNodes: [
812
+ {
813
+ tag: 'meta',
814
+ attrs: {},
815
+ content: [
816
+ {
817
+ tag: 'mentioned_users',
818
+ attrs: {},
819
+ content: jids.map(jid => ({
820
+ tag: 'to',
821
+ attrs: { jid: WABinary_1.jidNormalizedUser(jid) }
822
+ }))
823
+ }
824
+ ]
825
+ }
826
+ ]
827
+ });
828
+
829
+ for (const id of jids) {
830
+ try {
831
+ const normalizedId = WABinary_1.jidNormalizedUser(id);
832
+ const isPrivate = WABinary_1.isJidUser(normalizedId);
833
+ const type = isPrivate ? 'statusMentionMessage' : 'groupStatusMentionMessage';
834
+
835
+ const protocolMessage = {
836
+ [type]: {
837
+ message: {
838
+ protocolMessage: {
839
+ key: msg.key,
840
+ type: 25
841
+ }
842
+ }
843
+ },
844
+ messageContextInfo: {
845
+ messageSecret: crypto.randomBytes(32)
846
+ }
847
+ };
848
+
849
+ const statusMsg = await Utils_1.generateWAMessageFromContent(
850
+ normalizedId,
851
+ protocolMessage,
852
+ {}
853
+ );
854
+
855
+ await this.relayMessage(
856
+ normalizedId,
857
+ statusMsg.message,
858
+ {
859
+ additionalNodes: [{
860
+ tag: 'meta',
861
+ attrs: isPrivate ?
862
+ { is_status_mention: 'true' } :
863
+ { is_group_status_mention: 'true' }
864
+ }]
865
+ }
866
+ );
867
+
868
+ await Utils_1.delay(2000);
869
+ } catch (error) {
870
+ if (this.config.logger) {
871
+ this.config.logger.error(`Error sending status mention to ${id}: ${error}`);
872
+ }
873
+ }
874
+ }
875
+
876
+ return msg;
877
+ }
878
+ }
879
+
880
+ module.exports = ClutchHandler;