@than-xs/baileys 2.0.3

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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +422 -0
  3. package/WAProto/index.js +169661 -0
  4. package/engine-requirements.js +10 -0
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.js +147 -0
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.js +15 -0
  9. package/lib/Signal/Group/group-session-builder.js +64 -0
  10. package/lib/Signal/Group/group_cipher.js +96 -0
  11. package/lib/Signal/Group/index.js +57 -0
  12. package/lib/Signal/Group/keyhelper.js +55 -0
  13. package/lib/Signal/Group/queue-job.js +57 -0
  14. package/lib/Signal/Group/sender-chain-key.js +34 -0
  15. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  16. package/lib/Signal/Group/sender-key-message.js +69 -0
  17. package/lib/Signal/Group/sender-key-name.js +51 -0
  18. package/lib/Signal/Group/sender-key-record.js +53 -0
  19. package/lib/Signal/Group/sender-key-state.js +99 -0
  20. package/lib/Signal/Group/sender-message-key.js +29 -0
  21. package/lib/Signal/libsignal.js +174 -0
  22. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  23. package/lib/Socket/Client/index.js +19 -0
  24. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  25. package/lib/Socket/Client/web-socket-client.js +62 -0
  26. package/lib/Socket/business.js +260 -0
  27. package/lib/Socket/chats.js +1002 -0
  28. package/lib/Socket/dugong.js +637 -0
  29. package/lib/Socket/groups.js +317 -0
  30. package/lib/Socket/index.js +11 -0
  31. package/lib/Socket/messages-recv.js +1110 -0
  32. package/lib/Socket/messages-send.js +831 -0
  33. package/lib/Socket/newsletter.js +459 -0
  34. package/lib/Socket/registration.js +166 -0
  35. package/lib/Socket/socket.js +662 -0
  36. package/lib/Socket/usync.js +70 -0
  37. package/lib/Store/index.js +10 -0
  38. package/lib/Store/make-cache-manager-store.js +83 -0
  39. package/lib/Store/make-in-memory-store.js +427 -0
  40. package/lib/Store/make-ordered-dictionary.js +81 -0
  41. package/lib/Store/object-repository.js +27 -0
  42. package/lib/Types/Auth.js +2 -0
  43. package/lib/Types/Call.js +2 -0
  44. package/lib/Types/Chat.js +4 -0
  45. package/lib/Types/Contact.js +2 -0
  46. package/lib/Types/Events.js +2 -0
  47. package/lib/Types/GroupMetadata.js +2 -0
  48. package/lib/Types/Label.js +27 -0
  49. package/lib/Types/LabelAssociation.js +9 -0
  50. package/lib/Types/Message.js +9 -0
  51. package/lib/Types/Newsletter.js +38 -0
  52. package/lib/Types/Product.js +2 -0
  53. package/lib/Types/Signal.js +2 -0
  54. package/lib/Types/Socket.js +2 -0
  55. package/lib/Types/State.js +2 -0
  56. package/lib/Types/USync.js +2 -0
  57. package/lib/Types/index.js +42 -0
  58. package/lib/Utils/auth-utils.js +206 -0
  59. package/lib/Utils/baileys-event-stream.js +63 -0
  60. package/lib/Utils/business.js +234 -0
  61. package/lib/Utils/chat-utils.js +729 -0
  62. package/lib/Utils/crypto.js +151 -0
  63. package/lib/Utils/decode-wa-message.js +198 -0
  64. package/lib/Utils/event-buffer.js +514 -0
  65. package/lib/Utils/generics.js +498 -0
  66. package/lib/Utils/history.js +96 -0
  67. package/lib/Utils/index.js +33 -0
  68. package/lib/Utils/link-preview.js +93 -0
  69. package/lib/Utils/logger.js +7 -0
  70. package/lib/Utils/lt-hash.js +51 -0
  71. package/lib/Utils/make-mutex.js +43 -0
  72. package/lib/Utils/messages-media.js +819 -0
  73. package/lib/Utils/messages.js +819 -0
  74. package/lib/Utils/noise-handler.js +155 -0
  75. package/lib/Utils/process-message.js +321 -0
  76. package/lib/Utils/signal.js +153 -0
  77. package/lib/Utils/use-multi-file-auth-state.js +119 -0
  78. package/lib/Utils/validate-connection.js +229 -0
  79. package/lib/WABinary/constants.js +40 -0
  80. package/lib/WABinary/decode.js +252 -0
  81. package/lib/WABinary/encode.js +265 -0
  82. package/lib/WABinary/generic-utils.js +198 -0
  83. package/lib/WABinary/index.js +21 -0
  84. package/lib/WABinary/jid-utils.js +62 -0
  85. package/lib/WABinary/types.js +2 -0
  86. package/lib/WAM/BinaryInfo.js +13 -0
  87. package/lib/WAM/constants.js +15350 -0
  88. package/lib/WAM/encode.js +155 -0
  89. package/lib/WAM/index.js +19 -0
  90. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  91. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  92. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  93. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  94. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  95. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  96. package/lib/WAUSync/Protocols/index.js +20 -0
  97. package/lib/WAUSync/USyncQuery.js +89 -0
  98. package/lib/WAUSync/USyncUser.js +26 -0
  99. package/lib/WAUSync/index.js +19 -0
  100. package/lib/index.js +84 -0
  101. package/package.json +110 -0
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeUSyncSocket = void 0;
4
+ const boom_1 = require("@hapi/boom");
5
+ const WABinary_1 = require("../WABinary");
6
+ const socket_1 = require("./socket");
7
+ const makeUSyncSocket = (config) => {
8
+ const sock = (0, socket_1.makeSocket)(config);
9
+ const { generateMessageTag, query, } = sock;
10
+ const executeUSyncQuery = async (usyncQuery) => {
11
+ if (usyncQuery.protocols.length === 0) {
12
+ throw new boom_1.Boom('USyncQuery must have at least one protocol');
13
+ }
14
+ // todo: validate users, throw WARNING on no valid users
15
+ // variable below has only validated users
16
+ const validUsers = usyncQuery.users;
17
+ const userNodes = validUsers.map((user) => {
18
+ return {
19
+ tag: 'user',
20
+ attrs: {
21
+ jid: !user.phone ? user.id : undefined,
22
+ },
23
+ content: usyncQuery.protocols
24
+ .map((a) => a.getUserElement(user))
25
+ .filter(a => a !== null)
26
+ };
27
+ });
28
+ const listNode = {
29
+ tag: 'list',
30
+ attrs: {},
31
+ content: userNodes
32
+ };
33
+ const queryNode = {
34
+ tag: 'query',
35
+ attrs: {},
36
+ content: usyncQuery.protocols.map((a) => a.getQueryElement())
37
+ };
38
+ const iq = {
39
+ tag: 'iq',
40
+ attrs: {
41
+ to: WABinary_1.S_WHATSAPP_NET,
42
+ type: 'get',
43
+ xmlns: 'usync',
44
+ },
45
+ content: [
46
+ {
47
+ tag: 'usync',
48
+ attrs: {
49
+ context: usyncQuery.context,
50
+ mode: usyncQuery.mode,
51
+ sid: generateMessageTag(),
52
+ last: 'true',
53
+ index: '0',
54
+ },
55
+ content: [
56
+ queryNode,
57
+ listNode
58
+ ]
59
+ }
60
+ ],
61
+ };
62
+ const result = await query(iq);
63
+ return usyncQuery.parseUSyncQueryResult(result);
64
+ };
65
+ return {
66
+ ...sock,
67
+ executeUSyncQuery,
68
+ };
69
+ };
70
+ exports.makeUSyncSocket = makeUSyncSocket;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.makeCacheManagerAuthState = exports.makeInMemoryStore = void 0;
7
+ const make_cache_manager_store_1 = __importDefault(require("./make-cache-manager-store"));
8
+ exports.makeCacheManagerAuthState = make_cache_manager_store_1.default;
9
+ const make_in_memory_store_1 = __importDefault(require("./make-in-memory-store"));
10
+ exports.makeInMemoryStore = make_in_memory_store_1.default;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cache_manager_1 = require("cache-manager");
7
+ const WAProto_1 = require("../../WAProto");
8
+ const Utils_1 = require("../Utils");
9
+ const logger_1 = __importDefault(require("../Utils/logger"));
10
+ const makeCacheManagerAuthState = async (store, sessionKey) => {
11
+ const defaultKey = (file) => `${sessionKey}:${file}`;
12
+ const databaseConn = await (0, cache_manager_1.caching)(store);
13
+ const writeData = async (file, data) => {
14
+ let ttl = undefined;
15
+ if (file === 'creds') {
16
+ ttl = 63115200; // 2 years
17
+ }
18
+ await databaseConn.set(defaultKey(file), JSON.stringify(data, Utils_1.BufferJSON.replacer), ttl);
19
+ };
20
+ const readData = async (file) => {
21
+ try {
22
+ const data = await databaseConn.get(defaultKey(file));
23
+ if (data) {
24
+ return JSON.parse(data, Utils_1.BufferJSON.reviver);
25
+ }
26
+ return null;
27
+ }
28
+ catch (error) {
29
+ logger_1.default.error(error);
30
+ return null;
31
+ }
32
+ };
33
+ const removeData = async (file) => {
34
+ try {
35
+ return await databaseConn.del(defaultKey(file));
36
+ }
37
+ catch (_a) {
38
+ logger_1.default.error(`Error removing ${file} from session ${sessionKey}`);
39
+ }
40
+ };
41
+ const clearState = async () => {
42
+ try {
43
+ const result = await databaseConn.store.keys(`${sessionKey}*`);
44
+ await Promise.all(result.map(async (key) => await databaseConn.del(key)));
45
+ }
46
+ catch (err) {
47
+ }
48
+ };
49
+ const creds = (await readData('creds')) || (0, Utils_1.initAuthCreds)();
50
+ return {
51
+ clearState,
52
+ saveCreds: () => writeData('creds', creds),
53
+ state: {
54
+ creds,
55
+ keys: {
56
+ get: async (type, ids) => {
57
+ const data = {};
58
+ await Promise.all(ids.map(async (id) => {
59
+ let value = await readData(`${type}-${id}`);
60
+ if (type === 'app-state-sync-key' && value) {
61
+ value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
62
+ }
63
+ data[id] = value;
64
+ }));
65
+ return data;
66
+ },
67
+ set: async (data) => {
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ const tasks = [];
70
+ for (const category in data) {
71
+ for (const id in data[category]) {
72
+ const value = data[category][id];
73
+ const key = `${category}-${id}`;
74
+ tasks.push(value ? writeData(key, value) : removeData(key));
75
+ }
76
+ }
77
+ await Promise.all(tasks);
78
+ },
79
+ }
80
+ }
81
+ };
82
+ };
83
+ exports.default = makeCacheManagerAuthState;
@@ -0,0 +1,427 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.waLabelAssociationKey = exports.waMessageID = exports.waChatKey = void 0;
7
+ const WAProto_1 = require("../../WAProto");
8
+ const Defaults_1 = require("../Defaults");
9
+ const LabelAssociation_1 = require("../Types/LabelAssociation");
10
+ const Utils_1 = require("../Utils");
11
+ const WABinary_1 = require("../WABinary");
12
+ const make_ordered_dictionary_1 = __importDefault(require("./make-ordered-dictionary"));
13
+ const object_repository_1 = require("./object-repository");
14
+ const waChatKey = (pin) => ({
15
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
16
+ compare: (k1, k2) => k2.localeCompare(k1)
17
+ });
18
+ exports.waChatKey = waChatKey;
19
+ const waMessageID = (m) => m.key.id || '';
20
+ exports.waMessageID = waMessageID;
21
+ exports.waLabelAssociationKey = {
22
+ key: (la) => (la.type === LabelAssociation_1.LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
23
+ compare: (k1, k2) => k2.localeCompare(k1)
24
+ };
25
+ const makeMessagesDictionary = () => (0, make_ordered_dictionary_1.default)(exports.waMessageID);
26
+ exports.default = (config) => {
27
+ const socket = config.socket;
28
+ const chatKey = config.chatKey || (0, exports.waChatKey)(true);
29
+ const labelAssociationKey = config.labelAssociationKey || exports.waLabelAssociationKey;
30
+ const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
31
+ const KeyedDB = require('@adiwajshing/keyed-db').default;
32
+ const chats = new KeyedDB(chatKey, c => c.id);
33
+ const messages = {};
34
+ const contacts = {};
35
+ const groupMetadata = {};
36
+ const presences = {};
37
+ const state = { connection: 'close' };
38
+ const labels = new object_repository_1.ObjectRepository();
39
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
40
+ const assertMessageList = (jid) => {
41
+ if (!messages[jid]) {
42
+ messages[jid] = makeMessagesDictionary();
43
+ }
44
+ return messages[jid];
45
+ };
46
+ const contactsUpsert = (newContacts) => {
47
+ const oldContacts = new Set(Object.keys(contacts));
48
+ for (const contact of newContacts) {
49
+ oldContacts.delete(contact.id);
50
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
51
+ }
52
+ return oldContacts;
53
+ };
54
+ const labelsUpsert = (newLabels) => {
55
+ for (const label of newLabels) {
56
+ labels.upsertById(label.id, label);
57
+ }
58
+ };
59
+ const getValidContacts = () => {
60
+ for (const contact of Object.keys(contacts)) {
61
+ if (contact.indexOf('@') < 0) {
62
+ delete contacts[contact];
63
+ }
64
+ }
65
+ return Object.keys(contacts);
66
+ };
67
+ /**
68
+ * binds to a BaileysEventEmitter.
69
+ * It listens to all events and constructs a state that you can query accurate data from.
70
+ * Eg. can use the store to fetch chats, contacts, messages etc.
71
+ * @param ev typically the event emitter from the socket connection
72
+ */
73
+ const bind = (ev) => {
74
+ ev.on('connection.update', update => {
75
+ Object.assign(state, update);
76
+ });
77
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest }) => {
78
+ if (isLatest) {
79
+ chats.clear();
80
+ for (const id in messages) {
81
+ delete messages[id];
82
+ }
83
+ }
84
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
85
+ logger.debug({ chatsAdded }, 'synced chats');
86
+ const oldContacts = contactsUpsert(newContacts);
87
+ if (isLatest) {
88
+ for (const jid of oldContacts) {
89
+ delete contacts[jid];
90
+ }
91
+ }
92
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
93
+ for (const msg of newMessages) {
94
+ const jid = msg.key.remoteJid;
95
+ const list = assertMessageList(jid);
96
+ list.upsert(msg, 'prepend');
97
+ }
98
+ logger.debug({ messages: newMessages.length }, 'synced messages');
99
+ });
100
+ ev.on('contacts.upsert', contacts => {
101
+ contactsUpsert(contacts);
102
+ });
103
+ ev.on('contacts.update', async (updates) => {
104
+ var _a;
105
+ for (const update of updates) {
106
+ let contact;
107
+ if (contacts[update.id]) {
108
+ contact = contacts[update.id];
109
+ }
110
+ else {
111
+ const validContacts = getValidContacts();
112
+ const contactHashes = validContacts.map((contactId) => {
113
+ const { user } = (0, WABinary_1.jidDecode)(contactId);
114
+ return [contactId, ((0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
115
+ });
116
+ contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
117
+ }
118
+ if (contact) {
119
+ if (update.imgUrl === 'changed') {
120
+ contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
121
+ }
122
+ else if (update.imgUrl === 'removed') {
123
+ delete contact.imgUrl;
124
+ }
125
+ Object.assign(contacts[contact.id], contact);
126
+ }
127
+ else {
128
+ logger.debug({ update }, 'got update for non-existant contact');
129
+ }
130
+ }
131
+ });
132
+ ev.on('chats.upsert', newChats => {
133
+ chats.upsert(...newChats);
134
+ });
135
+ ev.on('chats.update', updates => {
136
+ for (let update of updates) {
137
+ const result = chats.update(update.id, chat => {
138
+ if (update.unreadCount > 0) {
139
+ update = { ...update };
140
+ update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
141
+ }
142
+ Object.assign(chat, update);
143
+ });
144
+ if (!result) {
145
+ logger.debug({ update }, 'got update for non-existant chat');
146
+ }
147
+ }
148
+ });
149
+ ev.on('labels.edit', (label) => {
150
+ if (label.deleted) {
151
+ return labels.deleteById(label.id);
152
+ }
153
+ // WhatsApp can store only up to 20 labels
154
+ if (labels.count() < 20) {
155
+ return labels.upsertById(label.id, label);
156
+ }
157
+ logger.error('Labels count exceed');
158
+ });
159
+ ev.on('labels.association', ({ type, association }) => {
160
+ switch (type) {
161
+ case 'add':
162
+ labelAssociations.upsert(association);
163
+ break;
164
+ case 'remove':
165
+ labelAssociations.delete(association);
166
+ break;
167
+ default:
168
+ console.error(`unknown operation type [${type}]`);
169
+ }
170
+ });
171
+ ev.on('presence.update', ({ id, presences: update }) => {
172
+ presences[id] = presences[id] || {};
173
+ Object.assign(presences[id], update);
174
+ });
175
+ ev.on('chats.delete', deletions => {
176
+ for (const item of deletions) {
177
+ if (chats.get(item)) {
178
+ chats.deleteById(item);
179
+ }
180
+ }
181
+ });
182
+ ev.on('messages.upsert', ({ messages: newMessages, type }) => {
183
+ switch (type) {
184
+ case 'append':
185
+ case 'notify':
186
+ for (const msg of newMessages) {
187
+ const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
188
+ const list = assertMessageList(jid);
189
+ list.upsert(msg, 'append');
190
+ if (type === 'notify') {
191
+ if (!chats.get(jid)) {
192
+ ev.emit('chats.upsert', [
193
+ {
194
+ id: jid,
195
+ conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
196
+ unreadCount: 1
197
+ }
198
+ ]);
199
+ }
200
+ }
201
+ }
202
+ break;
203
+ }
204
+ });
205
+ ev.on('messages.update', updates => {
206
+ var _a;
207
+ for (const { update, key } of updates) {
208
+ const list = assertMessageList((0, WABinary_1.jidNormalizedUser)(key.remoteJid));
209
+ if (update === null || update === void 0 ? void 0 : update.status) {
210
+ const listStatus = (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status;
211
+ if (listStatus && (update === null || update === void 0 ? void 0 : update.status) <= listStatus) {
212
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
213
+ delete update.status;
214
+ logger.debug({ update }, 'new update object');
215
+ }
216
+ }
217
+ const result = list.updateAssign(key.id, update);
218
+ if (!result) {
219
+ logger.debug({ update }, 'got update for non-existent message');
220
+ }
221
+ }
222
+ });
223
+ ev.on('messages.delete', item => {
224
+ if ('all' in item) {
225
+ const list = messages[item.jid];
226
+ list === null || list === void 0 ? void 0 : list.clear();
227
+ }
228
+ else {
229
+ const jid = item.keys[0].remoteJid;
230
+ const list = messages[jid];
231
+ if (list) {
232
+ const idSet = new Set(item.keys.map(k => k.id));
233
+ list.filter(m => !idSet.has(m.key.id));
234
+ }
235
+ }
236
+ });
237
+ ev.on('groups.update', updates => {
238
+ for (const update of updates) {
239
+ const id = update.id;
240
+ if (groupMetadata[id]) {
241
+ Object.assign(groupMetadata[id], update);
242
+ }
243
+ else {
244
+ logger.debug({ update }, 'got update for non-existant group metadata');
245
+ }
246
+ }
247
+ });
248
+ ev.on('group-participants.update', ({ id, participants, action }) => {
249
+ const metadata = groupMetadata[id];
250
+ if (metadata) {
251
+ switch (action) {
252
+ case 'add':
253
+ metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })));
254
+ break;
255
+ case 'demote':
256
+ case 'promote':
257
+ for (const participant of metadata.participants) {
258
+ if (participants.includes(participant.id)) {
259
+ participant.isAdmin = action === 'promote';
260
+ }
261
+ }
262
+ break;
263
+ case 'remove':
264
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
265
+ break;
266
+ }
267
+ }
268
+ });
269
+ ev.on('message-receipt.update', updates => {
270
+ for (const { key, receipt } of updates) {
271
+ const obj = messages[key.remoteJid];
272
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
273
+ if (msg) {
274
+ (0, Utils_1.updateMessageWithReceipt)(msg, receipt);
275
+ }
276
+ }
277
+ });
278
+ ev.on('messages.reaction', (reactions) => {
279
+ for (const { key, reaction } of reactions) {
280
+ const obj = messages[key.remoteJid];
281
+ const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
282
+ if (msg) {
283
+ (0, Utils_1.updateMessageWithReaction)(msg, reaction);
284
+ }
285
+ }
286
+ });
287
+ };
288
+ const toJSON = () => ({
289
+ chats,
290
+ contacts,
291
+ messages,
292
+ labels,
293
+ labelAssociations
294
+ });
295
+ const fromJSON = (json) => {
296
+ chats.upsert(...json.chats);
297
+ labelAssociations.upsert(...json.labelAssociations || []);
298
+ contactsUpsert(Object.values(json.contacts));
299
+ labelsUpsert(Object.values(json.labels || {}));
300
+ for (const jid in json.messages) {
301
+ const list = assertMessageList(jid);
302
+ for (const msg of json.messages[jid]) {
303
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append');
304
+ }
305
+ }
306
+ };
307
+ return {
308
+ chats,
309
+ contacts,
310
+ messages,
311
+ groupMetadata,
312
+ state,
313
+ presences,
314
+ labels,
315
+ labelAssociations,
316
+ bind,
317
+ /** loads messages from the store, if not found -- uses the legacy connection */
318
+ loadMessages: async (jid, count, cursor) => {
319
+ const list = assertMessageList(jid);
320
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after';
321
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
322
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
323
+ let messages;
324
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
325
+ if (cursorValue) {
326
+ const msgIdx = list.array.findIndex(m => m.key.id === (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id));
327
+ messages = list.array.slice(0, msgIdx);
328
+ }
329
+ else {
330
+ messages = list.array;
331
+ }
332
+ const diff = count - messages.length;
333
+ if (diff < 0) {
334
+ messages = messages.slice(-count); // get the last X messages
335
+ }
336
+ }
337
+ else {
338
+ messages = [];
339
+ }
340
+ return messages;
341
+ },
342
+ /**
343
+ * Get all available labels for profile
344
+ *
345
+ * Keep in mind that the list is formed from predefined tags and tags
346
+ * that were "caught" during their editing.
347
+ */
348
+ getLabels: () => {
349
+ return labels;
350
+ },
351
+ /**
352
+ * Get labels for chat
353
+ *
354
+ * @returns Label IDs
355
+ **/
356
+ getChatLabels: (chatId) => {
357
+ return labelAssociations.filter((la) => la.chatId === chatId).all();
358
+ },
359
+ /**
360
+ * Get labels for message
361
+ *
362
+ * @returns Label IDs
363
+ **/
364
+ getMessageLabels: (messageId) => {
365
+ const associations = labelAssociations
366
+ .filter((la) => la.messageId === messageId)
367
+ .all();
368
+ return associations.map(({ labelId }) => labelId);
369
+ },
370
+ loadMessage: async (jid, id) => { var _a; return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id); },
371
+ mostRecentMessage: async (jid) => {
372
+ var _a;
373
+ const message = (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0];
374
+ return message;
375
+ },
376
+ fetchImageUrl: async (jid, sock) => {
377
+ const contact = contacts[jid];
378
+ if (!contact) {
379
+ return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid);
380
+ }
381
+ if (typeof contact.imgUrl === 'undefined') {
382
+ contact.imgUrl = await (sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid));
383
+ }
384
+ return contact.imgUrl;
385
+ },
386
+ fetchGroupMetadata: async (jid, sock) => {
387
+ if (!groupMetadata[jid]) {
388
+ const metadata = await (sock === null || sock === void 0 ? void 0 : sock.groupMetadata(jid));
389
+ if (metadata) {
390
+ groupMetadata[jid] = metadata;
391
+ }
392
+ }
393
+ return groupMetadata[jid];
394
+ },
395
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
396
+ // if(!groupMetadata[jid]) {
397
+ // const metadata = await sock?.getBroadcastListInfo(jid)
398
+ // if(metadata) {
399
+ // groupMetadata[jid] = metadata
400
+ // }
401
+ // }
402
+ // return groupMetadata[jid]
403
+ // },
404
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
405
+ const list = messages[remoteJid];
406
+ const msg = list === null || list === void 0 ? void 0 : list.get(id);
407
+ return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
408
+ },
409
+ toJSON,
410
+ fromJSON,
411
+ writeToFile: (path) => {
412
+ // require fs here so that in case "fs" is not available -- the app does not crash
413
+ const { writeFileSync } = require('fs');
414
+ writeFileSync(path, JSON.stringify(toJSON()));
415
+ },
416
+ readFromFile: (path) => {
417
+ // require fs here so that in case "fs" is not available -- the app does not crash
418
+ const { readFileSync, existsSync } = require('fs');
419
+ if (existsSync(path)) {
420
+ logger.debug({ path }, 'reading from file');
421
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' });
422
+ const json = JSON.parse(jsonStr);
423
+ fromJSON(json);
424
+ }
425
+ }
426
+ };
427
+ };
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function makeOrderedDictionary(idGetter) {
4
+ const array = [];
5
+ const dict = {};
6
+ const get = (id) => dict[id];
7
+ const update = (item) => {
8
+ const id = idGetter(item);
9
+ const idx = array.findIndex(i => idGetter(i) === id);
10
+ if (idx >= 0) {
11
+ array[idx] = item;
12
+ dict[id] = item;
13
+ }
14
+ return false;
15
+ };
16
+ const upsert = (item, mode) => {
17
+ const id = idGetter(item);
18
+ if (get(id)) {
19
+ update(item);
20
+ }
21
+ else {
22
+ if (mode === 'append') {
23
+ array.push(item);
24
+ }
25
+ else {
26
+ array.splice(0, 0, item);
27
+ }
28
+ dict[id] = item;
29
+ }
30
+ };
31
+ const remove = (item) => {
32
+ const id = idGetter(item);
33
+ const idx = array.findIndex(i => idGetter(i) === id);
34
+ if (idx >= 0) {
35
+ array.splice(idx, 1);
36
+ delete dict[id];
37
+ return true;
38
+ }
39
+ return false;
40
+ };
41
+ return {
42
+ array,
43
+ get,
44
+ upsert,
45
+ update,
46
+ remove,
47
+ updateAssign: (id, update) => {
48
+ const item = get(id);
49
+ if (item) {
50
+ Object.assign(item, update);
51
+ delete dict[id];
52
+ dict[idGetter(item)] = item;
53
+ return true;
54
+ }
55
+ return false;
56
+ },
57
+ clear: () => {
58
+ array.splice(0, array.length);
59
+ Object.keys(dict).forEach(key => {
60
+ delete dict[key];
61
+ });
62
+ },
63
+ filter: (contain) => {
64
+ let i = 0;
65
+ while (i < array.length) {
66
+ if (!contain(array[i])) {
67
+ delete dict[idGetter(array[i])];
68
+ array.splice(i, 1);
69
+ }
70
+ else {
71
+ i += 1;
72
+ }
73
+ }
74
+ },
75
+ toJSON: () => array,
76
+ fromJSON: (newItems) => {
77
+ array.splice(0, array.length, ...newItems);
78
+ }
79
+ };
80
+ }
81
+ exports.default = makeOrderedDictionary;