@leonoremods/baileys 0.0.0-stage → 1.2.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 (150) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1204 -2
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +8083 -0
  5. package/WAProto/fix-imports.js +75 -0
  6. package/WAProto/index.d.ts +23020 -0
  7. package/WAProto/index.js +136324 -0
  8. package/engine-requirements.js +17 -0
  9. package/package.json +107 -4
  10. package/scripts/check-syntax.js +28 -0
  11. package/src/Defaults/index.js +186 -0
  12. package/src/Defaults/phonenumber-mcc.json +223 -0
  13. package/src/Signal/Group/ciphertext-message.js +15 -0
  14. package/src/Signal/Group/group-session-builder.js +86 -0
  15. package/src/Signal/Group/group_cipher.js +82 -0
  16. package/src/Signal/Group/index.js +140 -0
  17. package/src/Signal/Group/keyhelper.js +77 -0
  18. package/src/Signal/Group/sender-chain-key.js +29 -0
  19. package/src/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/src/Signal/Group/sender-key-message.js +69 -0
  21. package/src/Signal/Group/sender-key-name.js +51 -0
  22. package/src/Signal/Group/sender-key-record.js +44 -0
  23. package/src/Signal/Group/sender-key-state.js +87 -0
  24. package/src/Signal/Group/sender-message-key.js +29 -0
  25. package/src/Signal/libsignal.js +455 -0
  26. package/src/Signal/lid-mapping.js +273 -0
  27. package/src/Socket/Client/index.js +31 -0
  28. package/src/Socket/Client/types.js +13 -0
  29. package/src/Socket/Client/websocket.js +61 -0
  30. package/src/Socket/aigroups.js +221 -0
  31. package/src/Socket/business.js +411 -0
  32. package/src/Socket/chats.js +1449 -0
  33. package/src/Socket/communities.js +463 -0
  34. package/src/Socket/graphql.js +523 -0
  35. package/src/Socket/groups.js +516 -0
  36. package/src/Socket/index.js +31 -0
  37. package/src/Socket/interactive-handler.js +527 -0
  38. package/src/Socket/interop.js +339 -0
  39. package/src/Socket/luxu.js +349 -0
  40. package/src/Socket/managed-account.js +98 -0
  41. package/src/Socket/messages-recv.js +2685 -0
  42. package/src/Socket/messages-send.js +2047 -0
  43. package/src/Socket/mex.js +57 -0
  44. package/src/Socket/newsletter.js +455 -0
  45. package/src/Socket/privacy.js +125 -0
  46. package/src/Socket/registration.js +236 -0
  47. package/src/Socket/socket.js +983 -0
  48. package/src/Socket/text-router.js +65 -0
  49. package/src/Socket/username.js +130 -0
  50. package/src/Store/index.js +33 -0
  51. package/src/Store/keyed-db.js +118 -0
  52. package/src/Store/make-cache-manager-store.js +84 -0
  53. package/src/Store/make-in-memory-store.js +551 -0
  54. package/src/Store/make-ordered-dictionary.js +81 -0
  55. package/src/Store/object-repository.js +26 -0
  56. package/src/Types/Auth.js +31 -0
  57. package/src/Types/Bussines.js +2 -0
  58. package/src/Types/Call.js +2 -0
  59. package/src/Types/Chat.js +4 -0
  60. package/src/Types/Contact.js +2 -0
  61. package/src/Types/Events.js +2 -0
  62. package/src/Types/GroupMetadata.js +2 -0
  63. package/src/Types/Label.js +26 -0
  64. package/src/Types/LabelAssociation.js +8 -0
  65. package/src/Types/Message.js +93 -0
  66. package/src/Types/Mex.js +112 -0
  67. package/src/Types/Newsletter.js +109 -0
  68. package/src/Types/Product.js +2 -0
  69. package/src/Types/Signal.js +2 -0
  70. package/src/Types/Socket.js +2 -0
  71. package/src/Types/State.js +62 -0
  72. package/src/Types/USync.js +2 -0
  73. package/src/Types/index.js +56 -0
  74. package/src/Utils/auth-utils.js +254 -0
  75. package/src/Utils/browser-utils.js +112 -0
  76. package/src/Utils/business.js +240 -0
  77. package/src/Utils/chat-utils.js +1230 -0
  78. package/src/Utils/command-loader.d.ts +27 -0
  79. package/src/Utils/command-loader.js +89 -0
  80. package/src/Utils/companion-reg-client-utils.js +40 -0
  81. package/src/Utils/consumer-application.js +105 -0
  82. package/src/Utils/crypto.js +118 -0
  83. package/src/Utils/curve25519-js.js +242 -0
  84. package/src/Utils/decode-wa-message.js +529 -0
  85. package/src/Utils/event-buffer.js +580 -0
  86. package/src/Utils/generics.js +483 -0
  87. package/src/Utils/group-history.js +44 -0
  88. package/src/Utils/history.js +232 -0
  89. package/src/Utils/identity-change-handler.js +52 -0
  90. package/src/Utils/index.js +59 -0
  91. package/src/Utils/jid-display-normalization.js +195 -0
  92. package/src/Utils/link-preview.js +135 -0
  93. package/src/Utils/logger.js +8 -0
  94. package/src/Utils/lt-hash.js +25 -0
  95. package/src/Utils/make-mutex.js +36 -0
  96. package/src/Utils/message-composer.js +471 -0
  97. package/src/Utils/message-retry-manager.js +217 -0
  98. package/src/Utils/messages-media.js +843 -0
  99. package/src/Utils/messages.js +2817 -0
  100. package/src/Utils/meta-ai-msmsg.js +222 -0
  101. package/src/Utils/native-bridge.js +68 -0
  102. package/src/Utils/noise-handler.js +169 -0
  103. package/src/Utils/offline-node-processor.js +34 -0
  104. package/src/Utils/pre-key-manager.js +90 -0
  105. package/src/Utils/process-message.js +950 -0
  106. package/src/Utils/reporting-utils.js +261 -0
  107. package/src/Utils/session-pool.d.ts +14 -0
  108. package/src/Utils/session-pool.js +70 -0
  109. package/src/Utils/signal.js +217 -0
  110. package/src/Utils/socket-tools.js +252 -0
  111. package/src/Utils/stanza-ack.js +30 -0
  112. package/src/Utils/sticker.d.ts +13 -0
  113. package/src/Utils/sticker.js +123 -0
  114. package/src/Utils/sync-action-utils.js +45 -0
  115. package/src/Utils/tc-token-utils.js +158 -0
  116. package/src/Utils/use-multi-file-auth-state.js +111 -0
  117. package/src/Utils/validate-connection.js +209 -0
  118. package/src/Utils/view-once-cache.d.ts +12 -0
  119. package/src/Utils/view-once-cache.js +63 -0
  120. package/src/Utils/voip-rekey.js +22 -0
  121. package/src/WABinary/constants.js +1304 -0
  122. package/src/WABinary/decode.js +342 -0
  123. package/src/WABinary/encode.js +225 -0
  124. package/src/WABinary/generic-utils.js +238 -0
  125. package/src/WABinary/index.js +34 -0
  126. package/src/WABinary/jid-utils.js +351 -0
  127. package/src/WABinary/types.js +2 -0
  128. package/src/WAM/BinaryInfo.js +13 -0
  129. package/src/WAM/constants.js +39484 -0
  130. package/src/WAM/encode.js +149 -0
  131. package/src/WAM/index.js +32 -0
  132. package/src/WAUSync/Protocols/USyncBotProfileProtocol.js +53 -0
  133. package/src/WAUSync/Protocols/USyncBusinessProtocol.js +44 -0
  134. package/src/WAUSync/Protocols/USyncContactProtocol.js +55 -0
  135. package/src/WAUSync/Protocols/USyncDeviceProtocol.js +55 -0
  136. package/src/WAUSync/Protocols/USyncDisappearingModeProtocol.js +31 -0
  137. package/src/WAUSync/Protocols/USyncFeatureProtocol.js +54 -0
  138. package/src/WAUSync/Protocols/USyncLIDProtocol.js +32 -0
  139. package/src/WAUSync/Protocols/USyncNewsletterProtocol.js +481 -0
  140. package/src/WAUSync/Protocols/USyncPictureProtocol.js +34 -0
  141. package/src/WAUSync/Protocols/USyncSidelistProtocol.js +29 -0
  142. package/src/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  143. package/src/WAUSync/Protocols/USyncTextStatusProtocol.js +38 -0
  144. package/src/WAUSync/Protocols/USyncUsernameProtocol.js +28 -0
  145. package/src/WAUSync/Protocols/index.js +40 -0
  146. package/src/WAUSync/USyncQuery.js +126 -0
  147. package/src/WAUSync/USyncUser.js +50 -0
  148. package/src/WAUSync/index.js +32 -0
  149. package/src/antiban.js +4152 -0
  150. package/src/index.js +78 -0
@@ -0,0 +1,252 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Creates an opt-in outbound message queue around an existing Baileys socket.
5
+ * It does not retry failed sends automatically because a timeout can happen
6
+ * after WhatsApp has already accepted a message, and retrying could duplicate it.
7
+ */
8
+ const createSendQueue = (sock, options = {}) => {
9
+ if (!sock || typeof sock.sendMessage !== 'function') {
10
+ throw new TypeError('createSendQueue requires a socket with sendMessage()');
11
+ }
12
+
13
+ const concurrency = Math.max(1, Math.floor(Number(options.concurrency) || 1));
14
+ const intervalMs = Math.max(0, Math.floor(Number(options.intervalMs) || 0));
15
+ const maxPending = Math.max(1, Math.floor(Number(options.maxPending) || 100));
16
+ const queue = [];
17
+ const idleWaiters = [];
18
+ let active = 0;
19
+ let closed = false;
20
+ let lastStartedAt = 0;
21
+ let timer = null;
22
+
23
+ const settleIdle = () => {
24
+ if (active === 0 && queue.length === 0) {
25
+ while (idleWaiters.length) idleWaiters.shift()();
26
+ }
27
+ };
28
+
29
+ const drain = () => {
30
+ if (closed || timer) return;
31
+
32
+ while (active < concurrency && queue.length > 0) {
33
+ const waitMs = Math.max(0, intervalMs - (Date.now() - lastStartedAt));
34
+ if (waitMs > 0) {
35
+ timer = setTimeout(() => {
36
+ timer = null;
37
+ drain();
38
+ }, waitMs);
39
+ timer.unref?.();
40
+ return;
41
+ }
42
+
43
+ const task = queue.shift();
44
+ active += 1;
45
+ lastStartedAt = Date.now();
46
+
47
+ Promise.resolve()
48
+ .then(() => sock.sendMessage(task.jid, task.content, task.sendOptions))
49
+ .then(task.resolve, task.reject)
50
+ .finally(() => {
51
+ active -= 1;
52
+ drain();
53
+ settleIdle();
54
+ });
55
+ }
56
+
57
+ settleIdle();
58
+ };
59
+
60
+ return {
61
+ sendMessage(jid, content, sendOptions) {
62
+ if (closed) {
63
+ return Promise.reject(new Error('Send queue is closed'));
64
+ }
65
+ if (active + queue.length >= maxPending) {
66
+ return Promise.reject(new Error(`Send queue limit reached (${maxPending})`));
67
+ }
68
+
69
+ return new Promise((resolve, reject) => {
70
+ queue.push({ jid, content, sendOptions, resolve, reject });
71
+ drain();
72
+ });
73
+ },
74
+
75
+ onIdle() {
76
+ if (active === 0 && queue.length === 0) return Promise.resolve();
77
+ return new Promise(resolve => idleWaiters.push(resolve));
78
+ },
79
+
80
+ close(reason = new Error('Send queue closed')) {
81
+ if (closed) return 0;
82
+ closed = true;
83
+ if (timer) {
84
+ clearTimeout(timer);
85
+ timer = null;
86
+ }
87
+ const cancelled = queue.length;
88
+ while (queue.length) {
89
+ queue.shift().reject(reason);
90
+ }
91
+ settleIdle();
92
+ return cancelled;
93
+ },
94
+
95
+ get pending() {
96
+ return active + queue.length;
97
+ },
98
+
99
+ get size() {
100
+ return queue.length;
101
+ },
102
+
103
+ get isClosed() {
104
+ return closed;
105
+ }
106
+ };
107
+ };
108
+
109
+ /**
110
+ * Opt-in reconnect supervisor. Pass a callback that creates a fresh socket
111
+ * using the same persisted auth state. Logged-out sessions are not retried by
112
+ * default. stop() cancels future reconnect attempts but does not close the
113
+ * currently active socket.
114
+ */
115
+ const createReconnectManager = (connect, options = {}) => {
116
+ if (typeof connect !== 'function') {
117
+ throw new TypeError('createReconnectManager requires a connect() function');
118
+ }
119
+
120
+ const minDelayMs = Math.max(100, Number(options.minDelayMs) || 1000);
121
+ const maxDelayMs = Math.max(minDelayMs, Number(options.maxDelayMs) || 30000);
122
+ const factor = Math.max(1, Number(options.factor) || 2);
123
+ const jitter = Math.min(1, Math.max(0, Number(options.jitter) || 0.2));
124
+ const loggedOutStatusCode = options.loggedOutStatusCode ?? 401;
125
+ const shouldReconnect = typeof options.shouldReconnect === 'function'
126
+ ? options.shouldReconnect
127
+ : ({ statusCode }) => statusCode !== loggedOutStatusCode;
128
+
129
+ let socket = null;
130
+ let attempts = 0;
131
+ let stopped = false;
132
+ let retryTimer = null;
133
+ let connectingPromise = null;
134
+ let updateListener = null;
135
+
136
+ const reportError = error => {
137
+ try {
138
+ options.onError?.(error);
139
+ } catch {
140
+ // User-provided error callbacks must not break reconnect management.
141
+ }
142
+ };
143
+
144
+ const detach = () => {
145
+ if (socket?.ev?.off && updateListener) {
146
+ socket.ev.off('connection.update', updateListener);
147
+ }
148
+ updateListener = null;
149
+ };
150
+
151
+ const scheduleReconnect = update => {
152
+ if (stopped || retryTimer) return;
153
+
154
+ const statusCode =
155
+ update?.lastDisconnect?.error?.output?.statusCode ??
156
+ update?.error?.output?.statusCode ??
157
+ update?.statusCode;
158
+
159
+ const details = { ...update, statusCode, attempt: attempts + 1 };
160
+ let allowed = false;
161
+ try {
162
+ allowed = Boolean(shouldReconnect(details));
163
+ } catch (error) {
164
+ reportError(error);
165
+ return;
166
+ }
167
+ if (!allowed) {
168
+ options.onGiveUp?.(details);
169
+ return;
170
+ }
171
+
172
+ const baseDelay = Math.min(maxDelayMs, minDelayMs * Math.pow(factor, attempts));
173
+ const delayMs = Math.min(
174
+ maxDelayMs,
175
+ Math.round(baseDelay + (Math.random() * baseDelay * jitter))
176
+ );
177
+ attempts += 1;
178
+ options.onRetry?.({ ...details, delayMs });
179
+
180
+ retryTimer = setTimeout(() => {
181
+ retryTimer = null;
182
+ start().catch(reportError);
183
+ }, delayMs);
184
+ retryTimer.unref?.();
185
+ };
186
+
187
+ const start = () => {
188
+ if (stopped) return Promise.reject(new Error('Reconnect manager is stopped'));
189
+ if (connectingPromise) return connectingPromise;
190
+ if (retryTimer) {
191
+ clearTimeout(retryTimer);
192
+ retryTimer = null;
193
+ }
194
+
195
+ connectingPromise = Promise.resolve()
196
+ .then(() => connect())
197
+ .then(nextSocket => {
198
+ if (!nextSocket?.ev?.on) {
199
+ throw new TypeError('connect() must return a Baileys socket with ev.on()');
200
+ }
201
+ detach();
202
+ socket = nextSocket;
203
+ updateListener = update => {
204
+ if (update?.connection === 'open') {
205
+ attempts = 0;
206
+ } else if (update?.connection === 'close') {
207
+ scheduleReconnect(update);
208
+ }
209
+ };
210
+ socket.ev.on('connection.update', updateListener);
211
+ return socket;
212
+ })
213
+ .catch(error => {
214
+ reportError(error);
215
+ scheduleReconnect({ error });
216
+ throw error;
217
+ })
218
+ .finally(() => {
219
+ connectingPromise = null;
220
+ });
221
+
222
+ return connectingPromise;
223
+ };
224
+
225
+ const stop = () => {
226
+ stopped = true;
227
+ if (retryTimer) {
228
+ clearTimeout(retryTimer);
229
+ retryTimer = null;
230
+ }
231
+ detach();
232
+ };
233
+
234
+ return {
235
+ start,
236
+ stop,
237
+ get socket() {
238
+ return socket;
239
+ },
240
+ get attempts() {
241
+ return attempts;
242
+ },
243
+ get stopped() {
244
+ return stopped;
245
+ }
246
+ };
247
+ };
248
+
249
+ module.exports = {
250
+ createSendQueue,
251
+ createReconnectManager
252
+ };
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.buildAckStanza = buildAckStanza;
4
+ function buildAckStanza(node, errorCode, meId) {
5
+ const { tag, attrs } = node;
6
+ const stanza = {
7
+ tag: 'ack',
8
+ attrs: {
9
+ id: attrs.id,
10
+ to: attrs.from,
11
+ class: tag
12
+ }
13
+ };
14
+ if (errorCode) {
15
+ stanza.attrs.error = errorCode.toString();
16
+ }
17
+ if (attrs.participant) {
18
+ stanza.attrs.participant = attrs.participant;
19
+ }
20
+ if (attrs.recipient) {
21
+ stanza.attrs.recipient = attrs.recipient;
22
+ }
23
+ if (attrs.type) {
24
+ stanza.attrs.type = attrs.type;
25
+ }
26
+ if (tag === 'message' && meId) {
27
+ stanza.attrs.from = meId;
28
+ }
29
+ return stanza;
30
+ }
@@ -0,0 +1,13 @@
1
+ export interface StickerMetaOptions {
2
+ packName?: string;
3
+ packPublisher?: string;
4
+ categories?: string[];
5
+ }
6
+ export function addExifToWebp(webpBuffer: Buffer, options?: StickerMetaOptions): Promise<Buffer>;
7
+ export function imageToWebpSticker(imageBuffer: Buffer, options?: StickerMetaOptions & {
8
+ quality?: number;
9
+ }): Promise<Buffer>;
10
+ export function videoToWebpSticker(videoBuffer: Buffer, options?: StickerMetaOptions & {
11
+ fps?: number;
12
+ seconds?: number;
13
+ }): Promise<Buffer>;
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.imageToWebpSticker = exports.videoToWebpSticker = exports.addExifToWebp = void 0;
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const fs = require('fs');
7
+ const crypto = require('crypto');
8
+ const { exec } = require('child_process');
9
+ const addExifToWebp = async (webpBuffer, { packName = '', packPublisher = '', categories = [] } = {}) => {
10
+ const json = {
11
+ 'sticker-pack-id': crypto.randomBytes(16).toString('hex'),
12
+ 'sticker-pack-name': packName,
13
+ 'sticker-pack-publisher': packPublisher,
14
+ emojis: categories.length ? categories : ['😀']
15
+ };
16
+ const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf-8');
17
+ const exifAttr = Buffer.from([
18
+ 0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16,
19
+ 0x00, 0x00, 0x00
20
+ ]);
21
+ exifAttr.writeUIntLE(jsonBuffer.length, 14, 4);
22
+ const exifPayload = Buffer.concat([exifAttr, jsonBuffer]);
23
+ const pad = buf => (buf.length % 2 === 1 ? Buffer.concat([buf, Buffer.from([0x00])]) : buf);
24
+ const makeChunk = (tag, data) => {
25
+ const sizeField = Buffer.alloc(4);
26
+ sizeField.writeUInt32LE(data.length, 0);
27
+ return Buffer.concat([Buffer.from(tag, 'ascii'), sizeField, pad(data)]);
28
+ };
29
+ const exifChunk = makeChunk('EXIF', exifPayload);
30
+ if (webpBuffer.slice(0, 4).toString('ascii') !== 'RIFF' || webpBuffer.slice(8, 12).toString('ascii') !== 'WEBP') {
31
+ throw new Error('addExifToWebp expects a valid WebP buffer');
32
+ }
33
+ let offset = 12;
34
+ let vp8xChunk = null;
35
+ let vp8xOffset = -1;
36
+ const otherChunks = [];
37
+ while (offset < webpBuffer.length) {
38
+ const tag = webpBuffer.slice(offset, offset + 4).toString('ascii');
39
+ const size = webpBuffer.readUInt32LE(offset + 4);
40
+ const dataStart = offset + 8;
41
+ const dataEnd = dataStart + size;
42
+ const chunkTotal = 8 + size + (size % 2);
43
+ if (tag === 'VP8X') {
44
+ vp8xChunk = webpBuffer.slice(offset, offset + chunkTotal);
45
+ vp8xOffset = offset;
46
+ }
47
+ else if (tag !== 'EXIF') {
48
+ otherChunks.push(webpBuffer.slice(offset, offset + chunkTotal));
49
+ }
50
+ offset += chunkTotal;
51
+ }
52
+ let flags;
53
+ let canvasWidth;
54
+ let canvasHeight;
55
+ if (vp8xChunk) {
56
+ flags = vp8xChunk.readUInt8(8);
57
+ canvasWidth = vp8xChunk.readUIntLE(12, 3) + 1;
58
+ canvasHeight = vp8xChunk.readUIntLE(15, 3) + 1;
59
+ }
60
+ else {
61
+ flags = 0;
62
+ let sharp;
63
+ try {
64
+ sharp = require('sharp');
65
+ }
66
+ catch (error) {
67
+ throw new Error('addExifToWebp needs the optional "sharp" dependency to read image dimensions');
68
+ }
69
+ const meta = await sharp(webpBuffer).metadata();
70
+ canvasWidth = meta.width;
71
+ canvasHeight = meta.height;
72
+ }
73
+ flags |= 0x08;
74
+ const vp8xData = Buffer.alloc(10);
75
+ vp8xData.writeUInt8(flags, 0);
76
+ vp8xData.writeUIntLE(canvasWidth - 1, 4, 3);
77
+ vp8xData.writeUIntLE(canvasHeight - 1, 7, 3);
78
+ const newVp8xChunk = makeChunk('VP8X', vp8xData);
79
+ const body = Buffer.concat([newVp8xChunk, ...otherChunks, exifChunk]);
80
+ const fileSize = Buffer.alloc(4);
81
+ fileSize.writeUInt32LE(4 + body.length, 0);
82
+ return Buffer.concat([Buffer.from('RIFF', 'ascii'), fileSize, Buffer.from('WEBP', 'ascii'), body]);
83
+ };
84
+ exports.addExifToWebp = addExifToWebp;
85
+ const imageToWebpSticker = async (imageBuffer, options = {}) => {
86
+ let sharp;
87
+ try {
88
+ sharp = require('sharp');
89
+ }
90
+ catch (error) {
91
+ throw new Error('imageToWebpSticker requires the optional "sharp" dependency to be installed');
92
+ }
93
+ const webp = await sharp(imageBuffer)
94
+ .resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
95
+ .webp({ quality: options.quality ?? 80 })
96
+ .toBuffer();
97
+ return addExifToWebp(webp, options);
98
+ };
99
+ exports.imageToWebpSticker = imageToWebpSticker;
100
+ const videoToWebpSticker = async (videoBuffer, options = {}) => {
101
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'xazbails-sticker-'));
102
+ const inputPath = path.join(tmpDir, 'input.mp4');
103
+ const outputPath = path.join(tmpDir, 'output.webp');
104
+ fs.writeFileSync(inputPath, videoBuffer);
105
+ const fps = options.fps ?? 10;
106
+ const seconds = options.seconds ?? 5;
107
+ const cmd = `ffmpeg -y -i ${inputPath} -t ${seconds} -vf ` +
108
+ `"fps=${fps},scale=512:512:force_original_aspect_ratio=decrease,` +
109
+ `pad=512:512:(ow-iw)/2:(oh-ih)/2:color=0x00000000,split[a][b];` +
110
+ `[a]palettegen=reserve_transparent=1[p];[b][p]paletteuse" ` +
111
+ `-loop 0 -preset default -an -vsync 0 ${outputPath}`;
112
+ try {
113
+ await new Promise((resolve, reject) => {
114
+ exec(cmd, err => (err ? reject(err) : resolve()));
115
+ });
116
+ const webp = fs.readFileSync(outputPath);
117
+ return await addExifToWebp(webp, options);
118
+ }
119
+ finally {
120
+ fs.rmSync(tmpDir, { recursive: true, force: true });
121
+ }
122
+ };
123
+ exports.videoToWebpSticker = videoToWebpSticker;
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.emitSyncActionResults = exports.processContactAction = void 0;
4
+ const WABinary_1 = require('../WABinary');
5
+ const processContactAction = (action, id, logger) => {
6
+ const results = [];
7
+ if (!id) {
8
+ logger?.warn({ hasFullName: !!action.fullName, hasLidJid: !!action.lidJid, hasPnJid: !!action.pnJid }, 'contactAction sync: missing id in index');
9
+ return results;
10
+ }
11
+ const lidJid = action.lidJid;
12
+ const idIsPn = (0, WABinary_1.isPnUser)(id);
13
+ const phoneNumber = idIsPn ? id : action.pnJid || undefined;
14
+ results.push({
15
+ event: 'contacts.upsert',
16
+ data: [
17
+ {
18
+ id,
19
+ name: action.fullName || action.firstName || action.username || undefined,
20
+ username: action.username || undefined,
21
+ lid: lidJid || undefined,
22
+ phoneNumber
23
+ }
24
+ ]
25
+ });
26
+ if (lidJid && (0, WABinary_1.isLidUser)(lidJid) && idIsPn) {
27
+ results.push({
28
+ event: 'lid-mapping.update',
29
+ data: { lid: lidJid, pn: id }
30
+ });
31
+ }
32
+ return results;
33
+ };
34
+ exports.processContactAction = processContactAction;
35
+ const emitSyncActionResults = (ev, results) => {
36
+ for (const result of results) {
37
+ if (result.event === 'contacts.upsert') {
38
+ ev.emit('contacts.upsert', result.data);
39
+ }
40
+ else {
41
+ ev.emit('lid-mapping.update', result.data);
42
+ }
43
+ }
44
+ };
45
+ exports.emitSyncActionResults = emitSyncActionResults;
@@ -0,0 +1,158 @@
1
+ 'use strict';
2
+ Object.defineProperty(exports, '__esModule', { value: true });
3
+ exports.TC_TOKEN_INDEX_KEY = void 0;
4
+ exports.readTcTokenIndex = readTcTokenIndex;
5
+ exports.buildMergedTcTokenIndexWrite = buildMergedTcTokenIndexWrite;
6
+ exports.isTcTokenExpired = isTcTokenExpired;
7
+ exports.shouldSendNewTcToken = shouldSendNewTcToken;
8
+ exports.resolveTcTokenJid = resolveTcTokenJid;
9
+ exports.resolveIssuanceJid = resolveIssuanceJid;
10
+ exports.buildTcTokenFromJid = buildTcTokenFromJid;
11
+ exports.storeTcTokensFromIqResult = storeTcTokensFromIqResult;
12
+ const WABinary_1 = require('../WABinary');
13
+ const BOT_PHONE_REGEX = /^1313555\d{4}$|^131655500\d{2}$/;
14
+ function isRegularUser(jid) {
15
+ if (!jid)
16
+ return false;
17
+ const user = jid.split('@')[0] ?? '';
18
+ if (user === '0')
19
+ return false;
20
+ if (BOT_PHONE_REGEX.test(user))
21
+ return false;
22
+ if ((0, WABinary_1.isJidMetaAI)(jid))
23
+ return false;
24
+ return !!((0, WABinary_1.isPnUser)(jid) ||
25
+ (0, WABinary_1.isLidUser)(jid) ||
26
+ (0, WABinary_1.isHostedPnUser)(jid) ||
27
+ (0, WABinary_1.isHostedLidUser)(jid) ||
28
+ jid.endsWith('@c.us'));
29
+ }
30
+ const TC_TOKEN_BUCKET_DURATION = 604800;
31
+ const TC_TOKEN_NUM_BUCKETS = 4;
32
+ exports.TC_TOKEN_INDEX_KEY = '__index';
33
+ async function readTcTokenIndex(keys) {
34
+ const data = await keys.get('tctoken', [exports.TC_TOKEN_INDEX_KEY]);
35
+ const entry = data[exports.TC_TOKEN_INDEX_KEY];
36
+ if (!entry?.token?.length)
37
+ return [];
38
+ try {
39
+ const parsed = JSON.parse(Buffer.from(entry.token).toString());
40
+ if (!Array.isArray(parsed))
41
+ return [];
42
+ return parsed.filter(j => typeof j === 'string' && j.length > 0 && j !== exports.TC_TOKEN_INDEX_KEY);
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
48
+ async function buildMergedTcTokenIndexWrite(keys, addedJids) {
49
+ const persisted = await readTcTokenIndex(keys);
50
+ const merged = new Set(persisted);
51
+ for (const jid of addedJids) {
52
+ if (jid && jid !== exports.TC_TOKEN_INDEX_KEY)
53
+ merged.add(jid);
54
+ }
55
+ return {
56
+ [exports.TC_TOKEN_INDEX_KEY]: { token: Buffer.from(JSON.stringify([...merged])) }
57
+ };
58
+ }
59
+ function isTcTokenExpired(timestamp) {
60
+ if (timestamp === null || timestamp === undefined)
61
+ return true;
62
+ const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
63
+ if (isNaN(ts))
64
+ return true;
65
+ const now = Math.floor(Date.now() / 1000);
66
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
67
+ const cutoffBucket = currentBucket - (TC_TOKEN_NUM_BUCKETS - 1);
68
+ const cutoffTimestamp = cutoffBucket * TC_TOKEN_BUCKET_DURATION;
69
+ return ts < cutoffTimestamp;
70
+ }
71
+ function shouldSendNewTcToken(senderTimestamp) {
72
+ if (senderTimestamp === undefined)
73
+ return true;
74
+ const now = Math.floor(Date.now() / 1000);
75
+ const currentBucket = Math.floor(now / TC_TOKEN_BUCKET_DURATION);
76
+ const senderBucket = Math.floor(senderTimestamp / TC_TOKEN_BUCKET_DURATION);
77
+ return currentBucket > senderBucket;
78
+ }
79
+ async function resolveTcTokenJid(jid, getLIDForPN) {
80
+ if ((0, WABinary_1.isLidUser)(jid))
81
+ return jid;
82
+ const lid = await getLIDForPN(jid);
83
+ return lid ?? jid;
84
+ }
85
+ async function resolveIssuanceJid(jid, issueToLid, getLIDForPN, getPNForLID) {
86
+ if (issueToLid) {
87
+ if ((0, WABinary_1.isLidUser)(jid))
88
+ return jid;
89
+ const lid = await getLIDForPN(jid);
90
+ return lid ?? jid;
91
+ }
92
+ if (!(0, WABinary_1.isLidUser)(jid))
93
+ return jid;
94
+ if (getPNForLID) {
95
+ const pn = await getPNForLID(jid);
96
+ return pn ?? jid;
97
+ }
98
+ return jid;
99
+ }
100
+ async function buildTcTokenFromJid({ authState, jid, baseContent = [], getLIDForPN }) {
101
+ try {
102
+ const storageJid = await resolveTcTokenJid(jid, getLIDForPN);
103
+ const tcTokenData = await authState.keys.get('tctoken', [storageJid]);
104
+ const entry = tcTokenData?.[storageJid];
105
+ const tcTokenBuffer = entry?.token;
106
+ if (!tcTokenBuffer?.length || isTcTokenExpired(entry?.timestamp)) {
107
+ if (tcTokenBuffer) {
108
+ const cleared = entry?.senderTimestamp !== undefined
109
+ ? { token: Buffer.alloc(0), senderTimestamp: entry.senderTimestamp }
110
+ : null;
111
+ await authState.keys.set({ tctoken: { [storageJid]: cleared } });
112
+ }
113
+ return baseContent.length > 0 ? baseContent : undefined;
114
+ }
115
+ baseContent.push({
116
+ tag: 'tctoken',
117
+ attrs: {},
118
+ content: tcTokenBuffer
119
+ });
120
+ return baseContent;
121
+ }
122
+ catch (error) {
123
+ return baseContent.length > 0 ? baseContent : undefined;
124
+ }
125
+ }
126
+ async function storeTcTokensFromIqResult({ result, fallbackJid, keys, getLIDForPN, onNewJidStored }) {
127
+ const tokensNode = (0, WABinary_1.getBinaryNodeChild)(result, 'tokens');
128
+ if (!tokensNode)
129
+ return;
130
+ const tokenNodes = (0, WABinary_1.getBinaryNodeChildren)(tokensNode, 'token');
131
+ for (const tokenNode of tokenNodes) {
132
+ if (tokenNode.attrs.type !== 'trusted_contact' || !(tokenNode.content instanceof Uint8Array)) {
133
+ continue;
134
+ }
135
+ const rawJid = (0, WABinary_1.jidNormalizedUser)(fallbackJid || tokenNode.attrs.jid);
136
+ if (!isRegularUser(rawJid))
137
+ continue;
138
+ const storageJid = await resolveTcTokenJid(rawJid, getLIDForPN);
139
+ const existingTcData = await keys.get('tctoken', [storageJid]);
140
+ const existingEntry = existingTcData[storageJid];
141
+ const existingTs = existingEntry?.timestamp ? Number(existingEntry.timestamp) : 0;
142
+ const incomingTs = tokenNode.attrs.t ? Number(tokenNode.attrs.t) : 0;
143
+ if (!incomingTs)
144
+ continue;
145
+ if (existingTs > 0 && existingTs > incomingTs)
146
+ continue;
147
+ await keys.set({
148
+ tctoken: {
149
+ [storageJid]: {
150
+ ...existingEntry,
151
+ token: Buffer.from(tokenNode.content),
152
+ timestamp: tokenNode.attrs.t
153
+ }
154
+ }
155
+ });
156
+ onNewJidStored?.(storageJid);
157
+ }
158
+ }