@alannxd/baileys 6.0.5 → 6.0.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 (234) hide show
  1. package/WAProto/fix-import.js +29 -0
  2. package/WAProto/index.js +160 -201
  3. package/engine-requirements.js +1 -1
  4. package/lib/Defaults/baileys-version.json +3 -0
  5. package/lib/Defaults/index.d.ts +15 -37
  6. package/lib/Defaults/index.js +136 -119
  7. package/lib/Defaults/phonenumber-mcc.json +223 -0
  8. package/lib/Signal/Group/ciphertext-message.d.ts +0 -1
  9. package/lib/Signal/Group/ciphertext-message.js +5 -2
  10. package/lib/Signal/Group/group-session-builder.d.ts +3 -4
  11. package/lib/Signal/Group/group-session-builder.js +41 -7
  12. package/lib/Signal/Group/group_cipher.d.ts +4 -4
  13. package/lib/Signal/Group/group_cipher.js +51 -37
  14. package/lib/Signal/Group/index.d.ts +11 -12
  15. package/lib/Signal/Group/index.js +57 -12
  16. package/lib/Signal/Group/keyhelper.d.ts +1 -2
  17. package/lib/Signal/Group/keyhelper.js +44 -7
  18. package/lib/Signal/Group/queue-job.d.ts +1 -0
  19. package/lib/Signal/Group/queue-job.js +57 -0
  20. package/lib/Signal/Group/sender-chain-key.d.ts +2 -3
  21. package/lib/Signal/Group/sender-chain-key.js +15 -7
  22. package/lib/Signal/Group/sender-key-distribution-message.d.ts +1 -2
  23. package/lib/Signal/Group/sender-key-distribution-message.js +11 -8
  24. package/lib/Signal/Group/sender-key-message.d.ts +1 -2
  25. package/lib/Signal/Group/sender-key-message.js +12 -9
  26. package/lib/Signal/Group/sender-key-name.d.ts +0 -1
  27. package/lib/Signal/Group/sender-key-name.js +5 -2
  28. package/lib/Signal/Group/sender-key-record.d.ts +2 -3
  29. package/lib/Signal/Group/sender-key-record.js +21 -9
  30. package/lib/Signal/Group/sender-key-state.d.ts +6 -7
  31. package/lib/Signal/Group/sender-key-state.js +42 -27
  32. package/lib/Signal/Group/sender-message-key.d.ts +0 -1
  33. package/lib/Signal/Group/sender-message-key.js +7 -4
  34. package/lib/Signal/libsignal.d.ts +3 -5
  35. package/lib/Signal/libsignal.js +90 -347
  36. package/lib/Socket/Client/{types.d.ts → abstract-socket-client.d.ts} +5 -4
  37. package/lib/Socket/Client/abstract-socket-client.js +13 -0
  38. package/lib/Socket/Client/index.d.ts +3 -3
  39. package/lib/Socket/Client/index.js +19 -3
  40. package/lib/Socket/Client/mobile-socket-client.d.ts +13 -0
  41. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  42. package/lib/Socket/Client/{websocket.d.ts → web-socket-client.d.ts} +2 -3
  43. package/lib/Socket/Client/web-socket-client.js +62 -0
  44. package/lib/Socket/business.d.ts +108 -154
  45. package/lib/Socket/business.js +43 -162
  46. package/lib/Socket/chats.d.ts +239 -96
  47. package/lib/Socket/chats.js +427 -627
  48. package/lib/Socket/communities.d.ts +146 -239
  49. package/lib/Socket/communities.js +80 -90
  50. package/lib/Socket/groups.d.ts +57 -104
  51. package/lib/Socket/groups.js +161 -154
  52. package/lib/Socket/index.d.ts +115 -202
  53. package/lib/Socket/index.js +10 -11
  54. package/lib/Socket/luxu.d.ts +266 -22
  55. package/lib/Socket/luxu.js +465 -422
  56. package/lib/Socket/messages-recv.d.ts +84 -136
  57. package/lib/Socket/messages-recv.js +615 -1421
  58. package/lib/Socket/messages-send.d.ts +126 -142
  59. package/lib/Socket/messages-send.js +671 -878
  60. package/lib/Socket/newsletter.d.ts +85 -121
  61. package/lib/Socket/newsletter.js +272 -147
  62. package/lib/Socket/registration.d.ts +267 -0
  63. package/lib/Socket/registration.js +166 -0
  64. package/lib/Socket/socket.d.ts +19 -34
  65. package/lib/Socket/socket.js +313 -544
  66. package/lib/Socket/usync.d.ts +36 -0
  67. package/lib/Socket/usync.js +70 -0
  68. package/lib/Store/index.d.ts +3 -10
  69. package/lib/Store/index.js +10 -10
  70. package/lib/Store/make-cache-manager-store.d.ts +11 -17
  71. package/lib/Store/make-cache-manager-store.js +41 -43
  72. package/lib/Store/make-in-memory-store.d.ts +118 -39
  73. package/lib/Store/make-in-memory-store.js +341 -112
  74. package/lib/Store/make-ordered-dictionary.d.ts +10 -11
  75. package/lib/Store/make-ordered-dictionary.js +20 -14
  76. package/lib/Store/object-repository.d.ts +9 -10
  77. package/lib/Store/object-repository.js +6 -11
  78. package/lib/Types/Auth.d.ts +12 -19
  79. package/lib/Types/Auth.js +2 -2
  80. package/lib/Types/Call.d.ts +1 -3
  81. package/lib/Types/Call.js +2 -2
  82. package/lib/Types/Chat.d.ts +13 -35
  83. package/lib/Types/Chat.js +4 -8
  84. package/lib/Types/Contact.d.ts +1 -8
  85. package/lib/Types/Contact.js +2 -2
  86. package/lib/Types/Events.d.ts +17 -116
  87. package/lib/Types/Events.js +2 -2
  88. package/lib/Types/GroupMetadata.d.ts +5 -21
  89. package/lib/Types/GroupMetadata.js +2 -2
  90. package/lib/Types/Label.d.ts +0 -12
  91. package/lib/Types/Label.js +5 -3
  92. package/lib/Types/LabelAssociation.d.ts +0 -1
  93. package/lib/Types/LabelAssociation.js +5 -3
  94. package/lib/Types/Message.d.ts +58 -105
  95. package/lib/Types/Message.js +9 -11
  96. package/lib/Types/Newsletter.d.ts +103 -0
  97. package/lib/Types/Newsletter.js +38 -0
  98. package/lib/Types/Product.d.ts +1 -2
  99. package/lib/Types/Product.js +2 -2
  100. package/lib/Types/Signal.d.ts +2 -32
  101. package/lib/Types/Signal.js +2 -2
  102. package/lib/Types/Socket.d.ts +25 -50
  103. package/lib/Types/Socket.js +2 -3
  104. package/lib/Types/State.d.ts +2 -72
  105. package/lib/Types/State.js +2 -56
  106. package/lib/Types/USync.d.ts +2 -3
  107. package/lib/Types/USync.js +2 -2
  108. package/lib/Types/index.d.ts +14 -22
  109. package/lib/Types/index.js +31 -15
  110. package/lib/Utils/auth-utils.d.ts +6 -12
  111. package/lib/Utils/auth-utils.js +143 -239
  112. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  113. package/lib/Utils/baileys-event-stream.js +63 -0
  114. package/lib/Utils/business.d.ts +2 -3
  115. package/lib/Utils/business.js +69 -66
  116. package/lib/Utils/chat-utils.d.ts +23 -52
  117. package/lib/Utils/chat-utils.js +253 -396
  118. package/lib/Utils/crypto.d.ts +22 -18
  119. package/lib/Utils/crypto.js +90 -57
  120. package/lib/Utils/decode-wa-message.d.ts +8 -55
  121. package/lib/Utils/decode-wa-message.js +84 -203
  122. package/lib/Utils/event-buffer.d.ts +8 -9
  123. package/lib/Utils/event-buffer.js +77 -185
  124. package/lib/Utils/generics.d.ts +29 -28
  125. package/lib/Utils/generics.js +210 -180
  126. package/lib/Utils/history.d.ts +9 -18
  127. package/lib/Utils/history.js +55 -93
  128. package/lib/Utils/index.d.ts +17 -22
  129. package/lib/Utils/index.js +33 -22
  130. package/lib/Utils/link-preview.d.ts +5 -5
  131. package/lib/Utils/link-preview.js +24 -16
  132. package/lib/Utils/logger.d.ts +3 -11
  133. package/lib/Utils/logger.js +7 -3
  134. package/lib/Utils/lt-hash.d.ts +12 -8
  135. package/lib/Utils/lt-hash.js +46 -3
  136. package/lib/Utils/make-mutex.d.ts +2 -4
  137. package/lib/Utils/make-mutex.js +34 -24
  138. package/lib/Utils/messages-media.d.ts +44 -61
  139. package/lib/Utils/messages-media.js +482 -451
  140. package/lib/Utils/messages.d.ts +18 -32
  141. package/lib/Utils/messages.js +369 -458
  142. package/lib/Utils/noise-handler.d.ts +14 -13
  143. package/lib/Utils/noise-handler.js +99 -145
  144. package/lib/Utils/process-message.d.ts +12 -31
  145. package/lib/Utils/process-message.js +150 -459
  146. package/lib/Utils/signal.d.ts +5 -20
  147. package/lib/Utils/signal.js +72 -120
  148. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -2
  149. package/lib/Utils/use-multi-file-auth-state.js +27 -29
  150. package/lib/Utils/validate-connection.d.ts +7 -7
  151. package/lib/Utils/validate-connection.js +99 -73
  152. package/lib/WABinary/constants.d.ts +27 -25
  153. package/lib/WABinary/constants.js +20 -1281
  154. package/lib/WABinary/decode.d.ts +5 -5
  155. package/lib/WABinary/decode.js +42 -52
  156. package/lib/WABinary/encode.d.ts +3 -3
  157. package/lib/WABinary/encode.js +155 -110
  158. package/lib/WABinary/generic-utils.d.ts +7 -8
  159. package/lib/WABinary/generic-utils.js +49 -48
  160. package/lib/WABinary/index.d.ts +5 -6
  161. package/lib/WABinary/index.js +21 -6
  162. package/lib/WABinary/jid-utils.d.ts +8 -25
  163. package/lib/WABinary/jid-utils.js +40 -74
  164. package/lib/WABinary/types.d.ts +1 -2
  165. package/lib/WABinary/types.js +2 -2
  166. package/lib/WAM/BinaryInfo.d.ts +11 -3
  167. package/lib/WAM/BinaryInfo.js +5 -2
  168. package/lib/WAM/constants.d.ts +3 -5
  169. package/lib/WAM/constants.js +11958 -19461
  170. package/lib/WAM/encode.d.ts +3 -3
  171. package/lib/WAM/encode.js +22 -17
  172. package/lib/WAM/index.d.ts +3 -4
  173. package/lib/WAM/index.js +19 -4
  174. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +3 -4
  175. package/lib/WAUSync/Protocols/USyncContactProtocol.js +13 -33
  176. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +2 -3
  177. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +14 -11
  178. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +2 -3
  179. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +12 -9
  180. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +2 -3
  181. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +13 -9
  182. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +3 -4
  183. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +22 -20
  184. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +3 -5
  185. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +8 -13
  186. package/lib/WAUSync/Protocols/index.d.ts +4 -6
  187. package/lib/WAUSync/Protocols/index.js +20 -6
  188. package/lib/WAUSync/USyncQuery.d.ts +4 -6
  189. package/lib/WAUSync/USyncQuery.js +35 -44
  190. package/lib/WAUSync/USyncUser.d.ts +5 -10
  191. package/lib/WAUSync/USyncUser.js +5 -10
  192. package/lib/WAUSync/index.js +19 -4
  193. package/lib/index.d.ts +9 -10
  194. package/lib/index.js +34 -12
  195. package/package.json +50 -83
  196. package/WAProto/GenerateStatics.sh +0 -3
  197. package/WAProto/WAProto.proto +0 -5479
  198. package/WAProto/fix-imports.js +0 -85
  199. package/WAProto/index.d.ts +0 -14017
  200. package/lib/Signal/lid-mapping.d.ts +0 -23
  201. package/lib/Signal/lid-mapping.js +0 -277
  202. package/lib/Socket/Client/types.js +0 -11
  203. package/lib/Socket/Client/websocket.js +0 -54
  204. package/lib/Socket/mex.d.ts +0 -3
  205. package/lib/Socket/mex.js +0 -42
  206. package/lib/Store/keyed-db.d.ts +0 -22
  207. package/lib/Store/keyed-db.js +0 -108
  208. package/lib/Types/Bussines.d.ts +0 -25
  209. package/lib/Types/Bussines.js +0 -2
  210. package/lib/Types/Mex.d.ts +0 -141
  211. package/lib/Types/Mex.js +0 -37
  212. package/lib/Utils/browser-utils.d.ts +0 -4
  213. package/lib/Utils/browser-utils.js +0 -28
  214. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  215. package/lib/Utils/companion-reg-client-utils.js +0 -35
  216. package/lib/Utils/identity-change-handler.d.ts +0 -44
  217. package/lib/Utils/identity-change-handler.js +0 -50
  218. package/lib/Utils/message-retry-manager.d.ts +0 -115
  219. package/lib/Utils/message-retry-manager.js +0 -265
  220. package/lib/Utils/offline-node-processor.d.ts +0 -17
  221. package/lib/Utils/offline-node-processor.js +0 -40
  222. package/lib/Utils/pre-key-manager.d.ts +0 -28
  223. package/lib/Utils/pre-key-manager.js +0 -106
  224. package/lib/Utils/reporting-utils.d.ts +0 -11
  225. package/lib/Utils/reporting-utils.js +0 -258
  226. package/lib/Utils/stanza-ack.d.ts +0 -11
  227. package/lib/Utils/stanza-ack.js +0 -38
  228. package/lib/Utils/sync-action-utils.d.ts +0 -19
  229. package/lib/Utils/sync-action-utils.js +0 -49
  230. package/lib/Utils/tc-token-utils.d.ts +0 -37
  231. package/lib/Utils/tc-token-utils.js +0 -163
  232. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  233. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  234. package/lib/WAUSync/index.d.ts +0 -4
@@ -1,164 +1,290 @@
1
- import * as WAProto_1 from "../../WAProto/index.js";
2
- import * as Defaults_1 from "../Defaults/index.js";
3
- import { LabelAssociationType } from "../Types/LabelAssociation.js";
4
- import * as Utils_1 from "../Utils/index.js";
5
- import * as WABinary_1 from "../WABinary/index.js";
6
- import makeOrderedDictionary from "./make-ordered-dictionary.js";
7
- import { ObjectRepository } from "./object-repository.js";
8
- import KeyedDB from "./keyed-db.js";
9
-
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");
10
14
  const waChatKey = (pin) => ({
11
- key: (c) =>
12
- (pin ? (c.pinned ? "1" : "0") : "") +
13
- (c.archived ? "0" : "1") +
14
- (c.conversationTimestamp
15
- ? c.conversationTimestamp.toString(16).padStart(8, "0")
16
- : "") +
17
- c.id,
15
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
18
16
  compare: (k1, k2) => k2.localeCompare(k1)
19
17
  });
20
-
21
- export const waMessageID = (m) => m.key.id || "";
22
-
23
- export const waLabelAssociationKey = {
24
- key: (la) =>
25
- la.type === LabelAssociationType.Chat
26
- ? la.chatId + la.labelId
27
- : la.chatId + la.messageId + la.labelId,
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),
28
23
  compare: (k1, k2) => k2.localeCompare(k1)
29
24
  };
30
-
31
- const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
32
-
33
- export default function makeInMemoryStore(config) {
25
+ const makeMessagesDictionary = () => (0, make_ordered_dictionary_1.default)(exports.waMessageID);
26
+ exports.default = (config) => {
34
27
  const socket = config.socket;
35
- const chatKey = config.chatKey || waChatKey(true);
36
- const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
37
- const logger =
38
- config.logger ||
39
- Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({
40
- stream: "in-mem-store"
41
- });
42
-
43
- const chats = new KeyedDB(chatKey.compare, chatKey.key);
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);
44
33
  const messages = {};
45
34
  const contacts = {};
46
35
  const groupMetadata = {};
47
36
  const presences = {};
48
- const state = { connection: "close" };
49
- const labels = new ObjectRepository();
50
- const labelAssociations = new KeyedDB(labelAssociationKey.compare, labelAssociationKey.key);
51
-
37
+ const state = { connection: 'close' };
38
+ const labels = new object_repository_1.ObjectRepository();
39
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
52
40
  const assertMessageList = (jid) => {
53
- if (!messages[jid]) messages[jid] = makeMessagesDictionary();
41
+ if (!messages[jid]) {
42
+ messages[jid] = makeMessagesDictionary();
43
+ }
54
44
  return messages[jid];
55
45
  };
56
-
57
46
  const contactsUpsert = (newContacts) => {
58
47
  const oldContacts = new Set(Object.keys(contacts));
59
48
  for (const contact of newContacts) {
60
49
  oldContacts.delete(contact.id);
61
- contacts[contact.id] = { ...(contacts[contact.id] || {}), ...contact };
50
+ contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
62
51
  }
63
52
  return oldContacts;
64
53
  };
65
-
66
54
  const labelsUpsert = (newLabels) => {
67
- for (const label of newLabels) labels.upsertById(label.id, label);
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);
68
66
  };
69
-
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
+ */
70
73
  const bind = (ev) => {
71
- ev.on("connection.update", (update) => Object.assign(state, update));
72
-
73
- ev.on("messaging-history.set", ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
74
- if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) return;
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 }) => {
75
78
  if (isLatest) {
76
79
  chats.clear();
77
- for (const id in messages) delete messages[id];
80
+ for (const id in messages) {
81
+ delete messages[id];
82
+ }
78
83
  }
79
- chats.insertIfAbsent(...newChats);
84
+ const chatsAdded = chats.insertIfAbsent(...newChats).length;
85
+ logger.debug({ chatsAdded }, 'synced chats');
80
86
  const oldContacts = contactsUpsert(newContacts);
81
- if (isLatest) for (const jid of oldContacts) delete contacts[jid];
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');
82
93
  for (const msg of newMessages) {
83
94
  const jid = msg.key.remoteJid;
84
95
  const list = assertMessageList(jid);
85
- list.upsert(msg, "prepend");
96
+ list.upsert(msg, 'prepend');
86
97
  }
98
+ logger.debug({ messages: newMessages.length }, 'synced messages');
99
+ });
100
+ ev.on('contacts.upsert', contacts => {
101
+ contactsUpsert(contacts);
87
102
  });
88
-
89
- ev.on("contacts.upsert", contactsUpsert);
90
-
91
- ev.on("contacts.update", async (updates) => {
103
+ ev.on('contacts.update', async (updates) => {
104
+ var _a;
92
105
  for (const update of updates) {
93
- const contact = contacts[update.id];
94
- if (contact) Object.assign(contact, update);
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
+ }
95
130
  }
96
131
  });
97
-
98
- ev.on("chats.upsert", (newChats) => chats.upsert(...newChats));
99
-
100
- ev.on("chats.update", (updates) => {
132
+ ev.on('chats.upsert', newChats => {
133
+ chats.upsert(...newChats);
134
+ });
135
+ ev.on('chats.update', updates => {
101
136
  for (let update of updates) {
102
- chats.update(update.id, (chat) => Object.assign(chat, update));
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
+ }
103
147
  }
104
148
  });
105
-
106
- ev.on("labels.edit", (label) => {
107
- if (label.deleted) return labels.deleteById(label.id);
108
- if (labels.count() < 20) labels.upsertById(label.id, label);
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');
109
158
  });
110
-
111
- ev.on("labels.association", ({ type, association }) => {
112
- if (type === "add") labelAssociations.upsert(association);
113
- if (type === "remove") labelAssociations.delete(association);
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
+ }
114
170
  });
115
-
116
- ev.on("presence.update", ({ id, presences: update }) => {
171
+ ev.on('presence.update', ({ id, presences: update }) => {
117
172
  presences[id] = presences[id] || {};
118
173
  Object.assign(presences[id], update);
119
174
  });
120
-
121
- ev.on("chats.delete", (deletions) => {
122
- for (const item of deletions) chats.deleteById(item);
175
+ ev.on('chats.delete', deletions => {
176
+ for (const item of deletions) {
177
+ if (chats.get(item)) {
178
+ chats.deleteById(item);
179
+ }
180
+ }
123
181
  });
124
-
125
- ev.on("messages.upsert", ({ messages: newMessages, type }) => {
126
- if (type !== "append" && type !== "notify") return;
127
- for (const msg of newMessages) {
128
- const jid = WABinary_1.jidNormalizedUser(msg.key.remoteJid);
129
- const list = assertMessageList(jid);
130
- list.upsert(msg, "append");
131
- if (type === "notify" && !chats.get(jid))
132
- ev.emit("chats.upsert", [
133
- {
134
- id: jid,
135
- conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
136
- unreadCount: 1
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
+ }
137
200
  }
138
- ]);
201
+ }
202
+ break;
139
203
  }
140
204
  });
141
-
142
- ev.on("messages.update", (updates) => {
205
+ ev.on('messages.update', updates => {
206
+ var _a;
143
207
  for (const { update, key } of updates) {
144
- const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid));
145
- list.updateAssign(key.id, update);
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
+ }
146
221
  }
147
222
  });
148
-
149
- ev.on("messages.delete", (item) => {
150
- if ("all" in item) messages[item.jid]?.clear();
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
+ }
151
228
  else {
152
229
  const jid = item.keys[0].remoteJid;
153
230
  const list = messages[jid];
154
231
  if (list) {
155
- const idSet = new Set(item.keys.map((k) => k.id));
156
- list.filter((m) => !idSet.has(m.key.id));
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);
157
284
  }
158
285
  }
159
286
  });
160
287
  };
161
-
162
288
  const toJSON = () => ({
163
289
  chats,
164
290
  contacts,
@@ -166,21 +292,18 @@ export default function makeInMemoryStore(config) {
166
292
  labels,
167
293
  labelAssociations
168
294
  });
169
-
170
295
  const fromJSON = (json) => {
171
296
  chats.upsert(...json.chats);
172
- labelAssociations.upsert(...(json.labelAssociations || []));
297
+ labelAssociations.upsert(...json.labelAssociations || []);
173
298
  contactsUpsert(Object.values(json.contacts));
174
299
  labelsUpsert(Object.values(json.labels || {}));
175
300
  for (const jid in json.messages) {
176
301
  const list = assertMessageList(jid);
177
- for (const msg of json.messages[jid])
178
- list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), "append");
302
+ for (const msg of json.messages[jid]) {
303
+ list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append');
304
+ }
179
305
  }
180
306
  };
181
- const loadMessage = async (jid, id) => {
182
- return messages[jid]?.get(id)
183
- }
184
307
  return {
185
308
  chats,
186
309
  contacts,
@@ -191,8 +314,114 @@ export default function makeInMemoryStore(config) {
191
314
  labels,
192
315
  labelAssociations,
193
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
+ },
194
409
  toJSON,
195
410
  fromJSON,
196
- loadMessage
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
+ }
197
426
  };
198
- }
427
+ };
@@ -1,14 +1,13 @@
1
1
  declare function makeOrderedDictionary<T>(idGetter: (item: T) => string): {
2
- array: T[];
3
- get: (id: string) => T | undefined;
4
- upsert: (item: T, mode: 'append' | 'prepend') => void;
5
- update: (item: T) => boolean;
6
- remove: (item: T) => boolean;
7
- updateAssign: (id: string, update: Partial<T>) => boolean;
8
- clear: () => void;
9
- filter: (contain: (item: T) => boolean) => void;
10
- toJSON: () => T[];
11
- fromJSON: (newItems: T[]) => void;
2
+ array: T[];
3
+ get: (id: string) => T | undefined;
4
+ upsert: (item: T, mode: 'append' | 'prepend') => void;
5
+ update: (item: T) => boolean;
6
+ remove: (item: T) => boolean;
7
+ updateAssign: (id: string, update: Partial<T>) => boolean;
8
+ clear: () => void;
9
+ filter: (contain: (item: T) => boolean) => void;
10
+ toJSON: () => T[];
11
+ fromJSON: (newItems: T[]) => void;
12
12
  };
13
13
  export default makeOrderedDictionary;
14
- export { makeOrderedDictionary };
@@ -1,9 +1,9 @@
1
- export default function makeOrderedDictionary(idGetter) {
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function makeOrderedDictionary(idGetter) {
2
4
  const array = [];
3
5
  const dict = {};
4
-
5
6
  const get = (id) => dict[id];
6
-
7
7
  const update = (item) => {
8
8
  const id = idGetter(item);
9
9
  const idx = array.findIndex(i => idGetter(i) === id);
@@ -13,18 +13,21 @@ export default function makeOrderedDictionary(idGetter) {
13
13
  }
14
14
  return false;
15
15
  };
16
-
17
16
  const upsert = (item, mode) => {
18
17
  const id = idGetter(item);
19
18
  if (get(id)) {
20
19
  update(item);
21
- } else {
22
- if (mode === 'append') array.push(item);
23
- else array.unshift(item);
20
+ }
21
+ else {
22
+ if (mode === 'append') {
23
+ array.push(item);
24
+ }
25
+ else {
26
+ array.splice(0, 0, item);
27
+ }
24
28
  dict[id] = item;
25
29
  }
26
30
  };
27
-
28
31
  const remove = (item) => {
29
32
  const id = idGetter(item);
30
33
  const idx = array.findIndex(i => idGetter(i) === id);
@@ -35,7 +38,6 @@ export default function makeOrderedDictionary(idGetter) {
35
38
  }
36
39
  return false;
37
40
  };
38
-
39
41
  return {
40
42
  array,
41
43
  get,
@@ -53,8 +55,10 @@ export default function makeOrderedDictionary(idGetter) {
53
55
  return false;
54
56
  },
55
57
  clear: () => {
56
- array.length = 0;
57
- for (const key of Object.keys(dict)) delete dict[key];
58
+ array.splice(0, array.length);
59
+ Object.keys(dict).forEach(key => {
60
+ delete dict[key];
61
+ });
58
62
  },
59
63
  filter: (contain) => {
60
64
  let i = 0;
@@ -62,8 +66,9 @@ export default function makeOrderedDictionary(idGetter) {
62
66
  if (!contain(array[i])) {
63
67
  delete dict[idGetter(array[i])];
64
68
  array.splice(i, 1);
65
- } else {
66
- i++;
69
+ }
70
+ else {
71
+ i += 1;
67
72
  }
68
73
  }
69
74
  },
@@ -72,4 +77,5 @@ export default function makeOrderedDictionary(idGetter) {
72
77
  array.splice(0, array.length, ...newItems);
73
78
  }
74
79
  };
75
- }
80
+ }
81
+ exports.default = makeOrderedDictionary;
@@ -1,11 +1,10 @@
1
- declare class ObjectRepository<T> {
2
- private entityMap: Map<string, T>;
3
- constructor(entities?: { [id: string]: T });
4
- findById(id: string): T | undefined;
5
- findAll(): T[];
6
- upsertById(id: string, entity: T): Map<string, T>;
7
- deleteById(id: string): boolean;
8
- count(): number;
9
- toJSON(): T[];
1
+ export declare class ObjectRepository<T extends object> {
2
+ readonly entityMap: Map<string, T>;
3
+ constructor(entities?: Record<string, T>);
4
+ findById(id: string): T | undefined;
5
+ findAll(): T[];
6
+ upsertById(id: string, entity: T): Map<string, T>;
7
+ deleteById(id: string): boolean;
8
+ count(): number;
9
+ toJSON(): T[];
10
10
  }
11
- export { ObjectRepository };