fca-nx 6.8.8 → 7.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 (79) hide show
  1. package/README.md +24 -10
  2. package/func/checkUpdate.js +1 -1
  3. package/func/logAdapter.js +2 -0
  4. package/index.js +3 -0
  5. package/module/config.js +5 -3
  6. package/module/login.js +38 -13
  7. package/module/loginHelper.js +207 -148
  8. package/module/options.js +7 -1
  9. package/package.json +2 -2
  10. package/src/api/action/addfriend.js +9 -3
  11. package/src/api/action/changeAvatar.js +1 -0
  12. package/src/api/action/changeCover.js +3 -1
  13. package/src/api/action/enableAutoSaveAppState.js +18 -5
  14. package/src/api/action/refreshFb_dtsg.js +18 -76
  15. package/src/api/http/httpGet.js +6 -2
  16. package/src/api/http/httpPost.js +7 -2
  17. package/src/api/messaging/createNewGroup.js +1 -1
  18. package/src/api/messaging/deleteMessage.js +1 -1
  19. package/src/api/messaging/forwardMessage.js +9 -1
  20. package/src/api/messaging/getEmojiUrl.js +5 -1
  21. package/src/api/messaging/getMessage.js +4 -2
  22. package/src/api/messaging/getThemePictures.js +7 -0
  23. package/src/api/messaging/markAsRead.js +1 -0
  24. package/src/api/messaging/muteThread.js +1 -1
  25. package/src/api/messaging/pinMessage.js +10 -1
  26. package/src/api/messaging/scheduler.js +71 -4
  27. package/src/api/messaging/sendBroadcast.js +15 -0
  28. package/src/api/messaging/sendMessage.js +23 -1
  29. package/src/api/messaging/sendTypingIndicator.js +0 -15
  30. package/src/api/messaging/sessionGuard.js +45 -9
  31. package/src/api/messaging/setMessageReaction.js +2 -1
  32. package/src/api/messaging/threadColors.js +45 -12
  33. package/src/api/messaging/uploadAttachment.js +37 -3
  34. package/src/api/socket/OldMessage.js +7 -2
  35. package/src/api/socket/core/connectMqtt.js +68 -81
  36. package/src/api/socket/core/emitAuth.js +11 -2
  37. package/src/api/socket/core/getSeqID.js +52 -56
  38. package/src/api/socket/core/getTaskResponseData.js +3 -1
  39. package/src/api/socket/core/parseDelta.js +1 -1
  40. package/src/api/socket/detail/buildStream.js +4 -1
  41. package/src/api/socket/detail/constants.js +4 -1
  42. package/src/api/socket/e2ee/crypto.js +40 -2
  43. package/src/api/socket/e2ee/index.js +123 -10
  44. package/src/api/socket/e2ee/protocol.js +32 -1
  45. package/src/api/socket/e2ee/ratchet.js +44 -10
  46. package/src/api/socket/e2ee/store.js +13 -1
  47. package/src/api/socket/listenE2EE.js +25 -1
  48. package/src/api/socket/listenMqtt.js +94 -110
  49. package/src/api/socket/middleware/index.js +61 -7
  50. package/src/api/socket/sendMessage.js +19 -2
  51. package/src/api/socket/sendMessageMqtt.js +6 -0
  52. package/src/api/threads/getThreadHistory.js +68 -38
  53. package/src/api/threads/getThreadInfo.js +4 -3
  54. package/src/api/threads/getThreadList.js +34 -31
  55. package/src/api/threads/getThreadPictures.js +1 -1
  56. package/src/api/users/getUserInfo.js +5 -2
  57. package/src/api/users/getUserInfoV2.js +9 -3
  58. package/src/app/createFcaClient.js +2 -2
  59. package/src/core/sendReqMqtt.js +2 -1
  60. package/src/database/helpers.js +12 -0
  61. package/src/database/models/index.js +8 -9
  62. package/src/utils/broadcast.js +1 -1
  63. package/src/utils/clientIdentity.js +50 -3
  64. package/src/utils/cookies.js +4 -2
  65. package/src/utils/format/utils.js +10 -0
  66. package/src/utils/headers.js +26 -12
  67. package/src/utils/loginParser/autoLogin.js +12 -0
  68. package/src/utils/loginParser/parseAndCheckLogin.js +7 -0
  69. package/src/utils/loginParser/textUtils.js +6 -0
  70. package/src/utils/request/config.js +4 -1
  71. package/src/utils/request/methods.js +0 -13
  72. package/src/utils/request/proxy.js +13 -0
  73. package/src/utils/request/retry.js +0 -10
  74. package/src/utils/request/sanitize.js +1 -1
  75. package/src/utils/sendThrottle.js +14 -1
  76. package/src/utils/textEffects.js +92 -0
  77. package/src/utils/utils.js +17 -3
  78. package/src/utils/instanceLock.js +0 -35
  79. package/src/utils/ipGuard.js +0 -58
package/module/options.js CHANGED
@@ -22,7 +22,13 @@ function setOptions(globalOptions, options) {
22
22
  }
23
23
  switch (key) {
24
24
  case "userAgent": {
25
-
25
+ // Resolve through the centralized identity module so a custom UA still
26
+ // gets internally-consistent sec-ch-ua/platform/arch hints instead of
27
+ // silently keeping mismatched defaults from elsewhere in the code.
28
+ // Note: once a session is connected, its identity is cached on ctx
29
+ // (see src/utils/clientIdentity.js#getSessionIdentity) and will not
30
+ // change mid-session even if this is called again - this call only
31
+ // affects future/new sessions started from this globalOptions object.
26
32
  globalOptions.userAgent = getIdentity(options.userAgent).userAgent;
27
33
  break;
28
34
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.8.8",
4
- "description": "Facebook Messenger api",
3
+ "version": "7.0.0",
4
+ "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
7
7
  "exports": {
@@ -1,4 +1,6 @@
1
-
1
+ /**
2
+ * Send a friend request to a Facebook user.
3
+ */
2
4
 
3
5
  "use strict";
4
6
 
@@ -29,6 +31,9 @@ module.exports = function (defaultFuncs, api, ctx) {
29
31
  }
30
32
  };
31
33
 
34
+ /*
35
+ * Validate user ID
36
+ */
32
37
  let targetID;
33
38
  try {
34
39
  targetID = formatID(userID);
@@ -48,12 +53,13 @@ module.exports = function (defaultFuncs, api, ctx) {
48
53
  }
49
54
 
50
55
  const sendRequest = async function () {
51
-
56
+ // Facebook retired the old /ajax/friends/requests/send/ action. The
57
+ // profile button now uses this Relay mutation instead.
52
58
  if (!ctx.fb_dtsg && typeof api?.refreshFb_dtsg === "function") {
53
59
  try {
54
60
  await api.refreshFb_dtsg();
55
61
  } catch (_) {
56
-
62
+ // The request below will return the actionable Facebook error.
57
63
  }
58
64
  }
59
65
 
@@ -32,6 +32,7 @@ module.exports = function(defaultFuncs, api, ctx) {
32
32
  })
33
33
  );
34
34
 
35
+ // resolve all promises
35
36
  Promise.all(uploads)
36
37
  .then(function(resData) {
37
38
  callback(null, resData);
@@ -1,4 +1,6 @@
1
-
1
+ /**d
2
+ * Change Facebook Profile Cover Photo via GraphQL Mutation.
3
+ */
2
4
 
3
5
  "use strict";
4
6
 
@@ -3,12 +3,21 @@ const fs = require("fs");
3
3
  const path = require("path");
4
4
  const logger = require("../../../func/logger");
5
5
 
6
+ /**
7
+ * Enable automatic AppState saving
8
+ * @param {Object} options - Options for auto-save
9
+ * @param {string} [options.filePath] - Path to save AppState (default: "appstate.json")
10
+ * @param {number} [options.interval] - Save interval in milliseconds (default: 10 minutes)
11
+ * @param {boolean} [options.saveOnLogin] - Save immediately on login (default: true)
12
+ * @returns {Function} Function to disable auto-save
13
+ */
6
14
  module.exports = function (defaultFuncs, api, ctx) {
7
15
  return function enableAutoSaveAppState(options = {}) {
8
16
  const filePath = options.filePath || path.join(process.cwd(), "appstate.json");
9
- const interval = options.interval || 5 * 60 * 1000;
10
- const saveOnLogin = options.saveOnLogin !== false;
17
+ const interval = options.interval || 10 * 60 * 1000; // 10 minutes default
18
+ const saveOnLogin = options.saveOnLogin !== false; // default true
11
19
 
20
+ // Save function
12
21
  function saveAppState() {
13
22
  try {
14
23
  const appState = api.getAppState();
@@ -25,30 +34,34 @@ module.exports = function (defaultFuncs, api, ctx) {
25
34
  }
26
35
  }
27
36
 
37
+ // Save immediately if requested
28
38
  let immediateSaveTimer = null;
29
39
  if (saveOnLogin) {
30
-
40
+ // Delay a bit to ensure login is complete
31
41
  immediateSaveTimer = setTimeout(() => {
32
42
  saveAppState();
33
43
  immediateSaveTimer = null;
34
44
  }, 2000);
35
45
  }
36
46
 
47
+ // Set up interval
37
48
  const intervalId = setInterval(saveAppState, interval);
38
49
  logger(`Auto-save AppState enabled: ${filePath} (every ${Math.round(interval / 1000 / 60)} minutes)`, "info");
39
50
 
51
+ // Store interval ID for cleanup
40
52
  if (!ctx._autoSaveInterval) {
41
53
  ctx._autoSaveInterval = [];
42
54
  }
43
55
  ctx._autoSaveInterval.push(intervalId);
44
56
 
57
+ // Return disable function
45
58
  return function disableAutoSaveAppState() {
46
-
59
+ // Clear immediate save timer if still pending
47
60
  if (immediateSaveTimer) {
48
61
  clearTimeout(immediateSaveTimer);
49
62
  immediateSaveTimer = null;
50
63
  }
51
-
64
+ // Clear interval
52
65
  clearInterval(intervalId);
53
66
  const index = ctx._autoSaveInterval ? ctx._autoSaveInterval.indexOf(intervalId) : -1;
54
67
  if (index !== -1) {
@@ -1,35 +1,8 @@
1
1
  "use strict";
2
2
 
3
3
  const { getFrom } = require("../../utils/constants");
4
- const { get } = require("../../utils/request");
4
+ const { get } = require("../../utils/request")
5
5
  const { getType } = require("../../utils/format");
6
- const logger = require("../../../func/logger");
7
-
8
- function extractTokens(html) {
9
- if (!html || typeof html !== "string") return null;
10
- const fb_dtsg =
11
- getFrom(html, '["DTSGInitData",[],{"token":"', '","') ||
12
- getFrom(html, '"DTSGInitialData",[],{"token":"', '"') ||
13
- getFrom(html, 'name="fb_dtsg" value="', '"') ||
14
- getFrom(html, '"fb_dtsg":{"token":"', '"') ||
15
- getFrom(html, "fb_dtsg\":{\"token\":\"", "\"") ||
16
- null;
17
- const jazoest =
18
- getFrom(html, "jazoest=", '",') ||
19
- getFrom(html, 'name="jazoest" value="', '"') ||
20
- getFrom(html, '"jazoest":"', '"') ||
21
- null;
22
- if (!fb_dtsg) return null;
23
- return { fb_dtsg, jazoest: jazoest || (ctxJazoestFallback(fb_dtsg)) };
24
- }
25
-
26
- function ctxJazoestFallback(token) {
27
-
28
- let sum = 0;
29
- for (let i = 0; i < token.length; i++) sum += token.charCodeAt(i);
30
- return "2" + sum;
31
- }
32
-
33
6
  module.exports = function (defaultFuncs, api, ctx) {
34
7
  return function refreshFb_dtsg(obj, callback) {
35
8
  if (typeof obj === "function") {
@@ -46,60 +19,29 @@ module.exports = function (defaultFuncs, api, ctx) {
46
19
  rejectFunc = reject;
47
20
  });
48
21
  if (!callback) {
49
- callback = (err, data) => (err ? rejectFunc(err) : resolveFunc(data));
22
+ callback = (err, data) => err ? rejectFunc(err) : resolveFunc(data);
50
23
  }
51
-
52
- if (Object.keys(obj).length > 0) {
24
+ if (Object.keys(obj).length === 0) {
25
+ get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, { noRef: true }).then(({ data }) => {
26
+ const fb_dtsg = getFrom(data, '["DTSGInitData",[],{"token":"', '","');
27
+ const jazoest = getFrom(data, "jazoest=", '",');
28
+ if (!fb_dtsg) throw new Error("Could not find fb_dtsg in HTML after requesting Facebook.");
29
+ Object.assign(ctx, { fb_dtsg, jazoest });
30
+ callback(null, {
31
+ data: { fb_dtsg, jazoest },
32
+ message: "Refreshed fb_dtsg and jazoest",
33
+ });
34
+ }).catch(err => {
35
+ console.error("refreshFb_dtsg", err);
36
+ callback(err);
37
+ });
38
+ } else {
53
39
  Object.assign(ctx, obj);
54
40
  callback(null, {
55
41
  data: obj,
56
- message: `Refreshed ${Object.keys(obj).join(", ")}`
42
+ message: `Refreshed ${Object.keys(obj).join(", ")}`,
57
43
  });
58
- return returnPromise;
59
44
  }
60
-
61
- const urls = [
62
- "https://www.facebook.com/",
63
- "https://www.facebook.com/messages/",
64
- "https://www.messenger.com/"
65
- ];
66
-
67
- (async () => {
68
- let lastErr = null;
69
- for (let attempt = 0; attempt < 3; attempt++) {
70
- for (const url of urls) {
71
- try {
72
- const res = await get(url, ctx.jar, null, ctx.globalOptions, { noRef: true });
73
- const html = typeof res === "string" ? res : res && res.data;
74
- const tokens = extractTokens(html);
75
- if (tokens && tokens.fb_dtsg) {
76
- Object.assign(ctx, { fb_dtsg: tokens.fb_dtsg, jazoest: tokens.jazoest });
77
-
78
- try {
79
- const { saveCookies } = require("../../utils/client");
80
- if (res && res.headers) saveCookies(ctx.jar)(res);
81
- } catch (_) {}
82
- callback(null, {
83
- data: { fb_dtsg: tokens.fb_dtsg, jazoest: tokens.jazoest },
84
- message: "Refreshed fb_dtsg and jazoest"
85
- });
86
- return;
87
- }
88
- } catch (e) {
89
- lastErr = e;
90
- logger(
91
- `refreshFb_dtsg attempt ${attempt + 1} ${url}: ${e && e.message ? e.message : e}`,
92
- "warn"
93
- );
94
- }
95
- }
96
- await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
97
- }
98
- const err = lastErr || new Error("Could not find fb_dtsg in HTML after multiple attempts.");
99
- logger(`refreshFb_dtsg failed: ${err.message || err}`, "error");
100
- callback(err);
101
- })();
102
-
103
45
  return returnPromise;
104
46
  };
105
47
  };
@@ -1,4 +1,7 @@
1
-
1
+ /**
2
+ * Modified by Xalman
3
+ * HTTP Get Helper Function with Clean Promise & Callback Handling
4
+ */
2
5
 
3
6
  "use strict";
4
7
 
@@ -15,6 +18,7 @@ const httpGetFactory = function (defaultFuncs, api, ctx) {
15
18
  rejectFunc = reject;
16
19
  });
17
20
 
21
+ // Handle optional 'form' parameter when callback is passed as second argument
18
22
  if (
19
23
  !callback &&
20
24
  (getType(form) === "Function" || getType(form) === "AsyncFunction")
@@ -45,7 +49,7 @@ const httpGetFactory = function (defaultFuncs, api, ctx) {
45
49
  try {
46
50
  data = JSON.stringify(data, null, 2);
47
51
  } catch {
48
-
52
+ // Retain object if stringify fails
49
53
  }
50
54
  }
51
55
  handleCallback(null, data);
@@ -1,4 +1,7 @@
1
-
1
+ /**
2
+ * Modified by Xalman
3
+ * HTTP Post Helper Function with Clean Promise/Callback Handling
4
+ */
2
5
 
3
6
  "use strict";
4
7
 
@@ -15,6 +18,7 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
15
18
  rejectFunc = reject;
16
19
  });
17
20
 
21
+ // Callback parameter handling
18
22
  if (
19
23
  !callback &&
20
24
  (getType(form) === "Function" || getType(form) === "AsyncFunction")
@@ -40,6 +44,7 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
40
44
 
41
45
  const executor = notAPI ? post : (defaultFuncs?.post || post);
42
46
 
47
+ // Dynamic execution
43
48
  executor(url, ctx.jar, form, ctx.globalOptions || {})
44
49
  .then((resData) => {
45
50
  let data = resData?.data ?? resData;
@@ -47,7 +52,7 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
47
52
  try {
48
53
  data = JSON.stringify(data, null, 2);
49
54
  } catch {
50
-
55
+ // retain object if JSON stringify fails
51
56
  }
52
57
  }
53
58
  handleCallback(null, data);
@@ -48,7 +48,7 @@ module.exports = function(defaultFuncs, api, ctx) {
48
48
  fb_api_caller_class: "RelayModern",
49
49
  fb_api_req_friendly_name: "MessengerGroupCreateMutation",
50
50
  av: ctx.i_userID || ctx.userID,
51
-
51
+ //This doc_id is valid as of January 11th, 2020
52
52
  doc_id: "577041672419534",
53
53
  variables: JSON.stringify({
54
54
  input: {
@@ -68,7 +68,7 @@ module.exports = function (defaultFuncs, api, ctx) {
68
68
  try {
69
69
  ctx.mqttClient?.removeListener("message", handleRes);
70
70
  } catch (e) {
71
-
71
+ // ignore
72
72
  }
73
73
  };
74
74
 
@@ -2,6 +2,13 @@
2
2
 
3
3
  const { generateOfflineThreadingID } = require("../../utils/format");
4
4
 
5
+ /**
6
+ * Forward a message to one or multiple threads.
7
+ * @param {string} messageID - The ID of the message to forward.
8
+ * @param {string|string[]} threadID - Thread ID or array of thread IDs to forward to.
9
+ * @param {function} [callback] - Optional callback(err, results).
10
+ * @returns {Promise}
11
+ */
5
12
  module.exports = function (defaultFuncs, api, ctx) {
6
13
  return async function forwardMessage(messageID, threadID, callback) {
7
14
  let resolveFunc, rejectFunc;
@@ -29,6 +36,7 @@ module.exports = function (defaultFuncs, api, ctx) {
29
36
  return returnPromise;
30
37
  }
31
38
 
39
+ // Support forwarding to multiple threads
32
40
  const targets = Array.isArray(threadID) ? threadID : [threadID];
33
41
 
34
42
  const results = [];
@@ -76,7 +84,7 @@ module.exports = function (defaultFuncs, api, ctx) {
76
84
  ctx.mqttClient.publish("/ls_req", JSON.stringify(content), { qos: 1, retain: false });
77
85
  } catch (err) {
78
86
  errors.push({ threadID: tid, error: err.message || String(err) });
79
- return res();
87
+ return res(); // continue to next thread
80
88
  }
81
89
 
82
90
  const timeout = setTimeout(() => {
@@ -4,7 +4,11 @@ const util = require("util");
4
4
 
5
5
  module.exports = function() {
6
6
  return function getEmojiUrl(c, size, pixelRatio) {
7
-
7
+ /*
8
+ Resolves Facebook Messenger emoji image asset URL for an emoji character.
9
+ Supported sizes are 32, 64, and 128.
10
+ Supported pixel ratios are '1.0' and '1.5' (possibly more; haven't tested)
11
+ */
8
12
  const baseUrl = "https://static.xx.fbcdn.net/images/emoji.php/v8/z%s/%s";
9
13
  pixelRatio = pixelRatio || "1.0";
10
14
 
@@ -207,7 +207,9 @@ function formatMessage(threadID, data) {
207
207
  throw new Error(
208
208
  `Unknown message type: "${data.__typename}", if this happens to you let me know when it happens. Please open an issue at https://github.com/ntkhang03/fb-chat-api/issues.`
209
209
  );
210
-
210
+ // If this happens to you let me know when it happens
211
+ // Please open an issue at https://github.com/ntkhang03/fb-chat-api/issues.
212
+ // return Object.assign({ type: "unknown", data });
211
213
  }
212
214
  }
213
215
 
@@ -251,7 +253,7 @@ module.exports = function(defaultFuncs, api, ctx) {
251
253
  av: ctx.globalOptions.pageID,
252
254
  queries: JSON.stringify({
253
255
  o0: {
254
-
256
+ //This doc_id is valid as of ? (prob January 18, 2020)
255
257
  doc_id: "1768656253222505",
256
258
  query_params: {
257
259
  thread_and_message_id: {
@@ -3,6 +3,9 @@
3
3
  const log = require("../../../func/logAdapter");
4
4
  const { parseAndCheckLogin } = require("../../utils/client");
5
5
 
6
+ // api.getThemePictures(themeID, callback?)
7
+ // themeID = the theme_fbid (digits), e.g. from api.getThreadInfo(tid).threadTheme.id
8
+ // or from an api.createThemeAI() result.
6
9
  module.exports = function (defaultFuncs, api, ctx) {
7
10
  return function getThemePictures(id, callback) {
8
11
  let resolveFunc = function () { };
@@ -19,6 +22,8 @@ module.exports = function (defaultFuncs, api, ctx) {
19
22
  };
20
23
  }
21
24
 
25
+ // [Hardened] Accept numbers/bigint too. Previously any non-string id was silently
26
+ // replaced with "" and Facebook answered messenger_thread_theme: null.
22
27
  if (typeof id === "number" || typeof id === "bigint") id = String(id);
23
28
  id = typeof id === "string" ? id.trim() : "";
24
29
 
@@ -47,6 +52,8 @@ module.exports = function (defaultFuncs, api, ctx) {
47
52
  throw resData;
48
53
  }
49
54
 
55
+ // [Hardened] Request worked but Facebook has no theme with this ID for this account.
56
+ // Report as failure instead of a false "success" with null theme.
50
57
  if (!resData || !resData.data || !resData.data.messenger_thread_theme) {
51
58
  const notFound = {
52
59
  error: "Theme not found: Facebook returned no theme for ID " + id + ". Check the ID (use the theme_fbid of a real theme).",
@@ -29,6 +29,7 @@ module.exports = function(defaultFuncs, api, ctx) {
29
29
  form["watermarkTimestamp"] = new Date().getTime();
30
30
  form["shouldSendReadReceipt"] = true;
31
31
  form["commerce_last_message_type"] = "";
32
+ //form["titanOriginatedThreadId"] = utils.generateThreadingID(ctx.clientID);
32
33
 
33
34
  let resData;
34
35
  try {
@@ -2,7 +2,7 @@
2
2
  const log = require("../../../func/logAdapter");
3
3
  const { parseAndCheckLogin, saveCookies } = require("../../utils/client");
4
4
  module.exports = function(defaultFuncs, api, ctx) {
5
-
5
+ // muteSecond: -1=permanent mute, 0=unmute, 60=one minute, 3600=one hour, etc.
6
6
  return function muteThread(threadID, muteSeconds, callback) {
7
7
  let resolveFunc = function() {};
8
8
  let rejectFunc = function() {};
@@ -1,8 +1,16 @@
1
1
  "use strict";
2
2
 
3
+ /**
4
+ * Pin or unpin a message in a thread.
5
+ * @param {string} messageID - The ID of the message to pin/unpin.
6
+ * @param {string} threadID - The thread ID where the message is.
7
+ * @param {boolean} [pin=true] - true to pin, false to unpin.
8
+ * @param {function} [callback] - Optional callback(err, result).
9
+ * @returns {Promise}
10
+ */
3
11
  module.exports = function (defaultFuncs, api, ctx) {
4
12
  return function pinMessage(messageID, threadID, pin, callback) {
5
-
13
+ // Handle optional pin param
6
14
  if (typeof pin === "function") {
7
15
  callback = pin;
8
16
  pin = true;
@@ -37,6 +45,7 @@ module.exports = function (defaultFuncs, api, ctx) {
37
45
  const reqID = ++ctx.wsReqNumber;
38
46
  const taskID = ++ctx.wsTaskNumber;
39
47
 
48
+ // label 682 = pin, label 683 = unpin
40
49
  const label = pin ? "682" : "683";
41
50
 
42
51
  const taskPayload = {
@@ -1,8 +1,12 @@
1
1
  "use strict";
2
2
  const logger = require("../../../func/logger");
3
3
 
4
+ /**
5
+ * Message Scheduler System
6
+ * Allows scheduling messages to be sent at a specific time in the future
7
+ */
4
8
  module.exports = function (defaultFuncs, api, ctx) {
5
-
9
+ // Initialize scheduler on first call
6
10
  if (!ctx._scheduler) {
7
11
  ctx._scheduler = createSchedulerInstance(api);
8
12
  }
@@ -11,12 +15,38 @@ module.exports = function (defaultFuncs, api, ctx) {
11
15
  };
12
16
 
13
17
  function createSchedulerInstance(api) {
14
- const scheduledMessages = new Map();
18
+ const scheduledMessages = new Map(); // Map<id, ScheduledMessage>
15
19
  let nextId = 1;
16
20
 
21
+ /**
22
+ * Scheduled Message Object
23
+ * @typedef {Object} ScheduledMessage
24
+ * @property {string} id - Unique identifier
25
+ * @property {string|Object} message - Message content
26
+ * @property {string|string[]} threadID - Target thread ID(s)
27
+ * @property {number} timestamp - When to send (Unix timestamp in ms)
28
+ * @property {number} createdAt - When scheduled (Unix timestamp in ms)
29
+ * @property {Object} options - Additional options (replyMessageID, isGroup, etc.)
30
+ * @property {Function} callback - Optional callback when sent
31
+ * @property {NodeJS.Timeout} timeout - Timeout reference
32
+ * @property {boolean} cancelled - Whether cancelled
33
+ */
34
+
35
+ /**
36
+ * Schedule a message to be sent at a specific time
37
+ * @param {string|Object} message - Message content
38
+ * @param {string|string[]} threadID - Target thread ID(s)
39
+ * @param {Date|number|string} when - When to send (Date, timestamp, or ISO string)
40
+ * @param {Object} [options] - Additional options
41
+ * @param {string} [options.replyMessageID] - Message ID to reply to
42
+ * @param {boolean} [options.isGroup] - Whether it's a group chat
43
+ * @param {Function} [options.callback] - Callback when sent
44
+ * @returns {string} Scheduled message ID
45
+ */
17
46
  function scheduleMessage(message, threadID, when, options = {}) {
18
47
  let timestamp;
19
48
 
49
+ // Parse when parameter
20
50
  if (when instanceof Date) {
21
51
  timestamp = when.getTime();
22
52
  } else if (typeof when === "number") {
@@ -27,6 +57,7 @@ function createSchedulerInstance(api) {
27
57
  throw new Error("Invalid 'when' parameter. Must be Date, number (timestamp), or ISO string");
28
58
  }
29
59
 
60
+ // Validate timestamp
30
61
  if (isNaN(timestamp)) {
31
62
  throw new Error("Invalid date/time");
32
63
  }
@@ -39,6 +70,7 @@ function createSchedulerInstance(api) {
39
70
  const id = `scheduled_${nextId++}_${Date.now()}`;
40
71
  const delay = timestamp - now;
41
72
 
73
+ // Create scheduled message object
42
74
  const scheduled = {
43
75
  id,
44
76
  message,
@@ -53,12 +85,14 @@ function createSchedulerInstance(api) {
53
85
  cancelled: false
54
86
  };
55
87
 
88
+ // Set timeout to send message
56
89
  scheduled.timeout = setTimeout(() => {
57
90
  if (scheduled.cancelled) return;
58
91
 
59
92
  try {
60
93
  logger(`Sending scheduled message ${id}`, "info");
61
94
 
95
+ // Send message
62
96
  api.sendMessage(
63
97
  message,
64
98
  threadID,
@@ -87,6 +121,11 @@ function createSchedulerInstance(api) {
87
121
  return id;
88
122
  }
89
123
 
124
+ /**
125
+ * Cancel a scheduled message
126
+ * @param {string} id - Scheduled message ID
127
+ * @returns {boolean} True if cancelled, false if not found
128
+ */
90
129
  function cancelScheduledMessage(id) {
91
130
  const scheduled = scheduledMessages.get(id);
92
131
  if (!scheduled) {
@@ -94,7 +133,7 @@ function createSchedulerInstance(api) {
94
133
  }
95
134
 
96
135
  if (scheduled.cancelled) {
97
- return false;
136
+ return false; // Already cancelled
98
137
  }
99
138
 
100
139
  clearTimeout(scheduled.timeout);
@@ -104,12 +143,18 @@ function createSchedulerInstance(api) {
104
143
  return true;
105
144
  }
106
145
 
146
+ /**
147
+ * Get scheduled message info
148
+ * @param {string} id - Scheduled message ID
149
+ * @returns {ScheduledMessage|null} Scheduled message or null if not found
150
+ */
107
151
  function getScheduledMessage(id) {
108
152
  const scheduled = scheduledMessages.get(id);
109
153
  if (!scheduled || scheduled.cancelled) {
110
154
  return null;
111
155
  }
112
156
 
157
+ // Return a copy without internal properties
113
158
  return {
114
159
  id: scheduled.id,
115
160
  message: scheduled.message,
@@ -121,6 +166,10 @@ function createSchedulerInstance(api) {
121
166
  };
122
167
  }
123
168
 
169
+ /**
170
+ * List all scheduled messages
171
+ * @returns {ScheduledMessage[]} Array of scheduled messages
172
+ */
124
173
  function listScheduledMessages() {
125
174
  const now = Date.now();
126
175
  const list = [];
@@ -139,9 +188,14 @@ function createSchedulerInstance(api) {
139
188
  });
140
189
  }
141
190
 
191
+ // Sort by timestamp
142
192
  return list.sort((a, b) => a.timestamp - b.timestamp);
143
193
  }
144
194
 
195
+ /**
196
+ * Cancel all scheduled messages
197
+ * @returns {number} Number of cancelled messages
198
+ */
145
199
  function cancelAllScheduledMessages() {
146
200
  let count = 0;
147
201
  for (const id of scheduledMessages.keys()) {
@@ -153,10 +207,17 @@ function createSchedulerInstance(api) {
153
207
  return count;
154
208
  }
155
209
 
210
+ /**
211
+ * Get count of scheduled messages
212
+ * @returns {number} Count
213
+ */
156
214
  function getScheduledCount() {
157
215
  return scheduledMessages.size;
158
216
  }
159
217
 
218
+ /**
219
+ * Clear expired/cancelled messages from memory
220
+ */
160
221
  function cleanup() {
161
222
  const now = Date.now();
162
223
  let cleaned = 0;
@@ -173,8 +234,13 @@ function createSchedulerInstance(api) {
173
234
  }
174
235
  }
175
236
 
237
+ // Auto cleanup every 5 minutes
176
238
  const cleanupInterval = setInterval(cleanup, 5 * 60 * 1000);
177
239
 
240
+ /**
241
+ * Destroy scheduler and cleanup all resources
242
+ * @returns {number} Number of cancelled messages
243
+ */
178
244
  function destroy() {
179
245
  clearInterval(cleanupInterval);
180
246
  const count = cancelAllScheduledMessages();
@@ -182,6 +248,7 @@ function createSchedulerInstance(api) {
182
248
  return count;
183
249
  }
184
250
 
251
+ // Return scheduler API
185
252
  return {
186
253
  scheduleMessage,
187
254
  cancelScheduledMessage,
@@ -191,7 +258,7 @@ function createSchedulerInstance(api) {
191
258
  getScheduledCount,
192
259
  cleanup,
193
260
  destroy,
194
-
261
+ // Cleanup interval reference for manual cleanup if needed
195
262
  _cleanupInterval: cleanupInterval
196
263
  };
197
264
  }