@vinzsocket/baileys 2.1.0 → 2.8.9
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.
- package/lib/Signal/Group/group_cipher.d.ts +1 -0
- package/lib/Signal/Group/group_cipher.js +38 -28
- package/lib/Signal/Group/queue-job.d.ts +2 -0
- package/lib/Signal/Group/queue-job.js +57 -0
- package/lib/Socket/groups.js +2 -0
- package/lib/Socket/messages-send.js +450 -496
- package/lib/Store/index.d.ts +4 -0
- package/lib/Store/index.js +4 -0
- package/lib/Store/make-cache-manager-store.d.ts +17 -0
- package/lib/Store/make-cache-manager-store.js +102 -0
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/lib/Store/make-in-memory-store.js +427 -0
- package/lib/Store/make-ordered-dictionary.d.ts +14 -0
- package/lib/Store/make-ordered-dictionary.js +79 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +23 -0
- package/lib/Types/Message.d.ts +12 -42
- package/lib/Utils/extended-messages.d.ts +73 -0
- package/lib/Utils/extended-messages.js +231 -0
- package/lib/Utils/index.d.ts +3 -0
- package/lib/Utils/index.js +3 -0
- package/lib/Utils/lid-resolver.d.ts +17 -0
- package/lib/Utils/lid-resolver.js +67 -0
- package/lib/Utils/mention.d.ts +27 -0
- package/lib/Utils/mention.js +134 -0
- package/lib/Utils/messages.js +44 -143
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +8 -0
- package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +24 -0
- package/lib/WAUSync/Protocols/index.d.ts +1 -0
- package/lib/WAUSync/Protocols/index.js +1 -0
- package/lib/WAUSync/USyncQuery.d.ts +1 -0
- package/lib/WAUSync/USyncQuery.js +5 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/package.json +8 -7
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AuthenticationCreds, SignalDataTypeMap } from '../Types/Auth.js';
|
|
2
|
+
export type CacheManagerStoreLike = unknown;
|
|
3
|
+
declare const makeCacheManagerAuthState: (store: CacheManagerStoreLike, sessionKey: string) => Promise<{
|
|
4
|
+
clearState: () => Promise<void>;
|
|
5
|
+
saveCreds: () => Promise<void>;
|
|
6
|
+
state: {
|
|
7
|
+
creds: AuthenticationCreds;
|
|
8
|
+
keys: {
|
|
9
|
+
get: <T extends keyof SignalDataTypeMap>(type: T, ids: string[]) => Promise<{
|
|
10
|
+
[id: string]: SignalDataTypeMap[T];
|
|
11
|
+
}>;
|
|
12
|
+
set: (data: { [_: string]: { [id: string]: unknown } }) => Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
}>;
|
|
16
|
+
export { makeCacheManagerAuthState };
|
|
17
|
+
export default makeCacheManagerAuthState;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { proto } from '../../WAProto/index.js';
|
|
2
|
+
import { BufferJSON, initAuthCreds } from '../Utils/index.js';
|
|
3
|
+
import logger from '../Utils/logger.js';
|
|
4
|
+
/**
|
|
5
|
+
* Creates an authentication state backed by any `cache-manager` compatible
|
|
6
|
+
* store (Redis, Memcached, the built-in memory store, etc). Useful when you
|
|
7
|
+
* want your session/auth credentials to live outside the filesystem, e.g.
|
|
8
|
+
* for multi-instance or stateless bot deployments.
|
|
9
|
+
*
|
|
10
|
+
* Requires the optional `cache-manager` package to be installed
|
|
11
|
+
* (`npm install cache-manager`).
|
|
12
|
+
*
|
|
13
|
+
* @param store a `cache-manager` store config/instance, as accepted by `caching()`
|
|
14
|
+
* @param sessionKey a unique key prefix to namespace this session's data in the store
|
|
15
|
+
*/
|
|
16
|
+
export const makeCacheManagerAuthState = async (store, sessionKey) => {
|
|
17
|
+
let caching;
|
|
18
|
+
try {
|
|
19
|
+
const cacheManagerModule = await import('cache-manager');
|
|
20
|
+
// cache-manager ships as CJS; depending on the Node interop, the
|
|
21
|
+
// named export may land on the module itself or under `.default`.
|
|
22
|
+
caching = cacheManagerModule.caching || cacheManagerModule.default?.caching;
|
|
23
|
+
if (!caching) {
|
|
24
|
+
throw new Error('caching() not found in the "cache-manager" module');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new Error('The "cache-manager" package is required to use makeCacheManagerAuthState(). Install it with: npm install cache-manager');
|
|
29
|
+
}
|
|
30
|
+
const defaultKey = (file) => `${sessionKey}:${file}`;
|
|
31
|
+
const databaseConn = await caching(store);
|
|
32
|
+
const writeData = async (file, data) => {
|
|
33
|
+
let ttl = undefined;
|
|
34
|
+
if (file === 'creds') {
|
|
35
|
+
ttl = 63115200; // 2 years
|
|
36
|
+
}
|
|
37
|
+
await databaseConn.set(defaultKey(file), JSON.stringify(data, BufferJSON.replacer), ttl);
|
|
38
|
+
};
|
|
39
|
+
const readData = async (file) => {
|
|
40
|
+
try {
|
|
41
|
+
const data = await databaseConn.get(defaultKey(file));
|
|
42
|
+
if (data) {
|
|
43
|
+
return JSON.parse(data, BufferJSON.reviver);
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
logger.error(error);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const removeData = async (file) => {
|
|
53
|
+
try {
|
|
54
|
+
return await databaseConn.del(defaultKey(file));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
logger.error(`Error removing ${file} from session ${sessionKey}`);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const clearState = async () => {
|
|
61
|
+
try {
|
|
62
|
+
const result = await databaseConn.store.keys(`${sessionKey}*`);
|
|
63
|
+
await Promise.all(result.map(async (key) => await databaseConn.del(key)));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// ignore
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const creds = (await readData('creds')) || initAuthCreds();
|
|
70
|
+
return {
|
|
71
|
+
clearState,
|
|
72
|
+
saveCreds: () => writeData('creds', creds),
|
|
73
|
+
state: {
|
|
74
|
+
creds,
|
|
75
|
+
keys: {
|
|
76
|
+
get: async (type, ids) => {
|
|
77
|
+
const data = {};
|
|
78
|
+
await Promise.all(ids.map(async (id) => {
|
|
79
|
+
let value = await readData(`${type}-${id}`);
|
|
80
|
+
if (type === 'app-state-sync-key' && value) {
|
|
81
|
+
value = proto.Message.AppStateSyncKeyData.create(value);
|
|
82
|
+
}
|
|
83
|
+
data[id] = value;
|
|
84
|
+
}));
|
|
85
|
+
return data;
|
|
86
|
+
},
|
|
87
|
+
set: async (data) => {
|
|
88
|
+
const tasks = [];
|
|
89
|
+
for (const category in data) {
|
|
90
|
+
for (const id in data[category]) {
|
|
91
|
+
const value = data[category][id];
|
|
92
|
+
const key = `${category}-${id}`;
|
|
93
|
+
tasks.push(value ? writeData(key, value) : removeData(key));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
await Promise.all(tasks);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
export default makeCacheManagerAuthState;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type KeyedDB from '@adiwajshing/keyed-db';
|
|
2
|
+
import type { Comparable } from '@adiwajshing/keyed-db/lib/Types.js';
|
|
3
|
+
import type { Logger } from 'pino';
|
|
4
|
+
import { proto } from '../../WAProto/index.js';
|
|
5
|
+
import type makeWASocket from '../Socket/index.js';
|
|
6
|
+
import type { BaileysEventEmitter, Chat, ConnectionState, Contact, GroupMetadata, PresenceData, WAMessage, WAMessageCursor, WAMessageKey } from '../Types/index.js';
|
|
7
|
+
import type { Label } from '../Types/Label.js';
|
|
8
|
+
import type { LabelAssociation } from '../Types/LabelAssociation.js';
|
|
9
|
+
import { ObjectRepository } from './object-repository.js';
|
|
10
|
+
type WASocket = ReturnType<typeof makeWASocket>;
|
|
11
|
+
export declare const waChatKey: (pin: boolean) => {
|
|
12
|
+
key: (c: Chat) => string;
|
|
13
|
+
compare: (k1: string, k2: string) => number;
|
|
14
|
+
};
|
|
15
|
+
export declare const waMessageID: (m: WAMessage) => string;
|
|
16
|
+
export declare const waLabelAssociationKey: Comparable<LabelAssociation, string>;
|
|
17
|
+
export type BaileysInMemoryStoreConfig = {
|
|
18
|
+
chatKey?: Comparable<Chat, string>;
|
|
19
|
+
labelAssociationKey?: Comparable<LabelAssociation, string>;
|
|
20
|
+
logger?: Logger;
|
|
21
|
+
socket?: WASocket;
|
|
22
|
+
};
|
|
23
|
+
export declare const makeInMemoryStore: (config: BaileysInMemoryStoreConfig) => {
|
|
24
|
+
chats: KeyedDB<Chat, string>;
|
|
25
|
+
contacts: {
|
|
26
|
+
[_: string]: Contact;
|
|
27
|
+
};
|
|
28
|
+
messages: {
|
|
29
|
+
[_: string]: {
|
|
30
|
+
array: proto.IWebMessageInfo[];
|
|
31
|
+
get: (id: string) => proto.IWebMessageInfo | undefined;
|
|
32
|
+
upsert: (item: proto.IWebMessageInfo, mode: 'append' | 'prepend') => void;
|
|
33
|
+
update: (item: proto.IWebMessageInfo) => boolean;
|
|
34
|
+
remove: (item: proto.IWebMessageInfo) => boolean;
|
|
35
|
+
updateAssign: (id: string, update: Partial<proto.IWebMessageInfo>) => boolean;
|
|
36
|
+
clear: () => void;
|
|
37
|
+
filter: (contain: (item: proto.IWebMessageInfo) => boolean) => void;
|
|
38
|
+
toJSON: () => proto.IWebMessageInfo[];
|
|
39
|
+
fromJSON: (newItems: proto.IWebMessageInfo[]) => void;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
groupMetadata: {
|
|
43
|
+
[_: string]: GroupMetadata;
|
|
44
|
+
};
|
|
45
|
+
state: ConnectionState;
|
|
46
|
+
presences: {
|
|
47
|
+
[id: string]: {
|
|
48
|
+
[participant: string]: PresenceData;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
labels: ObjectRepository<Label>;
|
|
52
|
+
labelAssociations: KeyedDB<LabelAssociation, string>;
|
|
53
|
+
bind: (ev: BaileysEventEmitter) => void;
|
|
54
|
+
/** loads messages from the store, if not found -- uses the legacy connection */
|
|
55
|
+
loadMessages: (jid: string, count: number, cursor: WAMessageCursor) => Promise<proto.IWebMessageInfo[]>;
|
|
56
|
+
/**
|
|
57
|
+
* Get all available labels for profile
|
|
58
|
+
*
|
|
59
|
+
* Keep in mind that the list is formed from predefined tags and tags
|
|
60
|
+
* that were "caught" during their editing.
|
|
61
|
+
*/
|
|
62
|
+
getLabels: () => ObjectRepository<Label>;
|
|
63
|
+
/**
|
|
64
|
+
* Get labels for chat
|
|
65
|
+
*
|
|
66
|
+
* @returns Label IDs
|
|
67
|
+
**/
|
|
68
|
+
getChatLabels: (chatId: string) => LabelAssociation[];
|
|
69
|
+
/**
|
|
70
|
+
* Get labels for message
|
|
71
|
+
*
|
|
72
|
+
* @returns Label IDs
|
|
73
|
+
**/
|
|
74
|
+
getMessageLabels: (messageId: string) => string[];
|
|
75
|
+
loadMessage: (jid: string, id: string) => Promise<proto.IWebMessageInfo | undefined>;
|
|
76
|
+
mostRecentMessage: (jid: string) => Promise<proto.IWebMessageInfo>;
|
|
77
|
+
fetchImageUrl: (jid: string, sock: WASocket | undefined) => Promise<string | null | undefined>;
|
|
78
|
+
fetchGroupMetadata: (jid: string, sock: WASocket | undefined) => Promise<GroupMetadata>;
|
|
79
|
+
fetchMessageReceipts: ({ remoteJid, id }: WAMessageKey) => Promise<proto.IUserReceipt[] | null | undefined>;
|
|
80
|
+
toJSON: () => {
|
|
81
|
+
chats: KeyedDB<Chat, string>;
|
|
82
|
+
contacts: {
|
|
83
|
+
[_: string]: Contact;
|
|
84
|
+
};
|
|
85
|
+
messages: {
|
|
86
|
+
[_: string]: {
|
|
87
|
+
array: proto.IWebMessageInfo[];
|
|
88
|
+
get: (id: string) => proto.IWebMessageInfo | undefined;
|
|
89
|
+
upsert: (item: proto.IWebMessageInfo, mode: 'append' | 'prepend') => void;
|
|
90
|
+
update: (item: proto.IWebMessageInfo) => boolean;
|
|
91
|
+
remove: (item: proto.IWebMessageInfo) => boolean;
|
|
92
|
+
updateAssign: (id: string, update: Partial<proto.IWebMessageInfo>) => boolean;
|
|
93
|
+
clear: () => void;
|
|
94
|
+
filter: (contain: (item: proto.IWebMessageInfo) => boolean) => void;
|
|
95
|
+
toJSON: () => proto.IWebMessageInfo[];
|
|
96
|
+
fromJSON: (newItems: proto.IWebMessageInfo[]) => void;
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
labels: ObjectRepository<Label>;
|
|
100
|
+
labelAssociations: KeyedDB<LabelAssociation, string>;
|
|
101
|
+
};
|
|
102
|
+
fromJSON: (json: {
|
|
103
|
+
chats: Chat[];
|
|
104
|
+
contacts: {
|
|
105
|
+
[id: string]: Contact;
|
|
106
|
+
};
|
|
107
|
+
messages: {
|
|
108
|
+
[id: string]: proto.IWebMessageInfo[];
|
|
109
|
+
};
|
|
110
|
+
labels: {
|
|
111
|
+
[labelId: string]: Label;
|
|
112
|
+
};
|
|
113
|
+
labelAssociations: LabelAssociation[];
|
|
114
|
+
}) => void;
|
|
115
|
+
writeToFile: (path: string) => void;
|
|
116
|
+
readFromFile: (path: string) => void;
|
|
117
|
+
};
|
|
118
|
+
export default makeInMemoryStore;
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import { createRequire } from 'module';
|
|
2
|
+
import { proto } from '../../WAProto/index.js';
|
|
3
|
+
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults/index.js';
|
|
4
|
+
import { LabelAssociationType } from '../Types/LabelAssociation.js';
|
|
5
|
+
import { md5, toNumber, updateMessageWithReaction, updateMessageWithReceipt } from '../Utils/index.js';
|
|
6
|
+
import { jidDecode, jidNormalizedUser } from '../WABinary/index.js';
|
|
7
|
+
import { makeOrderedDictionary } from './make-ordered-dictionary.js';
|
|
8
|
+
import { ObjectRepository } from './object-repository.js';
|
|
9
|
+
// ESM has no native `require`; this gives us one to synchronously load
|
|
10
|
+
// optional CJS dependencies (keyed-db) only when actually needed, the
|
|
11
|
+
// same way the original implementation lazily required it.
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
export const waChatKey = (pin) => ({
|
|
14
|
+
key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
|
|
15
|
+
compare: (k1, k2) => k2.localeCompare(k1)
|
|
16
|
+
});
|
|
17
|
+
export const waMessageID = (m) => m.key.id || '';
|
|
18
|
+
export const waLabelAssociationKey = {
|
|
19
|
+
key: (la) => (la.type === LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
|
|
20
|
+
compare: (k1, k2) => k2.localeCompare(k1)
|
|
21
|
+
};
|
|
22
|
+
const makeMessagesDictionary = () => makeOrderedDictionary(waMessageID);
|
|
23
|
+
/**
|
|
24
|
+
* An in-memory cache for chats, contacts, messages, group metadata, presences
|
|
25
|
+
* and labels. Bind it to your socket's event emitter with `store.bind(sock.ev)`
|
|
26
|
+
* to keep it updated automatically.
|
|
27
|
+
*
|
|
28
|
+
* Requires the optional `@adiwajshing/keyed-db` package to be installed
|
|
29
|
+
* (`npm install @adiwajshing/keyed-db`).
|
|
30
|
+
*/
|
|
31
|
+
export const makeInMemoryStore = (config) => {
|
|
32
|
+
const socket = config.socket;
|
|
33
|
+
const chatKey = config.chatKey || waChatKey(true);
|
|
34
|
+
const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey;
|
|
35
|
+
const logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
|
|
36
|
+
let KeyedDB;
|
|
37
|
+
try {
|
|
38
|
+
KeyedDB = require('@adiwajshing/keyed-db').default;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new Error('The "@adiwajshing/keyed-db" package is required to use makeInMemoryStore(). Install it with: npm install @adiwajshing/keyed-db');
|
|
42
|
+
}
|
|
43
|
+
const chats = new KeyedDB(chatKey, c => c.id);
|
|
44
|
+
const messages = {};
|
|
45
|
+
const contacts = {};
|
|
46
|
+
const groupMetadata = {};
|
|
47
|
+
const presences = {};
|
|
48
|
+
const state = { connection: 'close' };
|
|
49
|
+
const labels = new ObjectRepository();
|
|
50
|
+
const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
|
|
51
|
+
const assertMessageList = (jid) => {
|
|
52
|
+
if (!messages[jid]) {
|
|
53
|
+
messages[jid] = makeMessagesDictionary();
|
|
54
|
+
}
|
|
55
|
+
return messages[jid];
|
|
56
|
+
};
|
|
57
|
+
const contactsUpsert = (newContacts) => {
|
|
58
|
+
const oldContacts = new Set(Object.keys(contacts));
|
|
59
|
+
for (const contact of newContacts) {
|
|
60
|
+
oldContacts.delete(contact.id);
|
|
61
|
+
contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
|
|
62
|
+
}
|
|
63
|
+
return oldContacts;
|
|
64
|
+
};
|
|
65
|
+
const labelsUpsert = (newLabels) => {
|
|
66
|
+
for (const label of newLabels) {
|
|
67
|
+
labels.upsertById(label.id, label);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const getValidContacts = () => {
|
|
71
|
+
for (const contact of Object.keys(contacts)) {
|
|
72
|
+
if (contact.indexOf('@') < 0) {
|
|
73
|
+
delete contacts[contact];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return Object.keys(contacts);
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* binds to a BaileysEventEmitter.
|
|
80
|
+
* It listens to all events and constructs a state that you can query accurate data from.
|
|
81
|
+
* Eg. can use the store to fetch chats, contacts, messages etc.
|
|
82
|
+
* @param ev typically the event emitter from the socket connection
|
|
83
|
+
*/
|
|
84
|
+
const bind = (ev) => {
|
|
85
|
+
ev.on('connection.update', update => {
|
|
86
|
+
Object.assign(state, update);
|
|
87
|
+
});
|
|
88
|
+
ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest }) => {
|
|
89
|
+
if (isLatest) {
|
|
90
|
+
chats.clear();
|
|
91
|
+
for (const id in messages) {
|
|
92
|
+
delete messages[id];
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const chatsAdded = chats.insertIfAbsent(...newChats).length;
|
|
96
|
+
logger.debug({ chatsAdded }, 'synced chats');
|
|
97
|
+
const oldContacts = contactsUpsert(newContacts);
|
|
98
|
+
if (isLatest) {
|
|
99
|
+
for (const jid of oldContacts) {
|
|
100
|
+
delete contacts[jid];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
|
|
104
|
+
for (const msg of newMessages) {
|
|
105
|
+
const jid = msg.key.remoteJid;
|
|
106
|
+
const list = assertMessageList(jid);
|
|
107
|
+
list.upsert(msg, 'prepend');
|
|
108
|
+
}
|
|
109
|
+
logger.debug({ messages: newMessages.length }, 'synced messages');
|
|
110
|
+
});
|
|
111
|
+
ev.on('contacts.upsert', contacts => {
|
|
112
|
+
contactsUpsert(contacts);
|
|
113
|
+
});
|
|
114
|
+
ev.on('contacts.update', async (updates) => {
|
|
115
|
+
for (const update of updates) {
|
|
116
|
+
let contact;
|
|
117
|
+
if (contacts[update.id]) {
|
|
118
|
+
contact = contacts[update.id];
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
const validContacts = getValidContacts();
|
|
122
|
+
const contactHashes = validContacts.map((contactId) => {
|
|
123
|
+
const { user } = jidDecode(contactId);
|
|
124
|
+
return [contactId, md5(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8')).toString('base64').slice(0, 3)];
|
|
125
|
+
});
|
|
126
|
+
contact = contacts[contactHashes.find(([, b]) => b === update.id)?.[0] || '']; // find contact by attrs.hash, when user is not saved as a contact
|
|
127
|
+
}
|
|
128
|
+
if (contact) {
|
|
129
|
+
if (update.imgUrl === 'changed') {
|
|
130
|
+
contact.imgUrl = socket ? await socket?.profilePictureUrl(contact.id) : undefined;
|
|
131
|
+
}
|
|
132
|
+
else if (update.imgUrl === 'removed') {
|
|
133
|
+
delete contact.imgUrl;
|
|
134
|
+
}
|
|
135
|
+
Object.assign(contacts[contact.id], contact);
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
logger.debug({ update }, 'got update for non-existant contact');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
ev.on('chats.upsert', newChats => {
|
|
143
|
+
chats.upsert(...newChats);
|
|
144
|
+
});
|
|
145
|
+
ev.on('chats.update', updates => {
|
|
146
|
+
for (let update of updates) {
|
|
147
|
+
const result = chats.update(update.id, chat => {
|
|
148
|
+
if (update.unreadCount > 0) {
|
|
149
|
+
update = { ...update };
|
|
150
|
+
update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
|
|
151
|
+
}
|
|
152
|
+
Object.assign(chat, update);
|
|
153
|
+
});
|
|
154
|
+
if (!result) {
|
|
155
|
+
logger.debug({ update }, 'got update for non-existant chat');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
ev.on('labels.edit', (label) => {
|
|
160
|
+
if (label.deleted) {
|
|
161
|
+
return labels.deleteById(label.id);
|
|
162
|
+
}
|
|
163
|
+
// WhatsApp can store only up to 20 labels
|
|
164
|
+
if (labels.count() < 20) {
|
|
165
|
+
return labels.upsertById(label.id, label);
|
|
166
|
+
}
|
|
167
|
+
logger.error('Labels count exceed');
|
|
168
|
+
});
|
|
169
|
+
ev.on('labels.association', ({ type, association }) => {
|
|
170
|
+
switch (type) {
|
|
171
|
+
case 'add':
|
|
172
|
+
labelAssociations.upsert(association);
|
|
173
|
+
break;
|
|
174
|
+
case 'remove':
|
|
175
|
+
labelAssociations.delete(association);
|
|
176
|
+
break;
|
|
177
|
+
default:
|
|
178
|
+
console.error(`unknown operation type [${type}]`);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
ev.on('presence.update', ({ id, presences: update }) => {
|
|
182
|
+
presences[id] = presences[id] || {};
|
|
183
|
+
Object.assign(presences[id], update);
|
|
184
|
+
});
|
|
185
|
+
ev.on('chats.delete', deletions => {
|
|
186
|
+
for (const item of deletions) {
|
|
187
|
+
if (chats.get(item)) {
|
|
188
|
+
chats.deleteById(item);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
ev.on('messages.upsert', ({ messages: newMessages, type }) => {
|
|
193
|
+
switch (type) {
|
|
194
|
+
case 'append':
|
|
195
|
+
case 'notify':
|
|
196
|
+
for (const msg of newMessages) {
|
|
197
|
+
const jid = jidNormalizedUser(msg.key.remoteJid);
|
|
198
|
+
const list = assertMessageList(jid);
|
|
199
|
+
list.upsert(msg, 'append');
|
|
200
|
+
if (type === 'notify') {
|
|
201
|
+
if (!chats.get(jid)) {
|
|
202
|
+
ev.emit('chats.upsert', [
|
|
203
|
+
{
|
|
204
|
+
id: jid,
|
|
205
|
+
conversationTimestamp: toNumber(msg.messageTimestamp),
|
|
206
|
+
unreadCount: 1
|
|
207
|
+
}
|
|
208
|
+
]);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
ev.on('messages.update', updates => {
|
|
216
|
+
for (const { update, key } of updates) {
|
|
217
|
+
const list = assertMessageList(jidNormalizedUser(key.remoteJid));
|
|
218
|
+
if (update?.status) {
|
|
219
|
+
const listStatus = list.get(key.id)?.status;
|
|
220
|
+
if (listStatus && update?.status <= listStatus) {
|
|
221
|
+
logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
|
|
222
|
+
delete update.status;
|
|
223
|
+
logger.debug({ update }, 'new update object');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const result = list.updateAssign(key.id, update);
|
|
227
|
+
if (!result) {
|
|
228
|
+
logger.debug({ update }, 'got update for non-existent message');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
ev.on('messages.delete', item => {
|
|
233
|
+
if ('all' in item) {
|
|
234
|
+
const list = messages[item.jid];
|
|
235
|
+
list?.clear();
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
const jid = item.keys[0].remoteJid;
|
|
239
|
+
const list = messages[jid];
|
|
240
|
+
if (list) {
|
|
241
|
+
const idSet = new Set(item.keys.map(k => k.id));
|
|
242
|
+
list.filter(m => !idSet.has(m.key.id));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
ev.on('groups.update', updates => {
|
|
247
|
+
for (const update of updates) {
|
|
248
|
+
const id = update.id;
|
|
249
|
+
if (groupMetadata[id]) {
|
|
250
|
+
Object.assign(groupMetadata[id], update);
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
logger.debug({ update }, 'got update for non-existant group metadata');
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
ev.on('group-participants.update', ({ id, participants, action }) => {
|
|
258
|
+
const metadata = groupMetadata[id];
|
|
259
|
+
if (metadata) {
|
|
260
|
+
switch (action) {
|
|
261
|
+
case 'add':
|
|
262
|
+
metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })));
|
|
263
|
+
break;
|
|
264
|
+
case 'demote':
|
|
265
|
+
case 'promote':
|
|
266
|
+
for (const participant of metadata.participants) {
|
|
267
|
+
if (participants.includes(participant.id)) {
|
|
268
|
+
participant.isAdmin = action === 'promote';
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
break;
|
|
272
|
+
case 'remove':
|
|
273
|
+
metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
ev.on('message-receipt.update', updates => {
|
|
279
|
+
for (const { key, receipt } of updates) {
|
|
280
|
+
const obj = messages[key.remoteJid];
|
|
281
|
+
const msg = obj?.get(key.id);
|
|
282
|
+
if (msg) {
|
|
283
|
+
updateMessageWithReceipt(msg, receipt);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
ev.on('messages.reaction', (reactions) => {
|
|
288
|
+
for (const { key, reaction } of reactions) {
|
|
289
|
+
const obj = messages[key.remoteJid];
|
|
290
|
+
const msg = obj?.get(key.id);
|
|
291
|
+
if (msg) {
|
|
292
|
+
updateMessageWithReaction(msg, reaction);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
};
|
|
297
|
+
const toJSON = () => ({
|
|
298
|
+
chats,
|
|
299
|
+
contacts,
|
|
300
|
+
messages,
|
|
301
|
+
labels,
|
|
302
|
+
labelAssociations
|
|
303
|
+
});
|
|
304
|
+
const fromJSON = (json) => {
|
|
305
|
+
chats.upsert(...json.chats);
|
|
306
|
+
labelAssociations.upsert(...(json.labelAssociations || []));
|
|
307
|
+
contactsUpsert(Object.values(json.contacts));
|
|
308
|
+
labelsUpsert(Object.values(json.labels || {}));
|
|
309
|
+
for (const jid in json.messages) {
|
|
310
|
+
const list = assertMessageList(jid);
|
|
311
|
+
for (const msg of json.messages[jid]) {
|
|
312
|
+
list.upsert(proto.WebMessageInfo.create(msg), 'append');
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
return {
|
|
317
|
+
chats,
|
|
318
|
+
contacts,
|
|
319
|
+
messages,
|
|
320
|
+
groupMetadata,
|
|
321
|
+
state,
|
|
322
|
+
presences,
|
|
323
|
+
labels,
|
|
324
|
+
labelAssociations,
|
|
325
|
+
bind,
|
|
326
|
+
/** loads messages from the store, if not found -- uses the legacy connection */
|
|
327
|
+
loadMessages: async (jid, count, cursor) => {
|
|
328
|
+
const list = assertMessageList(jid);
|
|
329
|
+
const mode = !cursor || 'before' in cursor ? 'before' : 'after';
|
|
330
|
+
const cursorKey = cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
|
|
331
|
+
const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
|
|
332
|
+
let messages;
|
|
333
|
+
if (list && mode === 'before' && (!cursorKey || cursorValue)) {
|
|
334
|
+
if (cursorValue) {
|
|
335
|
+
const msgIdx = list.array.findIndex(m => m.key.id === cursorKey?.id);
|
|
336
|
+
messages = list.array.slice(0, msgIdx);
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
messages = list.array;
|
|
340
|
+
}
|
|
341
|
+
const diff = count - messages.length;
|
|
342
|
+
if (diff < 0) {
|
|
343
|
+
messages = messages.slice(-count); // get the last X messages
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
messages = [];
|
|
348
|
+
}
|
|
349
|
+
return messages;
|
|
350
|
+
},
|
|
351
|
+
/**
|
|
352
|
+
* Get all available labels for profile
|
|
353
|
+
*
|
|
354
|
+
* Keep in mind that the list is formed from predefined tags and tags
|
|
355
|
+
* that were "caught" during their editing.
|
|
356
|
+
*/
|
|
357
|
+
getLabels: () => {
|
|
358
|
+
return labels;
|
|
359
|
+
},
|
|
360
|
+
/**
|
|
361
|
+
* Get labels for chat
|
|
362
|
+
*
|
|
363
|
+
* @returns Label IDs
|
|
364
|
+
**/
|
|
365
|
+
getChatLabels: (chatId) => {
|
|
366
|
+
return labelAssociations.filter((la) => la.chatId === chatId).all();
|
|
367
|
+
},
|
|
368
|
+
/**
|
|
369
|
+
* Get labels for message
|
|
370
|
+
*
|
|
371
|
+
* @returns Label IDs
|
|
372
|
+
**/
|
|
373
|
+
getMessageLabels: (messageId) => {
|
|
374
|
+
const associations = labelAssociations
|
|
375
|
+
.filter((la) => la.messageId === messageId)
|
|
376
|
+
.all();
|
|
377
|
+
return associations.map(({ labelId }) => labelId);
|
|
378
|
+
},
|
|
379
|
+
loadMessage: async (jid, id) => messages[jid]?.get(id),
|
|
380
|
+
mostRecentMessage: async (jid) => {
|
|
381
|
+
const message = messages[jid]?.array.slice(-1)[0];
|
|
382
|
+
return message;
|
|
383
|
+
},
|
|
384
|
+
fetchImageUrl: async (jid, sock) => {
|
|
385
|
+
const contact = contacts[jid];
|
|
386
|
+
if (!contact) {
|
|
387
|
+
return sock?.profilePictureUrl(jid);
|
|
388
|
+
}
|
|
389
|
+
if (typeof contact.imgUrl === 'undefined') {
|
|
390
|
+
contact.imgUrl = await sock?.profilePictureUrl(jid);
|
|
391
|
+
}
|
|
392
|
+
return contact.imgUrl;
|
|
393
|
+
},
|
|
394
|
+
fetchGroupMetadata: async (jid, sock) => {
|
|
395
|
+
if (!groupMetadata[jid]) {
|
|
396
|
+
const metadata = await sock?.groupMetadata(jid);
|
|
397
|
+
if (metadata) {
|
|
398
|
+
groupMetadata[jid] = metadata;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return groupMetadata[jid];
|
|
402
|
+
},
|
|
403
|
+
fetchMessageReceipts: async ({ remoteJid, id }) => {
|
|
404
|
+
const list = messages[remoteJid];
|
|
405
|
+
const msg = list?.get(id);
|
|
406
|
+
return msg?.userReceipt;
|
|
407
|
+
},
|
|
408
|
+
toJSON,
|
|
409
|
+
fromJSON,
|
|
410
|
+
writeToFile: (path) => {
|
|
411
|
+
// require fs here so that in case "fs" is not available -- the app does not crash
|
|
412
|
+
const { writeFileSync } = require('fs');
|
|
413
|
+
writeFileSync(path, JSON.stringify(toJSON()));
|
|
414
|
+
},
|
|
415
|
+
readFromFile: (path) => {
|
|
416
|
+
// require fs here so that in case "fs" is not available -- the app does not crash
|
|
417
|
+
const { readFileSync, existsSync } = require('fs');
|
|
418
|
+
if (existsSync(path)) {
|
|
419
|
+
logger.debug({ path }, 'reading from file');
|
|
420
|
+
const jsonStr = readFileSync(path, { encoding: 'utf-8' });
|
|
421
|
+
const json = JSON.parse(jsonStr);
|
|
422
|
+
fromJSON(json);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
};
|
|
427
|
+
export default makeInMemoryStore;
|