fca-riyad 37.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 (242) hide show
  1. package/CHANGELOG.md +325 -0
  2. package/DOCS.md +2712 -0
  3. package/README.md +410 -0
  4. package/func/checkUpdate.js +7 -0
  5. package/func/logAdapter.js +33 -0
  6. package/func/logger.js +48 -0
  7. package/index.d.ts +751 -0
  8. package/index.js +22 -0
  9. package/module/config.js +40 -0
  10. package/module/login.js +133 -0
  11. package/module/loginHelper.js +1359 -0
  12. package/module/options.js +44 -0
  13. package/package.json +95 -0
  14. package/src/api/action/addExternalModule.js +25 -0
  15. package/src/api/action/changeAvatar.js +137 -0
  16. package/src/api/action/changeBio.js +75 -0
  17. package/src/api/action/enableAutoSaveAppState.js +73 -0
  18. package/src/api/action/getCurrentUserID.js +7 -0
  19. package/src/api/action/handleFriendRequest.js +57 -0
  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 +126 -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 +91 -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 +111 -0
  35. package/src/api/messaging/createNewGroup.js +88 -0
  36. package/src/api/messaging/createPoll.js +46 -0
  37. package/src/api/messaging/createThemeAI.js +98 -0
  38. package/src/api/messaging/deleteMessage.js +136 -0
  39. package/src/api/messaging/deleteThread.js +56 -0
  40. package/src/api/messaging/editMessage.js +90 -0
  41. package/src/api/messaging/forwardAttachment.js +57 -0
  42. package/src/api/messaging/forwardMessage.js +134 -0
  43. package/src/api/messaging/getEmojiUrl.js +29 -0
  44. package/src/api/messaging/getFriendsList.js +82 -0
  45. package/src/api/messaging/getMessage.js +829 -0
  46. package/src/api/messaging/getThemePictures.js +62 -0
  47. package/src/api/messaging/handleMessageRequest.js +65 -0
  48. package/src/api/messaging/markAsDelivered.js +57 -0
  49. package/src/api/messaging/markAsRead.js +88 -0
  50. package/src/api/messaging/markAsReadAll.js +49 -0
  51. package/src/api/messaging/markAsSeen.js +61 -0
  52. package/src/api/messaging/muteThread.js +50 -0
  53. package/src/api/messaging/pinMessage.js +115 -0
  54. package/src/api/messaging/removeUserFromGroup.js +62 -0
  55. package/src/api/messaging/resolvePhotoUrl.js +43 -0
  56. package/src/api/messaging/scheduler.js +264 -0
  57. package/src/api/messaging/searchForThread.js +53 -0
  58. package/src/api/messaging/sendBroadcast.js +93 -0
  59. package/src/api/messaging/sendMessage.js +269 -0
  60. package/src/api/messaging/sendTypingIndicator.js +74 -0
  61. package/src/api/messaging/sessionGuard.js +130 -0
  62. package/src/api/messaging/setMessageReaction.js +95 -0
  63. package/src/api/messaging/setTitle.js +124 -0
  64. package/src/api/messaging/shareContact.js +49 -0
  65. package/src/api/messaging/threadColors.js +128 -0
  66. package/src/api/messaging/unsendMessage.js +81 -0
  67. package/src/api/messaging/uploadAttachment.js +492 -0
  68. package/src/api/socket/OldMessage.js +186 -0
  69. package/src/api/socket/core/connectMqtt.js +269 -0
  70. package/src/api/socket/core/emitAuth.js +103 -0
  71. package/src/api/socket/core/getSeqID.js +321 -0
  72. package/src/api/socket/core/getTaskResponseData.js +25 -0
  73. package/src/api/socket/core/parseDelta.js +387 -0
  74. package/src/api/socket/detail/buildStream.js +215 -0
  75. package/src/api/socket/detail/constants.js +28 -0
  76. package/src/api/socket/e2ee/crypto.js +173 -0
  77. package/src/api/socket/e2ee/e2ee/crypto.js +173 -0
  78. package/src/api/socket/e2ee/e2ee/index.js +421 -0
  79. package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +281 -0
  80. package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +14 -0
  81. package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +232 -0
  82. package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +82 -0
  83. package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +77 -0
  84. package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +66 -0
  85. package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +176 -0
  86. package/src/api/socket/e2ee/e2ee/proto/proto-writer.ts +76 -0
  87. package/src/api/socket/e2ee/e2ee/protocol.js +196 -0
  88. package/src/api/socket/e2ee/e2ee/ratchet.js +219 -0
  89. package/src/api/socket/e2ee/e2ee/store.js +182 -0
  90. package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +9162 -0
  91. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  92. package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  93. package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  94. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +82 -0
  95. package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +77 -0
  96. package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +66 -0
  97. package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  98. package/src/api/socket/e2ee/e2ee/vendor/proto/proto-writer.ts +76 -0
  99. package/src/api/socket/e2ee/index.js +437 -0
  100. package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
  101. package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
  102. package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
  103. package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
  104. package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
  105. package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
  106. package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
  107. package/src/api/socket/e2ee/proto/proto-writer.ts +76 -0
  108. package/src/api/socket/e2ee/protocol.js +196 -0
  109. package/src/api/socket/e2ee/ratchet.js +219 -0
  110. package/src/api/socket/e2ee/store.js +182 -0
  111. package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +9162 -0
  112. package/src/api/socket/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
  113. package/src/api/socket/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
  114. package/src/api/socket/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
  115. package/src/api/socket/e2ee/vendor/proto/MessageApplication.proto +82 -0
  116. package/src/api/socket/e2ee/vendor/proto/MessageTransport.proto +77 -0
  117. package/src/api/socket/e2ee/vendor/proto/WACommon.proto +66 -0
  118. package/src/api/socket/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
  119. package/src/api/socket/e2ee/vendor/proto/proto-writer.ts +76 -0
  120. package/src/api/socket/listenE2EE.js +75 -0
  121. package/src/api/socket/listenMqtt.js +388 -0
  122. package/src/api/socket/middleware/index.js +216 -0
  123. package/src/api/socket/sendMessage.js +309 -0
  124. package/src/api/socket/sendMessageMqtt.js +69 -0
  125. package/src/api/threads/getThreadHistory.js +664 -0
  126. package/src/api/threads/getThreadInfo.js +296 -0
  127. package/src/api/threads/getThreadList.js +293 -0
  128. package/src/api/threads/getThreadPictures.js +78 -0
  129. package/src/api/users/getUserID.js +65 -0
  130. package/src/api/users/getUserInfo.js +402 -0
  131. package/src/api/users/getUserInfoV2.js +134 -0
  132. package/src/app/MessengerBot.js +209 -0
  133. package/src/app/MessengerContext.js +32 -0
  134. package/src/app/createFcaClient.js +136 -0
  135. package/src/app/threadInfoRealtimeSync.js +284 -0
  136. package/src/core/sendReqMqtt.js +96 -0
  137. package/src/database/helpers.js +53 -0
  138. package/src/database/models/index.js +88 -0
  139. package/src/database/models/thread.js +50 -0
  140. package/src/database/models/user.js +46 -0
  141. package/src/database/threadData.js +94 -0
  142. package/src/database/userData.js +98 -0
  143. package/src/remote/remoteClient.js +123 -0
  144. package/src/utils/broadcast.js +51 -0
  145. package/src/utils/client.js +10 -0
  146. package/src/utils/constants.js +23 -0
  147. package/src/utils/cookies.js +68 -0
  148. package/src/utils/format/attachment.js +357 -0
  149. package/src/utils/format/cookie.js +9 -0
  150. package/src/utils/format/date.js +50 -0
  151. package/src/utils/format/decode.js +44 -0
  152. package/src/utils/format/delta.js +194 -0
  153. package/src/utils/format/ids.js +64 -0
  154. package/src/utils/format/index.js +64 -0
  155. package/src/utils/format/message.js +88 -0
  156. package/src/utils/format/presence.js +132 -0
  157. package/src/utils/format/readTyp.js +44 -0
  158. package/src/utils/format/thread.js +42 -0
  159. package/src/utils/format/utils.js +141 -0
  160. package/src/utils/headers.js +115 -0
  161. package/src/utils/loginParser/autoLogin.js +125 -0
  162. package/src/utils/loginParser/helpers.js +43 -0
  163. package/src/utils/loginParser/index.js +10 -0
  164. package/src/utils/loginParser/parseAndCheckLogin.js +220 -0
  165. package/src/utils/loginParser/textUtils.js +28 -0
  166. package/src/utils/nexca-logger.js +144 -0
  167. package/src/utils/nexca-utils.js +686 -0
  168. package/src/utils/request/client.js +26 -0
  169. package/src/utils/request/config.js +23 -0
  170. package/src/utils/request/defaults.js +46 -0
  171. package/src/utils/request/helpers.js +46 -0
  172. package/src/utils/request/index.js +17 -0
  173. package/src/utils/request/methods.js +163 -0
  174. package/src/utils/request/proxy.js +21 -0
  175. package/src/utils/request/retry.js +77 -0
  176. package/src/utils/request/sanitize.js +49 -0
  177. package/src/utils/versionCheck.js +47 -0
  178. package/src/vendor/fca-unofficial/.github/workflows/nodejs.yml +26 -0
  179. package/src/vendor/fca-unofficial/.github/workflows/npmpublish.yml +30 -0
  180. package/src/vendor/fca-unofficial/.travis.yml +6 -0
  181. package/src/vendor/fca-unofficial/DOCS.md +1731 -0
  182. package/src/vendor/fca-unofficial/LICENSE-MIT +21 -0
  183. package/src/vendor/fca-unofficial/README.md +225 -0
  184. package/src/vendor/fca-unofficial/index.js +619 -0
  185. package/src/vendor/fca-unofficial/package.json +76 -0
  186. package/src/vendor/fca-unofficial/src/addExternalModule.js +19 -0
  187. package/src/vendor/fca-unofficial/src/addUserToGroup.js +113 -0
  188. package/src/vendor/fca-unofficial/src/changeAdminStatus.js +79 -0
  189. package/src/vendor/fca-unofficial/src/changeArchivedStatus.js +55 -0
  190. package/src/vendor/fca-unofficial/src/changeBio.js +77 -0
  191. package/src/vendor/fca-unofficial/src/changeBlockedStatus.js +47 -0
  192. package/src/vendor/fca-unofficial/src/changeGroupImage.js +129 -0
  193. package/src/vendor/fca-unofficial/src/changeNickname.js +59 -0
  194. package/src/vendor/fca-unofficial/src/changeThreadColor.js +71 -0
  195. package/src/vendor/fca-unofficial/src/changeThreadEmoji.js +55 -0
  196. package/src/vendor/fca-unofficial/src/createNewGroup.js +86 -0
  197. package/src/vendor/fca-unofficial/src/createPoll.js +71 -0
  198. package/src/vendor/fca-unofficial/src/deleteMessage.js +56 -0
  199. package/src/vendor/fca-unofficial/src/deleteThread.js +56 -0
  200. package/src/vendor/fca-unofficial/src/forwardAttachment.js +60 -0
  201. package/src/vendor/fca-unofficial/src/getCurrentUserID.js +7 -0
  202. package/src/vendor/fca-unofficial/src/getEmojiUrl.js +29 -0
  203. package/src/vendor/fca-unofficial/src/getFriendsList.js +84 -0
  204. package/src/vendor/fca-unofficial/src/getThreadHistory.js +645 -0
  205. package/src/vendor/fca-unofficial/src/getThreadHistoryDeprecated.js +93 -0
  206. package/src/vendor/fca-unofficial/src/getThreadInfo.js +201 -0
  207. package/src/vendor/fca-unofficial/src/getThreadInfoDeprecated.js +80 -0
  208. package/src/vendor/fca-unofficial/src/getThreadList.js +238 -0
  209. package/src/vendor/fca-unofficial/src/getThreadListDeprecated.js +75 -0
  210. package/src/vendor/fca-unofficial/src/getThreadPictures.js +79 -0
  211. package/src/vendor/fca-unofficial/src/getUserID.js +66 -0
  212. package/src/vendor/fca-unofficial/src/getUserInfo.js +72 -0
  213. package/src/vendor/fca-unofficial/src/handleFriendRequest.js +61 -0
  214. package/src/vendor/fca-unofficial/src/handleMessageRequest.js +65 -0
  215. package/src/vendor/fca-unofficial/src/httpGet.js +52 -0
  216. package/src/vendor/fca-unofficial/src/httpPost.js +52 -0
  217. package/src/vendor/fca-unofficial/src/listenMqtt.js +788 -0
  218. package/src/vendor/fca-unofficial/src/logout.js +75 -0
  219. package/src/vendor/fca-unofficial/src/markAsDelivered.js +58 -0
  220. package/src/vendor/fca-unofficial/src/markAsRead.js +80 -0
  221. package/src/vendor/fca-unofficial/src/markAsReadAll.js +50 -0
  222. package/src/vendor/fca-unofficial/src/markAsSeen.js +59 -0
  223. package/src/vendor/fca-unofficial/src/muteThread.js +52 -0
  224. package/src/vendor/fca-unofficial/src/removeUserFromGroup.js +79 -0
  225. package/src/vendor/fca-unofficial/src/resolvePhotoUrl.js +45 -0
  226. package/src/vendor/fca-unofficial/src/searchForThread.js +53 -0
  227. package/src/vendor/fca-unofficial/src/sendMessage.js +459 -0
  228. package/src/vendor/fca-unofficial/src/sendTypingIndicator.js +103 -0
  229. package/src/vendor/fca-unofficial/src/setMessageReaction.js +117 -0
  230. package/src/vendor/fca-unofficial/src/setPostReaction.js +76 -0
  231. package/src/vendor/fca-unofficial/src/setTitle.js +86 -0
  232. package/src/vendor/fca-unofficial/src/threadColors.js +57 -0
  233. package/src/vendor/fca-unofficial/src/unfriend.js +52 -0
  234. package/src/vendor/fca-unofficial/src/unsendMessage.js +49 -0
  235. package/src/vendor/fca-unofficial/test/data/shareAttach.js +146 -0
  236. package/src/vendor/fca-unofficial/test/data/something.mov +0 -0
  237. package/src/vendor/fca-unofficial/test/data/test.png +0 -0
  238. package/src/vendor/fca-unofficial/test/data/test.txt +7 -0
  239. package/src/vendor/fca-unofficial/test/example-config.json +18 -0
  240. package/src/vendor/fca-unofficial/test/test-page.js +140 -0
  241. package/src/vendor/fca-unofficial/test/test.js +385 -0
  242. package/src/vendor/fca-unofficial/utils.js +1358 -0
@@ -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,53 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Shared helpers for database layer (userData, threadData).
5
+ * Keeps validation and payload normalization in one place.
6
+ */
7
+
8
+ const DB_NOT_INIT = "Database not initialized";
9
+
10
+ function validateId(value, fieldName = "id") {
11
+ if (value == null) {
12
+ throw new Error(`${fieldName} is required and cannot be undefined`);
13
+ }
14
+ if (typeof value !== "string" && typeof value !== "number") {
15
+ throw new Error(`Invalid ${fieldName}: must be a string or number`);
16
+ }
17
+ return String(value);
18
+ }
19
+
20
+ function validateData(data) {
21
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
22
+ throw new Error("Invalid data: must be a non-empty object");
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @param {string|string[]|null} keys - "userID" | ["userID","data"] | null
28
+ * @returns {string[]|undefined}
29
+ */
30
+ function normalizeAttributes(keys) {
31
+ if (keys == null) return undefined;
32
+ return typeof keys === "string" ? [keys] : Array.isArray(keys) ? keys : undefined;
33
+ }
34
+
35
+ /**
36
+ * Normalize payload: accept either { data } or raw object.
37
+ */
38
+ function normalizePayload(data, key = "data") {
39
+ return Object.prototype.hasOwnProperty.call(data, key) ? data : { [key]: data };
40
+ }
41
+
42
+ function wrapError(message, cause) {
43
+ return new Error(`${message}: ${cause && cause.message ? cause.message : cause}`);
44
+ }
45
+
46
+ module.exports = {
47
+ DB_NOT_INIT,
48
+ validateId,
49
+ validateData,
50
+ normalizeAttributes,
51
+ normalizePayload,
52
+ wrapError
53
+ };
@@ -0,0 +1,88 @@
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.isReady = true;
67
+ models.syncAll = async () => {
68
+ try {
69
+ if (!sequelize) {
70
+ throw new Error("Sequelize instance not initialized");
71
+ }
72
+ await sequelize.sync({ force: false });
73
+ } catch (error) {
74
+ console.error("Failed to synchronize models:", error && error.message ? error.message : String(error));
75
+ throw error;
76
+ }
77
+ };
78
+ } catch (initError) {
79
+ console.error("Database initialization error:", initError && initError.message ? initError.message : String(initError));
80
+ models.sequelize = null;
81
+ models.Sequelize = Sequelize;
82
+ models.isReady = false;
83
+ models.syncAll = async () => {
84
+ throw new Error("Database not initialized");
85
+ };
86
+ }
87
+
88
+ module.exports = models;
@@ -0,0 +1,50 @@
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
+ messageCount: {
20
+ type: DataTypes.INTEGER,
21
+ allowNull: false,
22
+ defaultValue: 0
23
+ },
24
+ data: {
25
+ type: DataTypes.TEXT,
26
+ allowNull: true,
27
+ get() {
28
+ const value = this.getDataValue('data');
29
+ if (typeof value === 'string') {
30
+ try {
31
+ return JSON.parse(value);
32
+ } catch {
33
+ return value;
34
+ }
35
+ }
36
+ return value;
37
+ },
38
+ set(value) {
39
+ this.setDataValue('data', typeof value === 'string' ? value : JSON.stringify(value));
40
+ }
41
+ }
42
+ },
43
+ {
44
+ sequelize,
45
+ modelName: "Thread",
46
+ timestamps: true
47
+ }
48
+ );
49
+ return Thread;
50
+ };
@@ -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,94 @@
1
+ "use strict";
2
+
3
+ const models = require("./models");
4
+ const {
5
+ DB_NOT_INIT,
6
+ validateId,
7
+ validateData,
8
+ normalizeAttributes,
9
+ wrapError
10
+ } = require("./helpers");
11
+
12
+ const Thread = models.Thread;
13
+ const ID_FIELD = "threadID";
14
+
15
+ module.exports = function (bot) {
16
+ return {
17
+ async create(threadID, data) {
18
+ if (!Thread) {
19
+ return { thread: { threadID: validateId(threadID, ID_FIELD), ...(data || {}) }, created: true };
20
+ }
21
+ try {
22
+ threadID = validateId(threadID, ID_FIELD);
23
+ let thread = await Thread.findOne({ where: { threadID } });
24
+ if (thread) return { thread: thread.get(), created: false };
25
+ thread = await Thread.create({ threadID, ...(data || {}) });
26
+ return { thread: thread.get(), created: true };
27
+ } catch (err) {
28
+ throw wrapError("Failed to create thread", err);
29
+ }
30
+ },
31
+
32
+ async get(threadID) {
33
+ if (!Thread) return null;
34
+ try {
35
+ threadID = validateId(threadID, ID_FIELD);
36
+ const thread = await Thread.findOne({ where: { threadID } });
37
+ return thread ? thread.get() : null;
38
+ } catch (err) {
39
+ throw wrapError("Failed to get thread", err);
40
+ }
41
+ },
42
+
43
+ async update(threadID, data) {
44
+ if (!Thread) {
45
+ return { thread: { threadID: validateId(threadID, ID_FIELD), ...(data || {}) }, created: false };
46
+ }
47
+ try {
48
+ threadID = validateId(threadID, ID_FIELD);
49
+ validateData(data);
50
+ const thread = await Thread.findOne({ where: { threadID } });
51
+ if (thread) {
52
+ await thread.update(data);
53
+ return { thread: thread.get(), created: false };
54
+ }
55
+ const newThread = await Thread.create({ ...data, threadID });
56
+ return { thread: newThread.get(), created: true };
57
+ } catch (err) {
58
+ throw wrapError("Failed to update thread", err);
59
+ }
60
+ },
61
+
62
+ async del(threadID) {
63
+ if (!Thread) throw new Error(DB_NOT_INIT);
64
+ try {
65
+ threadID = validateId(threadID, ID_FIELD);
66
+ const result = await Thread.destroy({ where: { threadID } });
67
+ if (result === 0) throw new Error("No thread found with the specified threadID");
68
+ return result;
69
+ } catch (err) {
70
+ throw wrapError("Failed to delete thread", err);
71
+ }
72
+ },
73
+
74
+ async delAll() {
75
+ if (!Thread) return 0;
76
+ try {
77
+ return await Thread.destroy({ where: {} });
78
+ } catch (err) {
79
+ throw wrapError("Failed to delete all threads", err);
80
+ }
81
+ },
82
+
83
+ async getAll(keys = null) {
84
+ if (!Thread) return [];
85
+ try {
86
+ const attributes = normalizeAttributes(keys);
87
+ const rows = await Thread.findAll({ attributes });
88
+ return rows.map((t) => t.get());
89
+ } catch (err) {
90
+ throw wrapError("Failed to get all threads", err);
91
+ }
92
+ }
93
+ };
94
+ };
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ const models = require("./models");
4
+ const {
5
+ DB_NOT_INIT,
6
+ validateId,
7
+ validateData,
8
+ normalizeAttributes,
9
+ normalizePayload,
10
+ wrapError
11
+ } = require("./helpers");
12
+
13
+ const User = models.User;
14
+ const ID_FIELD = "userID";
15
+
16
+ function stubUser(userID, data) {
17
+ return { user: { userID, ...normalizePayload(data || {}, "data") }, created: true };
18
+ }
19
+
20
+ module.exports = function (bot) {
21
+ return {
22
+ async create(userID, data) {
23
+ if (!User) return stubUser(validateId(userID, ID_FIELD), data);
24
+ try {
25
+ userID = validateId(userID, ID_FIELD);
26
+ validateData(data);
27
+ const payload = normalizePayload(data, "data");
28
+ let user = await User.findOne({ where: { userID } });
29
+ if (user) return { user: user.get(), created: false };
30
+ user = await User.create({ userID, ...payload });
31
+ return { user: user.get(), created: true };
32
+ } catch (err) {
33
+ throw wrapError("Failed to create user", err);
34
+ }
35
+ },
36
+
37
+ async get(userID) {
38
+ if (!User) return null;
39
+ try {
40
+ userID = validateId(userID, ID_FIELD);
41
+ const user = await User.findOne({ where: { userID } });
42
+ return user ? user.get() : null;
43
+ } catch (err) {
44
+ throw wrapError("Failed to get user", err);
45
+ }
46
+ },
47
+
48
+ async update(userID, data) {
49
+ if (!User) return { user: { userID: validateId(userID, ID_FIELD), ...normalizePayload(data || {}, "data") }, created: false };
50
+ try {
51
+ userID = validateId(userID, ID_FIELD);
52
+ validateData(data);
53
+ const payload = normalizePayload(data, "data");
54
+ const user = await User.findOne({ where: { userID } });
55
+ if (user) {
56
+ await user.update(payload);
57
+ return { user: user.get(), created: false };
58
+ }
59
+ const newUser = await User.create({ userID, ...payload });
60
+ return { user: newUser.get(), created: true };
61
+ } catch (err) {
62
+ throw wrapError("Failed to update user", err);
63
+ }
64
+ },
65
+
66
+ async del(userID) {
67
+ if (!User) throw new Error(DB_NOT_INIT);
68
+ try {
69
+ userID = validateId(userID, ID_FIELD);
70
+ const result = await User.destroy({ where: { userID } });
71
+ if (result === 0) throw new Error("No user found with the specified userID");
72
+ return result;
73
+ } catch (err) {
74
+ throw wrapError("Failed to delete user", err);
75
+ }
76
+ },
77
+
78
+ async delAll() {
79
+ if (!User) return 0;
80
+ try {
81
+ return await User.destroy({ where: {} });
82
+ } catch (err) {
83
+ throw wrapError("Failed to delete all users", err);
84
+ }
85
+ },
86
+
87
+ async getAll(keys = null) {
88
+ if (!User) return [];
89
+ try {
90
+ const attributes = normalizeAttributes(keys);
91
+ const rows = await User.findAll({ attributes });
92
+ return rows.map((u) => u.get());
93
+ } catch (err) {
94
+ throw wrapError("Failed to get all users", err);
95
+ }
96
+ }
97
+ };
98
+ };
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+
3
+ const WebSocket = require("ws");
4
+ const logger = require("../../func/logger");
5
+
6
+ function createRemoteClient(api, ctx, cfg) {
7
+ if (!cfg || !cfg.enabled || !cfg.url) return null;
8
+
9
+ const url = String(cfg.url);
10
+ const token = cfg.token ? String(cfg.token) : null;
11
+ const autoReconnect = cfg.autoReconnect !== false;
12
+ const emitter = ctx && ctx._emitter;
13
+
14
+ let ws = null;
15
+ let closed = false;
16
+ let reconnectTimer = null;
17
+
18
+ function log(message, level = "info") {
19
+ logger(`[remote] ${message}`, level);
20
+ }
21
+
22
+ function scheduleReconnect() {
23
+ if (!autoReconnect || closed) return;
24
+ if (reconnectTimer) return;
25
+ reconnectTimer = setTimeout(() => {
26
+ reconnectTimer = null;
27
+ if (!closed) connect();
28
+ }, 5000);
29
+ }
30
+
31
+ function safeEmit(event, payload) {
32
+ try {
33
+ if (emitter && typeof emitter.emit === "function") {
34
+ emitter.emit(event, payload);
35
+ }
36
+ } catch { }
37
+ }
38
+
39
+ function connect() {
40
+ try {
41
+ ws = new WebSocket(url, {
42
+ headers: token ? { Authorization: `Bearer ${token}` } : undefined
43
+ });
44
+ } catch (e) {
45
+ log(`connect error: ${e && e.message ? e.message : String(e)}`, "warn");
46
+ scheduleReconnect();
47
+ return;
48
+ }
49
+
50
+ ws.on("open", () => {
51
+ log("connected", "info");
52
+ const payload = {
53
+ type: "hello",
54
+ userID: ctx && ctx.userID,
55
+ region: ctx && ctx.region,
56
+ version: require("../../package.json").version
57
+ };
58
+ try {
59
+ ws.send(JSON.stringify(payload));
60
+ } catch { }
61
+ safeEmit("remoteConnected", payload);
62
+ });
63
+
64
+ ws.on("message", data => {
65
+ let msg;
66
+ try {
67
+ msg = JSON.parse(data.toString());
68
+ } catch {
69
+ return;
70
+ }
71
+ if (!msg || typeof msg !== "object") return;
72
+
73
+ switch (msg.type) {
74
+ case "ping":
75
+ try {
76
+ ws.send(JSON.stringify({ type: "pong" }));
77
+ } catch { }
78
+ break;
79
+ case "stop":
80
+ safeEmit("remoteStop", msg);
81
+ break;
82
+ case "broadcast":
83
+ safeEmit("remoteBroadcast", msg.payload || {});
84
+ break;
85
+ default:
86
+ safeEmit("remoteMessage", msg);
87
+ break;
88
+ }
89
+ });
90
+
91
+ ws.on("close", () => {
92
+ log("disconnected", "warn");
93
+ safeEmit("remoteDisconnected");
94
+ if (!closed) scheduleReconnect();
95
+ });
96
+
97
+ ws.on("error", err => {
98
+ log(`error: ${err && err.message ? err.message : String(err)}`, "warn");
99
+ });
100
+ }
101
+
102
+ connect();
103
+
104
+ return {
105
+ close() {
106
+ closed = true;
107
+ if (reconnectTimer) {
108
+ clearTimeout(reconnectTimer);
109
+ reconnectTimer = null;
110
+ }
111
+ try {
112
+ if (ws && ws.readyState === WebSocket.OPEN) {
113
+ ws.close();
114
+ }
115
+ } catch { }
116
+ }
117
+ };
118
+ }
119
+
120
+ module.exports = {
121
+ createRemoteClient
122
+ };
123
+
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+
3
+ const logger = require("../../func/logger");
4
+
5
+ function delay(ms) {
6
+ return new Promise(resolve => setTimeout(resolve, ms));
7
+ }
8
+
9
+ async function broadcast(api, threadIDs, message, options) {
10
+ const opts = options || {};
11
+ const delayMs = typeof opts.delayMs === "number" ? opts.delayMs : 1000;
12
+ const skipBlocked = opts.skipBlocked !== false;
13
+ const onResult = typeof opts.onResult === "function" ? opts.onResult : null;
14
+
15
+ if (!api || typeof api.sendMessage !== "function") {
16
+ throw new Error("broadcast: api.sendMessage is required.");
17
+ }
18
+
19
+ const ids = Array.isArray(threadIDs) ? threadIDs : [threadIDs];
20
+ const results = [];
21
+
22
+ for (const id of ids) {
23
+ try {
24
+ const res = await api.sendMessage(message, id);
25
+ const item = { threadID: id, ok: true, res };
26
+ results.push(item);
27
+ if (onResult) onResult(null, item);
28
+ } catch (e) {
29
+ const msg = e && e.error ? e.error : e && e.message ? e.message : String(e);
30
+ logger(`broadcast: failed for ${id}: ${msg}`, "warn");
31
+ const item = { threadID: id, ok: false, error: e };
32
+ results.push(item);
33
+ if (onResult) onResult(e, item);
34
+
35
+ if (
36
+ skipBlocked &&
37
+ /permission|blocked|not allowed|cannot send message|not authorized/i.test(msg)
38
+ ) {
39
+ // Skip only this target, continue with others
40
+ }
41
+ }
42
+ if (delayMs > 0) {
43
+ await delay(delayMs);
44
+ }
45
+ }
46
+
47
+ return results;
48
+ }
49
+
50
+ module.exports = broadcast;
51
+