@zervonex/baileys 0.0.0-stage → 3.0.1

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 (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3203 -2
  3. package/WAProto/WAProtoCompile.js +291 -0
  4. package/WAProto/fetcher.js +69 -0
  5. package/WAProto/index.js +88 -0
  6. package/WAProto/parser.js +313 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Builders/AIRich.js +590 -0
  9. package/lib/Builders/base.js +130 -0
  10. package/lib/Builders/builders.js +448 -0
  11. package/lib/Builders/index.js +3 -0
  12. package/lib/Defaults/index.js +225 -0
  13. package/lib/Defaults/phonenumber-mcc.json +223 -0
  14. package/lib/Signal/index.js +2 -0
  15. package/lib/Signal/libsignal.js +523 -0
  16. package/lib/Signal/lid-mapping.js +283 -0
  17. package/lib/Socket/Client/index.js +2 -0
  18. package/lib/Socket/Client/types.js +10 -0
  19. package/lib/Socket/Client/websocket.js +84 -0
  20. package/lib/Socket/business.js +152 -0
  21. package/lib/Socket/chats.js +855 -0
  22. package/lib/Socket/communities.js +147 -0
  23. package/lib/Socket/groups.js +294 -0
  24. package/lib/Socket/index.js +15 -0
  25. package/lib/Socket/messages-recv.js +904 -0
  26. package/lib/Socket/messages-send.js +693 -0
  27. package/lib/Socket/mex.js +34 -0
  28. package/lib/Socket/newsletter.js +752 -0
  29. package/lib/Socket/nexus-handler.js +55 -0
  30. package/lib/Socket/registration.js +155 -0
  31. package/lib/Socket/socket.js +798 -0
  32. package/lib/Socket/spam-report.js +65 -0
  33. package/lib/Socket/username.js +82 -0
  34. package/lib/Store/index.js +6 -0
  35. package/lib/Store/make-cache-manager-store.js +81 -0
  36. package/lib/Store/make-in-memory-store.js +425 -0
  37. package/lib/Store/make-ordered-dictionary.js +82 -0
  38. package/lib/Store/object-repository.js +31 -0
  39. package/lib/Store/reporting-info-store.js +38 -0
  40. package/lib/Types/Auth.js +2 -0
  41. package/lib/Types/Bussines.js +2 -0
  42. package/lib/Types/Call.js +2 -0
  43. package/lib/Types/Chat.js +8 -0
  44. package/lib/Types/Contact.js +2 -0
  45. package/lib/Types/Events.js +2 -0
  46. package/lib/Types/GroupMetadata.js +2 -0
  47. package/lib/Types/Label.js +25 -0
  48. package/lib/Types/LabelAssociation.js +7 -0
  49. package/lib/Types/Message.js +15 -0
  50. package/lib/Types/Newsletter.js +100 -0
  51. package/lib/Types/Product.js +2 -0
  52. package/lib/Types/Signal.js +2 -0
  53. package/lib/Types/Socket.js +14 -0
  54. package/lib/Types/State.js +26 -0
  55. package/lib/Types/USync.js +2 -0
  56. package/lib/Types/index.js +30 -0
  57. package/lib/Utils/auth-utils.js +142 -0
  58. package/lib/Utils/baileys-event-stream.js +33 -0
  59. package/lib/Utils/bot-capabilities.js +40 -0
  60. package/lib/Utils/bot-planning-replay.js +44 -0
  61. package/lib/Utils/browser-utils.js +26 -0
  62. package/lib/Utils/business.js +75 -0
  63. package/lib/Utils/chat-utils.js +316 -0
  64. package/lib/Utils/companion-reg-client-utils.js +20 -0
  65. package/lib/Utils/consumer-application.js +38 -0
  66. package/lib/Utils/crypto.js +52 -0
  67. package/lib/Utils/decode-wa-message.js +197 -0
  68. package/lib/Utils/event-buffer.js +273 -0
  69. package/lib/Utils/extras.js +186 -0
  70. package/lib/Utils/generics.js +195 -0
  71. package/lib/Utils/history.js +51 -0
  72. package/lib/Utils/identity-change-handler.js +19 -0
  73. package/lib/Utils/index.js +39 -0
  74. package/lib/Utils/key-store.js +3 -0
  75. package/lib/Utils/link-preview.js +51 -0
  76. package/lib/Utils/logger.js +2 -0
  77. package/lib/Utils/lt-hash.js +3 -0
  78. package/lib/Utils/make-mutex.js +16 -0
  79. package/lib/Utils/message-composer.js +59 -0
  80. package/lib/Utils/message-retry-manager.js +48 -0
  81. package/lib/Utils/messages-media.js +520 -0
  82. package/lib/Utils/messages.js +742 -0
  83. package/lib/Utils/meta-ai-msmsg.js +122 -0
  84. package/lib/Utils/meta-compositing.js +75 -0
  85. package/lib/Utils/modern-messages.js +235 -0
  86. package/lib/Utils/native-flow.js +55 -0
  87. package/lib/Utils/noise-handler.js +161 -0
  88. package/lib/Utils/pre-key-manager.js +76 -0
  89. package/lib/Utils/process-message.js +399 -0
  90. package/lib/Utils/reporting-utils.js +171 -0
  91. package/lib/Utils/signal.js +167 -0
  92. package/lib/Utils/spam-report-utils.js +142 -0
  93. package/lib/Utils/sync-action-utils.js +33 -0
  94. package/lib/Utils/tc-token-utils.js +102 -0
  95. package/lib/Utils/use-multi-file-auth-state.js +307 -0
  96. package/lib/Utils/validate-connection.js +181 -0
  97. package/lib/WABinary/constants.js +1321 -0
  98. package/lib/WABinary/decode.js +152 -0
  99. package/lib/WABinary/encode.js +140 -0
  100. package/lib/WABinary/generic-utils.js +179 -0
  101. package/lib/WABinary/index.js +6 -0
  102. package/lib/WABinary/jid-utils.js +235 -0
  103. package/lib/WABinary/types.js +4 -0
  104. package/lib/WAM/BinaryInfo.js +10 -0
  105. package/lib/WAM/constants.js +22853 -0
  106. package/lib/WAM/encode.js +150 -0
  107. package/lib/WAM/index.js +3 -0
  108. package/lib/WAUSync/Protocols/USyncBotProfileProtocol.js +30 -0
  109. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +48 -0
  110. package/lib/WAUSync/Protocols/USyncContactProtocol.js +23 -0
  111. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +28 -0
  112. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +15 -0
  113. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +24 -0
  114. package/lib/WAUSync/Protocols/USyncLIDProtocol.js +9 -0
  115. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +21 -0
  116. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +19 -0
  117. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +19 -0
  118. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +22 -0
  119. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +16 -0
  120. package/lib/WAUSync/Protocols/index.js +12 -0
  121. package/lib/WAUSync/USyncQuery.js +100 -0
  122. package/lib/WAUSync/USyncUser.js +20 -0
  123. package/lib/WAUSync/index.js +3 -0
  124. package/lib/index.js +68 -0
  125. package/package.json +216 -5
@@ -0,0 +1,65 @@
1
+ import { createReportingInfoStore } from '../Store/index.js'
2
+ import { SPAM_FLOWS, resolveReportJid, normalizeReportingTag, buildSpamReportIq, buildSimpleReportNode, parseSpamReportResponse } from '../Utils/index.js'
3
+ import { isJidGroup, isPnUser, isLidUser, jidNormalizedUser, S_WHATSAPP_NET } from '../WABinary/index.js'
4
+
5
+ export const makeSpamReportSocket = (sock, config) => {
6
+ const { query, signalRepository, updateBlockStatus, logger } = sock
7
+
8
+ if (!config.reportingInfoStore) config.reportingInfoStore = createReportingInfoStore()
9
+ const store = config.reportingInfoStore
10
+
11
+ const simpleReportQuery = (jid, messageKeys) => query({
12
+ tag: 'iq',
13
+ attrs: { type: 'set', xmlns: 'spam', to: S_WHATSAPP_NET },
14
+ content: [buildSimpleReportNode(jid, messageKeys)]
15
+ })
16
+
17
+ const reportSpam = async (jid, options = {}) => {
18
+ const { spamFlow = SPAM_FLOWS.ACCOUNT_INFO_REPORT, messages: manualMessages, maxMessages = 5 } = options
19
+ const reportJid = await resolveReportJid(jid, signalRepository?.lidMapping)
20
+ let messages = manualMessages
21
+ if (!messages?.length) {
22
+ messages = store.getForJid(reportJid, maxMessages)
23
+ if (!messages.length) messages = store.getForJid(jid, maxMessages)
24
+ }
25
+ if (!messages?.length) throw new Error(`reportSpam: no reporting_tag stored for ${jid}. Receive at least one message first.`)
26
+ const normalized = messages.slice(0, maxMessages).map(m => ({
27
+ stanzaId: m.stanzaId || m.id,
28
+ timestamp: Number(m.timestamp || m.sendTimestamp || m.t),
29
+ reportingTag: normalizeReportingTag(m.reportingTag || m.tag),
30
+ text: m.text ?? m.raw ?? '',
31
+ pushName: m.pushName || m.reportedPushName || '',
32
+ messageType: m.messageType || m.type || 'text',
33
+ fromJid: m.fromJid || m.from || reportJid
34
+ }))
35
+ logger?.debug?.({ jid: reportJid, spamFlow, count: normalized.length }, 'sending spam report IQ')
36
+ const result = await query(buildSpamReportIq(reportJid, normalized, spamFlow))
37
+ return { ...parseSpamReportResponse(result), messageCount: normalized.length }
38
+ }
39
+
40
+ const reportContact = async (jid, messageKeys = []) => {
41
+ const normalized = jidNormalizedUser(jid)
42
+ if (!isPnUser(normalized) && !isLidUser(normalized)) throw new Error('reportContact requires a valid contact JID')
43
+ const result = await simpleReportQuery(normalized, messageKeys)
44
+ await updateBlockStatus(normalized, 'block')
45
+ return parseSpamReportResponse(result)
46
+ }
47
+
48
+ const reportGroup = async (jid, messageKeys = []) => {
49
+ if (!isJidGroup(jid)) throw new Error('reportGroup requires a valid group JID')
50
+ const result = await simpleReportQuery(jid, messageKeys)
51
+ await query({ tag: 'iq', attrs: { type: 'set', xmlns: 'w:g2', to: '@g.us' }, content: [{ tag: 'leave', attrs: {}, content: [{ tag: 'group', attrs: { id: jid } }] }] })
52
+ return parseSpamReportResponse(result)
53
+ }
54
+
55
+ return {
56
+ ...sock,
57
+ reportSpam,
58
+ reportContact,
59
+ reportGroup,
60
+ getStoredReportingInfo: (jid, max = 5) => store.getForJid(jid, max),
61
+ clearStoredReportingInfo: jid => store.clear(jid),
62
+ reportingInfoStore: store,
63
+ SPAM_FLOWS
64
+ }
65
+ }
@@ -0,0 +1,82 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { executeWMexQuery } from './mex.js';
3
+ import { USyncQuery, USyncUser } from '../WAUSync/index.js';
4
+ import { makeRegistrationSocket } from './registration.js';
5
+ import { makeSpamReportSocket } from './spam-report.js';
6
+ import { USERNAME_QUERY_IDS, USERNAME_CHECK_RESULT, USERNAME_SOURCE } from '../Defaults/index.js';
7
+
8
+ export const makeUsernameSocket = config => {
9
+ const sock = makeRegistrationSocket(config);
10
+ const { query, generateMessageTag, executeUSyncQuery } = sock;
11
+
12
+ const mexQuery = (variables, queryId, dataPath) => executeWMexQuery(variables, queryId, dataPath, query, generateMessageTag);
13
+
14
+ const checkUsername = async (username, includeSuggestions = true, sessionId) => {
15
+ const session_id = sessionId || randomUUID();
16
+ const data = await mexQuery({ username, include_suggestions: includeSuggestions, session_id, source: USERNAME_SOURCE.USER_INPUT }, USERNAME_QUERY_IDS.CHECK, 'xwa2_username_check');
17
+ if (data?.result === USERNAME_CHECK_RESULT.SUCCESS) return { available: true, username, session_id };
18
+ return { available: false, username, session_id, suggestions: data?.suggestions ?? [], rejectionReasons: data?.rejection_reasons ?? [], suggestionsEligible: data?.suggestions_eligible ?? true };
19
+ };
20
+
21
+ const setUsername = async (username, options = {}) => {
22
+ const { source = USERNAME_SOURCE.USER_INPUT, sessionId, pin } = options;
23
+ const session_id = sessionId || randomUUID();
24
+ return mexQuery({ username, reserved: true, source, session_id, ...(pin ? { pin } : {}) }, USERNAME_QUERY_IDS.SET, 'xwa2_username_set');
25
+ };
26
+
27
+ const checkAndSetUsername = async username => {
28
+ const r = await checkUsername(username);
29
+ if (r.available) return setUsername(username);
30
+ return r;
31
+ };
32
+
33
+ const deleteUsername = async () => mexQuery({ username: null }, USERNAME_QUERY_IDS.SET, 'xwa2_username_delete');
34
+
35
+ const getMyUsername = async () => {
36
+ const data = await mexQuery({}, USERNAME_QUERY_IDS.GET, 'xwa2_username_get');
37
+ return data?.username ?? null;
38
+ };
39
+
40
+ const setUsernamePin = async pin => mexQuery(pin != null ? { pin } : {}, USERNAME_QUERY_IDS.PIN_SET, 'xwa2_username_pin_set');
41
+
42
+ const findUserByUsername = async (username, pin) => {
43
+ const usyncQuery = new USyncQuery().withContactProtocol();
44
+ const user = new USyncUser().withUsername(username);
45
+ if (pin) user.withUsernameKey(pin);
46
+ usyncQuery.withUser(user);
47
+ const result = await executeUSyncQuery(usyncQuery);
48
+ if (!result?.list?.length) return null;
49
+ const entry = result.list[0];
50
+ return { jid: entry.id, contact: entry.contact ?? false };
51
+ };
52
+
53
+ const fetchContactUsernames = async (...jids) => {
54
+ const usyncQuery = new USyncQuery().withUsernameProtocol();
55
+ for (const jid of jids) usyncQuery.withUser(new USyncUser().withId(jid));
56
+ const result = await executeUSyncQuery(usyncQuery);
57
+ return result?.list ?? [];
58
+ };
59
+
60
+ const checkUsernameMulti = async usernames => mexQuery({ usernames }, USERNAME_QUERY_IDS.CHECK_MULTI, 'xwa2_username_check_multi');
61
+
62
+ const getUsernameRecommendations = async (source = null) => mexQuery(source ? { source } : {}, USERNAME_QUERY_IDS.GET_RECOMMENDATIONS, 'xwa2_username_get_recommendations');
63
+
64
+ const base = {
65
+ ...sock,
66
+ checkUsername,
67
+ checkUsernameMulti,
68
+ setUsername,
69
+ checkAndSetUsername,
70
+ deleteUsername,
71
+ getMyUsername,
72
+ getUsernameRecommendations,
73
+ setUsernamePin,
74
+ findUserByUsername,
75
+ fetchContactUsernames,
76
+ USERNAME_QUERY_IDS,
77
+ USERNAME_CHECK_RESULT,
78
+ USERNAME_SOURCE
79
+ };
80
+
81
+ return makeSpamReportSocket(base, config);
82
+ };
@@ -0,0 +1,6 @@
1
+ export * from './make-cache-manager-store.js'
2
+ export * from './make-in-memory-store.js'
3
+ export * from './make-ordered-dictionary.js'
4
+ export * from './reporting-info-store.js'
5
+ export { makeInMemoryStore as default } from './make-in-memory-store.js'
6
+ export * from './object-repository.js'
@@ -0,0 +1,81 @@
1
+ import * as cacheManager from 'cache-manager';
2
+ import * as WAProto from '../../WAProto/index.js';
3
+ import { BufferJSON, initAuthCreds } from '../Utils/index.js';
4
+ import logger from '../Utils/logger.js';
5
+
6
+ const makeCacheManagerAuthState = async (store, sessionKey) => {
7
+ const defaultKey = (file) => `${sessionKey}:${file}`;
8
+ const databaseConn = await cacheManager.caching(store);
9
+
10
+ const writeData = async (file, data) => {
11
+ let ttl = undefined;
12
+ if (file === 'creds') {
13
+ ttl = 63115200; // 2 years
14
+ }
15
+ await databaseConn.set(defaultKey(file), JSON.stringify(data, BufferJSON.replacer), ttl);
16
+ };
17
+
18
+ const readData = async (file) => {
19
+ try {
20
+ const data = await databaseConn.get(defaultKey(file));
21
+ if (data) {
22
+ return JSON.parse(data, BufferJSON.reviver);
23
+ }
24
+ return null;
25
+ } catch (error) {
26
+ logger.error(error);
27
+ return null;
28
+ }
29
+ };
30
+
31
+ const removeData = async (file) => {
32
+ try {
33
+ return await databaseConn.del(defaultKey(file));
34
+ } catch {
35
+ logger.error(`Error removing ${file} from session ${sessionKey}`);
36
+ }
37
+ };
38
+
39
+ const clearState = async () => {
40
+ try {
41
+ const result = await databaseConn.store.keys(`${sessionKey}*`);
42
+ await Promise.all(result.map(async (key) => await databaseConn.del(key)));
43
+ } catch {}
44
+ };
45
+
46
+ const creds = (await readData('creds')) || initAuthCreds();
47
+
48
+ return {
49
+ clearState,
50
+ saveCreds: () => writeData('creds', creds),
51
+ state: {
52
+ creds,
53
+ keys: {
54
+ get: async (type, ids) => {
55
+ const data = {};
56
+ await Promise.all(ids.map(async (id) => {
57
+ let value = await readData(`${type}-${id}`);
58
+ if (type === 'app-state-sync-key' && value) {
59
+ value = WAProto.proto.Message.AppStateSyncKeyData.fromObject(value);
60
+ }
61
+ data[id] = value;
62
+ }));
63
+ return data;
64
+ },
65
+ set: async (data) => {
66
+ const tasks = [];
67
+ for (const category in data) {
68
+ for (const id in data[category]) {
69
+ const value = data[category][id];
70
+ const key = `${category}-${id}`;
71
+ tasks.push(value ? writeData(key, value) : removeData(key));
72
+ }
73
+ }
74
+ await Promise.all(tasks);
75
+ },
76
+ },
77
+ },
78
+ };
79
+ };
80
+
81
+ export { makeCacheManagerAuthState };
@@ -0,0 +1,425 @@
1
+ import WAProto from '../../WAProto/index.js';
2
+ import * as Defaults 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
+
9
+ const waChatKey = (pin) => ({
10
+ key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
11
+ compare: (k1, k2) => k2.localeCompare(k1)
12
+ });
13
+
14
+ const waMessageID = (m) => m.key.id || '';
15
+
16
+ const waLabelAssociationKey = {
17
+ key: (la) => (la.type === LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
18
+ compare: (k1, k2) => k2.localeCompare(k1)
19
+ };
20
+
21
+ const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
22
+
23
+ const makeInMemoryStore = (config) => {
24
+ const socket = config.socket
25
+ const chatKey = config.chatKey || waChatKey(true)
26
+ const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
27
+ const logger = config.logger || Defaults.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
28
+ const KeyedDB = require('@adiwajshing/keyed-db').default
29
+ const chats = new KeyedDB(chatKey, c => c.id)
30
+ const messages = {}
31
+ const contacts = {}
32
+ const groupMetadata = {}
33
+ const presences = {}
34
+ const state = { connection: 'close' }
35
+ const labels = new ObjectRepository()
36
+ const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key)
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
+ /**
57
+ * binds to a BaileysEventEmitter.
58
+ * It listens to all events and constructs a state that you can query accurate data from.
59
+ * Eg. can use the store to fetch chats, contacts, messages etc.
60
+ * @param ev typically the event emitter from the socket connection
61
+ */
62
+ const bind = (ev) => {
63
+ ev.on('connection.update', update => {
64
+ Object.assign(state, update)
65
+ })
66
+ ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
67
+ if (syncType === WAProto.proto.HistorySync.HistorySyncType.ON_DEMAND) {
68
+ return // FOR NOW,
69
+ //TODO: HANDLE
70
+ }
71
+ if (isLatest) {
72
+ chats.clear()
73
+ for (const id in messages) {
74
+ delete messages[id]
75
+ }
76
+ }
77
+ const chatsAdded = chats.insertIfAbsent(...newChats).length
78
+ logger.debug({ chatsAdded }, 'synced chats')
79
+ const oldContacts = contactsUpsert(newContacts)
80
+ if (isLatest) {
81
+ for (const jid of oldContacts) {
82
+ delete contacts[jid]
83
+ }
84
+ }
85
+ logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts')
86
+ for (const msg of newMessages) {
87
+ const jid = msg.key.remoteJid
88
+ const list = assertMessageList(jid)
89
+ list.upsert(msg, 'prepend')
90
+ }
91
+ logger.debug({ messages: newMessages.length }, 'synced messages')
92
+ })
93
+ ev.on('contacts.upsert', contacts => {
94
+ contactsUpsert(contacts)
95
+ })
96
+ ev.on('contacts.update', async (updates) => {
97
+ for (const update of updates) {
98
+ let contact
99
+ if (contacts[update.id]) {
100
+ contact = contacts[update.id]
101
+ }
102
+ else {
103
+ const contactHashes = await Promise.all(Object.keys(contacts).map(async (contactId) => {
104
+ const { user } = WABinary_1.jidDecode(contactId)
105
+ return [contactId, (Utils_1.md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)]
106
+ }))
107
+ contact = contacts[contactHashes.find(([, b]) => b === update.id?.[0]) || ''] // find contact by attrs.hash, when user is not saved as a contact
108
+ }
109
+ if (!contact) {
110
+ // Create new contact entry if the update has meaningful data
111
+ if (update.notify || update.verifiedName || update.name) {
112
+ contacts[update.id] = { id: update.id }
113
+ contact = contacts[update.id]
114
+ } else {
115
+ logger.debug({ update }, 'got update for non-existant contact')
116
+ continue
117
+ }
118
+ }
119
+ if (update.imgUrl === 'changed') {
120
+ contact.imgUrl = socket ? await socket.profilePictureUrl(contact.id) : undefined
121
+ }
122
+ else if (update.imgUrl === 'removed') {
123
+ delete contact.imgUrl
124
+ }
125
+ // Persist pushName, verifiedName, and name from the update
126
+ if (update.notify) contact.notify = update.notify
127
+ if (update.verifiedName) contact.verifiedName = update.verifiedName
128
+ if (update.name) contact.name = update.name
129
+ Object.assign(contacts[contact.id], contact)
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 = WABinary_1.jidNormalizedUser(msg.key.remoteJid)
188
+ const list = assertMessageList(jid)
189
+ list.upsert(msg, 'append')
190
+ if (type === 'notify' && !chats.get(jid)) {
191
+ ev.emit('chats.upsert', [
192
+ {
193
+ id: jid,
194
+ conversationTimestamp: Utils_1.toNumber(msg.messageTimestamp),
195
+ unreadCount: 1
196
+ }
197
+ ])
198
+ }
199
+ }
200
+ break
201
+ }
202
+ })
203
+ ev.on('messages.update', updates => {
204
+ for (const { update, key } of updates) {
205
+ const list = assertMessageList(WABinary_1.jidNormalizedUser(key.remoteJid))
206
+ if (update?.status) {
207
+ const listStatus = list.get(key.id)?.status
208
+ if (listStatus && update?.status <= listStatus) {
209
+ logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update')
210
+ delete update.status
211
+ logger.debug({ update }, 'new update object')
212
+ }
213
+ }
214
+ const result = list.updateAssign(key.id, update)
215
+ if (!result) {
216
+ logger.debug({ update }, 'got update for non-existent message')
217
+ }
218
+ }
219
+ })
220
+ ev.on('messages.delete', item => {
221
+ if ('all' in item) {
222
+ const list = messages[item.jid]
223
+ list?.clear()
224
+ }
225
+ else {
226
+ const jid = item.keys[0].remoteJid
227
+ const list = messages[jid]
228
+ if (list) {
229
+ const idSet = new Set(item.keys.map(k => k.id))
230
+ list.filter(m => !idSet.has(m.key.id))
231
+ }
232
+ }
233
+ })
234
+ ev.on('groups.update', updates => {
235
+ for (const update of updates) {
236
+ const id = update.id
237
+ if (groupMetadata[id]) {
238
+ Object.assign(groupMetadata[id], update)
239
+ }
240
+ else {
241
+ logger.debug({ update }, 'got update for non-existant group metadata')
242
+ }
243
+ }
244
+ })
245
+ ev.on('group-participants.update', ({ id, participants, action }) => {
246
+ const metadata = groupMetadata[id]
247
+ if (metadata) {
248
+ switch (action) {
249
+ case 'add':
250
+ metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })))
251
+ break
252
+ case 'demote':
253
+ case 'promote':
254
+ for (const participant of metadata.participants) {
255
+ if (participants.includes(participant.id)) {
256
+ participant.isAdmin = action === 'promote'
257
+ }
258
+ }
259
+ break
260
+ case 'remove':
261
+ metadata.participants = metadata.participants.filter(p => !participants.includes(p.id))
262
+ break
263
+ }
264
+ }
265
+ })
266
+ ev.on('message-receipt.update', updates => {
267
+ for (const { key, receipt } of updates) {
268
+ const obj = messages[key.remoteJid]
269
+ const msg = obj?.get(key.id)
270
+ if (msg) {
271
+ Utils_1.updateMessageWithReceipt(msg, receipt)
272
+ }
273
+ }
274
+ })
275
+ ev.on('messages.reaction', (reactions) => {
276
+ for (const { key, reaction } of reactions) {
277
+ const obj = messages[key.remoteJid]
278
+ const msg = obj?.get(key.id)
279
+ if (msg) {
280
+ Utils_1.updateMessageWithReaction(msg, reaction)
281
+ }
282
+ }
283
+ })
284
+ }
285
+ const toJSON = () => ({
286
+ chats,
287
+ contacts,
288
+ messages,
289
+ labels,
290
+ labelAssociations
291
+ })
292
+ const fromJSON = (json) => {
293
+ chats.upsert(...json.chats)
294
+ labelAssociations.upsert(...json.labelAssociations || [])
295
+ contactsUpsert(Object.values(json.contacts))
296
+ labelsUpsert(Object.values(json.labels || {}))
297
+ for (const jid in json.messages) {
298
+ const list = assertMessageList(jid)
299
+ for (const msg of json.messages[jid]) {
300
+ list.upsert(WAProto.proto.WebMessageInfo.fromObject(msg), 'append')
301
+ }
302
+ }
303
+ }
304
+ return {
305
+ chats,
306
+ contacts,
307
+ messages,
308
+ groupMetadata,
309
+ state,
310
+ presences,
311
+ labels,
312
+ labelAssociations,
313
+ bind,
314
+ /** loads messages from the store, if not found -- uses the legacy connection */
315
+ loadMessages: async (jid, count, cursor) => {
316
+ const list = assertMessageList(jid)
317
+ const mode = !cursor || 'before' in cursor ? 'before' : 'after'
318
+ const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined
319
+ const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined
320
+ let messages
321
+ if (list && mode === 'before' && (!cursorKey || cursorValue)) {
322
+ if (cursorValue) {
323
+ const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id)
324
+ messages = list.array.slice(0, msgIdx)
325
+ }
326
+ else {
327
+ messages = list.array
328
+ }
329
+ const diff = count - messages.length
330
+ if (diff < 0) {
331
+ messages = messages.slice(-count) // get the last X messages
332
+ }
333
+ }
334
+ else {
335
+ messages = []
336
+ }
337
+ return messages
338
+ },
339
+ /**
340
+ * Get all available labels for profile
341
+ *
342
+ * Keep in mind that the list is formed from predefined tags and tags
343
+ * that were "caught" during their editing.
344
+ */
345
+ getLabels: () => {
346
+ return labels
347
+ },
348
+ /**
349
+ * Get labels for chat
350
+ *
351
+ * @returns Label IDs
352
+ **/
353
+ getChatLabels: (chatId) => {
354
+ return labelAssociations.filter((la) => la.chatId === chatId).all()
355
+ },
356
+ /**
357
+ * Get labels for message
358
+ *
359
+ * @returns Label IDs
360
+ **/
361
+ getMessageLabels: (messageId) => {
362
+ const associations = labelAssociations
363
+ .filter((la) => la.messageId === messageId)
364
+ .all()
365
+ return associations.map(({ labelId }) => labelId)
366
+ },
367
+ loadMessage: async (jid, id) => messages[jid]?.get(id),
368
+ mostRecentMessage: async (jid) => {
369
+ const message = messages[jid]?.array.slice(-1)[0]
370
+ return message
371
+ },
372
+ fetchImageUrl: async (jid, sock) => {
373
+ const contact = contacts[jid]
374
+ if (!contact) {
375
+ return sock?.profilePictureUrl(jid)
376
+ }
377
+ if (typeof contact.imgUrl === 'undefined') {
378
+ contact.imgUrl = await sock?.profilePictureUrl(jid)
379
+ }
380
+ return contact.imgUrl
381
+ },
382
+ fetchGroupMetadata: async (jid, sock) => {
383
+ if (!groupMetadata[jid]) {
384
+ const metadata = await sock?.groupMetadata(jid)
385
+ if (metadata) {
386
+ groupMetadata[jid] = metadata
387
+ }
388
+ }
389
+ return groupMetadata[jid]
390
+ },
391
+ // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
392
+ // if(!groupMetadata[jid]) {
393
+ // const metadata = await sock?.getBroadcastListInfo(jid)
394
+ // if(metadata) {
395
+ // groupMetadata[jid] = metadata
396
+ // }
397
+ // }
398
+ // return groupMetadata[jid]
399
+ // },
400
+ fetchMessageReceipts: async ({ remoteJid, id }) => {
401
+ const list = messages[remoteJid]
402
+ const msg = list?.get(id)
403
+ return msg?.userReceipt
404
+ },
405
+ toJSON,
406
+ fromJSON,
407
+ writeToFile: (path) => {
408
+ // require fs here so that in case "fs" is not available -- the app does not crash
409
+ const { writeFileSync } = require('fs')
410
+ writeFileSync(path, JSON.stringify(toJSON()))
411
+ },
412
+ readFromFile: (path) => {
413
+ // require fs here so that in case "fs" is not available -- the app does not crash
414
+ const { readFileSync, existsSync } = require('fs')
415
+ if (existsSync(path)) {
416
+ logger.debug({ path }, 'reading from file')
417
+ const jsonStr = readFileSync(path, { encoding: 'utf-8' })
418
+ const json = JSON.parse(jsonStr)
419
+ fromJSON(json)
420
+ }
421
+ }
422
+ }
423
+ }
424
+
425
+ export { waChatKey, waMessageID, waLabelAssociationKey, makeInMemoryStore };