@cexy/hoonfca 1.0.0 → 1.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 (188) hide show
  1. package/LICENSE +3 -0
  2. package/README.md +451 -43
  3. package/examples/login-with-cookies.js +102 -0
  4. package/examples/verify.js +70 -0
  5. package/index.js +1 -466
  6. package/package.json +98 -6
  7. package/src/apis/addExternalModule.js +24 -0
  8. package/src/apis/addUserToGroup.js +108 -0
  9. package/src/apis/changeAdminStatus.js +148 -0
  10. package/src/apis/changeArchivedStatus.js +61 -0
  11. package/src/apis/changeAvatar.js +103 -0
  12. package/src/apis/changeBio.js +69 -0
  13. package/src/apis/changeBlockedStatus.js +54 -0
  14. package/src/apis/changeGroupImage.js +136 -0
  15. package/src/apis/changeThreadColor.js +116 -0
  16. package/src/{changeThreadEmoji.js → apis/changeThreadEmoji.js} +7 -8
  17. package/src/apis/comment.js +207 -0
  18. package/src/apis/createAITheme.js +129 -0
  19. package/src/apis/createNewGroup.js +79 -0
  20. package/src/apis/createPoll.js +73 -0
  21. package/src/apis/deleteMessage.js +44 -0
  22. package/src/apis/deleteThread.js +52 -0
  23. package/src/apis/e2ee.js +17 -0
  24. package/src/apis/editMessage.js +70 -0
  25. package/src/apis/emoji.js +124 -0
  26. package/src/apis/fetchThemeData.js +82 -0
  27. package/src/apis/follow.js +81 -0
  28. package/src/apis/forwardMessage.js +52 -0
  29. package/src/apis/friend.js +243 -0
  30. package/src/apis/gcmember.js +122 -0
  31. package/src/apis/gcname.js +123 -0
  32. package/src/apis/gcrule.js +119 -0
  33. package/src/apis/getAccess.js +111 -0
  34. package/src/apis/getBotInfo.js +88 -0
  35. package/src/apis/getBotInitialData.js +43 -0
  36. package/src/apis/getFriendsList.js +79 -0
  37. package/src/apis/getMessage.js +423 -0
  38. package/src/apis/getTheme.js +95 -0
  39. package/src/apis/getThemeInfo.js +116 -0
  40. package/src/apis/getThreadHistory.js +239 -0
  41. package/src/apis/getThreadInfo.js +267 -0
  42. package/src/apis/getThreadList.js +232 -0
  43. package/src/apis/getThreadPictures.js +58 -0
  44. package/src/apis/getUserID.js +117 -0
  45. package/src/apis/getUserInfo.js +513 -0
  46. package/src/apis/getUserInfoV2.js +146 -0
  47. package/src/apis/handleMessageRequest.js +50 -0
  48. package/src/apis/httpGet.js +63 -0
  49. package/src/apis/httpPost.js +89 -0
  50. package/src/apis/httpPostFormData.js +69 -0
  51. package/src/apis/listenMqtt.js +1236 -0
  52. package/src/apis/listenSpeed.js +179 -0
  53. package/src/apis/logout.js +87 -0
  54. package/src/apis/markAsDelivered.js +47 -0
  55. package/src/apis/markAsRead.js +99 -0
  56. package/src/apis/markAsReadAll.js +40 -0
  57. package/src/apis/markAsSeen.js +70 -0
  58. package/src/apis/mqttDeltaValue.js +278 -0
  59. package/src/apis/muteThread.js +45 -0
  60. package/src/apis/nickname.js +132 -0
  61. package/src/apis/notes.js +163 -0
  62. package/src/apis/pinMessage.js +150 -0
  63. package/src/apis/produceMetaTheme.js +180 -0
  64. package/src/apis/realtime.js +182 -0
  65. package/src/apis/removeUserFromGroup.js +117 -0
  66. package/src/apis/resolvePhotoUrl.js +58 -0
  67. package/src/apis/searchForThread.js +154 -0
  68. package/src/apis/sendMessage.js +354 -0
  69. package/src/apis/sendMessageMqtt.js +249 -0
  70. package/src/apis/sendTypingIndicator.js +91 -0
  71. package/src/apis/setMessageReaction.js +27 -0
  72. package/src/apis/setMessageReactionMqtt.js +61 -0
  73. package/src/apis/setThreadTheme.js +260 -0
  74. package/src/apis/setThreadThemeMqtt.js +94 -0
  75. package/src/apis/share.js +107 -0
  76. package/src/apis/shareContact.js +66 -0
  77. package/src/apis/stickers.js +257 -0
  78. package/src/apis/story.js +181 -0
  79. package/src/apis/theme.js +233 -0
  80. package/src/apis/unfriend.js +47 -0
  81. package/src/apis/unsendMessage.js +17 -0
  82. package/src/engine/client.js +92 -0
  83. package/src/engine/models/buildAPI.js +152 -0
  84. package/src/engine/models/loginHelper.js +519 -0
  85. package/src/engine/models/setOptions.js +88 -0
  86. package/src/security/e2ee.js +109 -0
  87. package/src/types/index.d.ts +498 -0
  88. package/src/utils/antiSuspension.js +506 -0
  89. package/src/utils/auth-helpers.js +149 -0
  90. package/src/utils/autoReLogin.js +336 -0
  91. package/src/utils/axios.js +436 -0
  92. package/src/utils/cache.js +54 -0
  93. package/src/utils/clients.js +282 -0
  94. package/src/utils/constants.js +410 -0
  95. package/src/utils/formatters/data/formatAttachment.js +370 -0
  96. package/src/utils/formatters/data/formatDelta.js +109 -0
  97. package/src/utils/formatters/index.js +159 -0
  98. package/src/utils/formatters/value/formatCookie.js +91 -0
  99. package/src/utils/formatters/value/formatDate.js +36 -0
  100. package/src/utils/formatters/value/formatID.js +16 -0
  101. package/src/utils/formatters.js +1373 -0
  102. package/src/utils/headers.js +230 -0
  103. package/src/utils/index.js +153 -0
  104. package/src/utils/monitoring.js +333 -0
  105. package/src/utils/rateLimiter.js +319 -0
  106. package/src/utils/tokenRefresh.js +657 -0
  107. package/src/utils/user-agents.js +238 -0
  108. package/src/utils/validation.js +157 -0
  109. package/replit.nix +0 -3
  110. package/src/addExternalModule.js +0 -25
  111. package/src/addUserToGroup.js +0 -98
  112. package/src/changeAdminStatus.js +0 -98
  113. package/src/changeArchivedStatus.js +0 -51
  114. package/src/changeAvatar.js +0 -89
  115. package/src/changeBio.js +0 -74
  116. package/src/changeBlockedStatus.js +0 -45
  117. package/src/changeBlockedStatusMqtt.js +0 -65
  118. package/src/changeCover.js +0 -92
  119. package/src/changeGroupImage.js +0 -110
  120. package/src/changeName.js +0 -106
  121. package/src/changeNickname.js +0 -58
  122. package/src/changeThreadColor.js +0 -62
  123. package/src/changeUsername.js +0 -80
  124. package/src/createCommentPost.js +0 -196
  125. package/src/createNewGroup.js +0 -81
  126. package/src/createPoll.js +0 -64
  127. package/src/createPost.js +0 -285
  128. package/src/data/getThreadInfo.json +0 -1
  129. package/src/deleteMessage.js +0 -55
  130. package/src/deleteThread.js +0 -55
  131. package/src/editMessage.js +0 -66
  132. package/src/follow.js +0 -71
  133. package/src/forwardAttachment.js +0 -57
  134. package/src/getAccess.js +0 -130
  135. package/src/getAvatarUser.js +0 -88
  136. package/src/getBotInitialData.js +0 -59
  137. package/src/getCtx.js +0 -5
  138. package/src/getCurrentUserID.js +0 -5
  139. package/src/getEmojiUrl.js +0 -18
  140. package/src/getFriendsList.js +0 -81
  141. package/src/getMessage.js +0 -827
  142. package/src/getOptions.js +0 -5
  143. package/src/getRegion.js +0 -7
  144. package/src/getThreadHistory.js +0 -496
  145. package/src/getThreadHistoryDeprecated.js +0 -95
  146. package/src/getThreadInfo.js +0 -194
  147. package/src/getThreadInfoDeprecated.js +0 -77
  148. package/src/getThreadList.js +0 -219
  149. package/src/getThreadListDeprecated.js +0 -86
  150. package/src/getThreadPictures.js +0 -85
  151. package/src/getUserID.js +0 -67
  152. package/src/getUserInfo.js +0 -89
  153. package/src/handleFriendRequest.js +0 -56
  154. package/src/handleMessageRequest.js +0 -65
  155. package/src/httpGet.js +0 -53
  156. package/src/httpPost.js +0 -53
  157. package/src/httpPostFormData.js +0 -58
  158. package/src/listenMqtt.js +0 -683
  159. package/src/listenNotification.js +0 -96
  160. package/src/logout.js +0 -77
  161. package/src/markAsDelivered.js +0 -53
  162. package/src/markAsRead.js +0 -74
  163. package/src/markAsReadAll.js +0 -46
  164. package/src/markAsSeen.js +0 -57
  165. package/src/muteThread.js +0 -49
  166. package/src/pinMessage.js +0 -60
  167. package/src/refreshFb_dtsg.js +0 -75
  168. package/src/removeUserFromGroup.js +0 -59
  169. package/src/resolvePhotoUrl.js +0 -47
  170. package/src/searchForThread.js +0 -55
  171. package/src/searchStickers.js +0 -59
  172. package/src/sendMessage.js +0 -444
  173. package/src/sendMessageMqtt.js +0 -326
  174. package/src/sendTypingIndicator.js +0 -54
  175. package/src/setMessageReaction.js +0 -126
  176. package/src/setMessageReactionMqtt.js +0 -74
  177. package/src/setPostReaction.js +0 -103
  178. package/src/setProfileGuard.js +0 -66
  179. package/src/setStoryReaction.js +0 -97
  180. package/src/setTitle.js +0 -100
  181. package/src/shareContact.js +0 -101
  182. package/src/shareLink.js +0 -105
  183. package/src/stopListenMqtt.js +0 -47
  184. package/src/threadColors.js +0 -119
  185. package/src/unfriend.js +0 -58
  186. package/src/unsendMessage.js +0 -51
  187. package/src/uploadAttachment.js +0 -98
  188. package/utils.js +0 -919
@@ -0,0 +1,249 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+ const { globalAntiSuspension } = require('../utils/antiSuspension');
5
+
6
+ module.exports = (defaultFuncs, api, ctx) => {
7
+ function detectAttachmentType(attachment) {
8
+ const p = attachment.path || "";
9
+ const ext = p.toLowerCase().split(".").pop();
10
+ const audio = ["mp3", "wav", "aac", "m4a", "ogg", "opus", "flac"];
11
+ const video = ["mp4", "mov", "avi", "mkv", "webm", "wmv", "flv"];
12
+ const image = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"];
13
+ if (audio.includes(ext)) return { voice_clip: "true" };
14
+ if (video.includes(ext)) return { video: "true" };
15
+ if (image.includes(ext)) return { image: "true" };
16
+ return { file: "true" };
17
+ }
18
+
19
+ async function uploadAttachment(attachments, callback) {
20
+ callback = callback || function () {};
21
+ var uploads = [];
22
+ try {
23
+ for (var i = 0; i < attachments.length; i++) {
24
+ if (!utils.isReadableStream(attachments[i])) {
25
+ throw { error: "Attachment should be a readable stream and not " + utils.getType(attachments[i]) + "." };
26
+ }
27
+
28
+ if (i > 0) {
29
+ await globalAntiSuspension.addSmartDelay();
30
+ }
31
+
32
+ var form = {
33
+ upload_1024: attachments[i],
34
+ ...detectAttachmentType(attachments[i]),
35
+ };
36
+
37
+ const upload = await defaultFuncs
38
+ .postFormData("https://upload.facebook.com/ajax/mercury/upload.php", ctx.jar, form, {}, { ...ctx, requestThreadID: String(ctx._lastThreadHint || "") })
39
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
40
+ .then(resData => {
41
+ if (resData.error) throw resData;
42
+ return resData.payload.metadata[0];
43
+ });
44
+
45
+ uploads.push(upload);
46
+ }
47
+ callback(null, uploads);
48
+ } catch (err) {
49
+ utils.error("uploadAttachment", err);
50
+ return callback(err);
51
+ }
52
+ }
53
+
54
+ function getSendPayload(threadID, msg, otid) {
55
+ const isString = typeof msg === 'string';
56
+ const body = isString ? msg : msg.body || "";
57
+ otid = otid.toString() || utils.generateOfflineThreadingID().toString();
58
+ let payload = {
59
+ thread_id: threadID.toString(),
60
+ otid,
61
+ source: 0,
62
+ send_type: 1,
63
+ sync_group: 1,
64
+ text: body,
65
+ initiating_source: 1,
66
+ skip_url_preview_gen: 0,
67
+ };
68
+ if (typeof msg === 'object') {
69
+ if (msg.sticker) {
70
+ payload.send_type = 2;
71
+ payload.sticker_id = msg.sticker;
72
+ payload.text = null;
73
+ }
74
+ if (msg.attachment) {
75
+ payload.send_type = 3;
76
+ payload.attachment_fbids = Array.isArray(msg.attachment) ? msg.attachment : [msg.attachment];
77
+ }
78
+ }
79
+ return payload;
80
+ }
81
+
82
+ function extractIdsFromPayload(payload) {
83
+ let messageID = null;
84
+ let threadID = null;
85
+ function walk(n) {
86
+ if (Array.isArray(n)) {
87
+ if (n[0] === 5 && (n[1] === "replaceOptimsiticMessage" || n[1] === "replaceOptimisticMessage")) {
88
+ messageID = String(n[3]);
89
+ }
90
+ if (n[0] === 5 && n[1] === "writeCTAIdToThreadsTable") {
91
+ const a = n[2];
92
+ if (Array.isArray(a) && a[0] === 19) threadID = String(a[1]);
93
+ }
94
+ for (const x of n) walk(x);
95
+ }
96
+ }
97
+ walk(payload?.step);
98
+ return { threadID, messageID };
99
+ }
100
+
101
+ function publishWithAck(content, reqID, callback) {
102
+ return new Promise((resolve, reject) => {
103
+ if (!ctx.mqttClient || typeof ctx.mqttClient.on !== "function" || typeof ctx.mqttClient.publish !== "function") {
104
+ const err = new Error("MQTT client is not initialized");
105
+ utils.error("sendMessageMqtt", err);
106
+ callback && callback(err);
107
+ return reject(err);
108
+ }
109
+
110
+ if (typeof ctx.mqttClient.setMaxListeners === "function") {
111
+ ctx.mqttClient.setMaxListeners(0);
112
+ }
113
+
114
+ let done = false;
115
+ const cleanup = () => {
116
+ if (done) return;
117
+ done = true;
118
+ ctx.mqttClient.removeListener("message", handleRes);
119
+ };
120
+ const handleRes = (topic, message) => {
121
+ if (topic !== "/ls_resp") return;
122
+ let jsonMsg;
123
+ try {
124
+ jsonMsg = JSON.parse(message.toString());
125
+ jsonMsg.payload = JSON.parse(jsonMsg.payload);
126
+ } catch {
127
+ return;
128
+ }
129
+ if (jsonMsg.request_id !== reqID) return;
130
+ const { threadID, messageID } = extractIdsFromPayload(jsonMsg.payload);
131
+ const result = { messageID, threadID };
132
+ cleanup();
133
+ callback && callback(undefined, result);
134
+ resolve(result);
135
+ };
136
+ ctx.mqttClient.on("message", handleRes);
137
+ ctx.mqttClient.publish("/ls_req", JSON.stringify(content), { qos: 1, retain: false }, err => {
138
+ if (err) {
139
+ cleanup();
140
+ callback && callback(err);
141
+ reject(err);
142
+ }
143
+ });
144
+ setTimeout(() => {
145
+ if (done) return;
146
+ cleanup();
147
+ const err = { error: "Timeout waiting for ACK" };
148
+ callback && callback(err);
149
+ reject(err);
150
+ }, 15000);
151
+ });
152
+ }
153
+
154
+ return async (msg, threadID, replyToMessage, callback) => {
155
+ if (typeof msg !== 'string' && typeof msg !== 'object') {
156
+ throw new Error("Message should be of type string or object, not " + utils.getType(msg) + ".");
157
+ }
158
+
159
+ if (typeof threadID !== 'string' && typeof threadID !== 'number') {
160
+ throw new Error("threadID must be a string or number.");
161
+ }
162
+
163
+ if (!callback && typeof threadID === "function") {
164
+ throw new Error("Pass a threadID as a second argument.");
165
+ }
166
+
167
+ if (!callback && typeof replyToMessage === "function") {
168
+ callback = replyToMessage;
169
+ replyToMessage = null;
170
+ }
171
+
172
+ // Apply anti-suspension throttling and volume checks before every MQTT send
173
+ try {
174
+ await globalAntiSuspension.prepareBeforeMessage(String(threadID), typeof msg === 'string' ? msg : (msg.body || ''));
175
+ } catch (suspErr) {
176
+ utils.warn("sendMessageMqtt", "Anti-suspension check raised:", suspErr && suspErr.message ? suspErr.message : suspErr);
177
+ }
178
+
179
+ const timestamp = Date.now();
180
+ const otid = utils.generateOfflineThreadingID();
181
+ const epoch_id = utils.generateOfflineThreadingID();
182
+ const payload = getSendPayload(threadID, msg, otid);
183
+
184
+ const tasks = [{
185
+ label: "46",
186
+ payload,
187
+ queue_name: threadID.toString(),
188
+ task_id: 0,
189
+ failure_count: null,
190
+ }, {
191
+ label: "21",
192
+ payload: {
193
+ thread_id: threadID.toString(),
194
+ last_read_watermark_ts: timestamp,
195
+ sync_group: 1,
196
+ },
197
+ queue_name: threadID.toString(),
198
+ task_id: 1,
199
+ failure_count: null,
200
+ }];
201
+
202
+ if (replyToMessage) {
203
+ tasks[0].payload.reply_metadata = {
204
+ reply_source_id: replyToMessage,
205
+ reply_source_type: 1,
206
+ reply_type: 0,
207
+ };
208
+ }
209
+
210
+ const request_id = ++ctx.wsReqNumber;
211
+ const form = {
212
+ app_id: "2220391788200892",
213
+ payload: {
214
+ tasks,
215
+ epoch_id,
216
+ version_id: "6120284488008082",
217
+ data_trace_id: null,
218
+ },
219
+ request_id,
220
+ type: 3,
221
+ };
222
+
223
+ if (msg.attachment) {
224
+ try {
225
+ ctx._lastThreadHint = threadID;
226
+ const files = await new Promise((resolve, reject) => {
227
+ uploadAttachment(
228
+ Array.isArray(msg.attachment) ? msg.attachment : [msg.attachment],
229
+ (err, files) => {
230
+ if (err) return reject(err);
231
+ return resolve(files);
232
+ }
233
+ );
234
+ });
235
+ form.payload.tasks[0].payload.attachment_fbids = files.map(file => Object.values(file)[0]);
236
+ } catch (err) {
237
+ utils.error("Attachment upload failed:", err);
238
+ throw err;
239
+ }
240
+ }
241
+
242
+ form.payload.tasks.forEach(task => {
243
+ task.payload = JSON.stringify(task.payload);
244
+ });
245
+ form.payload = JSON.stringify(form.payload);
246
+
247
+ return publishWithAck(form, request_id, callback);
248
+ };
249
+ };
@@ -0,0 +1,91 @@
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
+ * Thread-type cache so we only look up group status once per thread.
13
+ * Shared with sendMessage via ctx.threadTypeCache.
14
+ */
15
+ function getThreadCache() {
16
+ if (!ctx.threadTypeCache) ctx.threadTypeCache = Object.create(null);
17
+ return ctx.threadTypeCache;
18
+ }
19
+
20
+ /**
21
+ * Reliably determines whether a thread is a group by querying the API
22
+ * and caching the result. Falls back to string-length heuristic only on error.
23
+ */
24
+ async function isGroupThread(threadID) {
25
+ const tid = threadID.toString();
26
+ const cache = getThreadCache();
27
+ if (Object.prototype.hasOwnProperty.call(cache, tid)) return !!cache[tid];
28
+ try {
29
+ const info = await api.getThreadInfo(tid);
30
+ cache[tid] = !!info.isGroup;
31
+ return !!info.isGroup;
32
+ } catch (_) {
33
+ const fallback = tid.length >= 16;
34
+ cache[tid] = fallback;
35
+ return fallback;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Sends a typing indicator to a specific thread.
41
+ * @param {boolean} sendTyping - True to show typing indicator, false to hide.
42
+ * @param {string} threadID - The ID of the thread to send the typing indicator to.
43
+ * @param {Function} [callback] - An optional callback function.
44
+ * @returns {Promise<void>}
45
+ */
46
+ return async function sendTypingIndicatorV2(sendTyping, threadID, callback) {
47
+ if (!ctx.mqttClient) {
48
+ const err = new Error("You can only use sendTypingIndicator after you start listening.");
49
+ if (callback) callback(err);
50
+ else throw err;
51
+ return;
52
+ }
53
+
54
+ let count_req = 0;
55
+
56
+ let isGroup;
57
+ try {
58
+ isGroup = await isGroupThread(threadID);
59
+ } catch (_) {
60
+ isGroup = threadID.toString().length >= 16;
61
+ }
62
+
63
+ const wsContent = {
64
+ app_id: 2220391788200892,
65
+ payload: JSON.stringify({
66
+ label: 3,
67
+ payload: JSON.stringify({
68
+ thread_key: threadID.toString(),
69
+ is_group_thread: +isGroup,
70
+ is_typing: +sendTyping,
71
+ attribution: 0
72
+ }),
73
+ version: 5849951561777440
74
+ }),
75
+ request_id: ++count_req,
76
+ type: 4
77
+ };
78
+
79
+ // Wrap publish in a timeout so a stale MQTT connection never hangs this call.
80
+ await new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => reject(new Error("sendTypingIndicator: MQTT publish timed out")), 8000);
82
+ ctx.mqttClient.publish('/ls_req', JSON.stringify(wsContent), {}, (err, _packet) => {
83
+ clearTimeout(timer);
84
+ if (err) reject(err);
85
+ else resolve();
86
+ });
87
+ });
88
+
89
+ if (callback) callback();
90
+ };
91
+ };
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+
5
+
6
+ module.exports = function (defaultFuncs, api, ctx) {
7
+ return async (reaction, messageID) => {
8
+ if (!reaction) throw new Error("Please enter a valid emoji.");
9
+ const defData = await defaultFuncs.postFormData("https://www.facebook.com/webgraphql/mutation/", ctx.jar, {}, {
10
+ doc_id: "1491398900900362",
11
+ variables: JSON.stringify({
12
+ data: {
13
+ client_mutation_id: ctx.clientMutationId++,
14
+ actor_id: ctx.userID,
15
+ action: reaction == "" ? "REMOVE_REACTION" : "ADD_REACTION",
16
+ message_id: messageID,
17
+ reaction
18
+ }
19
+ }),
20
+ dpr: 1
21
+ });
22
+ const resData = await utils.parseAndCheckLogin(ctx, defaultFuncs)(defData);
23
+ if (!resData) {
24
+ throw new Error("setMessageReactionLegacy returned empty object.");
25
+ }
26
+ };
27
+ };
@@ -0,0 +1,61 @@
1
+
2
+ 'use strict';
3
+
4
+ const utils = require('../utils');
5
+
6
+ function isCallable(func) {
7
+   try {
8
+     Reflect.apply(func, null, []);
9
+     return true;
10
+   } catch (error) {
11
+     return false;
12
+   }
13
+ }
14
+
15
+ module.exports = function (defaultFuncs, api, ctx) {
16
+   return function setMessageReactionMqtt(reaction, messageID, threadID) {
17
+     if (!ctx.mqttClient) {
18
+       throw new Error('Not connected to MQTT');
19
+     }
20
+
21
+     ctx.wsReqNumber += 1;
22
+     ctx.wsTaskNumber += 1;
23
+
24
+     const taskPayload = {
25
+       thread_key: threadID,
26
+       timestamp_ms: Date.now(),
27
+       message_id: messageID,
28
+       reaction,
29
+       actor_id: ctx.userID,
30
+       reaction_style: null,
31
+       sync_group: 1,
32
+       send_attribution: Math.random() < 0.5 ? 65537 : 524289
33
+     };
34
+
35
+     const task = {
36
+       failure_count: null,
37
+       label: '29',
38
+       payload: JSON.stringify(taskPayload),
39
+       queue_name: JSON.stringify(['reaction', messageID]),
40
+       task_id: ctx.wsTaskNumber
41
+     };
42
+
43
+     const content = {
44
+       app_id: '2220391788200892',
45
+       payload: JSON.stringify({
46
+         data_trace_id: null,
47
+         epoch_id: parseInt(utils.generateOfflineThreadingID()),
48
+         tasks: [task],
49
+         version_id: '7158486590867448',
50
+       }),
51
+       request_id: ctx.wsReqNumber,
52
+       type: 3,
53
+     };
54
+
55
+     /*if (isCallable(callback)) {
56
+       ctx.reqCallbacks[ctx.wsReqNumber] = callback;
57
+     }*/
58
+
59
+     ctx.mqttClient.publish('/ls_req', JSON.stringify(content), { qos: 1, retain: false });
60
+   };
61
+ };
@@ -0,0 +1,260 @@
1
+ "use strict";
2
+
3
+ const utils = require("../utils");
4
+ const log = require("npmlog");
5
+
6
+ module.exports = function (defaultFuncs, api, ctx) {
7
+ return function setThreadTheme(threadID, themeData, callback) {
8
+ let resolveFunc, rejectFunc;
9
+ const promise = new Promise((resolve, reject) => {
10
+ resolveFunc = resolve;
11
+ rejectFunc = reject;
12
+ });
13
+
14
+ if (!callback) {
15
+ callback = function (err, data) {
16
+ if (err) return rejectFunc(err);
17
+ resolveFunc(data);
18
+ };
19
+ }
20
+
21
+ if (!threadID) {
22
+ return callback({ error: "threadID is required" });
23
+ }
24
+
25
+ (async function worker() {
26
+ try {
27
+ const now = Date.now();
28
+
29
+ // Try to fetch bootloader
30
+ try {
31
+ const bootParams = new URLSearchParams({
32
+ modules: "LSUpdateThreadTheme,LSUpdateThreadCustomEmoji,LSUpdateThreadThemePayloadCacheKey",
33
+ __aaid: 0,
34
+ __user: ctx.userID,
35
+ __a: 1,
36
+ __req: utils.getSignatureID(),
37
+ __hs: "20352.HYP:comet_pkg.2.1...0",
38
+ dpr: 1,
39
+ __ccg: "EXCELLENT",
40
+ __rev: "1027396270",
41
+ __s: utils.getSignatureID(),
42
+ __hsi: "7552524636527201016",
43
+ __comet_req: 15,
44
+ fb_dtsg_ag: ctx.fb_dtsg,
45
+ jazoest: ctx.jazoest,
46
+ __spin_r: "1027396270",
47
+ __spin_b: "trunk",
48
+ __spin_t: now,
49
+ __crn: "comet.fbweb.MWInboxHomeRoute"
50
+ });
51
+
52
+ await defaultFuncs.get(
53
+ "https://www.facebook.com/ajax/bootloader-endpoint/?" + bootParams.toString(),
54
+ ctx.jar
55
+ ).then(utils.parseAndCheckLogin(ctx, defaultFuncs));
56
+ } catch (bootErr) {
57
+ log.warn("setThreadTheme", "bootloader fetch failed, continuing");
58
+ }
59
+
60
+ let availableThemes = [];
61
+ try {
62
+ const themeQueryForm = {
63
+ av: ctx.userID,
64
+ __aaid: 0,
65
+ __user: ctx.userID,
66
+ __a: 1,
67
+ __req: utils.getSignatureID(),
68
+ __hs: "20352.HYP:comet_pkg.2.1...0",
69
+ dpr: 1,
70
+ __ccg: "EXCELLENT",
71
+ __rev: "1027396270",
72
+ __s: utils.getSignatureID(),
73
+ __hsi: "7552524636527201016",
74
+ __comet_req: 15,
75
+ fb_dtsg: ctx.fb_dtsg,
76
+ jazoest: ctx.jazoest,
77
+ lsd: ctx.fb_dtsg,
78
+ __spin_r: "1027396270",
79
+ __spin_b: "trunk",
80
+ __spin_t: now,
81
+ __crn: "comet.fbweb.MWInboxHomeRoute",
82
+ qpl_active_flow_ids: "25308101",
83
+ fb_api_caller_class: "RelayModern",
84
+ fb_api_req_friendly_name: "MWPThreadThemeQuery_AllThemesQuery",
85
+ variables: JSON.stringify({ version: "default" }),
86
+ server_timestamps: true,
87
+ doc_id: "24474714052117636"
88
+ };
89
+
90
+ const themeRes = await defaultFuncs
91
+ .post("https://www.facebook.com/api/graphql/", ctx.jar, themeQueryForm)
92
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
93
+
94
+ if (themeRes && themeRes.data && themeRes.data.messenger_thread_themes) {
95
+ availableThemes = themeRes.data.messenger_thread_themes;
96
+ }
97
+ } catch (fetchErr) {
98
+ log.warn("setThreadTheme", "Could not fetch available themes, proceeding without list");
99
+ }
100
+
101
+ let chosenThemeId = null;
102
+ let chosenEmoji = "👍";
103
+
104
+ if (typeof themeData === "string") {
105
+ const s = themeData.trim();
106
+
107
+ if (/^[0-9]+$/.test(s)) {
108
+ chosenThemeId = s;
109
+ } else {
110
+ const found = (availableThemes || []).find(function (t) {
111
+ return (
112
+ t.accessibility_label &&
113
+ t.accessibility_label.toLowerCase().includes(s.toLowerCase())
114
+ );
115
+ });
116
+ if (found) {
117
+ chosenThemeId = found.id;
118
+ } else {
119
+ const palette = {
120
+ blue: "196241301102133",
121
+ purple: "370940413392601",
122
+ green: "169463077092846",
123
+ pink: "230032715012014",
124
+ orange: "175615189761153",
125
+ red: "2136751179887052",
126
+ yellow: "2058653964378557",
127
+ teal: "417639218648241",
128
+ black: "539927563794799",
129
+ white: "2873642392710980",
130
+ default: "196241301102133"
131
+ };
132
+ chosenThemeId = palette[s.toLowerCase()] || palette.default;
133
+ }
134
+ }
135
+ } else if (typeof themeData === "object" && themeData !== null) {
136
+ chosenThemeId = themeData.themeId || themeData.theme_id || themeData.id || null;
137
+ chosenEmoji = themeData.emoji || themeData.customEmoji || chosenEmoji;
138
+ }
139
+
140
+ if (!chosenThemeId) {
141
+ chosenThemeId = "196241301102133";
142
+ }
143
+
144
+ // Try legacy approach first
145
+ try {
146
+ const legacyBody = {
147
+ dpr: 1,
148
+ queries: JSON.stringify({
149
+ o0: {
150
+ doc_id: "1727493033983591",
151
+ query_params: {
152
+ data: {
153
+ actor_id: ctx.userID,
154
+ client_mutation_id: "0",
155
+ source: "SETTINGS",
156
+ theme_id: chosenThemeId,
157
+ thread_id: threadID
158
+ }
159
+ }
160
+ }
161
+ })
162
+ };
163
+
164
+ const legacyResp = await defaultFuncs
165
+ .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, legacyBody)
166
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
167
+
168
+ if (legacyResp && !legacyResp[0]?.o0?.errors) {
169
+ return callback(null, {
170
+ threadID: threadID,
171
+ themeId: chosenThemeId,
172
+ customEmoji: chosenEmoji,
173
+ timestamp: now,
174
+ success: true,
175
+ method: "legacy",
176
+ availableThemes: availableThemes.length > 0
177
+ ? availableThemes.map(function (t) {
178
+ return { id: t.id, name: t.accessibility_label, description: t.description };
179
+ })
180
+ : null
181
+ });
182
+ }
183
+ } catch (legacyErr) {
184
+ log.warn("setThreadTheme", "Legacy approach failed; falling back to GraphQL mutation");
185
+ }
186
+
187
+ // Fall back to GraphQL mutation
188
+ const mutationBody = {
189
+ av: ctx.userID,
190
+ __aaid: 0,
191
+ __user: ctx.userID,
192
+ __a: 1,
193
+ __req: utils.getSignatureID(),
194
+ __hs: "20352.HYP:comet_pkg.2.1...0",
195
+ dpr: 1,
196
+ __ccg: "EXCELLENT",
197
+ __rev: "1027396270",
198
+ __s: utils.getSignatureID(),
199
+ __hsi: "7552524636527201016",
200
+ __comet_req: 15,
201
+ fb_dtsg: ctx.fb_dtsg,
202
+ jazoest: ctx.jazoest,
203
+ lsd: ctx.fb_dtsg,
204
+ __spin_r: "1027396270",
205
+ __spin_b: "trunk",
206
+ __spin_t: now,
207
+ __crn: "comet.fbweb.MWInboxHomeRoute",
208
+ fb_api_caller_class: "RelayModern",
209
+ fb_api_req_friendly_name: "MessengerThreadThemeUpdateMutation",
210
+ variables: JSON.stringify({
211
+ input: {
212
+ actor_id: ctx.userID,
213
+ client_mutation_id: Math.floor(Math.random() * 10000).toString(),
214
+ source: "SETTINGS",
215
+ thread_id: threadID.toString(),
216
+ theme_id: chosenThemeId.toString(),
217
+ custom_emoji: chosenEmoji
218
+ }
219
+ }),
220
+ server_timestamps: true,
221
+ doc_id: "9734829906576883"
222
+ };
223
+
224
+ const gqlResult = await defaultFuncs
225
+ .post("https://www.facebook.com/api/graphql/", ctx.jar, mutationBody)
226
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs));
227
+
228
+ if (gqlResult && gqlResult.errors && gqlResult.errors.length > 0) {
229
+ throw new Error("GraphQL Error: " + JSON.stringify(gqlResult.errors));
230
+ }
231
+
232
+ if (gqlResult && gqlResult.data && gqlResult.data.messenger_thread_theme_update) {
233
+ const updatePayload = gqlResult.data.messenger_thread_theme_update;
234
+ if (updatePayload.errors && updatePayload.errors.length > 0) {
235
+ throw new Error("Theme Update Error: " + JSON.stringify(updatePayload.errors));
236
+ }
237
+ }
238
+
239
+ return callback(null, {
240
+ threadID: threadID,
241
+ themeId: chosenThemeId,
242
+ customEmoji: chosenEmoji,
243
+ timestamp: now,
244
+ success: true,
245
+ method: "graphql",
246
+ availableThemes: availableThemes.length > 0
247
+ ? availableThemes.map(function (t) {
248
+ return { id: t.id, name: t.accessibility_label, description: t.description };
249
+ })
250
+ : null
251
+ });
252
+ } catch (err) {
253
+ log.error("setThreadTheme", err);
254
+ return callback(err);
255
+ }
256
+ })();
257
+
258
+ return promise;
259
+ };
260
+ };