keith-baileys 1.0.26

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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/WAProto/GenerateStatics.sh +2 -0
  4. package/WAProto/WAProto.proto +4633 -0
  5. package/WAProto/index.js +165029 -0
  6. package/WAProto/keith +1 -0
  7. package/engine-requirements.js +10 -0
  8. package/lib/Defaults/Keith +1 -0
  9. package/lib/Defaults/baileys-version.json +3 -0
  10. package/lib/Defaults/index.js +105 -0
  11. package/lib/Signal/Group/Keith +1 -0
  12. package/lib/Signal/Group/ciphertext-message.js +15 -0
  13. package/lib/Signal/Group/group-session-builder.js +64 -0
  14. package/lib/Signal/Group/group_cipher.js +96 -0
  15. package/lib/Signal/Group/index.js +57 -0
  16. package/lib/Signal/Group/keyhelper.js +55 -0
  17. package/lib/Signal/Group/queue-job.js +57 -0
  18. package/lib/Signal/Group/sender-chain-key.js +34 -0
  19. package/lib/Signal/Group/sender-key-distribution-message.js +66 -0
  20. package/lib/Signal/Group/sender-key-message.js +69 -0
  21. package/lib/Signal/Group/sender-key-name.js +51 -0
  22. package/lib/Signal/Group/sender-key-record.js +53 -0
  23. package/lib/Signal/Group/sender-key-state.js +99 -0
  24. package/lib/Signal/Group/sender-message-key.js +29 -0
  25. package/lib/Signal/Keith +1 -0
  26. package/lib/Signal/libsignal.js +174 -0
  27. package/lib/Socket/Client/Keith +1 -0
  28. package/lib/Socket/Client/index.js +18 -0
  29. package/lib/Socket/Client/types.js +13 -0
  30. package/lib/Socket/Client/websocket.js +62 -0
  31. package/lib/Socket/Keith +1 -0
  32. package/lib/Socket/business.js +260 -0
  33. package/lib/Socket/chats.js +880 -0
  34. package/lib/Socket/groups.js +340 -0
  35. package/lib/Socket/groupstatus.js +237 -0
  36. package/lib/Socket/index.js +10 -0
  37. package/lib/Socket/messages-recv.js +1077 -0
  38. package/lib/Socket/messages-send.js +988 -0
  39. package/lib/Socket/mex.js +46 -0
  40. package/lib/Socket/newsletter.js +233 -0
  41. package/lib/Socket/socket.js +617 -0
  42. package/lib/Socket/usync.js +65 -0
  43. package/lib/Types/Auth.js +2 -0
  44. package/lib/Types/Call.js +2 -0
  45. package/lib/Types/Chat.js +10 -0
  46. package/lib/Types/Contact.js +2 -0
  47. package/lib/Types/Events.js +2 -0
  48. package/lib/Types/GroupMetadata.js +2 -0
  49. package/lib/Types/Keith +1 -0
  50. package/lib/Types/Label.js +27 -0
  51. package/lib/Types/LabelAssociation.js +9 -0
  52. package/lib/Types/Message.js +7 -0
  53. package/lib/Types/Newsletter.js +33 -0
  54. package/lib/Types/Product.js +2 -0
  55. package/lib/Types/Signal.js +2 -0
  56. package/lib/Types/Socket.js +2 -0
  57. package/lib/Types/State.js +2 -0
  58. package/lib/Types/USync.js +2 -0
  59. package/lib/Types/index.js +42 -0
  60. package/lib/Utils/Keith +1 -0
  61. package/lib/Utils/auth-utils.js +199 -0
  62. package/lib/Utils/baileys-event-stream.js +63 -0
  63. package/lib/Utils/business.js +240 -0
  64. package/lib/Utils/chat-utils.js +741 -0
  65. package/lib/Utils/crypto.js +187 -0
  66. package/lib/Utils/decode-wa-message.js +283 -0
  67. package/lib/Utils/event-buffer.js +516 -0
  68. package/lib/Utils/generics.js +400 -0
  69. package/lib/Utils/history.js +100 -0
  70. package/lib/Utils/index.js +34 -0
  71. package/lib/Utils/lid-mapping.js +88 -0
  72. package/lib/Utils/link-preview.js +122 -0
  73. package/lib/Utils/logger.js +7 -0
  74. package/lib/Utils/lt-hash.js +51 -0
  75. package/lib/Utils/make-mutex.js +44 -0
  76. package/lib/Utils/messages-media.js +706 -0
  77. package/lib/Utils/messages.js +797 -0
  78. package/lib/Utils/noise-handler.js +150 -0
  79. package/lib/Utils/process-message.js +381 -0
  80. package/lib/Utils/signal.js +155 -0
  81. package/lib/Utils/use-multi-file-auth-state.js +124 -0
  82. package/lib/Utils/validate-connection.js +170 -0
  83. package/lib/WABinary/Keith +1 -0
  84. package/lib/WABinary/constants.js +1303 -0
  85. package/lib/WABinary/decode.js +266 -0
  86. package/lib/WABinary/encode.js +252 -0
  87. package/lib/WABinary/generic-utils.js +110 -0
  88. package/lib/WABinary/index.js +21 -0
  89. package/lib/WABinary/jid-utils.js +66 -0
  90. package/lib/WABinary/types.js +2 -0
  91. package/lib/WAM/BinaryInfo.js +13 -0
  92. package/lib/WAM/constants.js +15243 -0
  93. package/lib/WAM/encode.js +153 -0
  94. package/lib/WAM/index.js +19 -0
  95. package/lib/WAM/keith +1 -0
  96. package/lib/WAUSync/Keith +1 -0
  97. package/lib/WAUSync/Protocols/Keith +1 -0
  98. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  99. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  100. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  101. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  102. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +53 -0
  103. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +24 -0
  104. package/lib/WAUSync/Protocols/index.js +20 -0
  105. package/lib/WAUSync/USyncQuery.js +93 -0
  106. package/lib/WAUSync/USyncUser.js +26 -0
  107. package/lib/WAUSync/index.js +19 -0
  108. package/lib/index.js +30 -0
  109. package/package.json +32 -0
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ALL_WA_PATCH_NAMES = void 0;
4
+ exports.ALL_WA_PATCH_NAMES = [
5
+ 'critical_block',
6
+ 'critical_unblock_low',
7
+ 'regular_high',
8
+ 'regular_low',
9
+ 'regular'
10
+ ];
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LabelColor = void 0;
4
+ /** WhatsApp has 20 predefined colors */
5
+ var LabelColor;
6
+ (function (LabelColor) {
7
+ LabelColor[LabelColor["Color1"] = 0] = "Color1";
8
+ LabelColor[LabelColor["Color2"] = 1] = "Color2";
9
+ LabelColor[LabelColor["Color3"] = 2] = "Color3";
10
+ LabelColor[LabelColor["Color4"] = 3] = "Color4";
11
+ LabelColor[LabelColor["Color5"] = 4] = "Color5";
12
+ LabelColor[LabelColor["Color6"] = 5] = "Color6";
13
+ LabelColor[LabelColor["Color7"] = 6] = "Color7";
14
+ LabelColor[LabelColor["Color8"] = 7] = "Color8";
15
+ LabelColor[LabelColor["Color9"] = 8] = "Color9";
16
+ LabelColor[LabelColor["Color10"] = 9] = "Color10";
17
+ LabelColor[LabelColor["Color11"] = 10] = "Color11";
18
+ LabelColor[LabelColor["Color12"] = 11] = "Color12";
19
+ LabelColor[LabelColor["Color13"] = 12] = "Color13";
20
+ LabelColor[LabelColor["Color14"] = 13] = "Color14";
21
+ LabelColor[LabelColor["Color15"] = 14] = "Color15";
22
+ LabelColor[LabelColor["Color16"] = 15] = "Color16";
23
+ LabelColor[LabelColor["Color17"] = 16] = "Color17";
24
+ LabelColor[LabelColor["Color18"] = 17] = "Color18";
25
+ LabelColor[LabelColor["Color19"] = 18] = "Color19";
26
+ LabelColor[LabelColor["Color20"] = 19] = "Color20";
27
+ })(LabelColor || (exports.LabelColor = LabelColor = {}));
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LabelAssociationType = void 0;
4
+ /** Association type */
5
+ var LabelAssociationType;
6
+ (function (LabelAssociationType) {
7
+ LabelAssociationType["Chat"] = "label_jid";
8
+ LabelAssociationType["Message"] = "label_message";
9
+ })(LabelAssociationType || (exports.LabelAssociationType = LabelAssociationType = {}));
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WAMessageStatus = exports.WAMessageStubType = exports.WAProto = void 0;
4
+ const WAProto_1 = require("../../WAProto");
5
+ Object.defineProperty(exports, "WAProto", { enumerable: true, get: function () { return WAProto_1.proto; } });
6
+ exports.WAMessageStubType = WAProto_1.proto.WebMessageInfo.StubType;
7
+ exports.WAMessageStatus = WAProto_1.proto.WebMessageInfo.Status;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryIds = exports.XWAPaths = void 0;
4
+ var XWAPaths;
5
+ (function (XWAPaths) {
6
+ XWAPaths["xwa2_newsletter_create"] = "xwa2_newsletter_create";
7
+ XWAPaths["xwa2_newsletter_subscribers"] = "xwa2_newsletter_subscribers";
8
+ XWAPaths["xwa2_newsletter_view"] = "xwa2_newsletter_view";
9
+ XWAPaths["xwa2_newsletter_metadata"] = "xwa2_newsletter";
10
+ XWAPaths["xwa2_newsletter_admin_count"] = "xwa2_newsletter_admin";
11
+ XWAPaths["xwa2_newsletter_mute_v2"] = "xwa2_newsletter_mute_v2";
12
+ XWAPaths["xwa2_newsletter_unmute_v2"] = "xwa2_newsletter_unmute_v2";
13
+ XWAPaths["xwa2_newsletter_follow"] = "xwa2_newsletter_follow";
14
+ XWAPaths["xwa2_newsletter_unfollow"] = "xwa2_newsletter_unfollow";
15
+ XWAPaths["xwa2_newsletter_change_owner"] = "xwa2_newsletter_change_owner";
16
+ XWAPaths["xwa2_newsletter_demote"] = "xwa2_newsletter_demote";
17
+ XWAPaths["xwa2_newsletter_delete_v2"] = "xwa2_newsletter_delete_v2";
18
+ })(XWAPaths || (exports.XWAPaths = XWAPaths = {}));
19
+ var QueryIds;
20
+ (function (QueryIds) {
21
+ QueryIds["CREATE"] = "8823471724422422";
22
+ QueryIds["UPDATE_METADATA"] = "24250201037901610";
23
+ QueryIds["METADATA"] = "6563316087068696";
24
+ QueryIds["SUBSCRIBERS"] = "9783111038412085";
25
+ QueryIds["FOLLOW"] = "7871414976211147";
26
+ QueryIds["UNFOLLOW"] = "7238632346214362";
27
+ QueryIds["MUTE"] = "29766401636284406";
28
+ QueryIds["UNMUTE"] = "9864994326891137";
29
+ QueryIds["ADMIN_COUNT"] = "7130823597031706";
30
+ QueryIds["CHANGE_OWNER"] = "7341777602580933";
31
+ QueryIds["DEMOTE"] = "6551828931592903";
32
+ QueryIds["DELETE"] = "30062808666639665";
33
+ })(QueryIds || (exports.QueryIds = QueryIds = {}));
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,42 @@
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
+ __exportStar(require("./Newsletter"), exports);
30
+ var DisconnectReason;
31
+ (function (DisconnectReason) {
32
+ DisconnectReason[DisconnectReason["connectionClosed"] = 428] = "connectionClosed";
33
+ DisconnectReason[DisconnectReason["connectionLost"] = 408] = "connectionLost";
34
+ DisconnectReason[DisconnectReason["connectionReplaced"] = 440] = "connectionReplaced";
35
+ DisconnectReason[DisconnectReason["timedOut"] = 408] = "timedOut";
36
+ DisconnectReason[DisconnectReason["loggedOut"] = 401] = "loggedOut";
37
+ DisconnectReason[DisconnectReason["badSession"] = 500] = "badSession";
38
+ DisconnectReason[DisconnectReason["restartRequired"] = 515] = "restartRequired";
39
+ DisconnectReason[DisconnectReason["multideviceMismatch"] = 411] = "multideviceMismatch";
40
+ DisconnectReason[DisconnectReason["forbidden"] = 403] = "forbidden";
41
+ DisconnectReason[DisconnectReason["unavailableService"] = 503] = "unavailableService";
42
+ })(DisconnectReason || (exports.DisconnectReason = DisconnectReason = {}));
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,199 @@
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 = void 0;
7
+ exports.makeCacheableSignalKeyStore = makeCacheableSignalKeyStore;
8
+ const node_cache_1 = __importDefault(require("@cacheable/node-cache"));
9
+ const crypto_1 = require("crypto");
10
+ const Defaults_1 = require("../Defaults");
11
+ const crypto_2 = require("./crypto");
12
+ const generics_1 = require("./generics");
13
+ /**
14
+ * Adds caching capability to a SignalKeyStore
15
+ * @param store the store to add caching to
16
+ * @param logger to log trace events
17
+ * @param _cache cache store to use
18
+ */
19
+ function makeCacheableSignalKeyStore(store, logger, _cache) {
20
+ const cache = _cache ||
21
+ new node_cache_1.default({
22
+ stdTTL: Defaults_1.DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
23
+ useClones: false,
24
+ deleteOnExpire: true
25
+ });
26
+ function getUniqueId(type, id) {
27
+ return `${type}.${id}`;
28
+ }
29
+ return {
30
+ async get(type, ids) {
31
+ const data = {};
32
+ const idsToFetch = [];
33
+ for (const id of ids) {
34
+ const item = cache.get(getUniqueId(type, id));
35
+ if (typeof item !== 'undefined') {
36
+ data[id] = item;
37
+ }
38
+ else {
39
+ idsToFetch.push(id);
40
+ }
41
+ }
42
+ if (idsToFetch.length) {
43
+ logger === null || logger === void 0 ? void 0 : logger.trace({ items: idsToFetch.length }, 'loading from store');
44
+ const fetched = await store.get(type, idsToFetch);
45
+ for (const id of idsToFetch) {
46
+ const item = fetched[id];
47
+ if (item) {
48
+ data[id] = item;
49
+ cache.set(getUniqueId(type, id), item);
50
+ }
51
+ }
52
+ }
53
+ return data;
54
+ },
55
+ async set(data) {
56
+ let keys = 0;
57
+ for (const type in data) {
58
+ for (const id in data[type]) {
59
+ cache.set(getUniqueId(type, id), data[type][id]);
60
+ keys += 1;
61
+ }
62
+ }
63
+ logger === null || logger === void 0 ? void 0 : logger.trace({ keys }, 'updated cache');
64
+ await store.set(data);
65
+ },
66
+ async clear() {
67
+ var _a;
68
+ cache.flushAll();
69
+ await ((_a = store.clear) === null || _a === void 0 ? void 0 : _a.call(store));
70
+ }
71
+ };
72
+ }
73
+ /**
74
+ * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
75
+ * this allows batch read & write operations & improves the performance of the lib
76
+ * @param state the key store to apply this capability to
77
+ * @param logger logger to log events
78
+ * @returns SignalKeyStore with transaction capability
79
+ */
80
+ const addTransactionCapability = (state, logger, { maxCommitRetries, delayBetweenTriesMs }) => {
81
+ // number of queries made to the DB during the transaction
82
+ // only there for logging purposes
83
+ let dbQueriesInTransaction = 0;
84
+ let transactionCache = {};
85
+ let mutations = {};
86
+ let transactionsInProgress = 0;
87
+ return {
88
+ get: async (type, ids) => {
89
+ if (isInTransaction()) {
90
+ const dict = transactionCache[type];
91
+ const idsRequiringFetch = dict ? ids.filter(item => typeof dict[item] === 'undefined') : ids;
92
+ // only fetch if there are any items to fetch
93
+ if (idsRequiringFetch.length) {
94
+ dbQueriesInTransaction += 1;
95
+ const result = await state.get(type, idsRequiringFetch);
96
+ transactionCache[type] || (transactionCache[type] = {});
97
+ Object.assign(transactionCache[type], result);
98
+ }
99
+ return ids.reduce((dict, id) => {
100
+ var _a;
101
+ const value = (_a = transactionCache[type]) === null || _a === void 0 ? void 0 : _a[id];
102
+ if (value) {
103
+ dict[id] = value;
104
+ }
105
+ return dict;
106
+ }, {});
107
+ }
108
+ else {
109
+ return state.get(type, ids);
110
+ }
111
+ },
112
+ set: data => {
113
+ if (isInTransaction()) {
114
+ logger.trace({ types: Object.keys(data) }, 'caching in transaction');
115
+ for (const key in data) {
116
+ transactionCache[key] = transactionCache[key] || {};
117
+ Object.assign(transactionCache[key], data[key]);
118
+ mutations[key] = mutations[key] || {};
119
+ Object.assign(mutations[key], data[key]);
120
+ }
121
+ }
122
+ else {
123
+ return state.set(data);
124
+ }
125
+ },
126
+ isInTransaction,
127
+ async transaction(work) {
128
+ let result;
129
+ transactionsInProgress += 1;
130
+ if (transactionsInProgress === 1) {
131
+ logger.trace('entering transaction');
132
+ }
133
+ try {
134
+ result = await work();
135
+ // commit if this is the outermost transaction
136
+ if (transactionsInProgress === 1) {
137
+ if (Object.keys(mutations).length) {
138
+ logger.trace('committing transaction');
139
+ // retry mechanism to ensure we've some recovery
140
+ // in case a transaction fails in the first attempt
141
+ let tries = maxCommitRetries;
142
+ while (tries) {
143
+ tries -= 1;
144
+ //eslint-disable-next-line max-depth
145
+ try {
146
+ await state.set(mutations);
147
+ logger.trace({ dbQueriesInTransaction }, 'committed transaction');
148
+ break;
149
+ }
150
+ catch (error) {
151
+ logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`);
152
+ await (0, generics_1.delay)(delayBetweenTriesMs);
153
+ }
154
+ }
155
+ }
156
+ else {
157
+ logger.trace('no mutations in transaction');
158
+ }
159
+ }
160
+ }
161
+ finally {
162
+ transactionsInProgress -= 1;
163
+ if (transactionsInProgress === 0) {
164
+ transactionCache = {};
165
+ mutations = {};
166
+ dbQueriesInTransaction = 0;
167
+ }
168
+ }
169
+ return result;
170
+ }
171
+ };
172
+ function isInTransaction() {
173
+ return transactionsInProgress > 0;
174
+ }
175
+ };
176
+ exports.addTransactionCapability = addTransactionCapability;
177
+ const initAuthCreds = () => {
178
+ const identityKey = crypto_2.Curve.generateKeyPair();
179
+ return {
180
+ noiseKey: crypto_2.Curve.generateKeyPair(),
181
+ pairingEphemeralKeyPair: crypto_2.Curve.generateKeyPair(),
182
+ signedIdentityKey: identityKey,
183
+ signedPreKey: (0, crypto_2.signedKeyPair)(identityKey, 1),
184
+ registrationId: (0, generics_1.generateRegistrationId)(),
185
+ advSecretKey: (0, crypto_1.randomBytes)(32).toString('base64'),
186
+ processedHistoryMessages: [],
187
+ nextPreKeyId: 1,
188
+ firstUnuploadedPreKeyId: 1,
189
+ accountSyncCounter: 0,
190
+ accountSettings: {
191
+ unarchiveChats: false
192
+ },
193
+ registered: false,
194
+ pairingCode: undefined,
195
+ lastPropHash: undefined,
196
+ routingInfo: undefined
197
+ };
198
+ };
199
+ exports.initAuthCreds = initAuthCreds;
@@ -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;