stfca 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.
Files changed (82) hide show
  1. package/LICENSE-MIT +4 -0
  2. package/README.md +325 -0
  3. package/index.d.ts +615 -0
  4. package/index.js +1 -0
  5. package/module/config.js +33 -0
  6. package/module/login.js +48 -0
  7. package/module/loginHelper.js +722 -0
  8. package/module/options.js +44 -0
  9. package/package.json +69 -0
  10. package/src/api/action/addExternalModule.js +25 -0
  11. package/src/api/action/changeAvatar.js +137 -0
  12. package/src/api/action/changeBio.js +75 -0
  13. package/src/api/action/getCurrentUserID.js +7 -0
  14. package/src/api/action/handleFriendRequest.js +57 -0
  15. package/src/api/action/logout.js +76 -0
  16. package/src/api/action/refreshFb_dtsg.js +71 -0
  17. package/src/api/action/setPostReaction.js +106 -0
  18. package/src/api/action/unfriend.js +54 -0
  19. package/src/api/http/httpGet.js +46 -0
  20. package/src/api/http/httpPost.js +52 -0
  21. package/src/api/http/postFormData.js +47 -0
  22. package/src/api/messaging/addUserToGroup.js +68 -0
  23. package/src/api/messaging/changeAdminStatus.js +122 -0
  24. package/src/api/messaging/changeArchivedStatus.js +55 -0
  25. package/src/api/messaging/changeBlockedStatus.js +48 -0
  26. package/src/api/messaging/changeGroupImage.js +90 -0
  27. package/src/api/messaging/changeNickname.js +70 -0
  28. package/src/api/messaging/changeThreadColor.js +79 -0
  29. package/src/api/messaging/changeThreadEmoji.js +106 -0
  30. package/src/api/messaging/createNewGroup.js +88 -0
  31. package/src/api/messaging/createPoll.js +43 -0
  32. package/src/api/messaging/deleteMessage.js +56 -0
  33. package/src/api/messaging/deleteThread.js +56 -0
  34. package/src/api/messaging/editMessage.js +68 -0
  35. package/src/api/messaging/forwardAttachment.js +51 -0
  36. package/src/api/messaging/getEmojiUrl.js +29 -0
  37. package/src/api/messaging/getFriendsList.js +82 -0
  38. package/src/api/messaging/getMessage.js +829 -0
  39. package/src/api/messaging/handleMessageRequest.js +65 -0
  40. package/src/api/messaging/markAsDelivered.js +57 -0
  41. package/src/api/messaging/markAsRead.js +88 -0
  42. package/src/api/messaging/markAsReadAll.js +49 -0
  43. package/src/api/messaging/markAsSeen.js +61 -0
  44. package/src/api/messaging/muteThread.js +50 -0
  45. package/src/api/messaging/removeUserFromGroup.js +105 -0
  46. package/src/api/messaging/resolvePhotoUrl.js +43 -0
  47. package/src/api/messaging/searchForThread.js +52 -0
  48. package/src/api/messaging/sendMessage.js +379 -0
  49. package/src/api/messaging/sendMessageMqtt.js +323 -0
  50. package/src/api/messaging/sendTypingIndicator.js +67 -0
  51. package/src/api/messaging/setMessageReaction.js +75 -0
  52. package/src/api/messaging/setTitle.js +119 -0
  53. package/src/api/messaging/shareContact.js +49 -0
  54. package/src/api/messaging/threadColors.js +128 -0
  55. package/src/api/messaging/unsendMessage.js +81 -0
  56. package/src/api/messaging/uploadAttachment.js +95 -0
  57. package/src/api/socket/core/connectMqtt.js +179 -0
  58. package/src/api/socket/core/getSeqID.js +25 -0
  59. package/src/api/socket/core/getTaskResponseData.js +22 -0
  60. package/src/api/socket/core/markDelivery.js +12 -0
  61. package/src/api/socket/core/parseDelta.js +351 -0
  62. package/src/api/socket/detail/buildStream.js +208 -0
  63. package/src/api/socket/detail/constants.js +24 -0
  64. package/src/api/socket/listenMqtt.js +133 -0
  65. package/src/api/threads/getThreadHistory.js +664 -0
  66. package/src/api/threads/getThreadInfo.js +358 -0
  67. package/src/api/threads/getThreadList.js +248 -0
  68. package/src/api/threads/getThreadPictures.js +78 -0
  69. package/src/api/users/getUserID.js +65 -0
  70. package/src/api/users/getUserInfo.js +319 -0
  71. package/src/api/users/getUserInfoV2.js +133 -0
  72. package/src/core/sendReqMqtt.js +63 -0
  73. package/src/database/models/index.js +49 -0
  74. package/src/database/models/thread.js +31 -0
  75. package/src/database/models/user.js +32 -0
  76. package/src/database/threadData.js +98 -0
  77. package/src/database/userData.js +89 -0
  78. package/src/utils/client.js +214 -0
  79. package/src/utils/constants.js +23 -0
  80. package/src/utils/format.js +1111 -0
  81. package/src/utils/headers.js +41 -0
  82. package/src/utils/request.js +215 -0
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+
3
+ const log = require("npmlog");
4
+ const { formatID } = require("../../utils/format");
5
+ function formatData(data) {
6
+ return {
7
+ userID: formatID(data.uid.toString()),
8
+ photoUrl: data.photo,
9
+ indexRank: data.index_rank,
10
+ name: data.text,
11
+ isVerified: data.is_verified,
12
+ profileUrl: data.path,
13
+ category: data.category,
14
+ score: data.score,
15
+ type: data.type
16
+ };
17
+ }
18
+
19
+ module.exports = function(defaultFuncs, api, ctx) {
20
+ return function getUserID(name, callback) {
21
+ let resolveFunc = function() {};
22
+ let rejectFunc = function() {};
23
+ const returnPromise = new Promise(function(resolve, reject) {
24
+ resolveFunc = resolve;
25
+ rejectFunc = reject;
26
+ });
27
+
28
+ if (!callback) {
29
+ callback = function(err, friendList) {
30
+ if (err) {
31
+ return rejectFunc(err);
32
+ }
33
+ resolveFunc(friendList);
34
+ };
35
+ }
36
+
37
+ const form = {
38
+ value: name.toLowerCase(),
39
+ viewer: ctx.userID,
40
+ rsp: "search",
41
+ context: "search",
42
+ path: "/home.php",
43
+ request_id: ctx.clientId
44
+ };
45
+
46
+ defaultFuncs
47
+ .get("https://www.facebook.com/ajax/typeahead/search.php", ctx.jar, form)
48
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
49
+ .then(function(resData) {
50
+ if (resData.error) {
51
+ throw resData;
52
+ }
53
+
54
+ const data = resData.payload.entries;
55
+
56
+ callback(null, data.map(formatData));
57
+ })
58
+ .catch(function(err) {
59
+ log.error("getUserID", err);
60
+ return callback(err);
61
+ });
62
+
63
+ return returnPromise;
64
+ };
65
+ };
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const log = require("npmlog");
6
+ const { parseAndCheckLogin } = require("../../utils/client.js");
7
+
8
+ const DOC_PRIMARY = "5009315269112105";
9
+ const BATCH_PRIMARY = "MessengerParticipantsFetcher";
10
+ const DOC_V2 = "24418640587785718";
11
+ const FRIENDLY_V2 = "CometHovercardQueryRendererQuery";
12
+ const CALLER_V2 = "RelayModern";
13
+
14
+ function toJSONMaybe(s) {
15
+ if (!s) return null;
16
+ if (typeof s === "string") {
17
+ const t = s.trim().replace(/^for\s*\(\s*;\s*;\s*\)\s*;/, "");
18
+ try { return JSON.parse(t); } catch { return null; }
19
+ }
20
+ return s;
21
+ }
22
+
23
+ function usernameFromUrl(raw) {
24
+ if (!raw) return null;
25
+ try {
26
+ const u = new URL(raw);
27
+ if (/^www\.facebook\.com$/i.test(u.hostname)) {
28
+ const seg = u.pathname.replace(/^\//, "").replace(/\/$/, "");
29
+ if (seg && !/^profile\.php$/i.test(seg) && !seg.includes("/")) return seg;
30
+ }
31
+ } catch { }
32
+ return null;
33
+ }
34
+
35
+ function pickMeta(u) {
36
+ let friendshipStatus = null;
37
+ let gender = null;
38
+ let shortName = u?.short_name || null;
39
+ const pa = Array.isArray(u?.primaryActions) ? u.primaryActions : [];
40
+ const sa = Array.isArray(u?.secondaryActions) ? u.secondaryActions : [];
41
+ const aFriend = pa.find(x => x?.profile_action_type === "FRIEND");
42
+ if (aFriend?.client_handler?.profile_action?.restrictable_profile_owner) {
43
+ const p = aFriend.client_handler.profile_action.restrictable_profile_owner;
44
+ friendshipStatus = p?.friendship_status || null;
45
+ gender = p?.gender || gender;
46
+ shortName = p?.short_name || shortName;
47
+ }
48
+ if (!gender || !shortName) {
49
+ const aBlock = sa.find(x => x?.profile_action_type === "BLOCK");
50
+ const p2 = aBlock?.client_handler?.profile_action?.profile_owner;
51
+ if (p2) {
52
+ gender = p2.gender || gender;
53
+ shortName = p2.short_name || shortName;
54
+ }
55
+ }
56
+ return { friendshipStatus, gender, shortName };
57
+ }
58
+
59
+ function normalizeV2User(u) {
60
+ if (!u) return null;
61
+ const vanity = usernameFromUrl(u.profile_url || u.url);
62
+ const meta = pickMeta(u);
63
+ return {
64
+ id: u.id || null,
65
+ name: u.name || null,
66
+ firstName: meta.shortName || null,
67
+ vanity: vanity || u.username_for_profile || null,
68
+ thumbSrc: u.profile_picture?.uri || null,
69
+ profileUrl: u.profile_url || u.url || null,
70
+ gender: meta.gender || null,
71
+ type: "User",
72
+ isFriend: meta.friendshipStatus === "ARE_FRIENDS",
73
+ isMessengerUser: null,
74
+ isMessageBlockedByViewer: false,
75
+ workInfo: null,
76
+ messengerStatus: null
77
+ };
78
+ }
79
+
80
+ function normalizePrimaryActor(a) {
81
+ if (!a) return null;
82
+ return {
83
+ id: a.id || null,
84
+ name: a.name || null,
85
+ firstName: a.short_name || null,
86
+ vanity: a.username || null,
87
+ thumbSrc: a.big_image_src?.uri || null,
88
+ profileUrl: a.url || null,
89
+ gender: a.gender || null,
90
+ type: a.__typename || null,
91
+ isFriend: !!a.is_viewer_friend,
92
+ isMessengerUser: !!a.is_messenger_user,
93
+ isMessageBlockedByViewer: !!a.is_message_blocked_by_viewer,
94
+ workInfo: a.work_info || null,
95
+ messengerStatus: a.messenger_account_status_category || null
96
+ };
97
+ }
98
+
99
+ function mergeUserEntry(a, b) {
100
+ if (!a && !b) return null;
101
+ const x = a || {};
102
+ const y = b || {};
103
+ return {
104
+ id: x.id || y.id || null,
105
+ name: x.name || y.name || null,
106
+ firstName: x.firstName || y.firstName || null,
107
+ vanity: x.vanity || y.vanity || null,
108
+ thumbSrc: x.thumbSrc || y.thumbSrc || null,
109
+ profileUrl: x.profileUrl || y.profileUrl || null,
110
+ gender: x.gender || y.gender || null,
111
+ type: x.type || y.type || null,
112
+ isFriend: typeof x.isFriend === "boolean" ? x.isFriend : (typeof y.isFriend === "boolean" ? y.isFriend : false),
113
+ isMessengerUser: typeof x.isMessengerUser === "boolean" ? x.isMessengerUser : (typeof y.isMessengerUser === "boolean" ? y.isMessengerUser : null),
114
+ isMessageBlockedByViewer: typeof x.isMessageBlockedByViewer === "boolean" ? x.isMessageBlockedByViewer : (typeof y.isMessageBlockedByViewer === "boolean" ? y.isMessageBlockedByViewer : false),
115
+ workInfo: x.workInfo || y.workInfo || null,
116
+ messengerStatus: x.messengerStatus || y.messengerStatus || null
117
+ };
118
+ }
119
+
120
+ const queue = [];
121
+ let isProcessingQueue = false;
122
+ const processingUsers = new Set();
123
+ const queuedUsers = new Set();
124
+ const cooldown = new Map();
125
+
126
+ module.exports = function (defaultFuncs, api, ctx) {
127
+ const dbFiles = fs.readdirSync(path.join(__dirname, "../../database")).filter(f => path.extname(f) === ".js").reduce((acc, file) => {
128
+ acc[path.basename(file, ".js")] = require(path.join(__dirname, "../../database", file))(api);
129
+ return acc;
130
+ }, {});
131
+ const { userData } = dbFiles;
132
+ const { create, get, update, getAll } = userData;
133
+
134
+ async function fetchPrimary(ids) {
135
+ const form = {
136
+ queries: JSON.stringify({
137
+ o0: {
138
+ doc_id: DOC_PRIMARY,
139
+ query_params: { ids }
140
+ }
141
+ }),
142
+ batch_name: BATCH_PRIMARY
143
+ };
144
+ const resData = await defaultFuncs.post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form).then(parseAndCheckLogin(ctx, defaultFuncs));
145
+ if (!resData || resData.length === 0) throw new Error("Empty response");
146
+ const first = resData[0];
147
+ if (!first || !first.o0) throw new Error("Invalid batch payload");
148
+ if (first.o0.errors && first.o0.errors.length) throw new Error(first.o0.errors[0].message || "GraphQL error");
149
+ const result = first.o0.data;
150
+ if (!result || !Array.isArray(result.messaging_actors)) return {};
151
+ const out = {};
152
+ for (const actor of result.messaging_actors) {
153
+ const n = normalizePrimaryActor(actor);
154
+ if (n?.id) out[n.id] = n;
155
+ }
156
+ return out;
157
+ }
158
+
159
+ async function fetchV2One(uid) {
160
+ const av = String(ctx?.userID || "");
161
+ const variablesObj = {
162
+ actionBarRenderLocation: "WWW_COMET_HOVERCARD",
163
+ context: "DEFAULT",
164
+ entityID: String(uid),
165
+ scale: 1,
166
+ __relay_internal__pv__WorkCometIsEmployeeGKProviderrelayprovider: false
167
+ };
168
+ const form = {
169
+ av,
170
+ fb_api_caller_class: CALLER_V2,
171
+ fb_api_req_friendly_name: FRIENDLY_V2,
172
+ server_timestamps: true,
173
+ doc_id: DOC_V2,
174
+ variables: JSON.stringify(variablesObj)
175
+ };
176
+ const raw = await defaultFuncs.post("https://www.facebook.com/api/graphql/", null, form).then(parseAndCheckLogin(ctx, defaultFuncs));
177
+ const parsed = toJSONMaybe(raw) ?? raw;
178
+ const root = Array.isArray(parsed) ? parsed[0] : parsed;
179
+ const user = root?.data?.node?.comet_hovercard_renderer?.user || null;
180
+ const n = normalizeV2User(user);
181
+ return n && n.id ? { [n.id]: n } : {};
182
+ }
183
+
184
+ async function upsertUser(id, entry) {
185
+ try {
186
+ const existing = await get(id);
187
+ if (existing) {
188
+ await update(id, { data: entry });
189
+ } else {
190
+ await create(id, { data: entry });
191
+ }
192
+ } catch (e) {
193
+ console.warn(`user upsert ${id} error: ${e?.message || e}`);
194
+ }
195
+ }
196
+
197
+ async function fetchAndPersist(ids, creating = false) {
198
+ const result = {};
199
+ try {
200
+ const primary = await fetchPrimary(ids);
201
+ for (const id of ids) result[id] = primary[id] || null;
202
+ } catch (e) {
203
+ console.warn(`primary fetch error: ${e?.message || e}`);
204
+ }
205
+ if (creating) {
206
+ const needFallback = ids.filter(id => !result[id]);
207
+ if (needFallback.length) {
208
+ const tasks = needFallback.map(id => fetchV2One(id).catch(() => ({})));
209
+ const r = await Promise.allSettled(tasks);
210
+ for (let i = 0; i < needFallback.length; i++) {
211
+ const id = needFallback[i];
212
+ const ok = r[i].status === "fulfilled" ? r[i].value : {};
213
+ const n = ok[id] || null;
214
+ result[id] = n || null;
215
+ }
216
+ }
217
+ }
218
+ for (const id of ids) {
219
+ const merged = result[id] || null;
220
+ if (merged) await upsertUser(id, merged);
221
+ }
222
+ return result;
223
+ }
224
+
225
+ async function refreshAUser(id) {
226
+ try {
227
+ const out = await fetchAndPersist([id], false);
228
+ if (!out[id]) cooldown.set(id, Date.now() + 5 * 60 * 1000);
229
+ } catch (e) {
230
+ cooldown.set(id, Date.now() + 5 * 60 * 1000);
231
+ console.warn(`refresh user ${id} error: ${e?.message || e}`);
232
+ } finally {
233
+ queuedUsers.delete(id);
234
+ }
235
+ }
236
+
237
+ async function checkAndUpdateUsers() {
238
+ try {
239
+ const all = await getAll("userID");
240
+ const now = Date.now();
241
+ for (const row of all) {
242
+ const id = row.userID;
243
+ const cd = cooldown.get(id);
244
+ if (cd && now < cd) continue;
245
+ const lastUpdated = new Date(row.updatedAt).getTime();
246
+ if ((now - lastUpdated) / (1000 * 60) > 10 && !queuedUsers.has(id)) {
247
+ queuedUsers.add(id);
248
+ queue.push(() => refreshAUser(id));
249
+ }
250
+ }
251
+ } catch (e) {
252
+ console.error(`checkAndUpdateUsers error: ${e?.message || e}`);
253
+ }
254
+ }
255
+
256
+ async function processQueue() {
257
+ if (isProcessingQueue) return;
258
+ isProcessingQueue = true;
259
+ while (queue.length > 0) {
260
+ const task = queue.shift();
261
+ try {
262
+ await task();
263
+ } catch (e) {
264
+ console.error(`user queue error: ${e?.message || e}`);
265
+ }
266
+ }
267
+ isProcessingQueue = false;
268
+ }
269
+
270
+ setInterval(() => {
271
+ checkAndUpdateUsers();
272
+ processQueue();
273
+ }, 10000);
274
+
275
+ return function getUserInfo(idsOrId, callback) {
276
+ let resolveFunc, rejectFunc;
277
+ const returnPromise = new Promise((resolve, reject) => { resolveFunc = resolve; rejectFunc = reject; });
278
+ if (typeof callback !== "function") {
279
+ callback = (err, data) => { if (err) return rejectFunc(err); resolveFunc(data); };
280
+ }
281
+ const ids = Array.isArray(idsOrId) ? idsOrId.map(v => String(v)) : [String(idsOrId)];
282
+ Promise.all(ids.map(id => get(id).catch(() => null))).then(async cachedRows => {
283
+ const ret = {};
284
+ const needCreate = [];
285
+ for (let i = 0; i < ids.length; i++) {
286
+ const id = ids[i];
287
+ const row = cachedRows[i];
288
+ if (row?.data && row.data.id) {
289
+ ret[id] = row.data;
290
+ } else {
291
+ needCreate.push(id);
292
+ }
293
+ }
294
+ if (needCreate.length) {
295
+ const fetched = await fetchAndPersist(needCreate, true);
296
+ for (const id of needCreate) ret[id] = fetched[id] || {
297
+ id,
298
+ name: null,
299
+ firstName: null,
300
+ vanity: null,
301
+ thumbSrc: null,
302
+ profileUrl: null,
303
+ gender: null,
304
+ type: null,
305
+ isFriend: false,
306
+ isMessengerUser: null,
307
+ isMessageBlockedByViewer: false,
308
+ workInfo: null,
309
+ messengerStatus: null
310
+ };
311
+ }
312
+ return callback(null, ret);
313
+ }).catch(err => {
314
+ log.error("getUserInfo", "Error: " + (err?.message || "Unknown"));
315
+ callback(err);
316
+ });
317
+ return returnPromise;
318
+ };
319
+ };
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+
3
+ const { parseAndCheckLogin } = require("../../utils/client.js");
4
+ const DEFAULT_DOC_ID = "24418640587785718";
5
+ const DEFAULT_FRIENDLY_NAME = "CometHovercardQueryRendererQuery";
6
+ const DEFAULT_CALLER_CLASS = "RelayModern";
7
+
8
+ function toJSONMaybe(s) {
9
+ if (!s) return null;
10
+ if (typeof s === "string") {
11
+ const t = s.trim().replace(/^for\s*\(\s*;\s*;\s*\)\s*;/, "");
12
+ try { return JSON.parse(t); } catch { return null; }
13
+ }
14
+ return s;
15
+ }
16
+
17
+ function usernameFromUrl(raw) {
18
+ if (!raw) return null;
19
+ try {
20
+ const u = new URL(raw);
21
+ if (/^www\.facebook\.com$/i.test(u.hostname)) {
22
+ const seg = u.pathname.replace(/^\//, "").replace(/\/$/, "");
23
+ if (seg && !/^profile\.php$/i.test(seg) && !seg.includes("/")) return seg;
24
+ }
25
+ } catch { }
26
+ return null;
27
+ }
28
+
29
+ function pickMeta(u) {
30
+ let friendshipStatus = null;
31
+ let gender = null;
32
+ let shortName = u?.short_name || null;
33
+ const pa = Array.isArray(u?.primaryActions) ? u.primaryActions : [];
34
+ const sa = Array.isArray(u?.secondaryActions) ? u.secondaryActions : [];
35
+ const aFriend = pa.find(x => x?.profile_action_type === "FRIEND");
36
+ if (aFriend?.client_handler?.profile_action?.restrictable_profile_owner) {
37
+ const p = aFriend.client_handler.profile_action.restrictable_profile_owner;
38
+ friendshipStatus = p?.friendship_status || null;
39
+ gender = p?.gender || gender;
40
+ shortName = p?.short_name || shortName;
41
+ }
42
+ if (!gender || !shortName) {
43
+ const aBlock = sa.find(x => x?.profile_action_type === "BLOCK");
44
+ const p2 = aBlock?.client_handler?.profile_action?.profile_owner;
45
+ if (p2) {
46
+ gender = p2.gender || gender;
47
+ shortName = p2.short_name || shortName;
48
+ }
49
+ }
50
+ return { friendshipStatus, gender, shortName };
51
+ }
52
+
53
+ function normalizeUser(u) {
54
+ if (!u) return null;
55
+ const vanity = usernameFromUrl(u.profile_url || u.url);
56
+ const meta = pickMeta(u);
57
+ return {
58
+ id: u.id || null,
59
+ name: u.name || null,
60
+ username: vanity || u.username_for_profile || null,
61
+ profileUrl: u.profile_url || u.url || null,
62
+ url: u.url || null,
63
+ isVerified: !!u.is_verified,
64
+ isMemorialized: !!u.is_visibly_memorialized,
65
+ avatar: u.profile_picture?.uri || null,
66
+ shortName: meta.shortName || null,
67
+ gender: meta.gender || null,
68
+ friendshipStatus: meta.friendshipStatus || null
69
+ };
70
+ }
71
+
72
+ function toRetObjEntry(nu) {
73
+ return {
74
+ name: nu?.name || null,
75
+ firstName: nu?.shortName || null,
76
+ vanity: nu?.username || null,
77
+ thumbSrc: nu?.avatar || null,
78
+ profileUrl: nu?.profileUrl || null,
79
+ gender: nu?.gender || null,
80
+ type: "User",
81
+ isFriend: nu?.friendshipStatus === "ARE_FRIENDS",
82
+ isMessengerUser: null,
83
+ isMessageBlockedByViewer: false,
84
+ workInfo: null,
85
+ messengerStatus: null
86
+ };
87
+ }
88
+
89
+ module.exports = function (defaultFuncs, api, ctx) {
90
+ async function fetchOne(uid) {
91
+ const av = String(ctx?.userID || "");
92
+ const variablesObj = {
93
+ actionBarRenderLocation: "WWW_COMET_HOVERCARD",
94
+ context: "DEFAULT",
95
+ entityID: String(uid),
96
+ scale: 1,
97
+ __relay_internal__pv__WorkCometIsEmployeeGKProviderrelayprovider: false
98
+ };
99
+ const form = {
100
+ av,
101
+ fb_api_caller_class: DEFAULT_CALLER_CLASS,
102
+ fb_api_req_friendly_name: DEFAULT_FRIENDLY_NAME,
103
+ server_timestamps: true,
104
+ doc_id: DEFAULT_DOC_ID,
105
+ variables: JSON.stringify(variablesObj)
106
+ };
107
+ const raw = await defaultFuncs.post("https://www.facebook.com/api/graphql/", null, form).then(parseAndCheckLogin(ctx, defaultFuncs));
108
+ const parsed = toJSONMaybe(raw) ?? raw;
109
+ const root = Array.isArray(parsed) ? parsed[0] : parsed;
110
+ const user = root?.data?.node?.comet_hovercard_renderer?.user || null;
111
+ return normalizeUser(user);
112
+ }
113
+
114
+ return function getUserInfoV2(idOrList, callback) {
115
+ let resolveFunc, rejectFunc;
116
+ const returnPromise = new Promise((resolve, reject) => { resolveFunc = resolve; rejectFunc = reject; });
117
+ if (typeof callback !== "function") {
118
+ callback = (err, data) => { if (err) return rejectFunc(err); resolveFunc(data); };
119
+ }
120
+ const ids = Array.isArray(idOrList) ? idOrList.map(v => String(v)) : [String(idOrList)];
121
+ Promise.allSettled(ids.map(fetchOne))
122
+ .then(results => {
123
+ const retObj = {};
124
+ for (let i = 0; i < ids.length; i++) {
125
+ const nu = results[i].status === "fulfilled" ? results[i].value : null;
126
+ retObj[ids[i]] = toRetObjEntry(nu);
127
+ }
128
+ return callback(null, retObj);
129
+ })
130
+ .catch(err => { console.error("getUserInfoV2" + err); callback(err); });
131
+ return returnPromise;
132
+ };
133
+ };
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+
3
+ function lsRequest(ctx, payload, options, callback) {
4
+ return new Promise((resolve, reject) => {
5
+ const cb = typeof options === "function" ? options : callback;
6
+ const opts = typeof options === "object" && options ? options : {};
7
+ if (!ctx || !ctx.mqttClient) {
8
+ const err = new Error("Not connected to MQTT");
9
+ if (cb) cb(err);
10
+ return reject(err);
11
+ }
12
+ if (typeof ctx.wsReqNumber !== "number") ctx.wsReqNumber = 0;
13
+ const reqID = typeof opts.request_id === "number" ? opts.request_id : ++ctx.wsReqNumber;
14
+ const timeoutMs = typeof opts.timeout === "number" ? opts.timeout : 20000;
15
+ const qos = typeof opts.qos === "number" ? opts.qos : 1;
16
+ const retain = !!opts.retain;
17
+ const reqTopic = "/ls_req";
18
+ const respTopic = opts.respTopic || "/ls_resp";
19
+ const form = JSON.stringify({
20
+ app_id: opts.app_id || "",
21
+ payload: typeof payload === "string" ? payload : JSON.stringify(payload),
22
+ request_id: reqID,
23
+ type: opts.type == null ? 3 : opts.type
24
+ });
25
+ let timer = null;
26
+ const handleRes = (topic, message) => {
27
+ if (topic !== respTopic) return;
28
+ let msg;
29
+ try {
30
+ msg = JSON.parse(message.toString());
31
+ } catch {
32
+ return;
33
+ }
34
+ if (msg.request_id !== reqID) return;
35
+ if (typeof opts.filter === "function" && !opts.filter(msg)) return;
36
+ ctx.mqttClient.removeListener("message", handleRes);
37
+ if (timer) clearTimeout(timer);
38
+ try {
39
+ msg.payload = typeof msg.payload === "string" ? JSON.parse(msg.payload) : msg.payload;
40
+ } catch { }
41
+ const out = { success: true, response: msg.payload, raw: msg };
42
+ if (cb) cb(null, out);
43
+ resolve(out);
44
+ };
45
+ ctx.mqttClient.on("message", handleRes);
46
+ timer = setTimeout(() => {
47
+ ctx.mqttClient.removeListener("message", handleRes);
48
+ const err = new Error("MQTT response timeout");
49
+ if (cb) cb(err);
50
+ reject(err);
51
+ }, timeoutMs);
52
+ ctx.mqttClient.publish(reqTopic, form, { qos, retain }, (err) => {
53
+ if (err) {
54
+ if (timer) clearTimeout(timer);
55
+ ctx.mqttClient.removeListener("message", handleRes);
56
+ if (cb) cb(err);
57
+ reject(err);
58
+ }
59
+ });
60
+ });
61
+ };
62
+
63
+ module.exports = sendReqMqtt;
@@ -0,0 +1,49 @@
1
+ const { Sequelize } = require("sequelize");
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+ const databasePath = path.join(process.cwd(), "Fca_Database");
5
+ if (!fs.existsSync(databasePath)) {
6
+ fs.mkdirSync(databasePath, { recursive: true });
7
+ }
8
+ const sequelize = new Sequelize({
9
+ dialect: "sqlite",
10
+ storage: path.join(databasePath, "database.sqlite"),
11
+ logging: false,
12
+ pool: {
13
+ max: 5,
14
+ min: 0,
15
+ acquire: 30000,
16
+ idle: 10000
17
+ },
18
+ retry: {
19
+ max: 3
20
+ },
21
+ dialectOptions: {
22
+ timeout: 5000
23
+ },
24
+ isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
25
+ });
26
+ const models = {};
27
+ fs.readdirSync(__dirname)
28
+ .filter(file => file.endsWith(".js") && file !== "index.js")
29
+ .forEach(file => {
30
+ const model = require(path.join(__dirname, file))(sequelize);
31
+ models[model.name] = model;
32
+ });
33
+ Object.keys(models).forEach(modelName => {
34
+ if (models[modelName].associate) {
35
+ models[modelName].associate(models);
36
+ }
37
+ });
38
+ models.sequelize = sequelize;
39
+ models.Sequelize = Sequelize;
40
+ models.syncAll = async () => {
41
+ try {
42
+ await sequelize.sync({ force: false });
43
+ } catch (error) {
44
+ console.error("Failed to synchronize models:", error);
45
+ throw error;
46
+ }
47
+ };
48
+
49
+ module.exports = models;
@@ -0,0 +1,31 @@
1
+ module.exports = function(sequelize) {
2
+ const { Model, DataTypes } = require("sequelize");
3
+
4
+ class Thread extends Model {}
5
+
6
+ Thread.init(
7
+ {
8
+ num: {
9
+ type: DataTypes.INTEGER,
10
+ allowNull: false,
11
+ autoIncrement: true,
12
+ primaryKey: true
13
+ },
14
+ threadID: {
15
+ type: DataTypes.STRING,
16
+ allowNull: false,
17
+ unique: true
18
+ },
19
+ data: {
20
+ type: DataTypes.JSONB,
21
+ allowNull: true
22
+ }
23
+ },
24
+ {
25
+ sequelize,
26
+ modelName: "Thread",
27
+ timestamps: true
28
+ }
29
+ );
30
+ return Thread;
31
+ };
@@ -0,0 +1,32 @@
1
+ module.exports = function (sequelize) {
2
+ const { Model, DataTypes } = require("sequelize");
3
+
4
+ class User extends Model { }
5
+
6
+ User.init(
7
+ {
8
+ num: {
9
+ type: DataTypes.INTEGER,
10
+ allowNull: false,
11
+ autoIncrement: true,
12
+ primaryKey: true
13
+ },
14
+ userID: {
15
+ type: DataTypes.STRING,
16
+ allowNull: false,
17
+ unique: true
18
+ },
19
+ data: {
20
+ type: DataTypes.JSONB,
21
+ allowNull: true
22
+ }
23
+ },
24
+ {
25
+ sequelize,
26
+ modelName: "User",
27
+ timestamps: true
28
+ }
29
+ );
30
+
31
+ return User;
32
+ };