@mrlegendbot/baileys 1.2.4 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/WAProto/GenerateStatics.sh +3 -0
  2. package/WAProto/fix-imports.js +85 -0
  3. package/WAProto/index.d.ts +14017 -0
  4. package/WAProto/index.js +97691 -2
  5. package/lib/Defaults/index.d.ts +75 -0
  6. package/lib/Defaults/index.js +92 -89
  7. package/lib/Menu/index.d.ts +42 -0
  8. package/lib/Menu/index.js +283 -0
  9. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  10. package/lib/Signal/Group/ciphertext-message.js +10 -9
  11. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  12. package/lib/Signal/Group/group-session-builder.js +22 -21
  13. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  14. package/lib/Signal/Group/group_cipher.js +69 -75
  15. package/lib/Signal/Group/index.d.ts +12 -0
  16. package/lib/Signal/Group/index.js +1 -0
  17. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  18. package/lib/Signal/Group/keyhelper.js +10 -9
  19. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  20. package/lib/Signal/Group/sender-chain-key.js +22 -21
  21. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  22. package/lib/Signal/Group/sender-key-distribution-message.js +60 -51
  23. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  24. package/lib/Signal/Group/sender-key-message.js +62 -56
  25. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  26. package/lib/Signal/Group/sender-key-name.js +40 -38
  27. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  28. package/lib/Signal/Group/sender-key-record.js +34 -33
  29. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  30. package/lib/Signal/Group/sender-key-state.js +76 -72
  31. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  32. package/lib/Signal/Group/sender-message-key.js +23 -22
  33. package/lib/Signal/libsignal.d.ts +5 -0
  34. package/lib/Signal/libsignal.js +405 -506
  35. package/lib/Signal/lid-mapping.d.ts +23 -0
  36. package/lib/Signal/lid-mapping.js +258 -276
  37. package/lib/Socket/Client/index.d.ts +3 -0
  38. package/lib/Socket/Client/index.js +1 -0
  39. package/lib/Socket/Client/types.d.ts +16 -0
  40. package/lib/Socket/Client/types.js +7 -6
  41. package/lib/Socket/Client/websocket.d.ts +13 -0
  42. package/lib/Socket/Client/websocket.js +49 -48
  43. package/lib/Socket/business.d.ts +217 -0
  44. package/lib/Socket/business.js +369 -349
  45. package/lib/Socket/chats.d.ts +125 -0
  46. package/lib/Socket/chats.js +1148 -1172
  47. package/lib/Socket/communities.d.ts +273 -0
  48. package/lib/Socket/communities.js +413 -473
  49. package/lib/Socket/groups.d.ts +161 -0
  50. package/lib/Socket/groups.js +331 -387
  51. package/lib/Socket/index.d.ts +267 -0
  52. package/lib/Socket/index.js +19 -6
  53. package/lib/Socket/messages-recv.d.ts +203 -0
  54. package/lib/Socket/messages-recv.js +1719 -1782
  55. package/lib/Socket/messages-send.d.ts +199 -0
  56. package/lib/Socket/messages-send.js +2451 -1504
  57. package/lib/Socket/mex.d.ts +3 -0
  58. package/lib/Socket/mex.js +35 -40
  59. package/lib/Socket/newsletter.d.ts +170 -0
  60. package/lib/Socket/newsletter.js +191 -239
  61. package/lib/Socket/socket.d.ts +59 -0
  62. package/lib/Socket/socket.js +923 -992
  63. package/lib/Types/Auth.d.ts +117 -0
  64. package/lib/Types/Auth.js +1 -0
  65. package/lib/Types/Bussines.d.ts +25 -0
  66. package/lib/Types/Bussines.js +1 -0
  67. package/lib/Types/Call.d.ts +15 -0
  68. package/lib/Types/Call.js +1 -0
  69. package/lib/Types/Chat.d.ts +124 -0
  70. package/lib/Types/Chat.js +8 -1
  71. package/lib/Types/Contact.d.ts +26 -0
  72. package/lib/Types/Contact.js +1 -0
  73. package/lib/Types/Events.d.ts +256 -0
  74. package/lib/Types/Events.js +2 -1
  75. package/lib/Types/GroupMetadata.d.ts +71 -0
  76. package/lib/Types/GroupMetadata.js +1 -0
  77. package/lib/Types/Label.d.ts +47 -0
  78. package/lib/Types/Label.js +22 -20
  79. package/lib/Types/LabelAssociation.d.ts +30 -0
  80. package/lib/Types/LabelAssociation.js +4 -2
  81. package/lib/Types/Message.d.ts +320 -0
  82. package/lib/Types/Message.js +5 -3
  83. package/lib/Types/Mex.d.ts +141 -0
  84. package/lib/Types/Mex.js +31 -26
  85. package/lib/Types/Product.d.ts +79 -0
  86. package/lib/Types/Product.js +1 -0
  87. package/lib/Types/Signal.d.ts +87 -0
  88. package/lib/Types/Signal.js +2 -1
  89. package/lib/Types/Socket.d.ts +136 -0
  90. package/lib/Types/Socket.js +3 -2
  91. package/lib/Types/State.d.ts +97 -0
  92. package/lib/Types/State.js +52 -4
  93. package/lib/Types/USync.d.ts +26 -0
  94. package/lib/Types/USync.js +1 -0
  95. package/lib/Types/index.d.ts +66 -0
  96. package/lib/Types/index.js +11 -10
  97. package/lib/Utils/auth-utils.d.ts +24 -0
  98. package/lib/Utils/auth-utils.js +277 -240
  99. package/lib/Utils/browser-utils.d.ts +4 -0
  100. package/lib/Utils/browser-utils.js +23 -20
  101. package/lib/Utils/business.d.ts +23 -0
  102. package/lib/Utils/business.js +204 -200
  103. package/lib/Utils/chat-utils.d.ts +100 -0
  104. package/lib/Utils/chat-utils.js +810 -836
  105. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  106. package/lib/Utils/companion-reg-client-utils.js +25 -23
  107. package/lib/Utils/crypto.d.ts +37 -0
  108. package/lib/Utils/crypto.js +86 -70
  109. package/lib/Utils/decode-wa-message.d.ts +66 -0
  110. package/lib/Utils/decode-wa-message.js +284 -277
  111. package/lib/Utils/event-buffer.d.ts +36 -0
  112. package/lib/Utils/event-buffer.js +595 -592
  113. package/lib/Utils/generics.d.ts +92 -0
  114. package/lib/Utils/generics.js +335 -312
  115. package/lib/Utils/history.d.ts +24 -0
  116. package/lib/Utils/history.js +115 -123
  117. package/lib/Utils/identity-change-handler.d.ts +44 -0
  118. package/lib/Utils/identity-change-handler.js +50 -0
  119. package/lib/Utils/index.d.ts +22 -0
  120. package/lib/Utils/index.js +2 -1
  121. package/lib/Utils/link-preview.d.ts +21 -0
  122. package/lib/Utils/link-preview.js +73 -74
  123. package/lib/Utils/logger.d.ts +12 -0
  124. package/lib/Utils/logger.js +2 -3
  125. package/lib/Utils/lt-hash.d.ts +8 -0
  126. package/lib/Utils/lt-hash.js +6 -0
  127. package/lib/Utils/make-mutex.d.ts +9 -0
  128. package/lib/Utils/make-mutex.js +27 -27
  129. package/lib/Utils/message-retry-manager.d.ts +115 -0
  130. package/lib/Utils/message-retry-manager.js +254 -213
  131. package/lib/Utils/messages-media.d.ts +133 -0
  132. package/lib/Utils/messages-media.js +715 -741
  133. package/lib/Utils/messages.d.ts +91 -0
  134. package/lib/Utils/messages.js +827 -791
  135. package/lib/Utils/noise-handler.d.ts +20 -0
  136. package/lib/Utils/noise-handler.js +187 -215
  137. package/lib/Utils/offline-node-processor.d.ts +17 -0
  138. package/lib/Utils/offline-node-processor.js +40 -0
  139. package/lib/Utils/pre-key-manager.d.ts +28 -0
  140. package/lib/Utils/pre-key-manager.js +98 -69
  141. package/lib/Utils/process-message.d.ts +60 -0
  142. package/lib/Utils/process-message.js +586 -617
  143. package/lib/Utils/reporting-utils.d.ts +11 -0
  144. package/lib/Utils/reporting-utils.js +234 -553
  145. package/lib/Utils/signal.d.ts +47 -0
  146. package/lib/Utils/signal.js +170 -217
  147. package/lib/Utils/stanza-ack.d.ts +11 -0
  148. package/lib/Utils/stanza-ack.js +35 -27
  149. package/lib/Utils/sync-action-utils.d.ts +19 -0
  150. package/lib/Utils/sync-action-utils.js +41 -37
  151. package/lib/Utils/tc-token-utils.d.ts +37 -0
  152. package/lib/Utils/tc-token-utils.js +141 -120
  153. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  154. package/lib/Utils/use-multi-file-auth-state.js +105 -87
  155. package/lib/Utils/validate-connection.d.ts +11 -0
  156. package/lib/Utils/validate-connection.js +188 -190
  157. package/lib/WABinary/constants.d.ts +28 -0
  158. package/lib/WABinary/constants.js +1294 -28
  159. package/lib/WABinary/decode.d.ts +7 -0
  160. package/lib/WABinary/decode.js +249 -245
  161. package/lib/WABinary/encode.d.ts +3 -0
  162. package/lib/WABinary/encode.js +206 -201
  163. package/lib/WABinary/generic-utils.d.ts +15 -0
  164. package/lib/WABinary/generic-utils.js +89 -86
  165. package/lib/WABinary/index.d.ts +6 -0
  166. package/lib/WABinary/index.js +1 -0
  167. package/lib/WABinary/jid-utils.d.ts +48 -0
  168. package/lib/WABinary/jid-utils.js +77 -68
  169. package/lib/WABinary/types.d.ts +19 -0
  170. package/lib/WABinary/types.js +1 -0
  171. package/lib/WAM/BinaryInfo.d.ts +9 -0
  172. package/lib/WAM/BinaryInfo.js +8 -7
  173. package/lib/WAM/constants.d.ts +40 -0
  174. package/lib/WAM/constants.js +22853 -19892
  175. package/lib/WAM/encode.d.ts +3 -0
  176. package/lib/WAM/encode.js +132 -121
  177. package/lib/WAM/index.d.ts +4 -0
  178. package/lib/WAM/index.js +1 -0
  179. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  180. package/lib/WAUSync/Protocols/USyncContactProtocol.js +43 -46
  181. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  182. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +48 -47
  183. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  184. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +23 -22
  185. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  186. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +33 -30
  187. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  188. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +20 -19
  189. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  190. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +44 -53
  191. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  192. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -24
  193. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  194. package/lib/WAUSync/Protocols/index.js +1 -0
  195. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  196. package/lib/WAUSync/USyncQuery.js +88 -79
  197. package/lib/WAUSync/USyncUser.d.ts +17 -0
  198. package/lib/WAUSync/USyncUser.js +29 -28
  199. package/lib/WAUSync/index.d.ts +4 -0
  200. package/lib/WAUSync/index.js +1 -0
  201. package/lib/index.d.ts +12 -0
  202. package/lib/index.js +2 -2
  203. package/package.json +86 -22
  204. package/README.upstream.md +0 -1312
  205. package/WAProto/WAProto.json +0 -1
  206. package/WAProto/WAProto.proto +0 -6275
  207. package/WAProto/compiler.js +0 -550
  208. package/lib/Store/index.js +0 -8
  209. package/lib/Store/keyed-db.js +0 -108
  210. package/lib/Store/make-cache-manager-store.js +0 -70
  211. package/lib/Store/make-in-memory-store.js +0 -417
  212. package/lib/Store/make-ordered-dictionary.js +0 -69
  213. package/lib/Store/object-repository.js +0 -27
  214. package/lib/Utils/use-sqlite-auth-state.js +0 -162
@@ -1,70 +0,0 @@
1
- import { createRequire } from "module";
2
- const require = createRequire(import.meta.url);
3
- const cacheManager = require("cache-manager");
4
- import * as WAProto_1 from "../../WAProto/compiler.js";
5
- import * as Utils_1 from "../Utils/index.js";
6
- import logger from "../Utils/logger.js";
7
- export default async function makeCacheManagerAuthState(store, sessionKey) {
8
- const defaultKey = file => `${sessionKey}:${file}`;
9
- const databaseConn = await cacheManager.caching(store);
10
- const writeData = async (file, data) => {
11
- let ttl = undefined;
12
- if (file === "creds") ttl = 63115200;
13
- await databaseConn.set(defaultKey(file), JSON.stringify(data, Utils_1.BufferJSON.replacer), ttl);
14
- };
15
- const readData = async file => {
16
- try {
17
- const data = await databaseConn.get(defaultKey(file));
18
- if (data) return JSON.parse(data, Utils_1.BufferJSON.reviver);
19
- return null;
20
- } catch (error) {
21
- logger.error(error);
22
- return null;
23
- }
24
- };
25
- const removeData = async file => {
26
- try {
27
- return await databaseConn.del(defaultKey(file));
28
- } catch {
29
- logger.error(`Error removing ${file} from session ${sessionKey}`);
30
- }
31
- };
32
- const clearState = async () => {
33
- try {
34
- const result = await databaseConn.store.keys(`${sessionKey}*`);
35
- await Promise.all(result.map(async key => databaseConn.del(key)));
36
- } catch {}
37
- };
38
- const creds = (await readData("creds")) || Utils_1.initAuthCreds();
39
- return {
40
- clearState,
41
- saveCreds: () => writeData("creds", creds),
42
- state: {
43
- creds,
44
- keys: {
45
- get: async (type, ids) => {
46
- const data = {};
47
- await Promise.all(ids.map(async id => {
48
- let value = await readData(`${type}-${id}`);
49
- if (type === "app-state-sync-key" && value) {
50
- value = WAProto_1.proto.Message.AppStateSyncKeyData.fromObject(value);
51
- }
52
- data[id] = value;
53
- }));
54
- return data;
55
- },
56
- set: async data => {
57
- const tasks = [];
58
- for (const category in data) {
59
- for (const id in data[category]) {
60
- const value = data[category][id];
61
- const key = `${category}-${id}`;
62
- tasks.push(value ? writeData(key, value) : removeData(key));
63
- }
64
- }
65
- await Promise.all(tasks);
66
- }
67
- }
68
- }
69
- };
70
- }
@@ -1,417 +0,0 @@
1
- import { existsSync, readFileSync, writeFileSync } from 'fs';
2
- import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
3
- import { toNumber, updateMessageWithPollUpdate, updateMessageWithReaction, updateMessageWithReceipt } from '../Utils/index.js';
4
- import { jidNormalizedUser } from '../WABinary/index.js';
5
- import KeyedDB from './keyed-db.js';
6
- import makeOrderedDictionary from './make-ordered-dictionary.js';
7
- import { ObjectRepository } from './object-repository.js';
8
- const waChatKey = pin => (c1, c2) => {
9
- const pinnedDiff = pin ? Number(!!c2.pinned) - Number(!!c1.pinned) : 0;
10
- if (pinnedDiff) return pinnedDiff;
11
- const t1 = toNumber(c1.conversationTimestamp) || 0;
12
- const t2 = toNumber(c2.conversationTimestamp) || 0;
13
- if (t1 !== t2) return t2 - t1;
14
- return (c1.id || '').localeCompare(c2.id || '');
15
- };
16
- const waMessageID = m => m.key?.id || '';
17
- const waLabelAssociationKey = (a1, a2) => (a1.type || '').localeCompare(a2.type || '') || (a1.chatId || '').localeCompare(a2.chatId || '') || (a1.labelId || '').localeCompare(a2.labelId || '');
18
- const labelAssociationId = a => (a.type || '') + ':' + (a.chatId || a.messageId || '') + ':' + (a.labelId || '');
19
- const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
20
- export const makeInMemoryStore = (config = {}) => {
21
- const socket = config.socket;
22
- const chatKeyCompare = config.chatKey || waChatKey(true);
23
- const labelAssociationKeyCompare = config.labelAssociationKey || waLabelAssociationKey;
24
- const logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger?.child?.({
25
- stream: 'in-mem-store'
26
- });
27
- const chats = new KeyedDB(chatKeyCompare, c => c.id);
28
- const messages = {};
29
- const contacts = {};
30
- const groupMetadata = {};
31
- const presences = {};
32
- const state = {
33
- connection: 'close'
34
- };
35
- const labels = new ObjectRepository();
36
- const labelAssociations = new KeyedDB(labelAssociationKeyCompare, labelAssociationId);
37
- const assertMessageList = jid => {
38
- if (!messages[jid]) {
39
- messages[jid] = makeMessagesDictionary();
40
- }
41
- return messages[jid];
42
- };
43
- const contactsUpsert = newContacts => {
44
- const oldContacts = new Set(Object.keys(contacts));
45
- for (const contact of newContacts) {
46
- oldContacts.delete(contact.id);
47
- contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
48
- }
49
- return oldContacts;
50
- };
51
- const labelsUpsert = newLabels => {
52
- for (const label of newLabels) {
53
- labels.upsertById(label.id, label);
54
- }
55
- };
56
- const bind = ev => {
57
- ev.on('connection.update', update => {
58
- Object.assign(state, update);
59
- });
60
- ev.on('messaging-history.set', ({
61
- chats: newChats,
62
- contacts: newContacts,
63
- messages: newMessages,
64
- isLatest,
65
- syncType
66
- }) => {
67
- if (isLatest) {
68
- chats.clear();
69
- for (const id of Object.keys(messages)) {
70
- delete messages[id];
71
- }
72
- }
73
- const chatsAdded = chats.insertIfAbsent(...newChats).length;
74
- logger?.debug?.({
75
- chatsAdded
76
- }, 'synced chats');
77
- const oldContacts = contactsUpsert(newContacts);
78
- logger?.debug?.({
79
- deletedContacts: oldContacts.size,
80
- newContacts
81
- }, 'synced contacts');
82
- for (const msg of newMessages) {
83
- const jid = jidNormalizedUser(msg.key.remoteJid);
84
- const list = assertMessageList(jid);
85
- list.upsert(msg, 'prepend');
86
- }
87
- logger?.debug?.({
88
- messages: newMessages.length
89
- }, 'synced messages');
90
- });
91
- ev.on('contacts.upsert', newContacts => {
92
- contactsUpsert(newContacts);
93
- });
94
- ev.on('contacts.update', updates => {
95
- for (const update of updates) {
96
- let contact;
97
- if (update.id && (contact = contacts[update.id])) {
98
- Object.assign(contact, update);
99
- } else {
100
- logger?.debug?.({
101
- update
102
- }, 'got update for non-existant contact');
103
- }
104
- }
105
- });
106
- ev.on('chats.upsert', newChats => {
107
- chats.upsert(...newChats);
108
- });
109
- ev.on('chats.update', updates => {
110
- for (let update of updates) {
111
- const existing = chats.get(update.id);
112
- if (existing) {
113
- chats.upsert(Object.assign(existing, update));
114
- } else {
115
- logger?.debug?.({
116
- update
117
- }, 'got update for non-existant chat');
118
- }
119
- }
120
- });
121
- ev.on('labels.edit', label => {
122
- if (label.deleted) {
123
- labels.deleteById(label.id);
124
- return;
125
- }
126
- labels.upsertById(label.id, label);
127
- });
128
- ev.on('labels.association', ({
129
- type,
130
- association
131
- }) => {
132
- switch (type) {
133
- case 'add':
134
- labelAssociations.upsert(association);
135
- break;
136
- case 'remove':
137
- labelAssociations.deleteById(labelAssociationId(association));
138
- break;
139
- default:
140
- logger?.error?.(`unknown operation type ${type}`);
141
- }
142
- });
143
- ev.on('presence.update', ({
144
- id,
145
- presences: update
146
- }) => {
147
- presences[id] = presences[id] || {};
148
- Object.assign(presences[id], update);
149
- });
150
- ev.on('chats.delete', deletions => {
151
- for (const item of deletions) {
152
- if (chats.get(item)) {
153
- chats.deleteById(item);
154
- }
155
- }
156
- });
157
- ev.on('messages.upsert', ({
158
- messages: newMessages,
159
- type
160
- }) => {
161
- switch (type) {
162
- case 'append':
163
- case 'notify':
164
- for (const msg of newMessages) {
165
- const jid = jidNormalizedUser(msg.key.remoteJid);
166
- const list = assertMessageList(jid);
167
- list.upsert(msg, 'append');
168
- if (type === 'notify') {
169
- if (!chats.get(jid)) {
170
- ev.emit('chats.upsert', [{
171
- id: jid,
172
- conversationTimestamp: toNumber(msg.messageTimestamp),
173
- unreadCount: 1
174
- }]);
175
- }
176
- }
177
- }
178
- break;
179
- }
180
- });
181
- ev.on('messages.update', updates => {
182
- for (const {
183
- update,
184
- key
185
- } of updates) {
186
- const list = assertMessageList(jidNormalizedUser(key.remoteJid));
187
- if (update?.status) {
188
- const listStatus = list.get(key.id)?.status;
189
- if (listStatus && update.status <= listStatus) {
190
- logger?.debug?.({
191
- update,
192
- storedStatus: listStatus
193
- }, 'status stored newer then update');
194
- delete update.status;
195
- }
196
- }
197
- const result = list.updateAssign(key.id, update);
198
- if (!result) {
199
- logger?.debug?.({
200
- update
201
- }, 'got update for non-existent message');
202
- }
203
- }
204
- });
205
- ev.on('messages.delete', item => {
206
- if ('all' in item) {
207
- const list = messages[item.jid];
208
- list?.clear();
209
- } else {
210
- const jid = item.keys[0].remoteJid;
211
- const list = messages[jidNormalizedUser(jid)];
212
- if (list) {
213
- const idSet = new Set(item.keys.map(k => k.id));
214
- list.filter(m => !idSet.has(m.key.id));
215
- }
216
- }
217
- });
218
- ev.on('messages.reaction', reactions => {
219
- for (const {
220
- key,
221
- reaction
222
- } of reactions) {
223
- const obj = messages[jidNormalizedUser(key.remoteJid)];
224
- const msg = obj?.get(key.id);
225
- if (msg) {
226
- updateMessageWithReaction(msg, reaction);
227
- }
228
- }
229
- });
230
- ev.on('message-receipt.update', updates => {
231
- for (const {
232
- key,
233
- receipt
234
- } of updates) {
235
- const obj = messages[jidNormalizedUser(key.remoteJid)];
236
- const msg = obj?.get(key.id);
237
- if (msg) {
238
- updateMessageWithReceipt(msg, receipt);
239
- }
240
- }
241
- });
242
- ev.on('groups.update', updates => {
243
- for (const update of updates) {
244
- const id = update.id;
245
- if (groupMetadata[id]) {
246
- Object.assign(groupMetadata[id], update);
247
- } else {
248
- logger?.debug?.({
249
- update
250
- }, 'got update for non-existant group metadata');
251
- }
252
- }
253
- });
254
- ev.on('group-participants.update', ({
255
- id,
256
- participants,
257
- action
258
- }) => {
259
- const metadata = groupMetadata[id];
260
- if (metadata) {
261
- switch (action) {
262
- case 'add':
263
- metadata.participants.push(...participants.map(p => ({
264
- id: p,
265
- isAdmin: false,
266
- isSuperAdmin: false
267
- })));
268
- break;
269
- case 'demote':
270
- case 'promote':
271
- for (const participant of metadata.participants) {
272
- if (participants.includes(participant.id)) {
273
- participant.isAdmin = action === 'promote';
274
- }
275
- }
276
- break;
277
- case 'remove':
278
- metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
279
- break;
280
- }
281
- }
282
- });
283
- ev.on('groups.upsert', newGroups => {
284
- for (const group of newGroups) {
285
- groupMetadata[group.id] = group;
286
- }
287
- });
288
- };
289
- const toJSON = () => ({
290
- chats,
291
- contacts,
292
- messages,
293
- labels,
294
- labelAssociations
295
- });
296
- const fromJSON = json => {
297
- chats.upsert(...json.chats);
298
- labelAssociations.upsert(...(json.labelAssociations || []));
299
- contactsUpsert(Object.values(json.contacts));
300
- labelsUpsert(Object.values(json.labels || {}));
301
- for (const jid in json.messages) {
302
- const list = assertMessageList(jid);
303
- for (const msg of json.messages[jid]) {
304
- list.upsert(msg, 'append');
305
- }
306
- }
307
- };
308
- const writeToFile = path => {
309
- const data = JSON.stringify(toJSON(), BufferJSON_replacer);
310
- writeFileSync(path, data);
311
- };
312
- const readFromFile = path => {
313
- if (existsSync(path)) {
314
- logger?.debug?.({
315
- path
316
- }, 'reading from file');
317
- const jsonStr = readFileSync(path, {
318
- encoding: 'utf-8'
319
- });
320
- const json = JSON.parse(jsonStr, BufferJSON_reviver);
321
- fromJSON(json);
322
- }
323
- };
324
- return {
325
- chats,
326
- contacts,
327
- messages,
328
- groupMetadata,
329
- state,
330
- presences,
331
- labels,
332
- labelAssociations,
333
- bind,
334
- loadMessages: async (jid, count, cursor) => {
335
- const list = assertMessageList(jidNormalizedUser(jid));
336
- const mode = !cursor || 'before' in cursor ? 'before' : 'after';
337
- const cursorKey = cursor ? 'before' in cursor ? cursor.before : cursor.after : undefined;
338
- const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
339
- let messagesList;
340
- if (list && mode === 'before' && (!cursorKey || cursorValue)) {
341
- if (cursorValue) {
342
- const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id);
343
- messagesList = list.array.slice(0, msgIdx);
344
- } else {
345
- messagesList = list.array;
346
- }
347
- return messagesList.slice(-count);
348
- }
349
- return [];
350
- },
351
- loadMessage: async (jid, id) => messages[jidNormalizedUser(jid)]?.get(id),
352
- getMessage: (jid, id) => messages[jidNormalizedUser(jid)]?.get(id),
353
- mostRecentMessage: async jid => {
354
- const message = messages[jidNormalizedUser(jid)]?.array.slice(-1)[0];
355
- return message;
356
- },
357
- fetchImageUrl: async (jid, sock) => {
358
- const s = sock || socket;
359
- const contact = contacts[jid];
360
- if (!contact) {
361
- return s?.profilePictureUrl(jid);
362
- }
363
- if (typeof contact.imgUrl === 'undefined') {
364
- contact.imgUrl = await s?.profilePictureUrl(jid);
365
- }
366
- return contact.imgUrl;
367
- },
368
- fetchGroupMetadata: async (jid, sock) => {
369
- const s = sock || socket;
370
- if (!groupMetadata[jid]) {
371
- const metadata = await s?.groupMetadata(jid);
372
- if (metadata) {
373
- groupMetadata[jid] = metadata;
374
- }
375
- }
376
- return groupMetadata[jid];
377
- },
378
- fetchMessageReceipts: async ({
379
- remoteJid,
380
- id
381
- }, sock) => {
382
- const s = sock || socket;
383
- const list = messages[jidNormalizedUser(remoteJid)];
384
- const msg = list?.get(id);
385
- return msg?.userReceipt;
386
- },
387
- toJSON,
388
- fromJSON,
389
- writeToFile,
390
- readFromFile
391
- };
392
- };
393
- function BufferJSON_replacer(_key, value) {
394
- if (value?.type === 'Buffer' && Array.isArray(value?.data)) {
395
- return value;
396
- }
397
- if (value instanceof Uint8Array || typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
398
- return {
399
- type: 'Buffer',
400
- data: Buffer.from(value).toString('base64'),
401
- __enc: 'base64'
402
- };
403
- }
404
- return value;
405
- }
406
- function BufferJSON_reviver(_key, value) {
407
- if (value?.type === 'Buffer') {
408
- if (value.__enc === 'base64' && typeof value.data === 'string') {
409
- return Buffer.from(value.data, 'base64');
410
- }
411
- if (Array.isArray(value.data)) {
412
- return Buffer.from(value.data);
413
- }
414
- }
415
- return value;
416
- }
417
- export default makeInMemoryStore;
@@ -1,69 +0,0 @@
1
- export default function makeOrderedDictionary(idGetter) {
2
- const array = [];
3
- const dict = {};
4
- const get = id => dict[id];
5
- const update = item => {
6
- const id = idGetter(item);
7
- const idx = array.findIndex(i => idGetter(i) === id);
8
- if (idx >= 0) {
9
- array[idx] = item;
10
- dict[id] = item;
11
- }
12
- return false;
13
- };
14
- const upsert = (item, mode) => {
15
- const id = idGetter(item);
16
- if (get(id)) {
17
- update(item);
18
- } else {
19
- if (mode === 'append') array.push(item);else array.unshift(item);
20
- dict[id] = item;
21
- }
22
- };
23
- const remove = item => {
24
- const id = idGetter(item);
25
- const idx = array.findIndex(i => idGetter(i) === id);
26
- if (idx >= 0) {
27
- array.splice(idx, 1);
28
- delete dict[id];
29
- return true;
30
- }
31
- return false;
32
- };
33
- return {
34
- array,
35
- get,
36
- upsert,
37
- update,
38
- remove,
39
- updateAssign: (id, update) => {
40
- const item = get(id);
41
- if (item) {
42
- Object.assign(item, update);
43
- delete dict[id];
44
- dict[idGetter(item)] = item;
45
- return true;
46
- }
47
- return false;
48
- },
49
- clear: () => {
50
- array.length = 0;
51
- for (const key of Object.keys(dict)) delete dict[key];
52
- },
53
- filter: contain => {
54
- let i = 0;
55
- while (i < array.length) {
56
- if (!contain(array[i])) {
57
- delete dict[idGetter(array[i])];
58
- array.splice(i, 1);
59
- } else {
60
- i++;
61
- }
62
- }
63
- },
64
- toJSON: () => array,
65
- fromJSON: newItems => {
66
- array.splice(0, array.length, ...newItems);
67
- }
68
- };
69
- }
@@ -1,27 +0,0 @@
1
- export class ObjectRepository {
2
- constructor(entities = {}) {
3
- this.entityMap = new Map(Object.entries(entities));
4
- }
5
- findById(id) {
6
- return this.entityMap.get(id);
7
- }
8
- findAll() {
9
- return Array.from(this.entityMap.values());
10
- }
11
- upsertById(id, entity) {
12
- this.entityMap.set(id, {
13
- ...entity
14
- });
15
- return this;
16
- }
17
- deleteById(id) {
18
- return this.entityMap.delete(id);
19
- }
20
- count() {
21
- return this.entityMap.size;
22
- }
23
- toJSON() {
24
- return this.findAll();
25
- }
26
- }
27
- export default ObjectRepository;