@rexxhayanasi/elaina-baileys 1.0.6 → 1.0.7

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/README.MD CHANGED
@@ -21,8 +21,8 @@
21
21
  </p>
22
22
  </div>
23
23
  <p align="center">
24
- <a href="https://elaina-bail.vercel.app">
25
- <img src="https://img.shields.io/badge/Dokumentasi-Baileys-blue?style=for-the-badge&logo=readthedocs&logoColor=white" alt="Lihat Dokumentasi">
24
+ <a href="https://status-elainabaileys.vercel.app">
25
+ <img src="https://img.shields.io/badge/Status-Baileys-blue?style=for-the-badge&logo=readthedocs&logoColor=white" alt="Status Baileys">
26
26
  </a>
27
27
  </p>
28
28
 
@@ -1,10 +1,10 @@
1
- const { creator: CREATOR } = require("./creator.json");
1
+ const { creator: CREATOR } = require("../creator.json");
2
2
 
3
3
  const growagarden = async () => {
4
4
  try {
5
5
  const res = await fetch("https://gagstock.gleeze.com/grow-a-garden");
6
6
  if (!res.ok) {
7
- throw new Error("RClouds API Grow A Garden gagal mengambil data");
7
+ throw new Error("@rexxhayanasi/elaina-baileys API Grow A Garden gagal mengambil data");
8
8
  }
9
9
 
10
10
  const json = await res.json();
@@ -25,3 +25,4 @@ const growagarden = async () => {
25
25
  };
26
26
 
27
27
  module.exports = growagarden;
28
+ module.exports.default = growagarden;
@@ -1,4 +1,4 @@
1
- const { creator: CREATOR } = require("./creator.json");
1
+ const { creator: CREATOR } = require("../creator.json");
2
2
 
3
3
  // === Proxy download file ===
4
4
  async function proxyFile(fileUrl, filename, mimeType) {
@@ -90,9 +90,9 @@ async function tiktokdownload(params = {}) {
90
90
  }
91
91
  }
92
92
 
93
- // Video normal
93
+ // Video atau slide
94
94
  if (result?.play || result?.hdplay) {
95
- // Kalau slide
95
+ // Jika slide
96
96
  if (Array.isArray(result.images) && result.images.length > 0) {
97
97
  return await fetchImages(url);
98
98
  }
@@ -114,7 +114,7 @@ async function tiktokdownload(params = {}) {
114
114
  };
115
115
  }
116
116
 
117
- // fallback slide
117
+ // fallback slide
118
118
  return await fetchImages(url);
119
119
 
120
120
  } catch (err) {
@@ -127,4 +127,6 @@ async function tiktokdownload(params = {}) {
127
127
  }
128
128
  }
129
129
 
130
+ // *** FIX EKSPOR ***
130
131
  module.exports = tiktokdownload;
132
+ module.exports.default = tiktokdownload;
package/lib/Api/index.js CHANGED
@@ -1,7 +1,38 @@
1
- module.exports = {
2
- githubstalk: require("./tools/githubstalk"),
3
- stalkroblox: require("./stalker/stalkroblox"),
4
- growagarden: require("./Internet/growagarden"),
5
- tiktokdownload: require("./downloader/tiktokdownload"),
6
- loli: require("./nsfw/loli")
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
4
  };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.githubstalk =
7
+ exports.stalkroblox =
8
+ exports.ttstalk =
9
+ exports.growagarden =
10
+ exports.ttdl =
11
+ exports.loli =
12
+ exports.ssweb =
13
+ void 0;
14
+
15
+ // Bagian Stalker
16
+ const githubstalk_1 = __importDefault(require("./stalker/githubstalk"));
17
+ exports.githubstalk = githubstalk_1.default;
18
+
19
+ const stalkroblox_1 = __importDefault(require("./stalker/stalkroblox"));
20
+ exports.stalkroblox = stalkroblox_1.default;
21
+
22
+ const ttstalk_1 = __importDefault(require("./stalker/tiktokstalk"));
23
+ exports.ttstalk = ttstalk_1.default;
24
+
25
+ const growagarden_1 = __importDefault(require("./Internet/growagarden"));
26
+ exports.growagarden = growagarden_1.default;
27
+
28
+ // Bagian Downloader
29
+ const ttdl_1 = __importDefault(require("./downloader/tiktokdownload"));
30
+ exports.ttdl = ttdl_1.default;
31
+
32
+ // Bagian NSFW
33
+ const loli_1 = __importDefault(require("./nsfw/loli"));
34
+ exports.loli = loli_1.default;
35
+
36
+ // Bagian Tools
37
+ const ssweb_1 = __importDefault(require("./tools/ssweb"));
38
+ exports.ssweb = ssweb_1.default;
@@ -1,4 +1,4 @@
1
- const { creator: CREATOR } = require("./creator.json");
1
+ const { creator: CREATOR } = require("../creator.json");
2
2
 
3
3
  async function loli() {
4
4
  try {
@@ -23,11 +23,7 @@ async function loli() {
23
23
 
24
24
  const posts = await Promise.any(proxyList.map(parsePosts));
25
25
  if (!posts || posts.length === 0) {
26
- return {
27
- status: false,
28
- creator: CREATOR,
29
- images: []
30
- };
26
+ return { status: false, creator: CREATOR, images: [] };
31
27
  }
32
28
 
33
29
  const randomPost = posts[Math.floor(Math.random() * posts.length)];
@@ -60,17 +56,13 @@ async function loli() {
60
56
  const catboxUrl = (await uploadRes.text()).trim();
61
57
 
62
58
  if (!catboxUrl.startsWith("https://")) {
63
- return {
64
- status: false,
65
- creator: CREATOR,
66
- images: []
67
- };
59
+ return { status: false, creator: CREATOR, images: [] };
68
60
  }
69
61
 
70
62
  return {
71
63
  status: true,
72
- creator: CREATOR,
73
- images: [catboxUrl]
64
+ images: [catboxUrl],
65
+ creator: CREATOR
74
66
  };
75
67
 
76
68
  } catch (err) {
@@ -84,3 +76,4 @@ async function loli() {
84
76
  }
85
77
 
86
78
  module.exports = loli;
79
+ module.exports.default = loli;
@@ -1,9 +1,9 @@
1
- const { creator: CREATOR } = require("./creator.json");
1
+ const { creator: CREATOR } = require("../creator.json");
2
2
 
3
3
  const githubstalk = async (user) => {
4
4
  if (!user) {
5
5
  return {
6
- error: "Missing parameter ?user=<github_username>",
6
+ error: "Missing parameter Username",
7
7
  creator: CREATOR,
8
8
  };
9
9
  }
@@ -13,8 +13,7 @@ const githubstalk = async (user) => {
13
13
  try {
14
14
  const response = await fetch(url, {
15
15
  headers: {
16
- "User-Agent":
17
- "Mozilla/5.0",
16
+ "User-Agent": "Mozilla/5.0",
18
17
  Accept: "application/vnd.github+json",
19
18
  },
20
19
  });
@@ -44,3 +43,4 @@ const githubstalk = async (user) => {
44
43
  };
45
44
 
46
45
  module.exports = githubstalk;
46
+ module.exports.default = githubstalk;
@@ -1,4 +1,4 @@
1
- const { creator: CREATOR } = require("./creator.json");
1
+ const { creator: CREATOR } = require("../creator.json");
2
2
 
3
3
  const postJson = async (url, body) => {
4
4
  try {
@@ -91,3 +91,4 @@ const stalkroblox = async (username) => {
91
91
  };
92
92
 
93
93
  module.exports = stalkroblox;
94
+ module.exports.default = stalkroblox;
@@ -0,0 +1,68 @@
1
+ const { creator: CREATOR } = require("../creator.json");
2
+ const cheerio = require("cheerio");
3
+
4
+ async function tiktokStalk(username) {
5
+ try {
6
+ const url = `https://www.tiktok.com/@${username}?_t=ZS-8tHANz7ieoS&_r=1`;
7
+
8
+ const response = await fetch(url, {
9
+ headers: {
10
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
11
+ }
12
+ });
13
+
14
+ const html = await response.text();
15
+ const $ = cheerio.load(html);
16
+
17
+ const scriptData = $('#__UNIVERSAL_DATA_FOR_REHYDRATION__').html();
18
+ if (!scriptData) {
19
+ return {
20
+ status: false,
21
+ message: "User tidak ditemukan atau data tidak tersedia."
22
+ };
23
+ }
24
+
25
+ const parsedData = JSON.parse(scriptData);
26
+ const userDetail = parsedData.__DEFAULT_SCOPE__?.["webapp.user-detail"];
27
+
28
+ if (!userDetail) {
29
+ return {
30
+ status: false,
31
+ message: "User tidak ditemukan atau data tidak tersedia."
32
+ };
33
+ }
34
+
35
+ const userInfo = userDetail.userInfo?.user;
36
+ const stats = userDetail.userInfo?.stats;
37
+
38
+ const hasil = {
39
+ id: userInfo?.id || null,
40
+ username: userInfo?.uniqueId || null,
41
+ nama: userInfo?.nickname || null,
42
+ avatar: userInfo?.avatarLarger || null,
43
+ bio: userInfo?.signature || null,
44
+ region: userInfo?.region || "Tidak diketahui",
45
+ verifikasi: userInfo?.verified || false,
46
+ totalfollowers: stats?.followerCount || 0,
47
+ totalmengikuti: stats?.followingCount || 0,
48
+ totaldisukai: stats?.heart || 0,
49
+ totalvideo: stats?.videoCount || 0,
50
+ totalteman: stats?.friendCount || 0
51
+ };
52
+
53
+ return {
54
+ status: true,
55
+ creator: CREATOR,
56
+ results: hasil
57
+ };
58
+
59
+ } catch (error) {
60
+ return {
61
+ status: false,
62
+ message: error.message || "Terjadi kesalahan saat mengambil data."
63
+ };
64
+ }
65
+ }
66
+
67
+ module.exports = ttstalk;
68
+ module.exports.default = ttstalk;
@@ -0,0 +1,38 @@
1
+ async function ssweb(url = "", full = false, type = "desktop") {
2
+ type = type.toLowerCase();
3
+ if (!["desktop", "tablet", "phone"].includes(type)) type = "desktop";
4
+
5
+ const form = new URLSearchParams();
6
+ form.append("url", url);
7
+ form.append("device", type);
8
+ if (!!full) form.append("full", "on");
9
+ form.append("cacheLimit", 0);
10
+
11
+ const res = await fetch("https://www.screenshotmachine.com/capture.php", {
12
+ method: "POST",
13
+ body: form,
14
+ headers: {
15
+ "Content-Type": "application/x-www-form-urlencoded",
16
+ },
17
+ });
18
+
19
+ const cookies = res.headers.get("set-cookie");
20
+ const json = await res.json();
21
+
22
+ if (!json.link) {
23
+ throw new Error("Gagal mendapatkan link screenshot.");
24
+ }
25
+
26
+
27
+ const imgRes = await fetch("https://www.screenshotmachine.com/" + json.link, {
28
+ headers: {
29
+ cookie: cookies || "",
30
+ },
31
+ });
32
+
33
+ const arrayBuf = await imgRes.arrayBuffer();
34
+ return Buffer.from(arrayBuf);
35
+ }
36
+
37
+ module.exports = ssweb;
38
+ module.exports.default = ssweb;
@@ -28,7 +28,7 @@ exports.default = (config) => {
28
28
  const chatKey = config.chatKey || (0, exports.waChatKey)(true);
29
29
  const labelAssociationKey = config.labelAssociationKey || exports.waLabelAssociationKey;
30
30
  const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
31
- const KeyedDB = require('@adiwajshing/keyed-db').default;
31
+ const KeyedDB = require('@rexxhayanasi/keyed-db').default;
32
32
  const chats = new KeyedDB(chatKey, c => c.id);
33
33
  const messages = {};
34
34
  const contacts = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexxhayanasi/elaina-baileys",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Custom Baileys WhatsApp API",
5
5
  "keywords": [
6
6
  "baileys",
@@ -42,7 +42,7 @@
42
42
  "test": "jest"
43
43
  },
44
44
  "dependencies": {
45
- "@adiwajshing/keyed-db": "npm:@rexxhayanasi/keyed-db@^1.0.0",
45
+ "@rexxhayanasi/keyed-db": "^1.0.0",
46
46
  "@cacheable/node-cache": "^1.4.0",
47
47
  "@hapi/boom": "^9.1.3",
48
48
  "async-mutex": "^0.5.0",
@@ -50,7 +50,7 @@
50
50
  "chalk": "^4.1.2",
51
51
  "gradient-string": "^2.0.2",
52
52
  "cache-manager": "^5.7.6",
53
- "cheerio": "^1.0.0-rc.10",
53
+ "cheerio": "^1.0.0-rc.12",
54
54
  "libphonenumber-js": "^1.10.20",
55
55
  "libsignal": "npm:@rexxhayanasi/elaina-libsignal",
56
56
  "lodash": "^4.17.21",
@@ -1,13 +0,0 @@
1
- {
2
- "creator": {
3
- "name": "RexxHayanasi",
4
- "username": "rexxhayanasi",
5
- "github": "https://github.com/rexxhayanasi",
6
- "instagram": "https://instagram.com/rexxhayanasi",
7
- "website": "https://rexxhayanasi.dev",
8
- "contact": {
9
- "whatsapp": "https://wa.me/6285282530851",
10
- "email": "rexxhayanasi@gmail.com"
11
- }
12
- }
13
- }
@@ -1,13 +0,0 @@
1
- {
2
- "creator": {
3
- "name": "RexxHayanasi",
4
- "username": "rexxhayanasi",
5
- "github": "https://github.com/rexxhayanasi",
6
- "instagram": "https://instagram.com/rexxhayanasi",
7
- "website": "https://rexxhayanasi.dev",
8
- "contact": {
9
- "whatsapp": "https://wa.me/6285282530851",
10
- "email": "rexxhayanasi@gmail.com"
11
- }
12
- }
13
- }
@@ -1,13 +0,0 @@
1
- {
2
- "creator": {
3
- "name": "RexxHayanasi",
4
- "username": "rexxhayanasi",
5
- "github": "https://github.com/rexxhayanasi",
6
- "instagram": "https://instagram.com/rexxhayanasi",
7
- "website": "https://rexxhayanasi.dev",
8
- "contact": {
9
- "whatsapp": "https://wa.me/6285282530851",
10
- "email": "rexxhayanasi@gmail.com"
11
- }
12
- }
13
- }
@@ -1,13 +0,0 @@
1
- {
2
- "creator": {
3
- "name": "RexxHayanasi",
4
- "username": "rexxhayanasi",
5
- "github": "https://github.com/rexxhayanasi",
6
- "instagram": "https://instagram.com/rexxhayanasi",
7
- "website": "https://rexxhayanasi.dev",
8
- "contact": {
9
- "whatsapp": "https://wa.me/6285282530851",
10
- "email": "rexxhayanasi@gmail.com"
11
- }
12
- }
13
- }
@@ -1,439 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.waLabelAssociationKey = exports.waMessageID = exports.waChatKey = void 0;
7
- const WAProto_1 = require("../../WAProto");
8
- const Defaults_1 = require("../Defaults");
9
- const LabelAssociation_1 = require("../Types/LabelAssociation");
10
- const Utils_1 = require("../Utils");
11
- const WABinary_1 = require("../WABinary");
12
- const make_ordered_dictionary_1 = __importDefault(require("./make-ordered-dictionary"));
13
- const object_repository_1 = require("./object-repository");
14
- const waChatKey = (pin) => ({
15
- key: (c) => (pin ? (c.pinned ? '1' : '0') : '') + (c.archived ? '0' : '1') + (c.conversationTimestamp ? c.conversationTimestamp.toString(16).padStart(8, '0') : '') + c.id,
16
- compare: (k1, k2) => k2.localeCompare(k1)
17
- });
18
- exports.waChatKey = waChatKey;
19
- const waMessageID = (m) => m.key.id || '';
20
- exports.waMessageID = waMessageID;
21
- exports.waLabelAssociationKey = {
22
- key: (la) => (la.type === LabelAssociation_1.LabelAssociationType.Chat ? la.chatId + la.labelId : la.chatId + la.messageId + la.labelId),
23
- compare: (k1, k2) => k2.localeCompare(k1)
24
- };
25
- const makeMessagesDictionary = () => (0, make_ordered_dictionary_1.default)(exports.waMessageID);
26
- exports.default = (config) => {
27
- const socket = config.socket;
28
- const chatKey = config.chatKey || (0, exports.waChatKey)(true);
29
- const labelAssociationKey = config.labelAssociationKey || exports.waLabelAssociationKey;
30
- const logger = config.logger || Defaults_1.DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' });
31
- const KeyedDB = require('@adiwajshing/keyed-db').default;
32
- const chats = new KeyedDB(chatKey, c => c.id);
33
- const messages = {};
34
- const contacts = {};
35
- const groupMetadata = {};
36
- const presences = {};
37
- const state = { connection: 'close' };
38
- const labels = new object_repository_1.ObjectRepository();
39
- const labelAssociations = new KeyedDB(labelAssociationKey, labelAssociationKey.key);
40
- const assertMessageList = (jid) => {
41
- if (!messages[jid]) {
42
- messages[jid] = makeMessagesDictionary();
43
- }
44
- return messages[jid];
45
- };
46
- const contactsUpsert = (newContacts) => {
47
- const oldContacts = new Set(Object.keys(contacts));
48
- for (const contact of newContacts) {
49
- oldContacts.delete(contact.id);
50
- contacts[contact.id] = Object.assign(contacts[contact.id] || {}, contact);
51
- }
52
- return oldContacts;
53
- };
54
- const labelsUpsert = (newLabels) => {
55
- for (const label of newLabels) {
56
- labels.upsertById(label.id, label);
57
- }
58
- };
59
- const getValidContacts = () => {
60
- for (const contact of Object.keys(contacts)) {
61
- if (contact.indexOf('@') < 0) {
62
- delete contacts[contact];
63
- }
64
- }
65
- return Object.keys(contacts);
66
- };
67
- /**
68
- * binds to a WileysEventEmitter.
69
- * It listens to all events and constructs a state that you can query accurate data from.
70
- * Eg. can use the store to fetch chats, contacts, messages etc.
71
- * @param ev typically the event emitter from the socket connection
72
- */
73
- const bind = (ev) => {
74
- ev.on('connection.update', update => {
75
- Object.assign(state, update);
76
- });
77
- ev.on('messaging-history.set', ({ chats: newChats, contacts: newContacts, messages: newMessages, isLatest, syncType }) => {
78
- if (syncType === WAProto_1.proto.HistorySync.HistorySyncType.ON_DEMAND) {
79
- return; // FOR NOW,
80
- //TODO: HANDLE
81
- }
82
- if (isLatest) {
83
- chats.clear();
84
- for (const id in messages) {
85
- delete messages[id];
86
- }
87
- }
88
- const chatsAdded = chats.insertIfAbsent(...newChats).length;
89
- logger.debug({ chatsAdded }, 'synced chats');
90
- const oldContacts = contactsUpsert(newContacts);
91
- if (isLatest) {
92
- for (const jid of oldContacts) {
93
- delete contacts[jid];
94
- }
95
- }
96
- logger.debug({ deletedContacts: isLatest ? oldContacts.size : 0, newContacts }, 'synced contacts');
97
- for (const msg of newMessages) {
98
- const jid = msg.key.remoteJid;
99
- const list = assertMessageList(jid);
100
- list.upsert(msg, 'prepend');
101
- }
102
- logger.debug({ messages: newMessages.length }, 'synced messages');
103
- });
104
- ev.on('contacts.upsert', contacts => {
105
- contactsUpsert(contacts);
106
- });
107
- ev.on('contacts.update', async (updates) => {
108
- var _a;
109
- for (const update of updates) {
110
- let contact;
111
- if (contacts[update.id]) {
112
- contact = contacts[update.id];
113
- }
114
- else {
115
- const validContacts = getValidContacts();
116
- const contactHashes = validContacts.map((contactId) => {
117
- const { user } = (0, WABinary_1.jidDecode)(contactId);
118
- return [contactId, ((0, Utils_1.md5)(Buffer.from(user + 'WA_ADD_NOTIF', 'utf8'))).toString('base64').slice(0, 3)];
119
- });
120
- contact = contacts[((_a = contactHashes.find(([, b]) => b === update.id)) === null || _a === void 0 ? void 0 : _a[0]) || '']; // find contact by attrs.hash, when user is not saved as a contact
121
- }
122
- if (contact) {
123
- if (update.imgUrl === 'changed') {
124
- contact.imgUrl = socket ? await (socket === null || socket === void 0 ? void 0 : socket.profilePictureUrl(contact.id)) : undefined;
125
- }
126
- else if (update.imgUrl === 'removed') {
127
- delete contact.imgUrl;
128
- }
129
- Object.assign(contacts[contact.id], contact);
130
- }
131
- else {
132
- logger.debug({ update }, 'got update for non-existant contact');
133
- }
134
- }
135
- });
136
- ev.on('chats.upsert', newChats => {
137
- chats.upsert(...newChats);
138
- });
139
- ev.on('chats.update', updates => {
140
- for (let update of updates) {
141
- const result = chats.update(update.id, chat => {
142
- if (update.unreadCount > 0) {
143
- update = { ...update };
144
- update.unreadCount = (chat.unreadCount || 0) + update.unreadCount;
145
- }
146
- Object.assign(chat, update);
147
- });
148
- if (!result) {
149
- logger.debug({ update }, 'got update for non-existant chat');
150
- }
151
- }
152
- });
153
- ev.on('labels.edit', (label) => {
154
- if (label.deleted) {
155
- return labels.deleteById(label.id);
156
- }
157
- // WhatsApp can store only up to 20 labels
158
- if (labels.count() < 20) {
159
- return labels.upsertById(label.id, label);
160
- }
161
- logger.error('Labels count exceed');
162
- });
163
- ev.on('labels.association', ({ type, association }) => {
164
- switch (type) {
165
- case 'add':
166
- labelAssociations.upsert(association);
167
- break;
168
- case 'remove':
169
- labelAssociations.delete(association);
170
- break;
171
- default:
172
- console.error(`unknown operation type [${type}]`);
173
- }
174
- });
175
- ev.on('presence.update', ({ id, presences: update }) => {
176
- presences[id] = presences[id] || {};
177
- Object.assign(presences[id], update);
178
- });
179
- ev.on('chats.delete', deletions => {
180
- for (const item of deletions) {
181
- if (chats.get(item)) {
182
- chats.deleteById(item);
183
- }
184
- }
185
- });
186
- ev.on('messages.upsert', ({ messages: newMessages, type }) => {
187
- switch (type) {
188
- case 'append':
189
- case 'notify':
190
- for (const msg of newMessages) {
191
- const jid = (0, WABinary_1.jidNormalizedUser)(msg.key.remoteJid);
192
- const list = assertMessageList(jid);
193
- list.upsert(msg, 'append');
194
- if (type === 'notify' && !chats.get(jid)) {
195
- ev.emit('chats.upsert', [
196
- {
197
- id: jid,
198
- conversationTimestamp: (0, Utils_1.toNumber)(msg.messageTimestamp),
199
- unreadCount: 1
200
- }
201
- ]);
202
- }
203
- }
204
- break;
205
- }
206
- });
207
- ev.on('messages.update', updates => {
208
- var _a;
209
- for (const { update, key } of updates) {
210
- const list = assertMessageList((0, WABinary_1.jidNormalizedUser)(key.remoteJid));
211
- if (update === null || update === void 0 ? void 0 : update.status) {
212
- const listStatus = (_a = list.get(key.id)) === null || _a === void 0 ? void 0 : _a.status;
213
- if (listStatus && (update === null || update === void 0 ? void 0 : update.status) <= listStatus) {
214
- logger.debug({ update, storedStatus: listStatus }, 'status stored newer then update');
215
- delete update.status;
216
- logger.debug({ update }, 'new update object');
217
- }
218
- }
219
- const result = list.updateAssign(key.id, update);
220
- if (!result) {
221
- logger.debug({ update }, 'got update for non-existent message');
222
- }
223
- }
224
- });
225
- ev.on('messages.delete', item => {
226
- if ('all' in item) {
227
- const list = messages[item.jid];
228
- list === null || list === void 0 ? void 0 : list.clear();
229
- }
230
- else {
231
- const jid = item.keys[0].remoteJid;
232
- const list = messages[jid];
233
- if (list) {
234
- const idSet = new Set(item.keys.map(k => k.id));
235
- list.filter(m => !idSet.has(m.key.id));
236
- }
237
- }
238
- });
239
- ev.on('groups.update', updates => {
240
- for (const update of updates) {
241
- const id = update.id;
242
- if (groupMetadata[id]) {
243
- Object.assign(groupMetadata[id], update);
244
- }
245
- else {
246
- logger.debug({ update }, 'got update for non-existant group metadata');
247
- }
248
- }
249
- });
250
- ev.on('group-participants.update', ({ id, participants, action }) => {
251
- const metadata = groupMetadata[id];
252
- if (metadata) {
253
- switch (action) {
254
- case 'add':
255
- metadata.participants.push(...participants.map(id => ({ id, isAdmin: false, isSuperAdmin: false })));
256
- break;
257
- case 'demote':
258
- case 'promote':
259
- for (const participant of metadata.participants) {
260
- if (participants.includes(participant.id)) {
261
- participant.isAdmin = action === 'promote';
262
- }
263
- }
264
- break;
265
- case 'remove':
266
- metadata.participants = metadata.participants.filter(p => !participants.includes(p.id));
267
- break;
268
- }
269
- }
270
- });
271
- ev.on('message-receipt.update', updates => {
272
- for (const { key, receipt } of updates) {
273
- const obj = messages[key.remoteJid];
274
- const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
275
- if (msg) {
276
- (0, Utils_1.updateMessageWithReceipt)(msg, receipt);
277
- }
278
- }
279
- });
280
- ev.on('messages.reaction', (reactions) => {
281
- for (const { key, reaction } of reactions) {
282
- const obj = messages[key.remoteJid];
283
- const msg = obj === null || obj === void 0 ? void 0 : obj.get(key.id);
284
- if (msg) {
285
- (0, Utils_1.updateMessageWithReaction)(msg, reaction);
286
- }
287
- }
288
- });
289
- };
290
- const toJSON = () => ({
291
- chats,
292
- contacts,
293
- messages,
294
- labels,
295
- labelAssociations
296
- });
297
- const fromJSON = (json) => {
298
- chats.upsert(...json.chats);
299
- labelAssociations.upsert(...json.labelAssociations || []);
300
- contactsUpsert(Object.values(json.contacts));
301
- labelsUpsert(Object.values(json.labels || {}));
302
- for (const jid in json.messages) {
303
- const list = assertMessageList(jid);
304
- for (const msg of json.messages[jid]) {
305
- list.upsert(WAProto_1.proto.WebMessageInfo.fromObject(msg), 'append');
306
- }
307
- }
308
- };
309
- return {
310
- chats,
311
- contacts,
312
- messages,
313
- groupMetadata,
314
- state,
315
- presences,
316
- labels,
317
- labelAssociations,
318
- bind,
319
- /** loads messages from the store, if not found -- uses the legacy connection */
320
- loadMessages: async (jid, count, cursor) => {
321
- const list = assertMessageList(jid);
322
- const mode = !cursor || 'before' in cursor ? 'before' : 'after';
323
- const cursorKey = !!cursor ? ('before' in cursor ? cursor.before : cursor.after) : undefined;
324
- const cursorValue = cursorKey ? list.get(cursorKey.id) : undefined;
325
- let messages;
326
- if (list && mode === 'before' && (!cursorKey || cursorValue)) {
327
- if (cursorValue) {
328
- const msgIdx = list.array.findIndex(m => m.key.id === (cursorKey === null || cursorKey === void 0 ? void 0 : cursorKey.id));
329
- messages = list.array.slice(0, msgIdx);
330
- }
331
- else {
332
- messages = list.array;
333
- }
334
- const diff = count - messages.length;
335
- if (diff < 0) {
336
- messages = messages.slice(-count); // get the last X messages
337
- }
338
- }
339
- else {
340
- messages = [];
341
- }
342
- return messages;
343
- },
344
- /**
345
- * Get all available labels for profile
346
- *
347
- * Keep in mind that the list is formed from predefined tags and tags
348
- * that were "caught" during their editing.
349
- */
350
- getLabels: () => {
351
- return labels;
352
- },
353
- /**
354
- * Get labels for chat
355
- *
356
- * @returns Label IDs
357
- **/
358
- getChatLabels: (chatId) => {
359
- return labelAssociations.filter((la) => la.chatId === chatId).all();
360
- },
361
- /**
362
- * Get labels for message
363
- *
364
- * @returns Label IDs
365
- **/
366
- getMessageLabels: (messageId) => {
367
- const associations = labelAssociations
368
- .filter((la) => la.messageId === messageId)
369
- .all();
370
- return associations.map(({ labelId }) => labelId);
371
- },
372
- loadMessage: async (jid, id) => { var _a; return (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.get(id); },
373
- mostRecentMessage: async (jid) => {
374
- var _a;
375
- const message = (_a = messages[jid]) === null || _a === void 0 ? void 0 : _a.array.slice(-1)[0];
376
- return message;
377
- },
378
- fetchImageUrl: async (jid, sock) => {
379
- const contact = contacts[jid];
380
- if (!contact) {
381
- return sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid);
382
- }
383
- if (typeof contact.imgUrl === 'undefined') {
384
- contact.imgUrl = await (sock === null || sock === void 0 ? void 0 : sock.profilePictureUrl(jid));
385
- }
386
- return contact.imgUrl;
387
- },
388
- fetchGroupMetadata: async (jid, sock) => {
389
- if (!groupMetadata[jid]) {
390
- const metadata = await (sock === null || sock === void 0 ? void 0 : sock.groupMetadata(jid));
391
- if (metadata) {
392
- groupMetadata[jid] = metadata;
393
- }
394
- }
395
- return groupMetadata[jid];
396
- },
397
- // fetchBroadcastListInfo: async(jid: string, sock: WASocket | undefined) => {
398
- // if(!groupMetadata[jid]) {
399
- // const metadata = await sock?.getBroadcastListInfo(jid)
400
- // if(metadata) {
401
- // groupMetadata[jid] = metadata
402
- // }
403
- // }
404
- // return groupMetadata[jid]
405
- // },
406
- fetchMessageReceipts: async ({ remoteJid, id }) => {
407
- const list = messages[remoteJid];
408
- const msg = list === null || list === void 0 ? void 0 : list.get(id);
409
- return msg === null || msg === void 0 ? void 0 : msg.userReceipt;
410
- },
411
- toJSON,
412
- fromJSON,
413
- writeToFile: (path) => {
414
- // require fs here so that in case "fs" is not available -- the app does not crash
415
- const { writeFileSync } = require('fs');
416
- writeFileSync(path, JSON.stringify(toJSON()));
417
- },
418
- readFromFile: (path) => {
419
- // require fs here so that in case "fs" is not available -- the app does not crash
420
- const { readFileSync, existsSync } = require('fs');
421
- if (existsSync(path)) {
422
- logger.debug({ path }, 'reading from file');
423
- try {
424
- const jsonStr = readFileSync(path, { encoding: 'utf-8' });
425
- if (jsonStr.trim().length) {
426
- const json = JSON.parse(jsonStr);
427
- fromJSON(json);
428
- }
429
- else {
430
- logger.warn({ path }, 'skipping empty json file');
431
- }
432
- }
433
- catch (err) {
434
- logger.warn({ path, err }, 'failed to parse json from file');
435
- }
436
- }
437
- }
438
- };
439
- };
File without changes