@cexy/hoonfca 1.0.7 → 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 -233
  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
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+ const mqtt = require('mqtt');
5
+ const websocket = require('websocket-stream');
6
+ const HttpsProxyAgent = require('https-proxy-agent');
7
+ const EventEmitter = require('events');
8
+
9
+ function connectLightspeed(ctx, globalCallback) {
10
+ let client;
11
+ let isStopped = false;
12
+ const guard = (label, fn) => (...args) => {
13
+ try {
14
+ return fn(...args);
15
+ } catch (err) {
16
+ utils.error(`[Lightspeed] ${label} handler error:`, err && err.message ? err.message : err);
17
+ }
18
+ };
19
+
20
+ function startConnection(retryCount = 0) {
21
+ if (isStopped) return;
22
+
23
+ const chatOn = ctx.globalOptions.online;
24
+ const foreground = false;
25
+ const sessionID = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER) + 1;
26
+ const cookies = ctx.jar.getCookiesSync('https://www.facebook.com').join('; ');
27
+ const cid = ctx.clientID;
28
+
29
+ const username = {
30
+ u: ctx.userID,
31
+ s: sessionID,
32
+ chat_on: chatOn,
33
+ fg: foreground,
34
+ d: cid,
35
+ ct: 'websocket',
36
+ aid: '2220391788200892',
37
+ mqtt_sid: '',
38
+ cp: 3,
39
+ ecp: 10,
40
+ st: [],
41
+ pm: [],
42
+ dc: '',
43
+ no_auto_fg: true,
44
+ gas: null,
45
+ pack: [],
46
+ a: ctx.globalOptions.userAgent,
47
+ };
48
+
49
+ const queryParams = new URLSearchParams({
50
+ 'x-dgw-appid': '2220391788200892',
51
+ 'x-dgw-appversion': '0',
52
+ 'x-dgw-authtype': '1:0',
53
+ 'x-dgw-version': '5',
54
+ 'x-dgw-uuid': ctx.userID,
55
+ 'x-dgw-tier': 'prod',
56
+ 'x-dgw-loggingid': utils.getGUID(),
57
+ 'x-dgw-regionhint': ctx.region || 'PRN',
58
+ 'x-dgw-deviceid': ctx.clientID
59
+ });
60
+ const host = `wss://gateway.facebook.com/ws/lightspeed?${queryParams.toString()}`;
61
+
62
+ // Generate a unique clientId per session, just like a real browser would
63
+ const lsClientId = 'mqttwsclient_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
64
+ const options = {
65
+ clientId: lsClientId,
66
+ protocolId: 'MQIsdp',
67
+ protocolVersion: 3,
68
+ username: JSON.stringify(username),
69
+ clean: true,
70
+ wsOptions: {
71
+ headers: {
72
+ 'Cookie': cookies,
73
+ 'Origin': 'https://www.facebook.com',
74
+ 'User-Agent': username.a,
75
+ 'Referer': 'https://www.facebook.com/',
76
+ 'Host': new URL(host).hostname
77
+ }
78
+ },
79
+ keepalive: 60, // 60s is standard; 10s was too aggressive (sent PING every 10 seconds)
80
+ reconnectPeriod: 0
81
+ };
82
+
83
+ if (ctx.globalOptions.proxy) {
84
+ options.wsOptions.agent = new HttpsProxyAgent(ctx.globalOptions.proxy);
85
+ }
86
+
87
+ try {
88
+ client = new mqtt.Client(_ => websocket(host, options.wsOptions), options);
89
+ utils.log("[Lightspeed] Attempting MQTT connection...");
90
+ } catch (err) {
91
+ utils.error("[Lightspeed] MQTT Client creation failed:", err.message);
92
+ reconnect(retryCount + 1);
93
+ return;
94
+ }
95
+
96
+ client.on('connect', guard("connect", () => {
97
+ utils.log("[Lightspeed] MQTT client connected. Attempting to subscribe to topics...");
98
+ retryCount = 0;
99
+
100
+
101
+ const topicsToSubscribe = [
102
+ "/t_ms", // Para sa mga messages at deltas
103
+ "/orca_presence", // Para sa online status
104
+ "/messaging_events" // Para sa ibang events
105
+ ];
106
+
107
+ topicsToSubscribe.forEach(topic => {
108
+ client.subscribe(topic, (err) => {
109
+ if (err) {
110
+ utils.error(`[Lightspeed] Failed to subscribe to topic ${topic}:`, err.message);
111
+ } else {
112
+ utils.log(`[Lightspeed] Subscribed to topic: ${topic}`);
113
+ }
114
+ });
115
+ });
116
+
117
+ }));
118
+
119
+ client.on('message', guard("message", (topic, payload) => {
120
+ utils.log(`[Lightspeed] Payload Received on topic ${topic}:`);
121
+ globalCallback(null, { type: 'lightspeed_message', topic: topic.toString(), payload: payload });
122
+ }));
123
+
124
+ client.on('close', guard("close", () => {
125
+ utils.warn(`[Lightspeed] Connection closed.`);
126
+ if (!isStopped) {
127
+ reconnect(retryCount + 1);
128
+ }
129
+ }));
130
+
131
+ client.on('error', guard("error", (err) => {
132
+ utils.error("[Lightspeed] MQTT Connection Error:", err.message);
133
+ }));
134
+ }
135
+
136
+ function reconnect(retryCount) {
137
+ const delay = Math.min(3000 * Math.pow(2, retryCount), 60000);
138
+ utils.log(`[Lightspeed] Reconnecting in ${delay / 1000} seconds...`);
139
+ setTimeout(() => startConnection(retryCount), delay);
140
+ }
141
+
142
+ startConnection();
143
+
144
+ return {
145
+ stop: () => {
146
+ isStopped = true;
147
+ if (client) client.end(true);
148
+ utils.log("[Lightspeed] Listener has been manually stopped.");
149
+ }
150
+ };
151
+ }
152
+
153
+ module.exports = function (defaultFuncs, api, ctx) {
154
+ return (callback) => {
155
+ class MessageEmitter extends EventEmitter {
156
+ constructor() {
157
+ super();
158
+ this.listener = null;
159
+ }
160
+ stop() {
161
+ if (this.listener) {
162
+ this.listener.stop();
163
+ }
164
+ this.emit('stop');
165
+ }
166
+ }
167
+ const msgEmitter = new MessageEmitter();
168
+ const globalCallback = (error, message) => {
169
+ if (error) return msgEmitter.emit("error", error);
170
+ msgEmitter.emit("message", message);
171
+ };
172
+ if (typeof callback === 'function') {
173
+ msgEmitter.listener = connectLightspeed(ctx, callback);
174
+ } else {
175
+ msgEmitter.listener = connectLightspeed(ctx, globalCallback);
176
+ }
177
+ return msgEmitter;
178
+ };
179
+ };
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+
5
+ /**
6
+ * @param {Object} defaultFuncs
7
+ * @param {Object} api
8
+ * @param {Object} ctx
9
+ * @returns {function(): Promise<void>}
10
+ */
11
+ module.exports = function (defaultFuncs, api, ctx) {
12
+ /**
13
+ * Logs the current user out of Facebook.
14
+ * @returns {Promise<void>} A promise that resolves when logout is successful or rejects on error.
15
+ */
16
+ return async function logout() {
17
+ const form = {
18
+ pmid: "0",
19
+ };
20
+
21
+ try {
22
+ const resData = await defaultFuncs
23
+ .post(
24
+ "https://www.facebook.com/bluebar/modern_settings_menu/?help_type=364455653583099&show_contextual_help=1",
25
+ ctx.jar,
26
+ form,
27
+ )
28
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
29
+
30
+ const elem = resData.jsmods.instances[0][2][0].find(v => v.value === "logout");
31
+ if (!elem) {
32
+ throw { error: "Could not find logout form element." };
33
+ }
34
+
35
+ const html = resData.jsmods.markup.find(v => v[0] === elem.markup.__m)[1].__html;
36
+
37
+ const logoutForm = {
38
+ fb_dtsg: utils.getFrom(html, '"fb_dtsg" value="', '"'),
39
+ ref: utils.getFrom(html, '"ref" value="', '"'),
40
+ h: utils.getFrom(html, '"h" value="', '"'),
41
+ };
42
+
43
+ const logoutRes = await defaultFuncs
44
+ .post("https://www.facebook.com/logout.php", ctx.jar, logoutForm)
45
+ .then(utils.saveCookies(ctx.jar));
46
+
47
+ if (!logoutRes.headers || !logoutRes.headers.location) {
48
+ throw { error: "An error occurred when logging out." };
49
+ }
50
+
51
+ await defaultFuncs
52
+ .get(logoutRes.headers.location, ctx.jar)
53
+ .then(utils.saveCookies(ctx.jar));
54
+
55
+ ctx.loggedIn = false;
56
+
57
+ // Clear sensitive session tokens so stale credentials cannot be reused
58
+ // if this ctx object is accidentally referenced again after logout.
59
+ ctx.fb_dtsg = undefined;
60
+ ctx.fb_dtsg_ag = undefined;
61
+ ctx.lsd = undefined;
62
+ ctx.access_token = undefined;
63
+
64
+ // Stop background timers that are owned by this session, if present.
65
+ if (typeof ctx._stopTokenRefresh === 'function') {
66
+ try { ctx._stopTokenRefresh(); } catch (_) {}
67
+ }
68
+ if (typeof ctx._stopAutoReLogin === 'function') {
69
+ try { ctx._stopAutoReLogin(); } catch (_) {}
70
+ }
71
+ if (typeof ctx._stopCookieBackup === 'function') {
72
+ try { ctx._stopCookieBackup(); } catch (_) {}
73
+ }
74
+
75
+ // Invalidate the response cache so nothing stale is served after logout.
76
+ if (ctx.cache && typeof ctx.cache.clear === 'function') {
77
+ ctx.cache.clear();
78
+ }
79
+
80
+ utils.log("logout", "Logged out successfully.");
81
+
82
+ } catch (err) {
83
+ utils.error("logout", err);
84
+ throw err;
85
+ }
86
+ };
87
+ };
@@ -0,0 +1,47 @@
1
+
2
+ "use strict";
3
+
4
+ const utils = require('../utils');
5
+ /**
6
+ * @param {Object} defaultFuncs
7
+ * @param {Object} api
8
+ * @param {Object} ctx
9
+ * @returns {function(threadID: string, messageID: string): Promise<void>}
10
+ */
11
+ module.exports = function (defaultFuncs, api, ctx) {
12
+ /**
13
+ * Marks a message as delivered.
14
+ * @param {string} threadID - The ID of the thread.
15
+ * @param {string} messageID - The ID of the message to mark as delivered.
16
+ * @returns {Promise<void>} A promise that resolves on success or rejects on error.
17
+ */
18
+ return async function markAsDelivered(threadID, messageID) {
19
+ if (!threadID || !messageID) {
20
+ const err = "Error: messageID or threadID is not defined";
21
+ utils.error("markAsDelivered", err);
22
+ throw new Error(err);
23
+ }
24
+
25
+ const form = {};
26
+ form["message_ids[0]"] = messageID;
27
+ form["thread_ids[" + threadID + "][0]"] = messageID;
28
+
29
+ try {
30
+ const resData = await defaultFuncs
31
+ .post(
32
+ "https://www.facebook.com/ajax/mercury/delivery_receipts.php",
33
+ ctx.jar,
34
+ form,
35
+ )
36
+ .then(utils.saveCookies(ctx.jar))
37
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
38
+
39
+ if (resData.error) {
40
+ throw resData;
41
+ }
42
+ } catch (err) {
43
+ utils.error("markAsDelivered", err);
44
+ throw err;
45
+ }
46
+ };
47
+ };
@@ -1,88 +1,99 @@
1
- "use strict";
2
-
3
- const log = require("npmlog");
4
- const { parseAndCheckLogin, saveCookies } = require("../../utils/client");
5
- const { getType } = require("../../utils/format");
6
- module.exports = function(defaultFuncs, api, ctx) {
7
- return async function markAsRead(threadID, read, callback) {
8
- if (
9
- getType(read) === "Function" ||
10
- getType(read) === "AsyncFunction"
11
- ) {
12
- callback = read;
13
- read = true;
14
- }
15
- if (read == undefined) {
16
- read = true;
17
- }
18
-
19
- if (!callback) {
20
- callback = () => {};
21
- }
22
-
23
- const form = {};
24
-
25
- if (typeof ctx.globalOptions.pageID !== "undefined") {
26
- form["source"] = "PagesManagerMessagesInterface";
27
- form["request_user_id"] = ctx.globalOptions.pageID;
28
- form["ids[" + threadID + "]"] = read;
29
- form["watermarkTimestamp"] = new Date().getTime();
30
- form["shouldSendReadReceipt"] = true;
31
- form["commerce_last_message_type"] = "";
32
- //form["titanOriginatedThreadId"] = utils.generateThreadingID(ctx.clientID);
33
-
34
- let resData;
35
- try {
36
- resData = await defaultFuncs
37
- .post(
38
- "https://www.facebook.com/ajax/mercury/change_read_status.php",
39
- ctx.jar,
40
- form
41
- )
42
- .then(saveCookies(ctx.jar))
43
- .then(parseAndCheckLogin(ctx, defaultFuncs));
44
- } catch (e) {
45
- callback(e);
46
- return e;
47
- }
48
-
49
- if (resData.error) {
50
- const err = resData.error;
51
- log.error("markAsRead", err);
52
- if (getType(err) == "Object" && err.error === "Not logged in.") {
53
- ctx.loggedIn = false;
54
- }
55
- callback(err);
56
- return err;
57
- }
58
-
59
- callback();
60
- return null;
61
- } else {
62
- try {
63
- if (ctx.mqttClient) {
64
- const err = await new Promise(r =>
65
- ctx.mqttClient.publish(
66
- "/mark_thread",
67
- JSON.stringify({
68
- threadID,
69
- mark: "read",
70
- state: read
71
- }),
72
- { qos: 1, retain: false },
73
- r
74
- )
75
- );
76
- if (err) throw err;
77
- } else {
78
- throw {
79
- error: "You can only use this function after you start listening."
80
- };
81
- }
82
- } catch (e) {
83
- callback(e);
84
- return e;
85
- }
86
- }
87
- };
88
- };
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+
5
+ /**
6
+ * @param {Object} defaultFuncs
7
+ * @param {Object} api
8
+ * @param {Object} ctx
9
+ */
10
+ module.exports = function (defaultFuncs, api, ctx) {
11
+ /**
12
+ * Marks a thread as read.
13
+ * @param {string} threadID - The ID of the thread to mark as read.
14
+ * @param {boolean} [read=true] - Whether to mark as read (true) or unread (false). Defaults to true.
15
+ * @param {Function} [callback] - The callback function.
16
+ * @returns {Promise<null|Error>} A Promise that resolves with null on success, or rejects with an Error.
17
+ */
18
+ return async function markAsRead(threadID, read, callback) {
19
+ if (
20
+ utils.getType(read) === "Function" ||
21
+ utils.getType(read) === "AsyncFunction"
22
+ ) {
23
+ callback = read;
24
+ read = true;
25
+ }
26
+ if (read == undefined) {
27
+ read = true;
28
+ }
29
+
30
+ if (!callback) {
31
+ callback = () => {};
32
+ }
33
+
34
+ const form = {};
35
+
36
+ if (typeof ctx.globalOptions.pageID !== "undefined") {
37
+ form["source"] = "PagesManagerMessagesInterface";
38
+ form["request_user_id"] = ctx.globalOptions.pageID;
39
+ form["ids[" + threadID + "]"] = read;
40
+ form["watermarkTimestamp"] = new Date().getTime();
41
+ form["shouldSendReadReceipt"] = true;
42
+ form["commerce_last_message_type"] = "";
43
+
44
+ let resData;
45
+ try {
46
+ resData = await defaultFuncs
47
+ .post(
48
+ "https://www.facebook.com/ajax/mercury/change_read_status.php",
49
+ ctx.jar,
50
+ form,
51
+ )
52
+ .then(utils.saveCookies(ctx.jar))
53
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
54
+ } catch (e) {
55
+ callback(e);
56
+ return e;
57
+ }
58
+
59
+ if (resData.error) {
60
+ const err = resData.error;
61
+ utils.error("markAsRead", err);
62
+ callback(err);
63
+ return err;
64
+ }
65
+
66
+ callback();
67
+ return null;
68
+ } else {
69
+ try {
70
+ if (ctx.mqttClient) {
71
+ await new Promise((resolve, reject) => {
72
+ // Guard against a disconnected MQTT client hanging forever.
73
+ const timer = setTimeout(
74
+ () => reject(new Error("markAsRead: MQTT publish timed out after 8s")),
75
+ 8000
76
+ );
77
+ ctx.mqttClient.publish(
78
+ "/mark_thread",
79
+ JSON.stringify({ threadID, mark: "read", state: read }),
80
+ { qos: 1, retain: false },
81
+ (err, _packet) => {
82
+ clearTimeout(timer);
83
+ if (err) reject(err);
84
+ else resolve();
85
+ }
86
+ );
87
+ });
88
+ } else {
89
+ throw {
90
+ error: "You can only use this function after you start listening.",
91
+ };
92
+ }
93
+ } catch (e) {
94
+ callback(e);
95
+ return e;
96
+ }
97
+ }
98
+ };
99
+ };
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+
5
+
6
+ /**
7
+ * @param {Object} defaultFuncs
8
+ * @param {Object} api
9
+ * @param {Object} ctx
10
+ * @returns {function(): Promise<void>}
11
+ */
12
+ module.exports = function (defaultFuncs, api, ctx) {
13
+ /**
14
+ * @returns {Promise<void>}
15
+ */
16
+ return async function markAsReadAll() {
17
+ const form = {
18
+ folder: "inbox",
19
+ };
20
+
21
+ try {
22
+ const parsedData = await defaultFuncs
23
+ .post(
24
+ "https://www.facebook.com/ajax/mercury/mark_folder_as_read.php",
25
+ ctx.jar,
26
+ form
27
+ )
28
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
29
+
30
+ if (parsedData.error) {
31
+ throw parsedData;
32
+ }
33
+
34
+ return;
35
+ } catch (err) {
36
+ utils.error("markAsReadAll", err);
37
+ throw err;
38
+ }
39
+ };
40
+ };
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+
5
+ /**
6
+ * @param {Object} defaultFuncs
7
+ * @param {Object} api
8
+ * @param {Object} ctx
9
+ */
10
+ module.exports = function (defaultFuncs, api, ctx) {
11
+ /**
12
+ * Marks all messages as "seen" up to a specific timestamp.
13
+ * @param {number} [seen_timestamp=Date.now()] - The timestamp (in milliseconds) up to which messages should be marked as seen. If a function is provided, it's treated as the callback and the timestamp defaults to the current time.
14
+ * @param {Function} [callback] - The callback function.
15
+ * @returns {Promise<void>} A Promise that resolves on success or rejects with an error.
16
+ */
17
+ return async function markAsSeen(seen_timestamp, callback) {
18
+ let resolveFunc = function () {};
19
+ let rejectFunc = function () {};
20
+ const returnPromise = new Promise(function (resolve, reject) {
21
+ resolveFunc = resolve;
22
+ rejectFunc = reject;
23
+ });
24
+
25
+ if (utils.getType(seen_timestamp) == "Function" || utils.getType(seen_timestamp) == "AsyncFunction") {
26
+ callback = seen_timestamp;
27
+ seen_timestamp = Date.now();
28
+ } else if (seen_timestamp === undefined) {
29
+ seen_timestamp = Date.now();
30
+ }
31
+
32
+ if (!callback) {
33
+ callback = function (err, friendList) {
34
+ if (err) {
35
+ return rejectFunc(err);
36
+ }
37
+ resolveFunc(friendList);
38
+ };
39
+ }
40
+
41
+ const form = {
42
+ seen_timestamp: seen_timestamp,
43
+ };
44
+
45
+ try {
46
+ const resData = await defaultFuncs
47
+ .post(
48
+ "https://www.facebook.com/ajax/mercury/mark_seen.php",
49
+ ctx.jar,
50
+ form,
51
+ )
52
+ .then(utils.saveCookies(ctx.jar))
53
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
54
+
55
+ if (resData.error) {
56
+ throw resData;
57
+ }
58
+
59
+ return callback();
60
+ } catch (err) {
61
+ utils.error("markAsSeen", err);
62
+ if (utils.getType(err) == "Object" && err.error === "Not logged in.") {
63
+ ctx.loggedIn = false;
64
+ }
65
+ return callback(err);
66
+ }
67
+
68
+ return returnPromise;
69
+ };
70
+ };