@ryuhan/baileys 1.0.9 → 1.0.10

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.
@@ -1,8 +1,8 @@
1
1
  <p align="center">
2
- <img src="https://files.catbox.moe/f8tj1b.png" alt="Wileys Bot" width="150"/>
2
+ <img src="https://files.catbox.moe/f8tj1b.png" alt="Rimuru Bot" width="150"/>
3
3
  </p>
4
4
 
5
- <h1 align="center">💧 Wileys Baileys</h1>
5
+ <h1 align="center">💧 Rimuru Baileys</h1>
6
6
  <p align="center">TypeScript-based library for WhatsApp Web API integration, with built-in fixes for group identifiers like @lid and @jid.
7
7
  </p>
8
8
 
@@ -22,11 +22,11 @@
22
22
  - **💧 Handles all WhatsApp message types**
23
23
  - **💧 Fast and modern TypeScript codebase**
24
24
  - **💧 Multi-Device Support:** Works with latest WhatsApp multi-device protocol.
25
- - **💧 Media Handling:** Send and receive images, videos, audio, stickers, and documents.
26
- - **💧 Pairing Code Login:** Easy login using Pairing Code.
25
+ - **💧 Media Handling:** Send and receive images, videos, audio, stickers, and documents.
26
+ - **💧 Pairing Code Login:** Easy login using Pairing Code.
27
27
  - **💧 Simple & Extendable:** Clean code structure for customization and adding new features.
28
28
  - **💧 Support Botton Message:** You can add cool botton to your bot menu
29
- - **💧 High Compatibility:** Built on Wileys's fork of Baileys for reliable WhatsApp API integration.
29
+ - **💧 High Compatibility:** Built on Ryuhan's fork of Baileys for reliable WhatsApp API integration.
30
30
 
31
31
  ---
32
32
  ### 💧 Installation
@@ -103,3 +103,46 @@ start()
103
103
  }
104
104
  ```
105
105
  ---
106
+
107
+ ### 💧 Pairing Code Example
108
+
109
+ ```javascript
110
+ const { default: makeWASocket } = require("@ryuhan/baileys")
111
+
112
+ const sock = makeWASocket({
113
+ printQRInTerminal: false
114
+ })
115
+
116
+ // Custom Pairing Code with "MURUSAMA"
117
+ if (!sock.authState.creds.registered) {
118
+ const number = '6285134816783'
119
+ const code = await sock.requestPairingCode(number, "MURUSAMA")
120
+ console.log('💧 Pairing Code:', code)
121
+ }
122
+ ```
123
+
124
+ ---
125
+
126
+ ## ⚠️ Warning
127
+
128
+ This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries. The official WhatsApp website can be found at whatsapp.com.
129
+
130
+ The maintainers of Rimuru Baileys do not endorse the use of this application for violating WhatsApp's Terms of Service. We emphasize the personal responsibility of users to use it fairly and responsibly.
131
+
132
+ Use wisely. Avoid spam. Do not use excessive automation.
133
+
134
+ ---
135
+
136
+ ## 📚 Full Documentation
137
+
138
+ For complete documentation, visit the [GitHub Repository](https://github.com/ryuhandev/rimuru-baileys).
139
+
140
+ ---
141
+
142
+ ## 💝 Support
143
+
144
+ Support the development of this project by starring the repository and contributing!
145
+
146
+ ---
147
+
148
+ <p align="center">Made with 💧 by <a href="https://github.com/ryuhandev">@ryuhandev</a></p>
package/WAProto/p.html ADDED
@@ -0,0 +1 @@
1
+ Rimuru Baileys
@@ -8,7 +8,8 @@ const WAProto_1 = require("../../WAProto");
8
8
  const libsignal_1 = require("../Signal/libsignal");
9
9
  const browser_utils_1 = require("../Utils/browser-utils");
10
10
  const logger_1 = __importDefault(require("../Utils/logger"));
11
- exports.version = [2, 3000, 1027934701];
11
+ const rimuru_version_json_1 = require("./rimuru-version.json");
12
+ exports.version = rimuru_version_json_1.version;
12
13
  exports.UNAUTHORIZED_CODES = [401, 403, 419];
13
14
  exports.DEFAULT_ORIGIN = 'https://web.whatsapp.com';
14
15
  exports.CALL_VIDEO_PREFIX = 'https://call.whatsapp.com/video/';
@@ -58,6 +59,8 @@ exports.DEFAULT_CONNECTION_CONFIG = {
58
59
  shouldSyncHistoryMessage: () => true,
59
60
  shouldIgnoreJid: () => false,
60
61
  linkPreviewImageThumbnailWidth: 192,
62
+ // no forced delay between album items by default, to avoid slow perceived delivery
63
+ albumMessageItemDelayMs: 0,
61
64
  transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 3000 },
62
65
  generateHighQualityLinkPreview: false,
63
66
  enableAutoSessionRecreation: true,
@@ -110,12 +113,9 @@ exports.MIN_PREKEY_COUNT = 5;
110
113
  exports.INITIAL_PREKEY_COUNT = 812;
111
114
  exports.UPLOAD_TIMEOUT = 30000;
112
115
  exports.MIN_UPLOAD_INTERVAL = 5000;
113
- exports.DEFAULT_MAX_MSG_RETRY_COUNT = 5;
114
- exports.DEFAULT_PHONE_REQUEST_DELAY_MS = 3000;
115
116
  exports.DEFAULT_CACHE_TTLS = {
116
117
  SIGNAL_STORE: 5 * 60,
117
118
  MSG_RETRY: 60 * 60,
118
119
  CALL_OFFER: 5 * 60,
119
- USER_DEVICES: 5 * 60,
120
- IDENTITY_ASSERT: 5 // 5 seconds for debouncing
121
- };
120
+ USER_DEVICES: 5 * 60
121
+ };
@@ -0,0 +1,3 @@
1
+ {
2
+ "version": [2, 3000, 1033105955]
3
+ }
@@ -11,11 +11,6 @@ class WebSocketClient extends types_1.AbstractSocketClient {
11
11
  constructor() {
12
12
  super(...arguments);
13
13
  this.socket = null;
14
- // queue & dispatch variables for throttling outgoing messages to avoid rate limits
15
- this._queue = [];
16
- this._isDispatching = false;
17
- this._lastDispatch = 0;
18
- this._minSendIntervalMs = (Defaults_1.DEFAULT_CONNECTION_CONFIG && Defaults_1.DEFAULT_CONNECTION_CONFIG.minSendIntervalMs) || 50;
19
14
  }
20
15
  get isOpen() {
21
16
  var _a;
@@ -69,43 +64,9 @@ class WebSocketClient extends types_1.AbstractSocketClient {
69
64
  await this.connect();
70
65
  }
71
66
  send(str, cb) {
72
- // throttle sends to reduce rate-limit likelihood
73
- const doSend = () => {
74
- var _a;
75
- (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
76
- return Boolean(this.socket);
77
- };
78
- this._queue.push(doSend);
79
- this._dispatch();
67
+ var _a;
68
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
80
69
  return true;
81
70
  }
82
-
83
- _dispatch() {
84
- if (this._isDispatching) {
85
- return;
86
- }
87
- this._isDispatching = true;
88
- const tick = () => {
89
- const now = Date.now();
90
- if (this._queue.length === 0) {
91
- this._isDispatching = false;
92
- return;
93
- }
94
- const delta = now - this._lastDispatch;
95
- const wait = Math.max(0, this._minSendIntervalMs - delta);
96
- setTimeout(() => {
97
- const fn = this._queue.shift();
98
- this._lastDispatch = Date.now();
99
- try {
100
- fn && fn();
101
- }
102
- catch (_err) {
103
- // ignore send errors here; they'll surface elsewhere
104
- }
105
- tick();
106
- }, wait);
107
- };
108
- tick();
109
- }
110
71
  }
111
72
  exports.WebSocketClient = WebSocketClient;
@@ -33,25 +33,17 @@ const makeChatsSocket = (config) => {
33
33
  let pendingAppStateSync = false;
34
34
  let awaitingSyncTimeout;
35
35
  const processingMutex = (0, make_mutex_1.makeMutex)();
36
- const messageMutex = (0, make_mutex_1.makeMutex)();
37
- const notificationMutex = (0, make_mutex_1.makeMutex)();
38
- const receiptMutex = (0, make_mutex_1.makeMutex)();
39
36
  const placeholderResendCache = config.placeholderResendCache || new node_cache_1.default({
40
37
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY,
41
38
  useClones: false
42
39
  });
40
+ const receivedMessageDedupCache = new node_cache_1.default({
41
+ stdTTL: 3 * 60,
42
+ useClones: false
43
+ });
43
44
  if (!config.placeholderResendCache) {
44
45
  config.placeholderResendCache = placeholderResendCache;
45
46
  }
46
- // Initialize message retry manager
47
- const messageRetryManager = config.messageRetryManager || (0, Utils_1.createMessageRetryManager)({
48
- maxRetries: config.maxMsgRetryCount || Defaults_1.DEFAULT_MAX_MSG_RETRY_COUNT,
49
- phoneRequestDelayMs: config.phoneRequestDelayMs || Defaults_1.DEFAULT_PHONE_REQUEST_DELAY_MS,
50
- logger
51
- });
52
- if (!config.messageRetryManager) {
53
- config.messageRetryManager = messageRetryManager;
54
- }
55
47
  const getAppStateSyncKey = async (keyId) => {
56
48
  const { [keyId]: key } = await authState.keys.get('app-state-sync-key', [keyId]);
57
49
  return key;
@@ -740,8 +732,58 @@ const makeChatsSocket = (config) => {
740
732
  fetchPrivacySettings(),
741
733
  ]);
742
734
  };
735
+ const canonicalizeUserJid = (jid) => {
736
+ if (!jid) {
737
+ return jid;
738
+ }
739
+ if ((0, WABinary_1.isLidUser)(jid)) {
740
+ return (0, WABinary_1.lidToJid)(jid);
741
+ }
742
+ return jid;
743
+ };
744
+ const extractStanzaId = (msg) => {
745
+ var _a, _b;
746
+ const topLevelStanzaId = (_a = msg.messageContextInfo) === null || _a === void 0 ? void 0 : _a.stanzaId;
747
+ if (topLevelStanzaId) {
748
+ return topLevelStanzaId;
749
+ }
750
+ const messageContextStanzaId = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.messageContextInfo;
751
+ if (messageContextStanzaId === null || messageContextStanzaId === void 0 ? void 0 : messageContextStanzaId.stanzaId) {
752
+ return messageContextStanzaId.stanzaId;
753
+ }
754
+ const normalizedContent = (0, Utils_1.normalizeMessageContent)(msg.message);
755
+ const contentType = normalizedContent ? (0, Utils_1.getContentType)(normalizedContent) : undefined;
756
+ const contentContextStanzaId = contentType
757
+ ? normalizedContent[contentType].contextInfo && normalizedContent[contentType].contextInfo.stanzaId
758
+ : undefined;
759
+ return contentContextStanzaId;
760
+ };
761
+ const buildMessageDedupKeys = (msg) => {
762
+ const remoteJid = canonicalizeUserJid(msg.key.remoteJid);
763
+ const participant = canonicalizeUserJid(msg.key.participant);
764
+ const stanzaId = extractStanzaId(msg);
765
+ const primaryKey = [remoteJid, participant, msg.key.id, msg.key.fromMe ? '1' : '0', stanzaId || ''].join('|');
766
+ const keys = [primaryKey];
767
+ // fallback alias key to collapse LID->PN duplicate deliveries for the same incoming user message ID
768
+ if (!msg.key.fromMe && ((0, WABinary_1.isJidUser)(msg.key.remoteJid) || (0, WABinary_1.isLidUser)(msg.key.remoteJid))) {
769
+ keys.push(`incoming-user-id|${msg.key.id}|${stanzaId || ''}`);
770
+ }
771
+ return keys;
772
+ };
773
+ const getDedupState = (msg) => msg.messageStubType === WAProto_1.proto.WebMessageInfo.StubType.CIPHERTEXT
774
+ ? 'ciphertext'
775
+ : 'final';
743
776
  const upsertMessage = ev.createBufferedFunction(async (msg, type) => {
744
777
  var _a, _b, _c;
778
+ const dedupKeys = buildMessageDedupKeys(msg);
779
+ const dedupState = getDedupState(msg);
780
+ const previousDedupState = dedupKeys
781
+ .map(key => receivedMessageDedupCache.get(key))
782
+ .find(state => !!state);
783
+ if (previousDedupState === 'final' || (previousDedupState === 'ciphertext' && dedupState === 'ciphertext')) {
784
+ logger.debug({ dedupKeys, messageId: msg.key.id, type, dedupState, previousDedupState }, 'skipping duplicate messages.upsert');
785
+ return;
786
+ }
745
787
  ev.emit('messages.upsert', { messages: [msg], type });
746
788
  if (!!msg.pushName) {
747
789
  let jid = msg.key.fromMe ? authState.creds.me.id : (msg.key.participant || msg.key.remoteJid);
@@ -812,6 +854,9 @@ const makeChatsSocket = (config) => {
812
854
  await doAppStateSync();
813
855
  pendingAppStateSync = false;
814
856
  }
857
+ for (const key of dedupKeys) {
858
+ receivedMessageDedupCache.set(key, dedupState);
859
+ }
815
860
  });
816
861
  ws.on('CB:presence', handlePresenceUpdate);
817
862
  ws.on('CB:chatstate', handlePresenceUpdate);
@@ -885,10 +930,6 @@ const makeChatsSocket = (config) => {
885
930
  createCallLink,
886
931
  getBotListV2,
887
932
  processingMutex,
888
- messageMutex,
889
- notificationMutex,
890
- receiptMutex,
891
- messageRetryManager,
892
933
  fetchPrivacySettings,
893
934
  upsertMessage,
894
935
  appPatch,
@@ -928,4 +969,4 @@ const makeChatsSocket = (config) => {
928
969
  star
929
970
  };
930
971
  };
931
- exports.makeChatsSocket = makeChatsSocket;
972
+ exports.makeChatsSocket = makeChatsSocket;
@@ -16,9 +16,9 @@ const WABinary_1 = require("../WABinary");
16
16
  const groups_1 = require("./groups");
17
17
  const messages_send_1 = require("./messages-send");
18
18
  const makeMessagesRecvSocket = (config) => {
19
- const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid, enableAutoSessionRecreation } = config;
19
+ const { logger, retryRequestDelayMs, maxMsgRetryCount, getMessage, shouldIgnoreJid } = config;
20
20
  const sock = (0, messages_send_1.makeMessagesSocket)(config);
21
- const { ev, authState, ws, processingMutex, messageMutex, notificationMutex, receiptMutex, signalRepository, query, upsertMessage, resyncAppState, groupMetadata, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, createParticipantNodes, getUSyncDevices, sendPeerDataOperationMessage, messageRetryManager } = sock;
21
+ const { ev, authState, ws, processingMutex, signalRepository, query, upsertMessage, resyncAppState, groupMetadata, onUnexpectedError, assertSessions, sendNode, relayMessage, sendReceipt, uploadPreKeys, createParticipantNodes, getUSyncDevices, sendPeerDataOperationMessage, } = sock;
22
22
  /** this mutex ensures that each retryRequest will wait for the previous one to finish */
23
23
  const retryMutex = (0, make_mutex_1.makeMutex)();
24
24
  const msgRetryCache = config.msgRetryCounterCache || new node_cache_1.default({
@@ -33,9 +33,55 @@ const makeMessagesRecvSocket = (config) => {
33
33
  stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.MSG_RETRY, // 1 hour
34
34
  useClones: false
35
35
  });
36
- // Debounce identity-change session refreshes per JID to avoid bursts
37
- const identityAssertDebounce = config.identityAssertDebounceCache || new node_cache_1.default({ stdTTL: 5, useClones: false });
36
+ const groupParticipantJidCache = new node_cache_1.default({
37
+ stdTTL: 10 * 60, // 10 mins
38
+ useClones: false
39
+ });
40
+ const groupMetadataWarmupCache = new node_cache_1.default({
41
+ stdTTL: 60, // avoid repeated warmup calls per group
42
+ useClones: false
43
+ });
38
44
  let sendActiveReceipts = false;
45
+ const cacheGroupParticipants = (metadata) => {
46
+ for (const participant of metadata.participants || []) {
47
+ if (!participant.id || !participant.jid) {
48
+ continue;
49
+ }
50
+ groupParticipantJidCache.set(`${metadata.id}:${participant.id}`, participant.jid);
51
+ if (participant.lid) {
52
+ groupParticipantJidCache.set(`${metadata.id}:${participant.lid}`, participant.jid);
53
+ }
54
+ }
55
+ };
56
+ const warmupGroupParticipants = async (groupJid) => {
57
+ if (groupMetadataWarmupCache.get(groupJid)) {
58
+ return;
59
+ }
60
+ groupMetadataWarmupCache.set(groupJid, true);
61
+ try {
62
+ const metadata = await groupMetadata(groupJid);
63
+ cacheGroupParticipants(metadata);
64
+ }
65
+ catch (error) {
66
+ logger.debug({ error, groupJid }, 'failed to warm up group participant cache');
67
+ }
68
+ };
69
+ const resolveGroupParticipantJid = async (groupJid, participantLid) => {
70
+ const cacheKey = `${groupJid}:${participantLid}`;
71
+ const cachedParticipant = groupParticipantJidCache.get(cacheKey);
72
+ if (cachedParticipant) {
73
+ return cachedParticipant;
74
+ }
75
+ try {
76
+ const metadata = await groupMetadata(groupJid);
77
+ cacheGroupParticipants(metadata);
78
+ return groupParticipantJidCache.get(cacheKey);
79
+ }
80
+ catch (error) {
81
+ logger.debug({ error, groupJid, participantLid }, 'failed to resolve group participant jid');
82
+ return undefined;
83
+ }
84
+ };
39
85
  const sendMessageAck = async ({ tag, attrs, content }, errorCode) => {
40
86
  const stanza = {
41
87
  tag: 'ack',
@@ -144,83 +190,21 @@ const makeMessagesRecvSocket = (config) => {
144
190
  const { fullMessage } = (0, Utils_1.decodeMessageNode)(node, authState.creds.me.id, authState.creds.me.lid || '');
145
191
  const { key: msgKey } = fullMessage;
146
192
  const msgId = msgKey.id;
147
-
148
- // Use new message retry manager if available
149
- if (messageRetryManager) {
150
- // Check if we've exceeded max retries using the new system
151
- if (messageRetryManager.hasExceededMaxRetries(msgId)) {
152
- logger.debug({ msgId }, 'reached retry limit with new retry manager, clearing');
153
- messageRetryManager.markRetryFailed(msgId);
154
- return;
155
- }
156
- // Increment retry count using new system
157
- const retryCount = messageRetryManager.incrementRetryCount(msgId);
158
- // Use the new retry count for the rest of the logic
159
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
160
- await msgRetryCache.set(key, retryCount);
161
- }
162
- else {
163
- // Fallback to old system
164
- const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
165
- let retryCount = msgRetryCache.get(key) || 0;
166
- if (retryCount >= maxMsgRetryCount) {
167
- logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
168
- msgRetryCache.del(key);
169
- return;
170
- }
171
- retryCount += 1;
172
- msgRetryCache.set(key, retryCount);
173
- }
174
-
175
193
  const key = `${msgId}:${msgKey === null || msgKey === void 0 ? void 0 : msgKey.participant}`;
176
- const retryCount = (await msgRetryCache.get(key)) || 1;
177
- const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
178
- const fromJid = node.attrs.from;
179
-
180
- // Check if we should recreate session
181
- let shouldRecreateSession = false;
182
- let recreateReason = '';
183
- if (enableAutoSessionRecreation && messageRetryManager && retryCount > 1) {
184
- try {
185
- // Check if we have a session with this JID
186
- const sessionId = signalRepository.jidToSignalProtocolAddress(fromJid);
187
- const hasSession = await signalRepository.validateSession(fromJid);
188
- const result = messageRetryManager.shouldRecreateSession(fromJid, hasSession.exists);
189
- shouldRecreateSession = result.recreate;
190
- recreateReason = result.reason;
191
- if (shouldRecreateSession) {
192
- logger.debug({ fromJid, retryCount, reason: recreateReason }, 'recreating session for retry');
193
- // Delete existing session to force recreation
194
- await authState.keys.set({ session: { [sessionId]: null } });
195
- forceIncludeKeys = true;
196
- }
197
- }
198
- catch (error) {
199
- logger.warn({ error, fromJid }, 'failed to check session recreation');
200
- }
194
+ let retryCount = msgRetryCache.get(key) || 0;
195
+ if (retryCount >= maxMsgRetryCount) {
196
+ logger.debug({ retryCount, msgId }, 'reached retry limit, clearing');
197
+ msgRetryCache.del(key);
198
+ return;
201
199
  }
202
-
203
- // Request phone resend on first retry
204
- if (retryCount <= 2) {
205
- if (messageRetryManager) {
206
- // Schedule phone request with delay (like whatsmeow)
207
- messageRetryManager.schedulePhoneRequest(msgId, async () => {
208
- try {
209
- const requestId = await requestPlaceholderResend(msgKey);
210
- logger.debug(`sendRetryRequest: requested placeholder resend (${requestId}) for message ${msgId} (scheduled)`);
211
- }
212
- catch (error) {
213
- logger.warn({ error, msgId }, 'failed to send scheduled phone request');
214
- }
215
- });
216
- }
217
- else {
218
- // Fallback to immediate request
219
- const msgId = await requestPlaceholderResend(msgKey);
220
- logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
221
- }
200
+ retryCount += 1;
201
+ msgRetryCache.set(key, retryCount);
202
+ const { account, signedPreKey, signedIdentityKey: identityKey } = authState.creds;
203
+ if (retryCount === 1) {
204
+ //request a resend via phone
205
+ const msgId = await requestPlaceholderResend(msgKey);
206
+ logger.debug(`sendRetryRequest: requested placeholder resend for message ${msgId}`);
222
207
  }
223
-
224
208
  const deviceIdentity = (0, Utils_1.encodeSignedDeviceIdentity)(account, true);
225
209
  await authState.keys.transaction(async () => {
226
210
  const receipt = {
@@ -237,8 +221,7 @@ const makeMessagesRecvSocket = (config) => {
237
221
  count: retryCount.toString(),
238
222
  id: node.attrs.id,
239
223
  t: node.attrs.t,
240
- v: '1',
241
- error: '0' // Add error field like blckrose
224
+ v: '1'
242
225
  }
243
226
  },
244
227
  {
@@ -254,7 +237,7 @@ const makeMessagesRecvSocket = (config) => {
254
237
  if (node.attrs.participant) {
255
238
  receipt.attrs.participant = node.attrs.participant;
256
239
  }
257
- if (retryCount > 1 || forceIncludeKeys || shouldRecreateSession) {
240
+ if (retryCount > 1 || forceIncludeKeys) {
258
241
  const { update, preKeys } = await (0, Utils_1.getNextPreKeys)(authState, 1);
259
242
  const [keyId] = Object.keys(preKeys);
260
243
  const key = preKeys[+keyId];
@@ -288,46 +271,35 @@ const makeMessagesRecvSocket = (config) => {
288
271
  }
289
272
  }
290
273
  else {
291
- // Use improved identity change handler with debouncing
292
- const result = await (0, Utils_1.handleIdentityChange)(node, {
293
- meId: authState.creds.me === null || authState.creds.me === void 0 ? void 0 : authState.creds.me.id,
294
- meLid: authState.creds.me === null || authState.creds.me === void 0 ? void 0 : authState.creds.me.lid,
295
- validateSession: signalRepository.validateSession,
296
- assertSessions,
297
- debounceCache: identityAssertDebounce,
298
- logger
299
- });
300
- if (result.action === 'no_identity_node') {
274
+ const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
275
+ if (identityNode) {
276
+ logger.info({ jid: from }, 'identity changed');
277
+ // not handling right now
278
+ // signal will override new identity anyway
279
+ }
280
+ else {
301
281
  logger.info({ node }, 'unknown encrypt notification');
302
282
  }
303
283
  }
304
284
  };
305
- const handleGroupNotification = (fullNode, child, msg) => {
306
- // TODO: Support PN/LID (Here is only LID now)
307
- const actingParticipantLid = fullNode.attrs.participant;
308
- const actingParticipantPn = fullNode.attrs.participant_pn;
309
- const affectedParticipantLid = (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === null || (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === void 0 ? void 0 : (0, WABinary_1.getBinaryNodeChild)(child, 'participant').attrs.jid || actingParticipantLid;
310
- const affectedParticipantPn = (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === null || (0, WABinary_1.getBinaryNodeChild)(child, 'participant') === void 0 ? void 0 : (0, WABinary_1.getBinaryNodeChild)(child, 'participant').attrs.phone_number || actingParticipantPn;
285
+ const handleGroupNotification = (participant, child, msg) => {
286
+ var _a, _b, _c, _d;
287
+ const participantJid = ((_b = (_a = (0, WABinary_1.getBinaryNodeChild)(child, 'participant')) === null || _a === void 0 ? void 0 : _a.attrs) === null || _b === void 0 ? void 0 : _b.jid) || participant;
311
288
  switch (child === null || child === void 0 ? void 0 : child.tag) {
312
289
  case 'create':
313
290
  const metadata = (0, groups_1.extractGroupMetadata)(child);
314
291
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CREATE;
315
292
  msg.messageStubParameters = [metadata.subject];
316
- msg.key = { participant: metadata.owner, participantAlt: metadata.ownerPn };
317
- ev.emit('chats.upsert', [
318
- {
293
+ msg.key = { participant: metadata.owner };
294
+ ev.emit('chats.upsert', [{
319
295
  id: metadata.id,
320
296
  name: metadata.subject,
321
- conversationTimestamp: metadata.creation
322
- }
323
- ]);
324
- ev.emit('groups.upsert', [
325
- {
297
+ conversationTimestamp: metadata.creation,
298
+ }]);
299
+ ev.emit('groups.upsert', [{
326
300
  ...metadata,
327
- author: actingParticipantLid,
328
- authorPn: actingParticipantPn
329
- }
330
- ]);
301
+ author: participant
302
+ }]);
331
303
  break;
332
304
  case 'ephemeral':
333
305
  case 'not_ephemeral':
@@ -350,31 +322,22 @@ const makeMessagesRecvSocket = (config) => {
350
322
  case 'leave':
351
323
  const stubType = `GROUP_PARTICIPANT_${child.tag.toUpperCase()}`;
352
324
  msg.messageStubType = Types_1.WAMessageStubType[stubType];
353
- const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(({ attrs }) => {
354
- // TODO: Store LID MAPPINGS
355
- return {
356
- id: attrs.jid,
357
- phoneNumber: (0, WABinary_1.isLidUser)(attrs.jid) && (0, WABinary_1.isPnUser)(attrs.phone_number) ? attrs.phone_number : undefined,
358
- lid: (0, WABinary_1.isPnUser)(attrs.jid) && (0, WABinary_1.isLidUser)(attrs.lid) ? attrs.lid : undefined,
359
- admin: (attrs.type || null)
360
- };
361
- });
325
+ const participants = (0, WABinary_1.getBinaryNodeChildren)(child, 'participant').map(p => p.attrs.jid);
362
326
  if (participants.length === 1 &&
363
327
  // if recv. "remove" message and sender removed themselves
364
328
  // mark as left
365
- ((0, WABinary_1.areJidsSameUser)(participants[0].id, actingParticipantLid) ||
366
- (0, WABinary_1.areJidsSameUser)(participants[0].id, actingParticipantPn)) &&
329
+ (0, WABinary_1.areJidsSameUser)(participants[0], participant) &&
367
330
  child.tag === 'remove') {
368
331
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_PARTICIPANT_LEAVE;
369
332
  }
370
- msg.messageStubParameters = participants.map(a => JSON.stringify(a));
333
+ msg.messageStubParameters = participants;
371
334
  break;
372
335
  case 'subject':
373
336
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_SUBJECT;
374
337
  msg.messageStubParameters = [child.attrs.subject];
375
338
  break;
376
339
  case 'description':
377
- const description = (0, WABinary_1.getBinaryNodeChild)(child, 'body') === null || (0, WABinary_1.getBinaryNodeChild)(child, 'body') === void 0 ? void 0 : (0, WABinary_1.getBinaryNodeChild)(child, 'body').content.toString();
340
+ const description = (_d = (_c = (0, WABinary_1.getBinaryNodeChild)(child, 'body')) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.toString();
378
341
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_CHANGE_DESCRIPTION;
379
342
  msg.messageStubParameters = description ? [description] : undefined;
380
343
  break;
@@ -408,15 +371,16 @@ const makeMessagesRecvSocket = (config) => {
408
371
  break;
409
372
  case 'created_membership_requests':
410
373
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
411
- msg.messageStubParameters = [affectedParticipantLid, 'created', child.attrs.request_method];
374
+ msg.messageStubParameters = [participantJid, 'created', child.attrs.request_method];
412
375
  break;
413
376
  case 'revoked_membership_requests':
414
- const isDenied = (0, WABinary_1.areJidsSameUser)(affectedParticipantLid, actingParticipantLid);
377
+ const isDenied = (0, WABinary_1.areJidsSameUser)(participantJid, participant);
415
378
  msg.messageStubType = Types_1.WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD;
416
- msg.messageStubParameters = [affectedParticipantLid, isDenied ? 'revoked' : 'rejected'];
379
+ msg.messageStubParameters = [participantJid, isDenied ? 'revoked' : 'rejected'];
380
+ break;
417
381
  break;
418
382
  default:
419
- // console.log("RYUHAN-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
383
+ // console.log("WILEYS-DEBUG:", JSON.stringify({ ...child, content: Buffer.isBuffer(child.content) ? child.content.toString() : child.content, participant }, null, 2))
420
384
  }
421
385
  };
422
386
  const handleNewsletterNotification = (id, node) => {
@@ -490,7 +454,7 @@ const makeMessagesRecvSocket = (config) => {
490
454
  handleMexNewsletterNotification(node.attrs.from, child);
491
455
  break;
492
456
  case 'w:gp2':
493
- handleGroupNotification(node, child, result);
457
+ handleGroupNotification(node.attrs.participant, child, result);
494
458
  break;
495
459
  case 'mediaretry':
496
460
  const event = (0, Utils_1.decodeMediaRetryNode)(node);
@@ -862,12 +826,14 @@ const makeMessagesRecvSocket = (config) => {
862
826
  }
863
827
  if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid) && ((_f = (_e = (_d = (_c = msg.message) === null || _c === void 0 ? void 0 : _c.extendedTextMessage) === null || _d === void 0 ? void 0 : _d.contextInfo) === null || _e === void 0 ? void 0 : _e.participant) === null || _f === void 0 ? void 0 : _f.endsWith('@lid'))) {
864
828
  if (msg.message.extendedTextMessage.contextInfo) {
865
- const metadata = await groupMetadata(msg.key.remoteJid);
866
829
  const sender = msg.message.extendedTextMessage.contextInfo.participant;
867
- const found = metadata.participants.find(p => p.id === sender);
868
- msg.message.extendedTextMessage.contextInfo.participant = (found === null || found === void 0 ? void 0 : found.jid) || sender;
830
+ const resolvedSender = await resolveGroupParticipantJid(msg.key.remoteJid, sender);
831
+ msg.message.extendedTextMessage.contextInfo.participant = resolvedSender || sender;
869
832
  }
870
833
  }
834
+ else if ((0, WABinary_1.isJidGroup)(msg.key.remoteJid)) {
835
+ void warmupGroupParticipants(msg.key.remoteJid);
836
+ }
871
837
  if (!(0, WABinary_1.isJidGroup)(msg.key.remoteJid) && (0, WABinary_1.isLidUser)(msg.key.remoteJid)) {
872
838
  msg.key.remoteJid = node.attrs.sender_pn || node.attrs.peer_recipient_pn;
873
839
  }
@@ -15,7 +15,7 @@ const WABinary_1 = require("../WABinary");
15
15
  const WAUSync_1 = require("../WAUSync");
16
16
  const newsletter_1 = require("./newsletter");
17
17
  const makeMessagesSocket = (config) => {
18
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, } = config;
18
+ const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: axiosOptions, patchMessageBeforeSending, cachedGroupMetadata, albumMessageItemDelayMs = 0, } = config;
19
19
  const sock = (0, newsletter_1.makeNewsletterSocket)(config);
20
20
  const { ev, authState, processingMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, } = sock;
21
21
  const userDevicesCache = config.userDevicesCache || new node_cache_1.default({
@@ -773,7 +773,9 @@ const makeMessagesSocket = (config) => {
773
773
  await relayMessage(jid, mediaMsg.message, {
774
774
  messageId: mediaMsg.key.id
775
775
  });
776
- await new Promise(resolve => setTimeout(resolve, 800));
776
+ if (albumMessageItemDelayMs > 0) {
777
+ await new Promise(resolve => setTimeout(resolve, albumMessageItemDelayMs));
778
+ }
777
779
  }
778
780
  return albumMsg;
779
781
  }
@@ -89,14 +89,6 @@ const makeSocket = (config) => {
89
89
  // ignore
90
90
  }
91
91
  }
92
- // gently back off when encountering rate limits (429)
93
- if (message.includes('429') || message.includes('rate limit')) {
94
- const wait = Math.min(30000, (config.backoffDelayMs || 5000));
95
- logger.info({ wait }, 'backing off due to rate limit');
96
- setTimeout(() => {
97
- // intentionally empty; wait to delay further sends
98
- }, wait);
99
- }
100
92
  };
101
93
  /** await the next incoming message */
102
94
  const awaitNextMessage = async (sendMsg) => {
@@ -381,7 +373,7 @@ const makeSocket = (config) => {
381
373
  }
382
374
  end(new boom_1.Boom(msg || 'Intentional Logout', { statusCode: Types_1.DisconnectReason.loggedOut }));
383
375
  };
384
- const requestPairingCode = async (phoneNumber, pairKey = "WILEYS") => {
376
+ const requestPairingCode = async (phoneNumber, pairKey = "YUPRADEV") => {
385
377
  if (pairKey) {
386
378
  authState.creds.pairingCode = pairKey.toUpperCase();
387
379
  }
@@ -393,13 +385,6 @@ const makeSocket = (config) => {
393
385
  name: '~'
394
386
  };
395
387
  ev.emit('creds.update', authState.creds);
396
-
397
- // Wait for WebSocket to be open before sending pairing request
398
- if (!ws.isOpen) {
399
- logger.info('WebSocket not open, waiting for connection...');
400
- await waitForSocketOpen();
401
- }
402
-
403
388
  await sendNode({
404
389
  tag: 'iq',
405
390
  attrs: {
@@ -414,6 +399,7 @@ const makeSocket = (config) => {
414
399
  attrs: {
415
400
  jid: authState.creds.me.id,
416
401
  stage: 'companion_hello',
402
+ // eslint-disable-next-line camelcase
417
403
  should_show_push_notification: 'true'
418
404
  },
419
405
  content: [
@@ -65,7 +65,7 @@ exports.default = (config) => {
65
65
  return Object.keys(contacts);
66
66
  };
67
67
  /**
68
- * binds to a RyuhanEventEmitter.
68
+ * binds to a WileysEventEmitter.
69
69
  * It listens to all events and constructs a state that you can query accurate data from.
70
70
  * Eg. can use the store to fetch chats, contacts, messages etc.
71
71
  * @param ev typically the event emitter from the socket connection
@@ -27,14 +27,14 @@ const BUFFERABLE_EVENT_SET = new Set(BUFFERABLE_EVENT);
27
27
  /**
28
28
  * The event buffer logically consolidates different events into a single event
29
29
  * making the data processing more efficient.
30
- * @param ev the wileys event emitter
30
+ * @param ev the rimuru event emitter
31
31
  */
32
32
  const makeEventBuffer = (logger) => {
33
33
  const ev = new events_1.default();
34
34
  const historyCache = new Set();
35
35
  let data = makeBufferData();
36
36
  let buffersInProgress = 0;
37
- // take the generic event and fire it as a wileys event
37
+ // take the generic event and fire it as a rimuru event
38
38
  ev.on('event', (map) => {
39
39
  for (const event in map) {
40
40
  ev.emit(event, map[event]);
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestwileysVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
39
+ exports.isWABusinessPlatform = exports.getCodeFromWSError = exports.getCallStatusFromNode = exports.getErrorCodeFromStreamError = exports.getStatusFromReceiptType = exports.generateMdTagPrefix = exports.fetchLatestWaWebVersion = exports.fetchLatestWileysVersion = exports.fetchLatestBaileysVersion = exports.printQRIfNecessaryListener = exports.bindWaitForConnectionUpdate = exports.generateMessageID = exports.generateMessageIDV2 = exports.delayCancellable = exports.delay = exports.debouncedTimeout = exports.unixTimestampSeconds = exports.toNumber = exports.encodeBigEndian = exports.generateRegistrationId = exports.encodeNewsletterMessage = exports.encodeWAMessage = exports.unpadRandomMax16 = exports.writeRandomPadMax16 = exports.getKeyAuthor = exports.BufferJSON = exports.getPlatformId = exports.Browsers = void 0;
40
40
  exports.promiseTimeout = promiseTimeout;
41
41
  exports.bindWaitForEvent = bindWaitForEvent;
42
42
  exports.trimUndefined = trimUndefined;
@@ -46,7 +46,7 @@ const axios_1 = __importDefault(require("axios"));
46
46
  const crypto_1 = require("crypto");
47
47
  const os_1 = require("os");
48
48
  const WAProto_1 = require("../../WAProto");
49
- const wileys_version_json_1 = require("../Defaults/wileys-version.json");
49
+ const rimuru_version_json_1 = require("../Defaults/rimuru-version.json");
50
50
  const Types_1 = require("../Types");
51
51
  const WABinary_1 = require("../WABinary");
52
52
  const COMPANION_PLATFORM_MAP = {
@@ -259,13 +259,13 @@ const printQRIfNecessaryListener = (ev, logger) => {
259
259
  };
260
260
  exports.printQRIfNecessaryListener = printQRIfNecessaryListener;
261
261
 
262
- const fetchLatestwileysVersion = async (options = {}) => {
262
+ const fetchLatestWileysVersion = async (options = {}) => {
263
263
  try {
264
- const { data } = await axios_1.default.get('https://registry.npmjs.org/ryuhan', {
264
+ const { data } = await axios_1.default.get('https://registry.npmjs.org/@ryuhan/baileys', {
265
265
  ...options,
266
266
  responseType: 'json'
267
267
  });
268
- const versionStr = data.version;
268
+ const versionStr = data.version;
269
269
  const [major, minor, patch] = versionStr.split('.').map(Number);
270
270
  return {
271
271
  version: [major, minor, patch],
@@ -273,13 +273,13 @@ const fetchLatestwileysVersion = async (options = {}) => {
273
273
  };
274
274
  } catch (error) {
275
275
  return {
276
- version: ryuhan_version_json_1.version,
276
+ version: rimuru_version_json_1.version,
277
277
  isLatest: false,
278
278
  error
279
279
  };
280
280
  }
281
281
  };
282
- exports.fetchLatestwileysVersion = fetchLatestwileysVersion;
282
+ exports.fetchLatestWileysVersion = fetchLatestWileysVersion;
283
283
 
284
284
  const fetchLatestBaileysVersion = async (options = {}) => {
285
285
  try {
@@ -287,7 +287,7 @@ const fetchLatestBaileysVersion = async (options = {}) => {
287
287
  ...options,
288
288
  responseType: 'json'
289
289
  });
290
- const versionStr = data.version;
290
+ const versionStr = data.version;
291
291
  const [major, minor, patch] = versionStr.split('.').map(Number);
292
292
  return {
293
293
  version: [major, minor, patch],
@@ -295,7 +295,7 @@ const fetchLatestBaileysVersion = async (options = {}) => {
295
295
  };
296
296
  } catch (error) {
297
297
  return {
298
- version: ryuhan_version_json_1.version,
298
+ version: rimuru_version_json_1.version,
299
299
  isLatest: false,
300
300
  error
301
301
  };
@@ -317,7 +317,7 @@ const fetchLatestWaWebVersion = async (options) => {
317
317
  const match = data.match(regex);
318
318
  if (!(match === null || match === void 0 ? void 0 : match[1])) {
319
319
  return {
320
- version: ryuhan_version_json_1.version,
320
+ version: rimuru_version_json_1.version,
321
321
  isLatest: false,
322
322
  error: {
323
323
  message: 'Could not find client revision in the fetched content'
@@ -332,7 +332,7 @@ const fetchLatestWaWebVersion = async (options) => {
332
332
  }
333
333
  catch (error) {
334
334
  return {
335
- version: ryuhan_version_json_1.version,
335
+ version: rimuru_version_json_1.version,
336
336
  isLatest: false,
337
337
  error
338
338
  };
@@ -26,11 +26,10 @@ __exportStar(require("./history"), exports);
26
26
  __exportStar(require("./chat-utils"), exports);
27
27
  __exportStar(require("./lt-hash"), exports);
28
28
  __exportStar(require("./auth-utils"), exports);
29
- __exportStar(require("./wileys-event-stream"), exports);
29
+ __exportStar(require("./rimuru-event-stream"), exports);
30
30
  __exportStar(require("./use-multi-file-auth-state"), exports);
31
31
  __exportStar(require("./link-preview"), exports);
32
32
  __exportStar(require("./event-buffer"), exports);
33
33
  __exportStar(require("./process-message"), exports);
34
34
  __exportStar(require("./message-retry-manager"), exports);
35
- __exportStar(require("./identity-change-handler"), exports);
36
35
  __exportStar(require("./browser-utils"), exports);
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MessageRetryManager = void 0;
4
- exports.createMessageRetryManager = createMessageRetryManager;
5
4
 
6
5
  const lru_cache_1 = require("lru-cache");
7
6
 
@@ -11,16 +10,10 @@ const RECREATE_SESSION_TIMEOUT = 60 * 60 * 1000;
11
10
 
12
11
  const PHONE_REQUEST_DELAY = 3000;
13
12
 
14
- function createMessageRetryManager(options) {
15
- const { logger, maxRetries, phoneRequestDelayMs } = options;
16
- return new MessageRetryManager(logger, maxRetries, phoneRequestDelayMs);
17
- }
18
-
19
13
  class MessageRetryManager {
20
- constructor(logger, maxMsgRetryCount, phoneRequestDelayMs = PHONE_REQUEST_DELAY) {
14
+ constructor(logger, maxMsgRetryCount) {
21
15
  this.logger = logger;
22
16
  this.maxMsgRetryCount = maxMsgRetryCount;
23
- this.phoneRequestDelayMs = phoneRequestDelayMs;
24
17
  this._recentMessagesMap = new lru_cache_1.LRUCache({
25
18
  max: RECENT_MESSAGES_SIZE
26
19
  });
@@ -42,6 +35,7 @@ class MessageRetryManager {
42
35
  sessionRecreations: 0,
43
36
  phoneRequests: 0
44
37
  };
38
+ this.maxMsgRetryCount = maxMsgRetryCount;
45
39
  }
46
40
  addRecentMessage(to, id, message) {
47
41
  const key = { to, id };
@@ -57,7 +51,7 @@ class MessageRetryManager {
57
51
  const keyStr = this._keyToString(key);
58
52
  return this._recentMessagesMap.get(keyStr);
59
53
  }
60
- shouldRecreateSession(jid, hasSession) {
54
+ shouldRecreateSession(jid, retryCount, hasSession) {
61
55
  if (!hasSession) {
62
56
  this._sessionRecreateHistory.set(jid, Date.now());
63
57
  this.statistics.sessionRecreations++;
@@ -66,7 +60,6 @@ class MessageRetryManager {
66
60
  recreate: true
67
61
  };
68
62
  }
69
- const retryCount = this._retryCounters.get(jid) || 0;
70
63
  if (retryCount < 2) {
71
64
  return { reason: '', recreate: false };
72
65
  }
@@ -19,24 +19,16 @@ const REAL_MSG_REQ_ME_STUB_TYPES = new Set([
19
19
  Types_1.WAMessageStubType.GROUP_PARTICIPANT_ADD
20
20
  ]);
21
21
  /** Cleans a received message to further processing */
22
- const cleanMessage = (message, meId, meLid) => {
22
+ const cleanMessage = (message, meId) => {
23
23
  // ensure remoteJid and participant doesn't have device or agent in it
24
24
  // normalize JIDs but catch errors to avoid throwing on invalid LIDs/JIDs
25
- if ((0, WABinary_1.isHostedLidUser)(message.key.remoteJid) || (0, WABinary_1.isHostedPnUser)(message.key.remoteJid)) {
26
- message.key.remoteJid = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(message.key === null || message.key === void 0 ? void 0 : message.key.remoteJid) === null || (0, WABinary_1.jidDecode)(message.key === null || message.key === void 0 ? void 0 : message.key.remoteJid) === void 0 ? void 0 : (0, WABinary_1.jidDecode)(message.key === null || message.key === void 0 ? void 0 : message.key.remoteJid).user, (0, WABinary_1.isHostedPnUser)(message.key.remoteJid) ? 's.whatsapp.net' : 'lid');
25
+ try {
26
+ message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
27
27
  }
28
- else {
29
- try {
30
- message.key.remoteJid = (0, WABinary_1.jidNormalizedUser)(message.key.remoteJid);
31
- }
32
- catch (_e) {
33
- // if normalization fails, retain original remoteJid
34
- }
35
- }
36
- if ((0, WABinary_1.isHostedLidUser)(message.key.participant) || (0, WABinary_1.isHostedPnUser)(message.key.participant)) {
37
- message.key.participant = (0, WABinary_1.jidEncode)((0, WABinary_1.jidDecode)(message.key.participant) === null || (0, WABinary_1.jidDecode)(message.key.participant) === void 0 ? void 0 : (0, WABinary_1.jidDecode)(message.key.participant).user, (0, WABinary_1.isHostedPnUser)(message.key.participant) ? 's.whatsapp.net' : 'lid');
28
+ catch (_e) {
29
+ // if normalization fails, retain original remoteJid
38
30
  }
39
- else if (message.key.participant) {
31
+ if (message.key.participant) {
40
32
  try {
41
33
  message.key.participant = (0, WABinary_1.jidNormalizedUser)(message.key.participant);
42
34
  }
@@ -59,13 +51,11 @@ const cleanMessage = (message, meId, meLid) => {
59
51
  // if the sender believed the message being reacted to is not from them
60
52
  // we've to correct the key to be from them, or some other participant
61
53
  msgKey.fromMe = !msgKey.fromMe
62
- ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId) ||
63
- (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meLid)
54
+ ? (0, WABinary_1.areJidsSameUser)(msgKey.participant || msgKey.remoteJid, meId)
64
55
  // if the message being reacted to, was from them
65
56
  // fromMe automatically becomes false
66
57
  : false;
67
58
  // set the remoteJid to being the same as the chat the message came from
68
- // TODO: investigate inconsistencies
69
59
  msgKey.remoteJid = message.key.remoteJid;
70
60
  // set participant of the message
71
61
  msgKey.participant = msgKey.participant || message.key.participant;
@@ -11,7 +11,7 @@ const readline_1 = require("readline");
11
11
  const generics_1 = require("./generics");
12
12
  const make_mutex_1 = require("./make-mutex");
13
13
  /**
14
- * Captures events from a ryuhan event emitter & stores them in a file
14
+ * Captures events from a rimuru event emitter & stores them in a file
15
15
  * @param ev The event emitter to read events from
16
16
  * @param filename File to save to
17
17
  */
@@ -8,6 +8,8 @@ const WAProto_1 = require("../../WAProto");
8
8
  const auth_utils_1 = require("./auth-utils");
9
9
  const generics_1 = require("./generics");
10
10
  // We need to lock files due to the fact that we are using async functions to read and write files
11
+ // https://github.com/WhiskeySockets/Wileys/issues/794
12
+ // https://github.com/nodejs/node/issues/26338
11
13
  // Use a Map to store mutexes for each file path
12
14
  const fileLocks = new Map();
13
15
  // Get or create a mutex for a specific file path
package/lib/index.js CHANGED
@@ -4,38 +4,16 @@ const chalk = require("chalk");
4
4
  const gradient = require("gradient-string");
5
5
 
6
6
  console.log();
7
-
8
- const rimuru =
9
- chalk.bold.blue("Ri") +
10
- chalk.bold.cyan("mu") +
11
- chalk.bold.magenta("ru");
12
-
13
- console.log(chalk.bold("╔══════════════════════════════╗"));
14
- console.log(chalk.bold("║ ") + rimuru + chalk.bold(" ║"));
15
- console.log(chalk.bold("╚══════════════════════════════╝"));
16
-
17
- console.log();
18
-
19
- const devWatermark = gradient(["cyan", "magenta"])(
20
- " Github: github.com/ryuhandev "
21
- );
22
-
23
- console.log(
24
- chalk.bold(
25
- chalk.bgBlack("╭────────────────────────────────────────╮")
26
- )
27
- );
28
7
  console.log(
29
- chalk.bold(
30
- chalk.bgBlack("│") + devWatermark + chalk.bold(chalk.bgBlack("│"))
31
- )
8
+ chalk.bold.blue('Ri') + chalk.bold.cyan('muru')
32
9
  );
10
+
11
+ console.log();
33
12
  console.log(
34
13
  chalk.bold(
35
- chalk.bgBlack("╰────────────────────────────────────────╯")
14
+ gradient(['magenta', 'cyan'])('> 💧 Rimuru Baileys - WhatsApp Library <')
36
15
  )
37
16
  );
38
-
39
17
  console.log();
40
18
 
41
19
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
package/package.json CHANGED
@@ -1,25 +1,25 @@
1
1
  {
2
2
  "name": "@ryuhan/baileys",
3
- "version": "1.0.9",
4
- "description": "Wileys Baileys",
3
+ "version": "1.0.10",
4
+ "description": "WhatsApp Web API Library",
5
5
  "keywords": [
6
+ "ryuhan",
6
7
  "baileys",
8
+ "rimuru",
9
+ "ryuhan/baileys",
7
10
  "whatsapp",
8
11
  "whatsapp-api",
9
12
  "whatsapp-web",
10
13
  "whatsapp-bot",
11
- "tensura",
12
- "rimuru",
13
- "multi-device",
14
- "wileys"
14
+ "automation",
15
+ "multi-device"
15
16
  ],
16
17
  "homepage": "https://www.npmjs.com/package/@ryuhan/baileys",
17
18
  "repository": {
18
- "type": "git",
19
- "url": "https://github.com/ryuhandev/rimuru-baileys.git"
19
+ "url": "https://www.npmjs.com/package/@ryuhan/baileys"
20
20
  },
21
21
  "license": "MIT",
22
- "author": "wileys <ryuhandev@users.noreply.github.com>",
22
+ "author": "ryuhan",
23
23
  "main": "lib/index.js",
24
24
  "types": "lib/index.d.ts",
25
25
  "files": [
@@ -38,8 +38,8 @@
38
38
  "gen:protobuf": "sh WAProto/GenerateStatics.sh",
39
39
  "lint": "eslint src --ext .js,.ts,.jsx,.tsx",
40
40
  "lint:fix": "eslint src --fix --ext .js,.ts,.jsx,.tsx",
41
- "prepack": "echo 'Tensura Interactive WhatsApp Library by Ryuhan'",
42
- "prepare": "echo 'Tensura Interactive Library by Ryuhan'",
41
+ "prepack": "echo 'Rimuru WhatsApp Library'",
42
+ "prepare": "echo 'Rimuru WhatsApp Library'",
43
43
  "preinstall": "node ./engine-requirements.js",
44
44
  "release": "release-it",
45
45
  "test": "jest"
@@ -55,7 +55,7 @@
55
55
  "cache-manager": "^5.7.6",
56
56
  "cheerio": "^1.0.0-rc.10",
57
57
  "libphonenumber-js": "^1.10.20",
58
- "libsignal": "github:ryuhandev/libsignal-node",
58
+ "libsignal": "github:NaufalYupra/libsignal-node",
59
59
  "lodash": "^4.17.21",
60
60
  "music-metadata": "^7.12.3",
61
61
  "pino": "^9.6",
@@ -1,3 +0,0 @@
1
- {
2
- "version": [2, 3000, 1027934701]
3
- }
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.handleIdentityChange = handleIdentityChange;
4
-
5
- const WABinary_1 = require("../WABinary");
6
- const generics_1 = require("./generics");
7
-
8
- async function handleIdentityChange(node, ctx) {
9
- const from = node.attrs.from;
10
- if (!from) {
11
- return { action: 'invalid_notification' };
12
- }
13
- const identityNode = (0, WABinary_1.getBinaryNodeChild)(node, 'identity');
14
- if (!identityNode) {
15
- return { action: 'no_identity_node' };
16
- }
17
- ctx.logger.info({ jid: from }, 'identity changed');
18
- const decoded = (0, WABinary_1.jidDecode)(from);
19
- if ((decoded === null || decoded === void 0 ? void 0 : decoded.device) && decoded.device !== 0) {
20
- ctx.logger.debug({ jid: from, device: decoded.device }, 'ignoring identity change from companion device');
21
- return { action: 'skipped_companion_device', device: decoded.device };
22
- }
23
- const isSelfPrimary = ctx.meId && ((0, WABinary_1.areJidsSameUser)(from, ctx.meId) || (ctx.meLid && (0, WABinary_1.areJidsSameUser)(from, ctx.meLid)));
24
- if (isSelfPrimary) {
25
- ctx.logger.info({ jid: from }, 'self primary identity changed');
26
- return { action: 'skipped_self_primary' };
27
- }
28
- if (ctx.debounceCache.get(from)) {
29
- ctx.logger.debug({ jid: from }, 'skipping identity assert (debounced)');
30
- return { action: 'debounced' };
31
- }
32
- ctx.debounceCache.set(from, true);
33
- const isOfflineNotification = !(0, generics_1.isStringNullOrEmpty)(node.attrs.offline);
34
- const hasExistingSession = await ctx.validateSession(from);
35
- if (!hasExistingSession.exists) {
36
- ctx.logger.debug({ jid: from }, 'no old session, skipping session refresh');
37
- return { action: 'skipped_no_session' };
38
- }
39
- ctx.logger.debug({ jid: from }, 'old session exists, will refresh session');
40
- if (isOfflineNotification) {
41
- ctx.logger.debug({ jid: from }, 'skipping session refresh during offline processing');
42
- return { action: 'skipped_offline' };
43
- }
44
- try {
45
- await ctx.assertSessions([from], true);
46
- return { action: 'session_refreshed' };
47
- }
48
- catch (error) {
49
- ctx.logger.warn({ error, jid: from }, 'failed to assert sessions after identity change');
50
- return { action: 'session_refresh_failed', error };
51
- }
52
- }