@cexy/hoonfca 1.0.3 → 1.0.5

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 (135) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/DOCS.md +2636 -0
  3. package/LICENSE-MIT +21 -21
  4. package/README.md +632 -0
  5. package/func/checkUpdate.js +222 -0
  6. package/func/logger.js +48 -0
  7. package/index.d.ts +731 -605
  8. package/index.js +6 -777
  9. package/module/config.js +34 -0
  10. package/module/login.js +136 -0
  11. package/module/loginHelper.js +1034 -0
  12. package/module/options.js +45 -0
  13. package/package.json +53 -22
  14. package/src/api/action/addExternalModule.js +25 -0
  15. package/src/api/action/changeAvatar.js +137 -0
  16. package/src/{changeBio.js → api/action/changeBio.js} +75 -76
  17. package/src/api/action/enableAutoSaveAppState.js +73 -0
  18. package/src/{getCurrentUserID.js → api/action/getCurrentUserID.js} +7 -7
  19. package/src/{handleFriendRequest.js → api/action/handleFriendRequest.js} +57 -57
  20. package/src/api/action/logout.js +76 -0
  21. package/src/api/action/refreshFb_dtsg.js +48 -0
  22. package/src/api/action/setPostReaction.js +106 -0
  23. package/src/api/action/unfriend.js +54 -0
  24. package/src/api/http/httpGet.js +46 -0
  25. package/src/api/http/httpPost.js +52 -0
  26. package/src/api/http/postFormData.js +47 -0
  27. package/src/api/messaging/addUserToGroup.js +68 -0
  28. package/src/api/messaging/changeAdminStatus.js +122 -0
  29. package/src/api/messaging/changeArchivedStatus.js +55 -0
  30. package/src/api/messaging/changeBlockedStatus.js +48 -0
  31. package/src/api/messaging/changeGroupImage.js +90 -0
  32. package/src/api/messaging/changeNickname.js +70 -0
  33. package/src/api/messaging/changeThreadColor.js +79 -0
  34. package/src/api/messaging/changeThreadEmoji.js +106 -0
  35. package/src/{createNewGroup.js → api/messaging/createNewGroup.js} +88 -88
  36. package/src/api/messaging/createPoll.js +43 -0
  37. package/src/api/messaging/createThemeAI.js +98 -0
  38. package/src/{deleteMessage.js → api/messaging/deleteMessage.js} +56 -56
  39. package/src/{deleteThread.js → api/messaging/deleteThread.js} +56 -56
  40. package/src/api/messaging/editMessage.js +68 -0
  41. package/src/api/messaging/forwardAttachment.js +51 -0
  42. package/src/{getEmojiUrl.js → api/messaging/getEmojiUrl.js} +8 -8
  43. package/src/{getFriendsList.js → api/messaging/getFriendsList.js} +82 -84
  44. package/src/api/messaging/getMessage.js +829 -0
  45. package/src/api/messaging/getThemePictures.js +62 -0
  46. package/src/api/messaging/handleMessageRequest.js +65 -0
  47. package/src/{markAsDelivered.js → api/messaging/markAsDelivered.js} +57 -58
  48. package/src/{markAsRead.js → api/messaging/markAsRead.js} +88 -88
  49. package/src/{markAsReadAll.js → api/messaging/markAsReadAll.js} +49 -50
  50. package/src/api/messaging/markAsSeen.js +61 -0
  51. package/src/{muteThread.js → api/messaging/muteThread.js} +50 -52
  52. package/src/api/messaging/removeUserFromGroup.js +106 -0
  53. package/src/{resolvePhotoUrl.js → api/messaging/resolvePhotoUrl.js} +43 -45
  54. package/src/api/messaging/scheduler.js +264 -0
  55. package/src/{searchForThread.js → api/messaging/searchForThread.js} +52 -53
  56. package/src/api/messaging/sendMessage.js +272 -0
  57. package/src/api/messaging/sendTypingIndicator.js +67 -0
  58. package/src/api/messaging/setMessageReaction.js +76 -0
  59. package/src/api/messaging/setTitle.js +119 -0
  60. package/src/{shareContact.js → api/messaging/shareContact.js} +49 -53
  61. package/src/api/messaging/threadColors.js +128 -0
  62. package/src/api/messaging/unsendMessage.js +81 -0
  63. package/src/api/messaging/uploadAttachment.js +94 -0
  64. package/src/api/socket/core/connectMqtt.js +255 -0
  65. package/src/api/socket/core/emitAuth.js +106 -0
  66. package/src/api/socket/core/getSeqID.js +40 -0
  67. package/src/api/socket/core/getTaskResponseData.js +22 -0
  68. package/src/api/socket/core/markDelivery.js +12 -0
  69. package/src/api/socket/core/parseDelta.js +391 -0
  70. package/src/api/socket/detail/buildStream.js +208 -0
  71. package/src/api/socket/detail/constants.js +24 -0
  72. package/src/api/socket/listenMqtt.js +364 -0
  73. package/src/api/socket/middleware/index.js +216 -0
  74. package/src/{getThreadHistory.js → api/threads/getThreadHistory.js} +664 -647
  75. package/src/api/threads/getThreadInfo.js +438 -0
  76. package/src/{getThreadList.js → api/threads/getThreadList.js} +293 -292
  77. package/src/{getThreadPictures.js → api/threads/getThreadPictures.js} +78 -79
  78. package/src/{getUserID.js → api/users/getUserID.js} +65 -66
  79. package/src/api/users/getUserInfo.js +327 -0
  80. package/src/api/users/getUserInfoV2.js +134 -0
  81. package/src/core/sendReqMqtt.js +96 -0
  82. package/src/database/models/index.js +87 -0
  83. package/src/database/models/thread.js +45 -0
  84. package/src/database/models/user.js +46 -0
  85. package/src/database/threadData.js +98 -0
  86. package/src/database/userData.js +89 -0
  87. package/src/utils/client.js +320 -0
  88. package/src/utils/constants.js +23 -0
  89. package/{utils.js → src/utils/format.js} +1115 -1447
  90. package/src/utils/headers.js +115 -0
  91. package/src/utils/request.js +305 -0
  92. package/.travis.yml +0 -6
  93. package/src/addExternalModule.js +0 -23
  94. package/src/addUserToGroup.js +0 -113
  95. package/src/changeAdminStatus.js +0 -95
  96. package/src/changeApprovalMode.js +0 -79
  97. package/src/changeArchivedStatus.js +0 -55
  98. package/src/changeBlockedStatus.js +0 -47
  99. package/src/changeBlockedStatusMqtt.js +0 -86
  100. package/src/changeGroupImage.js +0 -133
  101. package/src/changeNickname.js +0 -59
  102. package/src/changeThreadColor.js +0 -71
  103. package/src/changeThreadEmoji.js +0 -55
  104. package/src/createPoll.js +0 -130
  105. package/src/editMessage.js +0 -63
  106. package/src/forwardAttachment.js +0 -60
  107. package/src/forwardMessage.js +0 -63
  108. package/src/getGroupsList.js +0 -83
  109. package/src/getMarketplace.js +0 -84
  110. package/src/getNotifications.js +0 -86
  111. package/src/getPagesList.js +0 -83
  112. package/src/getStories.js +0 -88
  113. package/src/getThreadInfo.js +0 -222
  114. package/src/getUserInfo.js +0 -128
  115. package/src/handleMessageRequest.js +0 -65
  116. package/src/httpGet.js +0 -58
  117. package/src/httpPost.js +0 -58
  118. package/src/listenMqtt.js +0 -1018
  119. package/src/logout.js +0 -75
  120. package/src/markAsSeen.js +0 -61
  121. package/src/pinMessage.js +0 -61
  122. package/src/removeUserFromGroup.js +0 -79
  123. package/src/searchUsers.js +0 -89
  124. package/src/sendComment.js +0 -161
  125. package/src/sendMessage.js +0 -457
  126. package/src/sendTypingIndicator.js +0 -179
  127. package/src/setBio.js +0 -86
  128. package/src/setMessageReaction.js +0 -186
  129. package/src/setPostReaction.js +0 -71
  130. package/src/setTheme.js +0 -313
  131. package/src/setTitle.js +0 -90
  132. package/src/shareLink.js +0 -62
  133. package/src/threadColors.js +0 -57
  134. package/src/unfriend.js +0 -53
  135. package/src/unsendMessage.js +0 -104
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+
3
+ const { parseAndCheckLogin } = require("../../utils/client.js");
4
+ const logger = require("../../../func/logger");
5
+ const DEFAULT_DOC_ID = "24418640587785718";
6
+ const DEFAULT_FRIENDLY_NAME = "CometHovercardQueryRendererQuery";
7
+ const DEFAULT_CALLER_CLASS = "RelayModern";
8
+
9
+ function toJSONMaybe(s) {
10
+ if (!s) return null;
11
+ if (typeof s === "string") {
12
+ const t = s.trim().replace(/^for\s*\(\s*;\s*;\s*\)\s*;/, "");
13
+ try { return JSON.parse(t); } catch { return null; }
14
+ }
15
+ return s;
16
+ }
17
+
18
+ function usernameFromUrl(raw) {
19
+ if (!raw) return null;
20
+ try {
21
+ const u = new URL(raw);
22
+ if (/^www\.facebook\.com$/i.test(u.hostname)) {
23
+ const seg = u.pathname.replace(/^\//, "").replace(/\/$/, "");
24
+ if (seg && !/^profile\.php$/i.test(seg) && !seg.includes("/")) return seg;
25
+ }
26
+ } catch { }
27
+ return null;
28
+ }
29
+
30
+ function pickMeta(u) {
31
+ let friendshipStatus = null;
32
+ let gender = null;
33
+ let shortName = u?.short_name || null;
34
+ const pa = Array.isArray(u?.primaryActions) ? u.primaryActions : [];
35
+ const sa = Array.isArray(u?.secondaryActions) ? u.secondaryActions : [];
36
+ const aFriend = pa.find(x => x?.profile_action_type === "FRIEND");
37
+ if (aFriend?.client_handler?.profile_action?.restrictable_profile_owner) {
38
+ const p = aFriend.client_handler.profile_action.restrictable_profile_owner;
39
+ friendshipStatus = p?.friendship_status || null;
40
+ gender = p?.gender || gender;
41
+ shortName = p?.short_name || shortName;
42
+ }
43
+ if (!gender || !shortName) {
44
+ const aBlock = sa.find(x => x?.profile_action_type === "BLOCK");
45
+ const p2 = aBlock?.client_handler?.profile_action?.profile_owner;
46
+ if (p2) {
47
+ gender = p2.gender || gender;
48
+ shortName = p2.short_name || shortName;
49
+ }
50
+ }
51
+ return { friendshipStatus, gender, shortName };
52
+ }
53
+
54
+ function normalizeUser(u) {
55
+ if (!u) return null;
56
+ const vanity = usernameFromUrl(u.profile_url || u.url);
57
+ const meta = pickMeta(u);
58
+ return {
59
+ id: u.id || null,
60
+ name: u.name || null,
61
+ username: vanity || u.username_for_profile || null,
62
+ profileUrl: u.profile_url || u.url || null,
63
+ url: u.url || null,
64
+ isVerified: !!u.is_verified,
65
+ isMemorialized: !!u.is_visibly_memorialized,
66
+ avatar: u.profile_picture?.uri || null,
67
+ shortName: meta.shortName || null,
68
+ gender: meta.gender || null,
69
+ friendshipStatus: meta.friendshipStatus || null
70
+ };
71
+ }
72
+
73
+ function toRetObjEntry(nu) {
74
+ return {
75
+ name: nu?.name || null,
76
+ firstName: nu?.shortName || null,
77
+ vanity: nu?.username || null,
78
+ thumbSrc: nu?.avatar || null,
79
+ profileUrl: nu?.profileUrl || null,
80
+ gender: nu?.gender || null,
81
+ type: "User",
82
+ isFriend: nu?.friendshipStatus === "ARE_FRIENDS",
83
+ isMessengerUser: null,
84
+ isMessageBlockedByViewer: false,
85
+ workInfo: null,
86
+ messengerStatus: null
87
+ };
88
+ }
89
+
90
+ module.exports = function (defaultFuncs, api, ctx) {
91
+ async function fetchOne(uid) {
92
+ const av = String(ctx?.userID || "");
93
+ const variablesObj = {
94
+ actionBarRenderLocation: "WWW_COMET_HOVERCARD",
95
+ context: "DEFAULT",
96
+ entityID: String(uid),
97
+ scale: 1,
98
+ __relay_internal__pv__WorkCometIsEmployeeGKProviderrelayprovider: false
99
+ };
100
+ const form = {
101
+ av,
102
+ fb_api_caller_class: DEFAULT_CALLER_CLASS,
103
+ fb_api_req_friendly_name: DEFAULT_FRIENDLY_NAME,
104
+ server_timestamps: true,
105
+ doc_id: DEFAULT_DOC_ID,
106
+ variables: JSON.stringify(variablesObj)
107
+ };
108
+ const raw = await defaultFuncs.post("https://www.facebook.com/api/graphql/", null, form).then(parseAndCheckLogin(ctx, defaultFuncs));
109
+ const parsed = toJSONMaybe(raw) ?? raw;
110
+ const root = Array.isArray(parsed) ? parsed[0] : parsed;
111
+ const user = root?.data?.node?.comet_hovercard_renderer?.user || null;
112
+ return normalizeUser(user);
113
+ }
114
+
115
+ return function getUserInfoV2(idOrList, callback) {
116
+ let resolveFunc, rejectFunc;
117
+ const returnPromise = new Promise((resolve, reject) => { resolveFunc = resolve; rejectFunc = reject; });
118
+ if (typeof callback !== "function") {
119
+ callback = (err, data) => { if (err) return rejectFunc(err); resolveFunc(data); };
120
+ }
121
+ const ids = Array.isArray(idOrList) ? idOrList.map(v => String(v)) : [String(idOrList)];
122
+ Promise.allSettled(ids.map(fetchOne))
123
+ .then(results => {
124
+ const retObj = {};
125
+ for (let i = 0; i < ids.length; i++) {
126
+ const nu = results[i].status === "fulfilled" ? results[i].value : null;
127
+ retObj[ids[i]] = toRetObjEntry(nu);
128
+ }
129
+ return callback(null, retObj);
130
+ })
131
+ .catch(err => { logger("getUserInfoV2" + err, "error"); callback(err); });
132
+ return returnPromise;
133
+ };
134
+ };
@@ -0,0 +1,96 @@
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;
@@ -0,0 +1,87 @@
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;
@@ -0,0 +1,45 @@
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
+ };
@@ -0,0 +1,46 @@
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
+ };
@@ -0,0 +1,98 @@
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
+ };
@@ -0,0 +1,89 @@
1
+ const { User } = require("./models");
2
+
3
+ const validateUserID = userID => {
4
+ if (typeof userID !== "string" && typeof userID !== "number") {
5
+ throw new Error("Invalid userID: must be a string or number.");
6
+ }
7
+ return String(userID);
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(userID, data) {
18
+ try {
19
+ userID = validateUserID(userID);
20
+ validateData(data);
21
+ let user = await User.findOne({ where: { userID } });
22
+ if (user) return { user: user.get(), created: false };
23
+ const payload = Object.prototype.hasOwnProperty.call(data, "data") ? data : { data };
24
+ user = await User.create({ userID, ...payload });
25
+ return { user: user.get(), created: true };
26
+ } catch (error) {
27
+ throw new Error(`Failed to create user: ${error.message}`);
28
+ }
29
+ },
30
+
31
+ async get(userID) {
32
+ try {
33
+ userID = validateUserID(userID);
34
+ const user = await User.findOne({ where: { userID } });
35
+ return user ? user.get() : null;
36
+ } catch (error) {
37
+ throw new Error(`Failed to get user: ${error.message}`);
38
+ }
39
+ },
40
+
41
+ async update(userID, data) {
42
+ try {
43
+ userID = validateUserID(userID);
44
+ validateData(data);
45
+ const payload = Object.prototype.hasOwnProperty.call(data, "data") ? data : { data };
46
+ const user = await User.findOne({ where: { userID } });
47
+ if (user) {
48
+ await user.update(payload);
49
+ return { user: user.get(), created: false };
50
+ } else {
51
+ const newUser = await User.create({ userID, ...payload });
52
+ return { user: newUser.get(), created: true };
53
+ }
54
+ } catch (error) {
55
+ throw new Error(`Failed to update user: ${error.message}`);
56
+ }
57
+ },
58
+
59
+ async del(userID) {
60
+ try {
61
+ if (!userID) throw new Error("userID is required and cannot be undefined");
62
+ userID = validateUserID(userID);
63
+ const result = await User.destroy({ where: { userID } });
64
+ if (result === 0) throw new Error("No user found with the specified userID");
65
+ return result;
66
+ } catch (error) {
67
+ throw new Error(`Failed to delete user: ${error.message}`);
68
+ }
69
+ },
70
+
71
+ async delAll() {
72
+ try {
73
+ return await User.destroy({ where: {} });
74
+ } catch (error) {
75
+ throw new Error(`Failed to delete all users: ${error.message}`);
76
+ }
77
+ },
78
+
79
+ async getAll(keys = null) {
80
+ try {
81
+ const attributes = typeof keys === "string" ? [keys] : Array.isArray(keys) ? keys : undefined;
82
+ const users = await User.findAll({ attributes });
83
+ return users.map(u => u.get());
84
+ } catch (error) {
85
+ throw new Error(`Failed to get all users: ${error.message}`);
86
+ }
87
+ }
88
+ };
89
+ };