@cexy/hoonfca 1.0.6 → 2.0.1

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 (191) hide show
  1. package/LICENSE +3 -0
  2. package/examples/login-with-cookies.js +102 -0
  3. package/examples/verify.js +70 -0
  4. package/index.js +2 -8
  5. package/package.json +82 -61
  6. package/src/{api/action → apis}/addExternalModule.js +24 -25
  7. package/src/apis/addUserToGroup.js +108 -0
  8. package/src/apis/changeAdminStatus.js +148 -0
  9. package/src/apis/changeArchivedStatus.js +61 -0
  10. package/src/apis/changeAvatar.js +103 -0
  11. package/src/apis/changeBio.js +69 -0
  12. package/src/apis/changeBlockedStatus.js +54 -0
  13. package/src/apis/changeGroupImage.js +136 -0
  14. package/src/apis/changeThreadColor.js +116 -0
  15. package/src/apis/changeThreadEmoji.js +53 -0
  16. package/src/apis/comment.js +207 -0
  17. package/src/apis/createAITheme.js +129 -0
  18. package/src/apis/createNewGroup.js +79 -0
  19. package/src/apis/createPoll.js +73 -0
  20. package/src/apis/deleteMessage.js +44 -0
  21. package/src/apis/deleteThread.js +52 -0
  22. package/src/apis/e2ee.js +17 -0
  23. package/src/apis/editMessage.js +70 -0
  24. package/src/apis/emoji.js +124 -0
  25. package/src/apis/fetchThemeData.js +82 -0
  26. package/src/apis/follow.js +81 -0
  27. package/src/apis/forwardMessage.js +52 -0
  28. package/src/apis/friend.js +243 -0
  29. package/src/apis/gcmember.js +122 -0
  30. package/src/apis/gcname.js +123 -0
  31. package/src/apis/gcrule.js +119 -0
  32. package/src/apis/getAccess.js +111 -0
  33. package/src/apis/getBotInfo.js +88 -0
  34. package/src/apis/getBotInitialData.js +43 -0
  35. package/src/apis/getFriendsList.js +79 -0
  36. package/src/apis/getMessage.js +423 -0
  37. package/src/apis/getTheme.js +95 -0
  38. package/src/apis/getThemeInfo.js +116 -0
  39. package/src/apis/getThreadHistory.js +239 -0
  40. package/src/apis/getThreadInfo.js +267 -0
  41. package/src/apis/getThreadList.js +232 -0
  42. package/src/apis/getThreadPictures.js +58 -0
  43. package/src/apis/getUserID.js +117 -0
  44. package/src/apis/getUserInfo.js +513 -0
  45. package/src/{api/users → apis}/getUserInfoV2.js +146 -134
  46. package/src/apis/handleMessageRequest.js +50 -0
  47. package/src/apis/httpGet.js +63 -0
  48. package/src/apis/httpPost.js +89 -0
  49. package/src/apis/httpPostFormData.js +69 -0
  50. package/src/apis/listenMqtt.js +1236 -0
  51. package/src/apis/listenSpeed.js +179 -0
  52. package/src/apis/logout.js +87 -0
  53. package/src/apis/markAsDelivered.js +47 -0
  54. package/src/{api/messaging → apis}/markAsRead.js +99 -88
  55. package/src/apis/markAsReadAll.js +40 -0
  56. package/src/apis/markAsSeen.js +70 -0
  57. package/src/apis/mqttDeltaValue.js +278 -0
  58. package/src/apis/muteThread.js +45 -0
  59. package/src/apis/nickname.js +132 -0
  60. package/src/apis/notes.js +163 -0
  61. package/src/apis/pinMessage.js +150 -0
  62. package/src/apis/produceMetaTheme.js +180 -0
  63. package/src/apis/realtime.js +182 -0
  64. package/src/apis/removeUserFromGroup.js +117 -0
  65. package/src/apis/resolvePhotoUrl.js +58 -0
  66. package/src/apis/searchForThread.js +154 -0
  67. package/src/apis/sendMessage.js +354 -0
  68. package/src/apis/sendMessageMqtt.js +249 -0
  69. package/src/apis/sendTypingIndicator.js +91 -0
  70. package/src/apis/setMessageReaction.js +27 -0
  71. package/src/apis/setMessageReactionMqtt.js +61 -0
  72. package/src/apis/setThreadTheme.js +260 -0
  73. package/src/apis/setThreadThemeMqtt.js +94 -0
  74. package/src/apis/share.js +107 -0
  75. package/src/apis/shareContact.js +66 -0
  76. package/src/apis/stickers.js +257 -0
  77. package/src/apis/story.js +181 -0
  78. package/src/apis/theme.js +233 -0
  79. package/src/apis/unfriend.js +47 -0
  80. package/src/apis/unsendMessage.js +17 -0
  81. package/src/engine/client.js +92 -0
  82. package/src/engine/models/buildAPI.js +152 -0
  83. package/src/engine/models/loginHelper.js +519 -0
  84. package/src/engine/models/setOptions.js +88 -0
  85. package/src/security/e2ee.js +109 -0
  86. package/src/types/index.d.ts +498 -0
  87. package/src/utils/antiSuspension.js +506 -0
  88. package/src/utils/auth-helpers.js +149 -0
  89. package/src/utils/autoReLogin.js +336 -0
  90. package/src/utils/axios.js +436 -0
  91. package/src/utils/cache.js +54 -0
  92. package/src/utils/clients.js +282 -0
  93. package/src/utils/constants.js +410 -23
  94. package/src/utils/formatters/data/formatAttachment.js +370 -0
  95. package/src/utils/formatters/data/formatDelta.js +109 -0
  96. package/src/utils/formatters/index.js +159 -0
  97. package/src/utils/formatters/value/formatCookie.js +91 -0
  98. package/src/utils/formatters/value/formatDate.js +36 -0
  99. package/src/utils/formatters/value/formatID.js +16 -0
  100. package/src/utils/formatters.js +1373 -0
  101. package/src/utils/headers.js +214 -99
  102. package/src/utils/index.js +153 -0
  103. package/src/utils/monitoring.js +333 -0
  104. package/src/utils/rateLimiter.js +319 -0
  105. package/src/utils/tokenRefresh.js +657 -0
  106. package/src/utils/user-agents.js +238 -0
  107. package/src/utils/validation.js +157 -0
  108. package/CHANGELOG.md +0 -181
  109. package/DOCS.md +0 -2636
  110. package/LICENSE-MIT +0 -21
  111. package/README.md +0 -632
  112. package/func/checkUpdate.js +0 -231
  113. package/func/logger.js +0 -48
  114. package/index.d.ts +0 -746
  115. package/module/config.js +0 -67
  116. package/module/login.js +0 -154
  117. package/module/loginHelper.js +0 -1034
  118. package/module/options.js +0 -54
  119. package/src/api/action/changeAvatar.js +0 -137
  120. package/src/api/action/changeBio.js +0 -75
  121. package/src/api/action/enableAutoSaveAppState.js +0 -73
  122. package/src/api/action/getCurrentUserID.js +0 -7
  123. package/src/api/action/handleFriendRequest.js +0 -57
  124. package/src/api/action/logout.js +0 -76
  125. package/src/api/action/refreshFb_dtsg.js +0 -48
  126. package/src/api/action/setPostReaction.js +0 -106
  127. package/src/api/action/unfriend.js +0 -54
  128. package/src/api/http/httpGet.js +0 -46
  129. package/src/api/http/httpPost.js +0 -52
  130. package/src/api/http/postFormData.js +0 -47
  131. package/src/api/messaging/addUserToGroup.js +0 -68
  132. package/src/api/messaging/changeAdminStatus.js +0 -122
  133. package/src/api/messaging/changeArchivedStatus.js +0 -55
  134. package/src/api/messaging/changeBlockedStatus.js +0 -48
  135. package/src/api/messaging/changeGroupImage.js +0 -90
  136. package/src/api/messaging/changeNickname.js +0 -70
  137. package/src/api/messaging/changeThreadColor.js +0 -79
  138. package/src/api/messaging/changeThreadEmoji.js +0 -106
  139. package/src/api/messaging/createNewGroup.js +0 -88
  140. package/src/api/messaging/createPoll.js +0 -43
  141. package/src/api/messaging/createThemeAI.js +0 -98
  142. package/src/api/messaging/deleteMessage.js +0 -56
  143. package/src/api/messaging/deleteThread.js +0 -56
  144. package/src/api/messaging/editMessage.js +0 -68
  145. package/src/api/messaging/forwardAttachment.js +0 -51
  146. package/src/api/messaging/getEmojiUrl.js +0 -29
  147. package/src/api/messaging/getFriendsList.js +0 -82
  148. package/src/api/messaging/getMessage.js +0 -829
  149. package/src/api/messaging/getThemePictures.js +0 -62
  150. package/src/api/messaging/handleMessageRequest.js +0 -65
  151. package/src/api/messaging/markAsDelivered.js +0 -57
  152. package/src/api/messaging/markAsReadAll.js +0 -49
  153. package/src/api/messaging/markAsSeen.js +0 -61
  154. package/src/api/messaging/muteThread.js +0 -50
  155. package/src/api/messaging/removeUserFromGroup.js +0 -106
  156. package/src/api/messaging/resolvePhotoUrl.js +0 -43
  157. package/src/api/messaging/scheduler.js +0 -264
  158. package/src/api/messaging/searchForThread.js +0 -52
  159. package/src/api/messaging/sendMessage.js +0 -272
  160. package/src/api/messaging/sendTypingIndicator.js +0 -67
  161. package/src/api/messaging/setMessageReaction.js +0 -76
  162. package/src/api/messaging/setTitle.js +0 -119
  163. package/src/api/messaging/shareContact.js +0 -49
  164. package/src/api/messaging/threadColors.js +0 -128
  165. package/src/api/messaging/unsendMessage.js +0 -81
  166. package/src/api/messaging/uploadAttachment.js +0 -94
  167. package/src/api/socket/core/connectMqtt.js +0 -255
  168. package/src/api/socket/core/emitAuth.js +0 -106
  169. package/src/api/socket/core/getSeqID.js +0 -40
  170. package/src/api/socket/core/getTaskResponseData.js +0 -22
  171. package/src/api/socket/core/markDelivery.js +0 -12
  172. package/src/api/socket/core/parseDelta.js +0 -391
  173. package/src/api/socket/detail/buildStream.js +0 -208
  174. package/src/api/socket/detail/constants.js +0 -24
  175. package/src/api/socket/listenMqtt.js +0 -364
  176. package/src/api/socket/middleware/index.js +0 -216
  177. package/src/api/threads/getThreadHistory.js +0 -664
  178. package/src/api/threads/getThreadInfo.js +0 -438
  179. package/src/api/threads/getThreadList.js +0 -293
  180. package/src/api/threads/getThreadPictures.js +0 -78
  181. package/src/api/users/getUserID.js +0 -65
  182. package/src/api/users/getUserInfo.js +0 -327
  183. package/src/core/sendReqMqtt.js +0 -96
  184. package/src/database/models/index.js +0 -87
  185. package/src/database/models/thread.js +0 -45
  186. package/src/database/models/user.js +0 -46
  187. package/src/database/threadData.js +0 -98
  188. package/src/database/userData.js +0 -89
  189. package/src/utils/client.js +0 -320
  190. package/src/utils/format.js +0 -1115
  191. package/src/utils/request.js +0 -305
@@ -1,327 +0,0 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const log = require("npmlog");
6
- const logger = require("../../../func/logger");
7
- const { parseAndCheckLogin } = require("../../utils/client.js");
8
-
9
- const DOC_PRIMARY = "5009315269112105";
10
- const BATCH_PRIMARY = "MessengerParticipantsFetcher";
11
- const DOC_V2 = "24418640587785718";
12
- const FRIENDLY_V2 = "CometHovercardQueryRendererQuery";
13
- const CALLER_V2 = "RelayModern";
14
-
15
- function toJSONMaybe(s) {
16
- if (!s) return null;
17
- if (typeof s === "string") {
18
- const t = s.trim().replace(/^for\s*\(\s*;\s*;\s*\)\s*;/, "");
19
- try { return JSON.parse(t); } catch { return null; }
20
- }
21
- return s;
22
- }
23
-
24
- function usernameFromUrl(raw) {
25
- if (!raw) return null;
26
- try {
27
- const u = new URL(raw);
28
- if (/^www\.facebook\.com$/i.test(u.hostname)) {
29
- const seg = u.pathname.replace(/^\//, "").replace(/\/$/, "");
30
- if (seg && !/^profile\.php$/i.test(seg) && !seg.includes("/")) return seg;
31
- }
32
- } catch { }
33
- return null;
34
- }
35
-
36
- function pickMeta(u) {
37
- let friendshipStatus = null;
38
- let gender = null;
39
- let shortName = u?.short_name || null;
40
- const pa = Array.isArray(u?.primaryActions) ? u.primaryActions : [];
41
- const sa = Array.isArray(u?.secondaryActions) ? u.secondaryActions : [];
42
- const aFriend = pa.find(x => x?.profile_action_type === "FRIEND");
43
- if (aFriend?.client_handler?.profile_action?.restrictable_profile_owner) {
44
- const p = aFriend.client_handler.profile_action.restrictable_profile_owner;
45
- friendshipStatus = p?.friendship_status || null;
46
- gender = p?.gender || gender;
47
- shortName = p?.short_name || shortName;
48
- }
49
- if (!gender || !shortName) {
50
- const aBlock = sa.find(x => x?.profile_action_type === "BLOCK");
51
- const p2 = aBlock?.client_handler?.profile_action?.profile_owner;
52
- if (p2) {
53
- gender = p2.gender || gender;
54
- shortName = p2.short_name || shortName;
55
- }
56
- }
57
- return { friendshipStatus, gender, shortName };
58
- }
59
-
60
- function normalizeV2User(u) {
61
- if (!u) return null;
62
- const vanity = usernameFromUrl(u.profile_url || u.url);
63
- const meta = pickMeta(u);
64
- return {
65
- id: u.id || null,
66
- name: u.name || null,
67
- firstName: meta.shortName || null,
68
- vanity: vanity || u.username_for_profile || null,
69
- thumbSrc: u.profile_picture?.uri || null,
70
- profileUrl: u.profile_url || u.url || null,
71
- gender: meta.gender || null,
72
- type: "User",
73
- isFriend: meta.friendshipStatus === "ARE_FRIENDS",
74
- isMessengerUser: null,
75
- isMessageBlockedByViewer: false,
76
- workInfo: null,
77
- messengerStatus: null
78
- };
79
- }
80
-
81
- function normalizePrimaryActor(a) {
82
- if (!a) return null;
83
- return {
84
- id: a.id || null,
85
- name: a.name || null,
86
- firstName: a.short_name || null,
87
- vanity: a.username || null,
88
- thumbSrc: a.big_image_src?.uri || null,
89
- profileUrl: a.url || null,
90
- gender: a.gender || null,
91
- type: a.__typename || null,
92
- isFriend: !!a.is_viewer_friend,
93
- isMessengerUser: !!a.is_messenger_user,
94
- isMessageBlockedByViewer: !!a.is_message_blocked_by_viewer,
95
- workInfo: a.work_info || null,
96
- messengerStatus: a.messenger_account_status_category || null
97
- };
98
- }
99
-
100
- function mergeUserEntry(a, b) {
101
- if (!a && !b) return null;
102
- const x = a || {};
103
- const y = b || {};
104
- return {
105
- id: x.id || y.id || null,
106
- name: x.name || y.name || null,
107
- firstName: x.firstName || y.firstName || null,
108
- vanity: x.vanity || y.vanity || null,
109
- thumbSrc: x.thumbSrc || y.thumbSrc || null,
110
- profileUrl: x.profileUrl || y.profileUrl || null,
111
- gender: x.gender || y.gender || null,
112
- type: x.type || y.type || null,
113
- isFriend: typeof x.isFriend === "boolean" ? x.isFriend : (typeof y.isFriend === "boolean" ? y.isFriend : false),
114
- isMessengerUser: typeof x.isMessengerUser === "boolean" ? x.isMessengerUser : (typeof y.isMessengerUser === "boolean" ? y.isMessengerUser : null),
115
- isMessageBlockedByViewer: typeof x.isMessageBlockedByViewer === "boolean" ? x.isMessageBlockedByViewer : (typeof y.isMessageBlockedByViewer === "boolean" ? y.isMessageBlockedByViewer : false),
116
- workInfo: x.workInfo || y.workInfo || null,
117
- messengerStatus: x.messengerStatus || y.messengerStatus || null
118
- };
119
- }
120
-
121
- const queue = [];
122
- let isProcessingQueue = false;
123
- const processingUsers = new Set();
124
- const queuedUsers = new Set();
125
- const cooldown = new Map();
126
-
127
- module.exports = function (defaultFuncs, api, ctx) {
128
- const dbFiles = fs.readdirSync(path.join(__dirname, "../../database")).filter(f => path.extname(f) === ".js").reduce((acc, file) => {
129
- acc[path.basename(file, ".js")] = require(path.join(__dirname, "../../database", file))(api);
130
- return acc;
131
- }, {});
132
- const { userData } = dbFiles;
133
- const { create, get, update, getAll } = userData;
134
-
135
- async function fetchPrimary(ids) {
136
- const form = {
137
- queries: JSON.stringify({
138
- o0: {
139
- doc_id: DOC_PRIMARY,
140
- query_params: { ids }
141
- }
142
- }),
143
- batch_name: BATCH_PRIMARY
144
- };
145
- const resData = await defaultFuncs.post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form).then(parseAndCheckLogin(ctx, defaultFuncs));
146
- if (!resData || resData.length === 0) throw new Error("Empty response");
147
- const first = resData[0];
148
- if (!first || !first.o0) throw new Error("Invalid batch payload");
149
- if (first.o0.errors && first.o0.errors.length) throw new Error(first.o0.errors[0].message || "GraphQL error");
150
- const result = first.o0.data;
151
- if (!result || !Array.isArray(result.messaging_actors)) return {};
152
- const out = {};
153
- for (const actor of result.messaging_actors) {
154
- const n = normalizePrimaryActor(actor);
155
- if (n?.id) out[n.id] = n;
156
- }
157
- return out;
158
- }
159
-
160
- async function fetchV2One(uid) {
161
- const av = String(ctx?.userID || "");
162
- const variablesObj = {
163
- actionBarRenderLocation: "WWW_COMET_HOVERCARD",
164
- context: "DEFAULT",
165
- entityID: String(uid),
166
- scale: 1,
167
- __relay_internal__pv__WorkCometIsEmployeeGKProviderrelayprovider: false
168
- };
169
- const form = {
170
- av,
171
- fb_api_caller_class: CALLER_V2,
172
- fb_api_req_friendly_name: FRIENDLY_V2,
173
- server_timestamps: true,
174
- doc_id: DOC_V2,
175
- variables: JSON.stringify(variablesObj)
176
- };
177
- const raw = await defaultFuncs.post("https://www.facebook.com/api/graphql/", null, form).then(parseAndCheckLogin(ctx, defaultFuncs));
178
- const parsed = toJSONMaybe(raw) ?? raw;
179
- const root = Array.isArray(parsed) ? parsed[0] : parsed;
180
- const user = root?.data?.node?.comet_hovercard_renderer?.user || null;
181
- const n = normalizeV2User(user);
182
- return n && n.id ? { [n.id]: n } : {};
183
- }
184
-
185
- async function upsertUser(id, entry) {
186
- try {
187
- const existing = await get(id);
188
- if (existing) {
189
- await update(id, { data: entry });
190
- } else {
191
- await create(id, { data: entry });
192
- }
193
- } catch (e) {
194
- logger(`user upsert ${id} error: ${e?.message || e}`, "warn");
195
- }
196
- }
197
-
198
- async function fetchAndPersist(ids, creating = false) {
199
- const result = {};
200
- try {
201
- const primary = await fetchPrimary(ids);
202
- for (const id of ids) result[id] = primary[id] || null;
203
- } catch (e) {
204
- logger(`primary fetch error: ${e?.message || e}`, "warn");
205
- }
206
- if (creating) {
207
- const needFallback = ids.filter(id => !result[id]);
208
- if (needFallback.length) {
209
- const tasks = needFallback.map(id => fetchV2One(id).catch(() => ({})));
210
- const r = await Promise.allSettled(tasks);
211
- for (let i = 0; i < needFallback.length; i++) {
212
- const id = needFallback[i];
213
- const ok = r[i].status === "fulfilled" ? r[i].value : {};
214
- const n = ok[id] || null;
215
- result[id] = n || null;
216
- }
217
- }
218
- }
219
- for (const id of ids) {
220
- const merged = result[id] || null;
221
- if (merged) await upsertUser(id, merged);
222
- }
223
- return result;
224
- }
225
-
226
- async function refreshAUser(id) {
227
- try {
228
- const out = await fetchAndPersist([id], false);
229
- if (!out[id]) cooldown.set(id, Date.now() + 5 * 60 * 1000);
230
- } catch (e) {
231
- cooldown.set(id, Date.now() + 5 * 60 * 1000);
232
- logger(`refresh user ${id} error: ${e?.message || e}`, "warn");
233
- } finally {
234
- queuedUsers.delete(id);
235
- }
236
- }
237
-
238
- async function checkAndUpdateUsers() {
239
- try {
240
- const all = await getAll("userID");
241
- const now = Date.now();
242
- for (const row of all) {
243
- const id = row.userID;
244
- const cd = cooldown.get(id);
245
- if (cd && now < cd) continue;
246
- const lastUpdated = new Date(row.updatedAt).getTime();
247
- if ((now - lastUpdated) / (1000 * 60) > 10 && !queuedUsers.has(id)) {
248
- queuedUsers.add(id);
249
- queue.push(() => refreshAUser(id));
250
- }
251
- }
252
- } catch (e) {
253
- logger(`checkAndUpdateUsers error: ${e?.message || e}`, "error");
254
- }
255
- }
256
-
257
- async function processQueue() {
258
- if (isProcessingQueue) return;
259
- isProcessingQueue = true;
260
- while (queue.length > 0) {
261
- const task = queue.shift();
262
- try {
263
- await task();
264
- } catch (e) {
265
- logger(`user queue error: ${e?.message || e}`, "error");
266
- }
267
- }
268
- isProcessingQueue = false;
269
- }
270
-
271
- // Store interval reference for cleanup
272
- const updateInterval = setInterval(() => {
273
- checkAndUpdateUsers();
274
- processQueue();
275
- }, 10000);
276
-
277
- // Store interval in ctx for cleanup on logout/stop
278
- if (!ctx._userInfoIntervals) {
279
- ctx._userInfoIntervals = [];
280
- }
281
- ctx._userInfoIntervals.push(updateInterval);
282
-
283
- return function getUserInfo(idsOrId, callback) {
284
- let resolveFunc, rejectFunc;
285
- const returnPromise = new Promise((resolve, reject) => { resolveFunc = resolve; rejectFunc = reject; });
286
- if (typeof callback !== "function") {
287
- callback = (err, data) => { if (err) return rejectFunc(err); resolveFunc(data); };
288
- }
289
- const ids = Array.isArray(idsOrId) ? idsOrId.map(v => String(v)) : [String(idsOrId)];
290
- Promise.all(ids.map(id => get(id).catch(() => null))).then(async cachedRows => {
291
- const ret = {};
292
- const needCreate = [];
293
- for (let i = 0; i < ids.length; i++) {
294
- const id = ids[i];
295
- const row = cachedRows[i];
296
- if (row?.data && row.data.id) {
297
- ret[id] = row.data;
298
- } else {
299
- needCreate.push(id);
300
- }
301
- }
302
- if (needCreate.length) {
303
- const fetched = await fetchAndPersist(needCreate, true);
304
- for (const id of needCreate) ret[id] = fetched[id] || {
305
- id,
306
- name: null,
307
- firstName: null,
308
- vanity: null,
309
- thumbSrc: null,
310
- profileUrl: null,
311
- gender: null,
312
- type: null,
313
- isFriend: false,
314
- isMessengerUser: null,
315
- isMessageBlockedByViewer: false,
316
- workInfo: null,
317
- messengerStatus: null
318
- };
319
- }
320
- return callback(null, ret);
321
- }).catch(err => {
322
- log.error("getUserInfo", "Error: " + (err?.message || "Unknown"));
323
- callback(err);
324
- });
325
- return returnPromise;
326
- };
327
- };
@@ -1,96 +0,0 @@
1
- "use strict";
2
-
3
- function sendReqMqtt(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
- let cleaned = false;
27
-
28
- // Cleanup function to ensure listeners and timers are always removed
29
- const cleanup = () => {
30
- if (cleaned) return;
31
- cleaned = true;
32
- try {
33
- if (timer) {
34
- clearTimeout(timer);
35
- timer = null;
36
- }
37
- if (ctx.mqttClient && typeof ctx.mqttClient.removeListener === "function") {
38
- ctx.mqttClient.removeListener("message", handleRes);
39
- }
40
- } catch (err) {
41
- // Ignore cleanup errors
42
- }
43
- };
44
-
45
- const handleRes = (topic, message) => {
46
- if (topic !== respTopic) return;
47
- let msg;
48
- try {
49
- msg = JSON.parse(message.toString());
50
- } catch {
51
- return;
52
- }
53
- if (msg.request_id !== reqID) return;
54
- if (typeof opts.filter === "function" && !opts.filter(msg)) return;
55
- cleanup();
56
- try {
57
- msg.payload = typeof msg.payload === "string" ? JSON.parse(msg.payload) : msg.payload;
58
- } catch { }
59
- const out = { success: true, response: msg.payload, raw: msg };
60
- if (cb) cb(null, out);
61
- resolve(out);
62
- };
63
-
64
- try {
65
- ctx.mqttClient.on("message", handleRes);
66
- } catch (err) {
67
- cleanup();
68
- const error = new Error("Failed to attach message listener");
69
- if (cb) cb(error);
70
- return reject(error);
71
- }
72
-
73
- timer = setTimeout(() => {
74
- cleanup();
75
- const err = new Error("MQTT response timeout");
76
- if (cb) cb(err);
77
- reject(err);
78
- }, timeoutMs);
79
-
80
- try {
81
- ctx.mqttClient.publish(reqTopic, form, { qos, retain }, (err) => {
82
- if (err) {
83
- cleanup();
84
- if (cb) cb(err);
85
- reject(err);
86
- }
87
- });
88
- } catch (err) {
89
- cleanup();
90
- if (cb) cb(err);
91
- reject(err);
92
- }
93
- });
94
- }
95
-
96
- module.exports = sendReqMqtt;
@@ -1,87 +0,0 @@
1
- const { Sequelize } = require("sequelize");
2
- const fs = require("fs");
3
- const path = require("path");
4
-
5
- let sequelize = null;
6
- let models = {};
7
-
8
- try {
9
- const databasePath = path.join(process.cwd(), "Fca_Database");
10
- if (!fs.existsSync(databasePath)) {
11
- fs.mkdirSync(databasePath, { recursive: true });
12
- }
13
-
14
- sequelize = new Sequelize({
15
- dialect: "sqlite",
16
- storage: path.join(databasePath, "database.sqlite"),
17
- logging: false,
18
- pool: {
19
- max: 5,
20
- min: 0,
21
- acquire: 30000,
22
- idle: 10000
23
- },
24
- retry: {
25
- max: 3
26
- },
27
- dialectOptions: {
28
- timeout: 5000
29
- },
30
- isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
31
- });
32
-
33
- // Load models with error handling
34
- try {
35
- const modelFiles = fs.readdirSync(__dirname)
36
- .filter(file => file.endsWith(".js") && file !== "index.js");
37
-
38
- for (const file of modelFiles) {
39
- try {
40
- const model = require(path.join(__dirname, file))(sequelize);
41
- if (model && model.name) {
42
- models[model.name] = model;
43
- }
44
- } catch (modelError) {
45
- // Log but continue loading other models
46
- console.error(`Failed to load model ${file}:`, modelError && modelError.message ? modelError.message : String(modelError));
47
- }
48
- }
49
-
50
- // Associate models
51
- Object.keys(models).forEach(modelName => {
52
- try {
53
- if (models[modelName].associate) {
54
- models[modelName].associate(models);
55
- }
56
- } catch (assocError) {
57
- console.error(`Failed to associate model ${modelName}:`, assocError && assocError.message ? assocError.message : String(assocError));
58
- }
59
- });
60
- } catch (loadError) {
61
- console.error("Failed to load models:", loadError && loadError.message ? loadError.message : String(loadError));
62
- }
63
-
64
- models.sequelize = sequelize;
65
- models.Sequelize = Sequelize;
66
- models.syncAll = async () => {
67
- try {
68
- if (!sequelize) {
69
- throw new Error("Sequelize instance not initialized");
70
- }
71
- await sequelize.sync({ force: false });
72
- } catch (error) {
73
- console.error("Failed to synchronize models:", error && error.message ? error.message : String(error));
74
- throw error;
75
- }
76
- };
77
- } catch (initError) {
78
- // If initialization fails completely, still export a valid structure
79
- console.error("Database initialization error:", initError && initError.message ? initError.message : String(initError));
80
- models.sequelize = null;
81
- models.Sequelize = Sequelize;
82
- models.syncAll = async () => {
83
- throw new Error("Database not initialized");
84
- };
85
- }
86
-
87
- module.exports = models;
@@ -1,45 +0,0 @@
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.TEXT,
21
- allowNull: true,
22
- get() {
23
- const value = this.getDataValue('data');
24
- if (typeof value === 'string') {
25
- try {
26
- return JSON.parse(value);
27
- } catch {
28
- return value;
29
- }
30
- }
31
- return value;
32
- },
33
- set(value) {
34
- this.setDataValue('data', typeof value === 'string' ? value : JSON.stringify(value));
35
- }
36
- }
37
- },
38
- {
39
- sequelize,
40
- modelName: "Thread",
41
- timestamps: true
42
- }
43
- );
44
- return Thread;
45
- };
@@ -1,46 +0,0 @@
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.TEXT,
21
- allowNull: true,
22
- get() {
23
- const value = this.getDataValue('data');
24
- if (typeof value === 'string') {
25
- try {
26
- return JSON.parse(value);
27
- } catch {
28
- return value;
29
- }
30
- }
31
- return value;
32
- },
33
- set(value) {
34
- this.setDataValue('data', typeof value === 'string' ? value : JSON.stringify(value));
35
- }
36
- }
37
- },
38
- {
39
- sequelize,
40
- modelName: "User",
41
- timestamps: true
42
- }
43
- );
44
-
45
- return User;
46
- };
@@ -1,98 +0,0 @@
1
- const { Thread } = require("./models");
2
-
3
- const validateThreadID = threadID => {
4
- if (typeof threadID !== "string" && typeof threadID !== "number") {
5
- throw new Error("Invalid threadID: must be a string or number.");
6
- }
7
- return String(threadID);
8
- };
9
- const validateData = data => {
10
- if (!data || typeof data !== "object" || Array.isArray(data)) {
11
- throw new Error("Invalid data: must be a non-empty object.");
12
- }
13
- };
14
-
15
- module.exports = function(bot) {
16
- return {
17
- async create(threadID, data) {
18
- try {
19
- let thread = await Thread.findOne({ where: { threadID } });
20
- if (thread) {
21
- return { thread: thread.get(), created: false };
22
- }
23
- thread = await Thread.create({ threadID, ...data });
24
- return { thread: thread.get(), created: true };
25
- } catch (error) {
26
- throw new Error(`Failed to create thread: ${error.message}`);
27
- }
28
- },
29
-
30
- async get(threadID) {
31
- try {
32
- threadID = validateThreadID(threadID);
33
- const thread = await Thread.findOne({ where: { threadID } });
34
- return thread ? thread.get() : null;
35
- } catch (error) {
36
- throw new Error(`Failed to get thread: ${error.message}`);
37
- }
38
- },
39
-
40
- async update(threadID, data) {
41
- try {
42
- threadID = validateThreadID(threadID);
43
- validateData(data);
44
- const thread = await Thread.findOne({ where: { threadID } });
45
-
46
- if (thread) {
47
- await thread.update(data);
48
- return { thread: thread.get(), created: false };
49
- } else {
50
- const newThread = await Thread.create({ ...data, threadID });
51
- return { thread: newThread.get(), created: true };
52
- }
53
- } catch (error) {
54
- throw new Error(`Failed to update thread: ${error.message}`);
55
- }
56
- },
57
-
58
- async del(threadID) {
59
- try {
60
- if (!threadID) {
61
- throw new Error("threadID is required and cannot be undefined");
62
- }
63
- threadID = validateThreadID(threadID);
64
- if (!threadID) {
65
- throw new Error("Invalid threadID");
66
- }
67
- const result = await Thread.destroy({ where: { threadID } });
68
- if (result === 0) {
69
- throw new Error("No thread found with the specified threadID");
70
- }
71
- return result;
72
- } catch (error) {
73
- throw new Error(`Failed to delete thread: ${error.message}`);
74
- }
75
- },
76
- async delAll() {
77
- try {
78
- return await Thread.destroy({ where: {} });
79
- } catch (error) {
80
- throw new Error(`Failed to delete all threads: ${error.message}`);
81
- }
82
- },
83
- async getAll(keys = null) {
84
- try {
85
- const attributes =
86
- typeof keys === "string"
87
- ? [keys]
88
- : Array.isArray(keys)
89
- ? keys
90
- : undefined;
91
- const threads = await Thread.findAll({ attributes });
92
- return threads.map(thread => thread.get());
93
- } catch (error) {
94
- throw new Error(`Failed to get all threads: ${error.message}`);
95
- }
96
- }
97
- };
98
- };