@genuxofficial/baileys 1.0.0
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/LICENSE +21 -0
- package/README.md +1 -0
- package/WAProto/GenerateStatics.sh +4 -0
- package/WAProto/WAProto.proto +3344 -0
- package/WAProto/index.d.ts +37016 -0
- package/WAProto/index.js +101044 -0
- package/WASignalGroup/GroupProtocol.js +1697 -0
- package/WASignalGroup/ciphertext_message.js +16 -0
- package/WASignalGroup/group_cipher.js +120 -0
- package/WASignalGroup/group_session_builder.js +46 -0
- package/WASignalGroup/index.js +5 -0
- package/WASignalGroup/keyhelper.js +21 -0
- package/WASignalGroup/protobufs.js +3 -0
- package/WASignalGroup/queue_job.js +69 -0
- package/WASignalGroup/sender_chain_key.js +50 -0
- package/WASignalGroup/sender_key_distribution_message.js +78 -0
- package/WASignalGroup/sender_key_message.js +92 -0
- package/WASignalGroup/sender_key_name.js +70 -0
- package/WASignalGroup/sender_key_record.js +56 -0
- package/WASignalGroup/sender_key_state.js +129 -0
- package/WASignalGroup/sender_message_key.js +39 -0
- package/lib/Defaults/baileys-version.json +3 -0
- package/lib/Defaults/index.d.ts +53 -0
- package/lib/Defaults/index.js +106 -0
- package/lib/Signal/libsignal.d.ts +3 -0
- package/lib/Signal/libsignal.js +152 -0
- package/lib/Socket/Client/index.d.ts +2 -0
- package/lib/Socket/Client/index.js +18 -0
- package/lib/Socket/Client/types.d.ts +17 -0
- package/lib/Socket/Client/types.js +13 -0
- package/lib/Socket/Client/websocket.d.ts +12 -0
- package/lib/Socket/Client/websocket.js +62 -0
- package/lib/Socket/business.d.ts +149 -0
- package/lib/Socket/business.js +260 -0
- package/lib/Socket/chats.d.ts +85 -0
- package/lib/Socket/chats.js +850 -0
- package/lib/Socket/groups.d.ts +124 -0
- package/lib/Socket/groups.js +314 -0
- package/lib/Socket/index.d.ts +149 -0
- package/lib/Socket/index.js +10 -0
- package/lib/Socket/messages-recv.d.ts +136 -0
- package/lib/Socket/messages-recv.js +912 -0
- package/lib/Socket/messages-send.d.ts +130 -0
- package/lib/Socket/messages-send.js +673 -0
- package/lib/Socket/socket.d.ts +45 -0
- package/lib/Socket/socket.js +622 -0
- package/lib/Socket/usync.d.ts +38 -0
- package/lib/Socket/usync.js +70 -0
- package/lib/Store/index.d.ts +3 -0
- package/lib/Store/index.js +10 -0
- package/lib/Store/make-cache-manager-store.d.ts +14 -0
- package/lib/Store/make-cache-manager-store.js +83 -0
- package/lib/Store/make-in-memory-store.d.ts +118 -0
- package/lib/Store/make-in-memory-store.js +420 -0
- package/lib/Store/make-ordered-dictionary.d.ts +13 -0
- package/lib/Store/make-ordered-dictionary.js +81 -0
- package/lib/Store/object-repository.d.ts +10 -0
- package/lib/Store/object-repository.js +27 -0
- package/lib/Types/Auth.d.ts +105 -0
- package/lib/Types/Auth.js +2 -0
- package/lib/Types/Call.d.ts +13 -0
- package/lib/Types/Call.js +2 -0
- package/lib/Types/Chat.d.ts +108 -0
- package/lib/Types/Chat.js +4 -0
- package/lib/Types/Contact.d.ts +19 -0
- package/lib/Types/Contact.js +2 -0
- package/lib/Types/Events.d.ts +172 -0
- package/lib/Types/Events.js +2 -0
- package/lib/Types/GroupMetadata.d.ts +56 -0
- package/lib/Types/GroupMetadata.js +2 -0
- package/lib/Types/Label.d.ts +46 -0
- package/lib/Types/Label.js +27 -0
- package/lib/Types/LabelAssociation.d.ts +29 -0
- package/lib/Types/LabelAssociation.js +9 -0
- package/lib/Types/Message.d.ts +271 -0
- package/lib/Types/Message.js +9 -0
- package/lib/Types/Product.d.ts +78 -0
- package/lib/Types/Product.js +2 -0
- package/lib/Types/Signal.d.ts +57 -0
- package/lib/Types/Signal.js +2 -0
- package/lib/Types/Socket.d.ts +118 -0
- package/lib/Types/Socket.js +2 -0
- package/lib/Types/State.d.ts +27 -0
- package/lib/Types/State.js +2 -0
- package/lib/Types/USync.d.ts +25 -0
- package/lib/Types/USync.js +2 -0
- package/lib/Types/index.d.ts +63 -0
- package/lib/Types/index.js +41 -0
- package/lib/Utils/auth-utils.d.ts +18 -0
- package/lib/Utils/auth-utils.js +200 -0
- package/lib/Utils/baileys-event-stream.d.ts +16 -0
- package/lib/Utils/baileys-event-stream.js +63 -0
- package/lib/Utils/business.d.ts +22 -0
- package/lib/Utils/business.js +234 -0
- package/lib/Utils/chat-utils.d.ts +72 -0
- package/lib/Utils/chat-utils.js +745 -0
- package/lib/Utils/crypto.d.ts +42 -0
- package/lib/Utils/crypto.js +181 -0
- package/lib/Utils/decode-wa-message.d.ts +36 -0
- package/lib/Utils/decode-wa-message.js +205 -0
- package/lib/Utils/event-buffer.d.ts +35 -0
- package/lib/Utils/event-buffer.js +520 -0
- package/lib/Utils/generics.d.ts +94 -0
- package/lib/Utils/generics.js +433 -0
- package/lib/Utils/history.d.ts +19 -0
- package/lib/Utils/history.js +94 -0
- package/lib/Utils/index.d.ts +17 -0
- package/lib/Utils/index.js +33 -0
- package/lib/Utils/link-preview.d.ts +21 -0
- package/lib/Utils/link-preview.js +116 -0
- package/lib/Utils/logger.d.ts +11 -0
- package/lib/Utils/logger.js +7 -0
- package/lib/Utils/lt-hash.d.ts +12 -0
- package/lib/Utils/lt-hash.js +51 -0
- package/lib/Utils/make-mutex.d.ts +7 -0
- package/lib/Utils/make-mutex.js +44 -0
- package/lib/Utils/messages-media.d.ts +108 -0
- package/lib/Utils/messages-media.js +667 -0
- package/lib/Utils/messages.d.ts +78 -0
- package/lib/Utils/messages.js +760 -0
- package/lib/Utils/noise-handler.d.ts +21 -0
- package/lib/Utils/noise-handler.js +150 -0
- package/lib/Utils/process-message.d.ts +42 -0
- package/lib/Utils/process-message.js +373 -0
- package/lib/Utils/signal.d.ts +33 -0
- package/lib/Utils/signal.js +153 -0
- package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
- package/lib/Utils/use-multi-file-auth-state.js +94 -0
- package/lib/Utils/validate-connection.d.ts +10 -0
- package/lib/Utils/validate-connection.js +175 -0
- package/lib/WABinary/constants.d.ts +27 -0
- package/lib/WABinary/constants.js +40 -0
- package/lib/WABinary/decode.d.ts +8 -0
- package/lib/WABinary/decode.js +254 -0
- package/lib/WABinary/encode.d.ts +4 -0
- package/lib/WABinary/encode.js +234 -0
- package/lib/WABinary/generic-utils.d.ts +16 -0
- package/lib/WABinary/generic-utils.js +110 -0
- package/lib/WABinary/index.d.ts +5 -0
- package/lib/WABinary/index.js +21 -0
- package/lib/WABinary/jid-utils.d.ts +31 -0
- package/lib/WABinary/jid-utils.js +62 -0
- package/lib/WABinary/types.d.ts +18 -0
- package/lib/WABinary/types.js +2 -0
- package/lib/WAM/BinaryInfo.d.ts +18 -0
- package/lib/WAM/BinaryInfo.js +13 -0
- package/lib/WAM/constants.d.ts +39 -0
- package/lib/WAM/constants.js +15350 -0
- package/lib/WAM/encode.d.ts +4 -0
- package/lib/WAM/encode.js +155 -0
- package/lib/WAM/index.d.ts +3 -0
- package/lib/WAM/index.js +19 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
- package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
- package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
- package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
- package/lib/WAUSync/Protocols/index.d.ts +4 -0
- package/lib/WAUSync/Protocols/index.js +20 -0
- package/lib/WAUSync/USyncQuery.d.ts +26 -0
- package/lib/WAUSync/USyncQuery.js +79 -0
- package/lib/WAUSync/USyncUser.d.ts +10 -0
- package/lib/WAUSync/USyncUser.js +22 -0
- package/lib/WAUSync/index.d.ts +3 -0
- package/lib/WAUSync/index.js +19 -0
- package/lib/index.d.ts +12 -0
- package/lib/index.js +31 -0
- package/package.json +104 -0
@@ -0,0 +1,41 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
+
if (k2 === undefined) k2 = k;
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
7
|
+
}
|
8
|
+
Object.defineProperty(o, k2, desc);
|
9
|
+
}) : (function(o, m, k, k2) {
|
10
|
+
if (k2 === undefined) k2 = k;
|
11
|
+
o[k2] = m[k];
|
12
|
+
}));
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
15
|
+
};
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
17
|
+
exports.DisconnectReason = void 0;
|
18
|
+
__exportStar(require("./Auth"), exports);
|
19
|
+
__exportStar(require("./GroupMetadata"), exports);
|
20
|
+
__exportStar(require("./Chat"), exports);
|
21
|
+
__exportStar(require("./Contact"), exports);
|
22
|
+
__exportStar(require("./State"), exports);
|
23
|
+
__exportStar(require("./Message"), exports);
|
24
|
+
__exportStar(require("./Socket"), exports);
|
25
|
+
__exportStar(require("./Events"), exports);
|
26
|
+
__exportStar(require("./Product"), exports);
|
27
|
+
__exportStar(require("./Call"), exports);
|
28
|
+
__exportStar(require("./Signal"), exports);
|
29
|
+
var DisconnectReason;
|
30
|
+
(function (DisconnectReason) {
|
31
|
+
DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
|
32
|
+
DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
|
33
|
+
DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
|
34
|
+
DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
|
35
|
+
DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
|
36
|
+
DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
|
37
|
+
DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
|
38
|
+
DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
|
39
|
+
DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
|
40
|
+
DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
|
41
|
+
})(DisconnectReason = exports.DisconnectReason || (exports.DisconnectReason = {}));
|
@@ -0,0 +1,18 @@
|
|
1
|
+
import type { AuthenticationCreds, CacheStore, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types';
|
2
|
+
import { ILogger } from './logger';
|
3
|
+
/**
|
4
|
+
* Adds caching capability to a SignalKeyStore
|
5
|
+
* @param store the store to add caching to
|
6
|
+
* @param logger to log trace events
|
7
|
+
* @param _cache cache store to use
|
8
|
+
*/
|
9
|
+
export declare function makeCacheableSignalKeyStore(store: SignalKeyStore, logger: ILogger, _cache?: CacheStore): SignalKeyStore;
|
10
|
+
/**
|
11
|
+
* Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
|
12
|
+
* this allows batch read & write operations & improves the performance of the lib
|
13
|
+
* @param state the key store to apply this capability to
|
14
|
+
* @param logger logger to log events
|
15
|
+
* @returns SignalKeyStore with transaction capability
|
16
|
+
*/
|
17
|
+
export declare const addTransactionCapability: (state: SignalKeyStore, logger: ILogger, { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions) => SignalKeyStoreWithTransaction;
|
18
|
+
export declare const initAuthCreds: () => AuthenticationCreds;
|
@@ -0,0 +1,200 @@
|
|
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.initAuthCreds = exports.addTransactionCapability = exports.makeCacheableSignalKeyStore = void 0;
|
7
|
+
const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
|
8
|
+
const crypto_1 = require("crypto");
|
9
|
+
const Defaults_1 = require("../Defaults");
|
10
|
+
const crypto_2 = require("./crypto");
|
11
|
+
const generics_1 = require("./generics");
|
12
|
+
/**
|
13
|
+
* Adds caching capability to a SignalKeyStore
|
14
|
+
* @param store the store to add caching to
|
15
|
+
* @param logger to log trace events
|
16
|
+
* @param _cache cache store to use
|
17
|
+
*/
|
18
|
+
function makeCacheableSignalKeyStore(store, logger, _cache) {
|
19
|
+
const cache = _cache || new node_cache_1.default({
|
20
|
+
stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE,
|
21
|
+
useClones: false,
|
22
|
+
deleteOnExpire: true,
|
23
|
+
});
|
24
|
+
function getUniqueId(type, id) {
|
25
|
+
return `${type}.${id}`;
|
26
|
+
}
|
27
|
+
return {
|
28
|
+
async get(type, ids) {
|
29
|
+
const data = {};
|
30
|
+
const idsToFetch = [];
|
31
|
+
for (const id of ids) {
|
32
|
+
const item = cache.get(getUniqueId(type, id));
|
33
|
+
if (typeof item !== 'undefined') {
|
34
|
+
data[id] = item;
|
35
|
+
}
|
36
|
+
else {
|
37
|
+
idsToFetch.push(id);
|
38
|
+
}
|
39
|
+
}
|
40
|
+
if (idsToFetch.length) {
|
41
|
+
logger.trace({ items: idsToFetch.length }, 'loading from store');
|
42
|
+
const fetched = await store.get(type, idsToFetch);
|
43
|
+
for (const id of idsToFetch) {
|
44
|
+
const item = fetched[id];
|
45
|
+
if (item) {
|
46
|
+
data[id] = item;
|
47
|
+
cache.set(getUniqueId(type, id), item);
|
48
|
+
}
|
49
|
+
}
|
50
|
+
}
|
51
|
+
return data;
|
52
|
+
},
|
53
|
+
async set(data) {
|
54
|
+
let keys = 0;
|
55
|
+
for (const type in data) {
|
56
|
+
for (const id in data[type]) {
|
57
|
+
cache.set(getUniqueId(type, id), data[type][id]);
|
58
|
+
keys += 1;
|
59
|
+
}
|
60
|
+
}
|
61
|
+
logger.trace({ keys }, 'updated cache');
|
62
|
+
await store.set(data);
|
63
|
+
},
|
64
|
+
async clear() {
|
65
|
+
var _a;
|
66
|
+
cache.flushAll();
|
67
|
+
await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
|
68
|
+
}
|
69
|
+
};
|
70
|
+
}
|
71
|
+
exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
|
72
|
+
/**
|
73
|
+
* Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
|
74
|
+
* this allows batch read & write operations & improves the performance of the lib
|
75
|
+
* @param state the key store to apply this capability to
|
76
|
+
* @param logger logger to log events
|
77
|
+
* @returns SignalKeyStore with transaction capability
|
78
|
+
*/
|
79
|
+
const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
|
80
|
+
// number of queries made to the DB during the transaction
|
81
|
+
// only there for logging purposes
|
82
|
+
let dbQueriesInTransaction = 0;
|
83
|
+
let transactionCache = {};
|
84
|
+
let mutations = {};
|
85
|
+
let transactionsInProgress = 0;
|
86
|
+
return {
|
87
|
+
get: async (type, ids) => {
|
88
|
+
if (isInTransaction()) {
|
89
|
+
const dict = transactionCache[type];
|
90
|
+
const idsRequiringFetch = dict
|
91
|
+
? ids.filter(item => typeof dict[item] === 'undefined')
|
92
|
+
: ids;
|
93
|
+
// only fetch if there are any items to fetch
|
94
|
+
if (idsRequiringFetch.length) {
|
95
|
+
dbQueriesInTransaction += 1;
|
96
|
+
const result = await state.get(type, idsRequiringFetch);
|
97
|
+
transactionCache[type] || (transactionCache[type] = {});
|
98
|
+
Object.assign(transactionCache[type], result);
|
99
|
+
}
|
100
|
+
return ids.reduce((dict, id) => {
|
101
|
+
var _a;
|
102
|
+
const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
|
103
|
+
if (value) {
|
104
|
+
dict[id] = value;
|
105
|
+
}
|
106
|
+
return dict;
|
107
|
+
}, {});
|
108
|
+
}
|
109
|
+
else {
|
110
|
+
return state.get(type, ids);
|
111
|
+
}
|
112
|
+
},
|
113
|
+
set: data => {
|
114
|
+
if (isInTransaction()) {
|
115
|
+
logger.trace({ types: Object.keys(data) }, 'caching in transaction');
|
116
|
+
for (const key in data) {
|
117
|
+
transactionCache[key] = transactionCache[key] || {};
|
118
|
+
Object.assign(transactionCache[key], data[key]);
|
119
|
+
mutations[key] = mutations[key] || {};
|
120
|
+
Object.assign(mutations[key], data[key]);
|
121
|
+
}
|
122
|
+
}
|
123
|
+
else {
|
124
|
+
return state.set(data);
|
125
|
+
}
|
126
|
+
},
|
127
|
+
isInTransaction,
|
128
|
+
async transaction(work) {
|
129
|
+
let result;
|
130
|
+
transactionsInProgress += 1;
|
131
|
+
if (transactionsInProgress === 1) {
|
132
|
+
logger.trace('entering transaction');
|
133
|
+
}
|
134
|
+
try {
|
135
|
+
result = await work();
|
136
|
+
// commit if this is the outermost transaction
|
137
|
+
if (transactionsInProgress === 1) {
|
138
|
+
if (Object.keys(mutations).length) {
|
139
|
+
logger.trace('committing transaction');
|
140
|
+
// retry mechanism to ensure we've some recovery
|
141
|
+
// in case a transaction fails in the first attempt
|
142
|
+
let tries = maxCommitRetries;
|
143
|
+
while (tries) {
|
144
|
+
tries -= 1;
|
145
|
+
//eslint-disable-next-line max-depth
|
146
|
+
try {
|
147
|
+
await state.set(mutations);
|
148
|
+
logger.trace({ dbQueriesInTransaction }, 'committed transaction');
|
149
|
+
break;
|
150
|
+
}
|
151
|
+
catch (error) {
|
152
|
+
logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
|
153
|
+
await (0, generics_1.delay)(delayBetweenTriesMs);
|
154
|
+
}
|
155
|
+
}
|
156
|
+
}
|
157
|
+
else {
|
158
|
+
logger.trace('no mutations in transaction');
|
159
|
+
}
|
160
|
+
}
|
161
|
+
}
|
162
|
+
finally {
|
163
|
+
transactionsInProgress -= 1;
|
164
|
+
if (transactionsInProgress === 0) {
|
165
|
+
transactionCache = {};
|
166
|
+
mutations = {};
|
167
|
+
dbQueriesInTransaction = 0;
|
168
|
+
}
|
169
|
+
}
|
170
|
+
return result;
|
171
|
+
}
|
172
|
+
};
|
173
|
+
function isInTransaction() {
|
174
|
+
return transactionsInProgress > 0;
|
175
|
+
}
|
176
|
+
};
|
177
|
+
exports.addTransactionCapability = addTransactionCapability;
|
178
|
+
const initAuthCreds = () => {
|
179
|
+
const identityKey = crypto_2.Curve.generateKeyPair();
|
180
|
+
return {
|
181
|
+
noiseKey: crypto_2.Curve.generateKeyPair(),
|
182
|
+
pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
|
183
|
+
signedIdentityKey: identityKey,
|
184
|
+
signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
|
185
|
+
registrationId: (0, generics_1.generateRegistrationId)(),
|
186
|
+
advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
|
187
|
+
processedHistoryMessages: [],
|
188
|
+
nextPreKeyId: 1,
|
189
|
+
firstUnuploadedPreKeyId: 1,
|
190
|
+
accountSyncCounter: 0,
|
191
|
+
accountSettings: {
|
192
|
+
unarchiveChats: false
|
193
|
+
},
|
194
|
+
registered: false,
|
195
|
+
pairingCode: undefined,
|
196
|
+
lastPropHash: undefined,
|
197
|
+
routingInfo: undefined,
|
198
|
+
};
|
199
|
+
};
|
200
|
+
exports.initAuthCreds = initAuthCreds;
|
@@ -0,0 +1,16 @@
|
|
1
|
+
import type { BaileysEventEmitter } from '../Types';
|
2
|
+
/**
|
3
|
+
* Captures events from a baileys event emitter & stores them in a file
|
4
|
+
* @param ev The event emitter to read events from
|
5
|
+
* @param filename File to save to
|
6
|
+
*/
|
7
|
+
export declare const captureEventStream: (ev: BaileysEventEmitter, filename: string) => void;
|
8
|
+
/**
|
9
|
+
* Read event file and emit events from there
|
10
|
+
* @param filename filename containing event data
|
11
|
+
* @param delayIntervalMs delay between each event emit
|
12
|
+
*/
|
13
|
+
export declare const readAndEmitEventStream: (filename: string, delayIntervalMs?: number) => {
|
14
|
+
ev: BaileysEventEmitter;
|
15
|
+
task: Promise<void>;
|
16
|
+
};
|
@@ -0,0 +1,63 @@
|
|
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.readAndEmitEventStream = exports.captureEventStream = void 0;
|
7
|
+
const events_1 = __importDefault(require("events"));
|
8
|
+
const fs_1 = require("fs");
|
9
|
+
const promises_1 = require("fs/promises");
|
10
|
+
const readline_1 = require("readline");
|
11
|
+
const generics_1 = require("./generics");
|
12
|
+
const make_mutex_1 = require("./make-mutex");
|
13
|
+
/**
|
14
|
+
* Captures events from a baileys event emitter & stores them in a file
|
15
|
+
* @param ev The event emitter to read events from
|
16
|
+
* @param filename File to save to
|
17
|
+
*/
|
18
|
+
const captureEventStream = (ev, filename) => {
|
19
|
+
const oldEmit = ev.emit;
|
20
|
+
// write mutex so data is appended in order
|
21
|
+
const writeMutex = (0, make_mutex_1.makeMutex)();
|
22
|
+
// monkey patch eventemitter to capture all events
|
23
|
+
ev.emit = function (...args) {
|
24
|
+
const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
|
25
|
+
const result = oldEmit.apply(ev, args);
|
26
|
+
writeMutex.mutex(async () => {
|
27
|
+
await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
|
28
|
+
});
|
29
|
+
return result;
|
30
|
+
};
|
31
|
+
};
|
32
|
+
exports.captureEventStream = captureEventStream;
|
33
|
+
/**
|
34
|
+
* Read event file and emit events from there
|
35
|
+
* @param filename filename containing event data
|
36
|
+
* @param delayIntervalMs delay between each event emit
|
37
|
+
*/
|
38
|
+
const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
|
39
|
+
const ev = new events_1.default();
|
40
|
+
const fireEvents = async () => {
|
41
|
+
// from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
|
42
|
+
const fileStream = (0, fs_1.createReadStream)(filename);
|
43
|
+
const rl = (0, readline_1.createInterface)({
|
44
|
+
input: fileStream,
|
45
|
+
crlfDelay: Infinity
|
46
|
+
});
|
47
|
+
// Note: we use the crlfDelay option to recognize all instances of CR LF
|
48
|
+
// ('\r\n') in input.txt as a single line break.
|
49
|
+
for await (const line of rl) {
|
50
|
+
if (line) {
|
51
|
+
const { event, data } = JSON.parse(line);
|
52
|
+
ev.emit(event, data);
|
53
|
+
delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
|
54
|
+
}
|
55
|
+
}
|
56
|
+
fileStream.close();
|
57
|
+
};
|
58
|
+
return {
|
59
|
+
ev,
|
60
|
+
task: fireEvents()
|
61
|
+
};
|
62
|
+
};
|
63
|
+
exports.readAndEmitEventStream = readAndEmitEventStream;
|
@@ -0,0 +1,22 @@
|
|
1
|
+
import { CatalogCollection, OrderDetails, Product, ProductCreate, ProductUpdate, WAMediaUpload, WAMediaUploadFunction } from '../Types';
|
2
|
+
import { BinaryNode } from '../WABinary';
|
3
|
+
export declare const parseCatalogNode: (node: BinaryNode) => {
|
4
|
+
products: Product[];
|
5
|
+
nextPageCursor: string | undefined;
|
6
|
+
};
|
7
|
+
export declare const parseCollectionsNode: (node: BinaryNode) => {
|
8
|
+
collections: CatalogCollection[];
|
9
|
+
};
|
10
|
+
export declare const parseOrderDetailsNode: (node: BinaryNode) => OrderDetails;
|
11
|
+
export declare const toProductNode: (productId: string | undefined, product: ProductCreate | ProductUpdate) => BinaryNode;
|
12
|
+
export declare const parseProductNode: (productNode: BinaryNode) => Product;
|
13
|
+
/**
|
14
|
+
* Uploads images not already uploaded to WA's servers
|
15
|
+
*/
|
16
|
+
export declare function uploadingNecessaryImagesOfProduct<T extends ProductUpdate | ProductCreate>(product: T, waUploadToServer: WAMediaUploadFunction, timeoutMs?: number): Promise<T>;
|
17
|
+
/**
|
18
|
+
* Uploads images not already uploaded to WA's servers
|
19
|
+
*/
|
20
|
+
export declare const uploadingNecessaryImages: (images: WAMediaUpload[], waUploadToServer: WAMediaUploadFunction, timeoutMs?: number) => Promise<{
|
21
|
+
url: string;
|
22
|
+
}[]>;
|
@@ -0,0 +1,234 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.uploadingNecessaryImages = exports.uploadingNecessaryImagesOfProduct = exports.parseProductNode = exports.toProductNode = exports.parseOrderDetailsNode = exports.parseCollectionsNode = exports.parseCatalogNode = void 0;
|
4
|
+
const boom_1 = require("@hapi/boom");
|
5
|
+
const crypto_1 = require("crypto");
|
6
|
+
const WABinary_1 = require("../WABinary");
|
7
|
+
const messages_media_1 = require("./messages-media");
|
8
|
+
const parseCatalogNode = (node) => {
|
9
|
+
const catalogNode = (0, WABinary_1.getBinaryNodeChild)(node, 'product_catalog');
|
10
|
+
const products = (0, WABinary_1.getBinaryNodeChildren)(catalogNode, 'product').map(exports.parseProductNode);
|
11
|
+
const paging = (0, WABinary_1.getBinaryNodeChild)(catalogNode, 'paging');
|
12
|
+
return {
|
13
|
+
products,
|
14
|
+
nextPageCursor: paging
|
15
|
+
? (0, WABinary_1.getBinaryNodeChildString)(paging, 'after')
|
16
|
+
: undefined
|
17
|
+
};
|
18
|
+
};
|
19
|
+
exports.parseCatalogNode = parseCatalogNode;
|
20
|
+
const parseCollectionsNode = (node) => {
|
21
|
+
const collectionsNode = (0, WABinary_1.getBinaryNodeChild)(node, 'collections');
|
22
|
+
const collections = (0, WABinary_1.getBinaryNodeChildren)(collectionsNode, 'collection').map(collectionNode => {
|
23
|
+
const id = (0, WABinary_1.getBinaryNodeChildString)(collectionNode, 'id');
|
24
|
+
const name = (0, WABinary_1.getBinaryNodeChildString)(collectionNode, 'name');
|
25
|
+
const products = (0, WABinary_1.getBinaryNodeChildren)(collectionNode, 'product').map(exports.parseProductNode);
|
26
|
+
return {
|
27
|
+
id,
|
28
|
+
name,
|
29
|
+
products,
|
30
|
+
status: parseStatusInfo(collectionNode)
|
31
|
+
};
|
32
|
+
});
|
33
|
+
return {
|
34
|
+
collections
|
35
|
+
};
|
36
|
+
};
|
37
|
+
exports.parseCollectionsNode = parseCollectionsNode;
|
38
|
+
const parseOrderDetailsNode = (node) => {
|
39
|
+
const orderNode = (0, WABinary_1.getBinaryNodeChild)(node, 'order');
|
40
|
+
const products = (0, WABinary_1.getBinaryNodeChildren)(orderNode, 'product').map(productNode => {
|
41
|
+
const imageNode = (0, WABinary_1.getBinaryNodeChild)(productNode, 'image');
|
42
|
+
return {
|
43
|
+
id: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'id'),
|
44
|
+
name: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'name'),
|
45
|
+
imageUrl: (0, WABinary_1.getBinaryNodeChildString)(imageNode, 'url'),
|
46
|
+
price: +(0, WABinary_1.getBinaryNodeChildString)(productNode, 'price'),
|
47
|
+
currency: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'currency'),
|
48
|
+
quantity: +(0, WABinary_1.getBinaryNodeChildString)(productNode, 'quantity')
|
49
|
+
};
|
50
|
+
});
|
51
|
+
const priceNode = (0, WABinary_1.getBinaryNodeChild)(orderNode, 'price');
|
52
|
+
const orderDetails = {
|
53
|
+
price: {
|
54
|
+
total: +(0, WABinary_1.getBinaryNodeChildString)(priceNode, 'total'),
|
55
|
+
currency: (0, WABinary_1.getBinaryNodeChildString)(priceNode, 'currency'),
|
56
|
+
},
|
57
|
+
products
|
58
|
+
};
|
59
|
+
return orderDetails;
|
60
|
+
};
|
61
|
+
exports.parseOrderDetailsNode = parseOrderDetailsNode;
|
62
|
+
const toProductNode = (productId, product) => {
|
63
|
+
const attrs = {};
|
64
|
+
const content = [];
|
65
|
+
if (typeof productId !== 'undefined') {
|
66
|
+
content.push({
|
67
|
+
tag: 'id',
|
68
|
+
attrs: {},
|
69
|
+
content: Buffer.from(productId)
|
70
|
+
});
|
71
|
+
}
|
72
|
+
if (typeof product.name !== 'undefined') {
|
73
|
+
content.push({
|
74
|
+
tag: 'name',
|
75
|
+
attrs: {},
|
76
|
+
content: Buffer.from(product.name)
|
77
|
+
});
|
78
|
+
}
|
79
|
+
if (typeof product.description !== 'undefined') {
|
80
|
+
content.push({
|
81
|
+
tag: 'description',
|
82
|
+
attrs: {},
|
83
|
+
content: Buffer.from(product.description)
|
84
|
+
});
|
85
|
+
}
|
86
|
+
if (typeof product.retailerId !== 'undefined') {
|
87
|
+
content.push({
|
88
|
+
tag: 'retailer_id',
|
89
|
+
attrs: {},
|
90
|
+
content: Buffer.from(product.retailerId)
|
91
|
+
});
|
92
|
+
}
|
93
|
+
if (product.images.length) {
|
94
|
+
content.push({
|
95
|
+
tag: 'media',
|
96
|
+
attrs: {},
|
97
|
+
content: product.images.map(img => {
|
98
|
+
if (!('url' in img)) {
|
99
|
+
throw new boom_1.Boom('Expected img for product to already be uploaded', { statusCode: 400 });
|
100
|
+
}
|
101
|
+
return {
|
102
|
+
tag: 'image',
|
103
|
+
attrs: {},
|
104
|
+
content: [
|
105
|
+
{
|
106
|
+
tag: 'url',
|
107
|
+
attrs: {},
|
108
|
+
content: Buffer.from(img.url.toString())
|
109
|
+
}
|
110
|
+
]
|
111
|
+
};
|
112
|
+
})
|
113
|
+
});
|
114
|
+
}
|
115
|
+
if (typeof product.price !== 'undefined') {
|
116
|
+
content.push({
|
117
|
+
tag: 'price',
|
118
|
+
attrs: {},
|
119
|
+
content: Buffer.from(product.price.toString())
|
120
|
+
});
|
121
|
+
}
|
122
|
+
if (typeof product.currency !== 'undefined') {
|
123
|
+
content.push({
|
124
|
+
tag: 'currency',
|
125
|
+
attrs: {},
|
126
|
+
content: Buffer.from(product.currency)
|
127
|
+
});
|
128
|
+
}
|
129
|
+
if ('originCountryCode' in product) {
|
130
|
+
if (typeof product.originCountryCode === 'undefined') {
|
131
|
+
attrs['compliance_category'] = 'COUNTRY_ORIGIN_EXEMPT';
|
132
|
+
}
|
133
|
+
else {
|
134
|
+
content.push({
|
135
|
+
tag: 'compliance_info',
|
136
|
+
attrs: {},
|
137
|
+
content: [
|
138
|
+
{
|
139
|
+
tag: 'country_code_origin',
|
140
|
+
attrs: {},
|
141
|
+
content: Buffer.from(product.originCountryCode)
|
142
|
+
}
|
143
|
+
]
|
144
|
+
});
|
145
|
+
}
|
146
|
+
}
|
147
|
+
if (typeof product.isHidden !== 'undefined') {
|
148
|
+
attrs['is_hidden'] = product.isHidden.toString();
|
149
|
+
}
|
150
|
+
const node = {
|
151
|
+
tag: 'product',
|
152
|
+
attrs,
|
153
|
+
content
|
154
|
+
};
|
155
|
+
return node;
|
156
|
+
};
|
157
|
+
exports.toProductNode = toProductNode;
|
158
|
+
const parseProductNode = (productNode) => {
|
159
|
+
const isHidden = productNode.attrs.is_hidden === 'true';
|
160
|
+
const id = (0, WABinary_1.getBinaryNodeChildString)(productNode, 'id');
|
161
|
+
const mediaNode = (0, WABinary_1.getBinaryNodeChild)(productNode, 'media');
|
162
|
+
const statusInfoNode = (0, WABinary_1.getBinaryNodeChild)(productNode, 'status_info');
|
163
|
+
const product = {
|
164
|
+
id,
|
165
|
+
imageUrls: parseImageUrls(mediaNode),
|
166
|
+
reviewStatus: {
|
167
|
+
whatsapp: (0, WABinary_1.getBinaryNodeChildString)(statusInfoNode, 'status'),
|
168
|
+
},
|
169
|
+
availability: 'in stock',
|
170
|
+
name: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'name'),
|
171
|
+
retailerId: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'retailer_id'),
|
172
|
+
url: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'url'),
|
173
|
+
description: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'description'),
|
174
|
+
price: +(0, WABinary_1.getBinaryNodeChildString)(productNode, 'price'),
|
175
|
+
currency: (0, WABinary_1.getBinaryNodeChildString)(productNode, 'currency'),
|
176
|
+
isHidden,
|
177
|
+
};
|
178
|
+
return product;
|
179
|
+
};
|
180
|
+
exports.parseProductNode = parseProductNode;
|
181
|
+
/**
|
182
|
+
* Uploads images not already uploaded to WA's servers
|
183
|
+
*/
|
184
|
+
async function uploadingNecessaryImagesOfProduct(product, waUploadToServer, timeoutMs = 30000) {
|
185
|
+
product = {
|
186
|
+
...product,
|
187
|
+
images: product.images ? await (0, exports.uploadingNecessaryImages)(product.images, waUploadToServer, timeoutMs) : product.images
|
188
|
+
};
|
189
|
+
return product;
|
190
|
+
}
|
191
|
+
exports.uploadingNecessaryImagesOfProduct = uploadingNecessaryImagesOfProduct;
|
192
|
+
/**
|
193
|
+
* Uploads images not already uploaded to WA's servers
|
194
|
+
*/
|
195
|
+
const uploadingNecessaryImages = async (images, waUploadToServer, timeoutMs = 30000) => {
|
196
|
+
const results = await Promise.all(images.map(async (img) => {
|
197
|
+
if ('url' in img) {
|
198
|
+
const url = img.url.toString();
|
199
|
+
if (url.includes('.whatsapp.net')) {
|
200
|
+
return { url };
|
201
|
+
}
|
202
|
+
}
|
203
|
+
const { stream } = await (0, messages_media_1.getStream)(img);
|
204
|
+
const hasher = (0, crypto_1.createHash)('sha256');
|
205
|
+
const contentBlocks = [];
|
206
|
+
for await (const block of stream) {
|
207
|
+
hasher.update(block);
|
208
|
+
contentBlocks.push(block);
|
209
|
+
}
|
210
|
+
const sha = hasher.digest('base64');
|
211
|
+
const { directPath } = await waUploadToServer((0, messages_media_1.toReadable)(Buffer.concat(contentBlocks)), {
|
212
|
+
mediaType: 'product-catalog-image',
|
213
|
+
fileEncSha256B64: sha,
|
214
|
+
timeoutMs
|
215
|
+
});
|
216
|
+
return { url: (0, messages_media_1.getUrlFromDirectPath)(directPath) };
|
217
|
+
}));
|
218
|
+
return results;
|
219
|
+
};
|
220
|
+
exports.uploadingNecessaryImages = uploadingNecessaryImages;
|
221
|
+
const parseImageUrls = (mediaNode) => {
|
222
|
+
const imgNode = (0, WABinary_1.getBinaryNodeChild)(mediaNode, 'image');
|
223
|
+
return {
|
224
|
+
requested: (0, WABinary_1.getBinaryNodeChildString)(imgNode, 'request_image_url'),
|
225
|
+
original: (0, WABinary_1.getBinaryNodeChildString)(imgNode, 'original_image_url')
|
226
|
+
};
|
227
|
+
};
|
228
|
+
const parseStatusInfo = (mediaNode) => {
|
229
|
+
const node = (0, WABinary_1.getBinaryNodeChild)(mediaNode, 'status_info');
|
230
|
+
return {
|
231
|
+
status: (0, WABinary_1.getBinaryNodeChildString)(node, 'status'),
|
232
|
+
canAppeal: (0, WABinary_1.getBinaryNodeChildString)(node, 'can_appeal') === 'true',
|
233
|
+
};
|
234
|
+
};
|
@@ -0,0 +1,72 @@
|
|
1
|
+
/// <reference types="node" />
|
2
|
+
/// <reference types="node" />
|
3
|
+
import { AxiosRequestConfig } from 'axios';
|
4
|
+
import { proto } from '../../WAProto';
|
5
|
+
import { BaileysEventEmitter, ChatModification, ChatMutation, Contact, InitialAppStateSyncOptions, LTHashState, WAPatchCreate, WAPatchName } from '../Types';
|
6
|
+
import { BinaryNode } from '../WABinary';
|
7
|
+
import { ILogger } from './logger';
|
8
|
+
type FetchAppStateSyncKey = (keyId: string) => Promise<proto.Message.IAppStateSyncKeyData | null | undefined>;
|
9
|
+
export type ChatMutationMap = {
|
10
|
+
[index: string]: ChatMutation;
|
11
|
+
};
|
12
|
+
export declare const newLTHashState: () => LTHashState;
|
13
|
+
export declare const encodeSyncdPatch: ({ type, index, syncAction, apiVersion, operation }: WAPatchCreate, myAppStateKeyId: string, state: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey) => Promise<{
|
14
|
+
patch: proto.ISyncdPatch;
|
15
|
+
state: LTHashState;
|
16
|
+
}>;
|
17
|
+
export declare const decodeSyncdMutations: (msgMutations: (proto.ISyncdMutation | proto.ISyncdRecord)[], initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
|
18
|
+
hash: Buffer;
|
19
|
+
indexValueMap: {
|
20
|
+
[indexMacBase64: string]: {
|
21
|
+
valueMac: Uint8Array | Buffer;
|
22
|
+
};
|
23
|
+
};
|
24
|
+
}>;
|
25
|
+
export declare const decodeSyncdPatch: (msg: proto.ISyncdPatch, name: WAPatchName, initialState: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, onMutation: (mutation: ChatMutation) => void, validateMacs: boolean) => Promise<{
|
26
|
+
hash: Buffer;
|
27
|
+
indexValueMap: {
|
28
|
+
[indexMacBase64: string]: {
|
29
|
+
valueMac: Uint8Array | Buffer;
|
30
|
+
};
|
31
|
+
};
|
32
|
+
}>;
|
33
|
+
export declare const extractSyncdPatches: (result: BinaryNode, options: AxiosRequestConfig<{}>) => Promise<{
|
34
|
+
critical_block: {
|
35
|
+
patches: proto.ISyncdPatch[];
|
36
|
+
hasMorePatches: boolean;
|
37
|
+
snapshot?: proto.ISyncdSnapshot | undefined;
|
38
|
+
};
|
39
|
+
critical_unblock_low: {
|
40
|
+
patches: proto.ISyncdPatch[];
|
41
|
+
hasMorePatches: boolean;
|
42
|
+
snapshot?: proto.ISyncdSnapshot | undefined;
|
43
|
+
};
|
44
|
+
regular_high: {
|
45
|
+
patches: proto.ISyncdPatch[];
|
46
|
+
hasMorePatches: boolean;
|
47
|
+
snapshot?: proto.ISyncdSnapshot | undefined;
|
48
|
+
};
|
49
|
+
regular_low: {
|
50
|
+
patches: proto.ISyncdPatch[];
|
51
|
+
hasMorePatches: boolean;
|
52
|
+
snapshot?: proto.ISyncdSnapshot | undefined;
|
53
|
+
};
|
54
|
+
regular: {
|
55
|
+
patches: proto.ISyncdPatch[];
|
56
|
+
hasMorePatches: boolean;
|
57
|
+
snapshot?: proto.ISyncdSnapshot | undefined;
|
58
|
+
};
|
59
|
+
}>;
|
60
|
+
export declare const downloadExternalBlob: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<Buffer>;
|
61
|
+
export declare const downloadExternalPatch: (blob: proto.IExternalBlobReference, options: AxiosRequestConfig<{}>) => Promise<proto.SyncdMutations>;
|
62
|
+
export declare const decodeSyncdSnapshot: (name: WAPatchName, snapshot: proto.ISyncdSnapshot, getAppStateSyncKey: FetchAppStateSyncKey, minimumVersionNumber: number | undefined, validateMacs?: boolean) => Promise<{
|
63
|
+
state: LTHashState;
|
64
|
+
mutationMap: ChatMutationMap;
|
65
|
+
}>;
|
66
|
+
export declare const decodePatches: (name: WAPatchName, syncds: proto.ISyncdPatch[], initial: LTHashState, getAppStateSyncKey: FetchAppStateSyncKey, options: AxiosRequestConfig<{}>, minimumVersionNumber?: number, logger?: ILogger, validateMacs?: boolean) => Promise<{
|
67
|
+
state: LTHashState;
|
68
|
+
mutationMap: ChatMutationMap;
|
69
|
+
}>;
|
70
|
+
export declare const chatModificationToAppPatch: (mod: ChatModification, jid: string) => WAPatchCreate;
|
71
|
+
export declare const processSyncAction: (syncAction: ChatMutation, ev: BaileysEventEmitter, me: Contact, initialSyncOpts?: InitialAppStateSyncOptions, logger?: ILogger) => void;
|
72
|
+
export {};
|