@cexy/hoonfca 1.0.1 → 1.0.2

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 (170) hide show
  1. package/.travis.yml +6 -0
  2. package/LICENSE-MIT +21 -0
  3. package/index.d.ts +620 -0
  4. package/index.js +778 -1
  5. package/package.json +31 -84
  6. package/src/{apis/addExternalModule.js → addExternalModule.js} +4 -5
  7. package/src/addUserToGroup.js +113 -0
  8. package/src/changeAdminStatus.js +95 -0
  9. package/src/changeApprovalMode.js +79 -0
  10. package/src/changeArchivedStatus.js +55 -0
  11. package/src/changeBio.js +76 -0
  12. package/src/changeBlockedStatus.js +47 -0
  13. package/src/changeBlockedStatusMqtt.js +86 -0
  14. package/src/changeGroupImage.js +133 -0
  15. package/src/changeNickname.js +59 -0
  16. package/src/changeThreadColor.js +71 -0
  17. package/src/{apis/changeThreadEmoji.js → changeThreadEmoji.js} +8 -6
  18. package/src/createNewGroup.js +88 -0
  19. package/src/createPoll.js +130 -0
  20. package/src/deleteMessage.js +56 -0
  21. package/src/deleteThread.js +56 -0
  22. package/src/editMessage.js +63 -0
  23. package/src/forwardAttachment.js +60 -0
  24. package/src/forwardMessage.js +63 -0
  25. package/src/getCurrentUserID.js +7 -0
  26. package/src/getEmojiUrl.js +29 -0
  27. package/src/getFriendsList.js +84 -0
  28. package/src/getGroupsList.js +83 -0
  29. package/src/getMarketplace.js +84 -0
  30. package/src/getNotifications.js +86 -0
  31. package/src/getPagesList.js +83 -0
  32. package/src/getStories.js +88 -0
  33. package/src/getThreadHistory.js +647 -0
  34. package/src/getThreadInfo.js +222 -0
  35. package/src/getThreadList.js +292 -0
  36. package/src/getThreadPictures.js +79 -0
  37. package/src/getUserID.js +66 -0
  38. package/src/getUserInfo.js +128 -0
  39. package/src/handleFriendRequest.js +57 -0
  40. package/src/handleMessageRequest.js +65 -0
  41. package/src/{apis/httpGet.js → httpGet.js} +15 -20
  42. package/src/httpPost.js +58 -0
  43. package/src/listenMqtt.js +1018 -0
  44. package/src/logout.js +75 -0
  45. package/src/markAsDelivered.js +58 -0
  46. package/src/{apis/markAsRead.js → markAsRead.js} +19 -30
  47. package/src/markAsReadAll.js +50 -0
  48. package/src/markAsSeen.js +61 -0
  49. package/src/muteThread.js +52 -0
  50. package/src/pinMessage.js +61 -0
  51. package/src/removeUserFromGroup.js +79 -0
  52. package/src/resolvePhotoUrl.js +45 -0
  53. package/src/searchForThread.js +53 -0
  54. package/src/searchUsers.js +89 -0
  55. package/src/sendComment.js +161 -0
  56. package/src/sendMessage.js +457 -0
  57. package/src/sendTypingIndicator.js +179 -0
  58. package/src/setBio.js +86 -0
  59. package/src/setMessageReaction.js +186 -0
  60. package/src/setPostReaction.js +71 -0
  61. package/src/setTheme.js +313 -0
  62. package/src/setTitle.js +90 -0
  63. package/src/shareContact.js +53 -0
  64. package/src/shareLink.js +62 -0
  65. package/src/threadColors.js +57 -0
  66. package/src/unfriend.js +53 -0
  67. package/src/unsendMessage.js +104 -0
  68. package/utils.js +1447 -0
  69. package/LICENSE +0 -3
  70. package/README.md +0 -491
  71. package/examples/login-with-cookies.js +0 -102
  72. package/examples/verify.js +0 -70
  73. package/src/apis/addUserToGroup.js +0 -108
  74. package/src/apis/changeAdminStatus.js +0 -148
  75. package/src/apis/changeArchivedStatus.js +0 -61
  76. package/src/apis/changeAvatar.js +0 -103
  77. package/src/apis/changeBio.js +0 -69
  78. package/src/apis/changeBlockedStatus.js +0 -54
  79. package/src/apis/changeGroupImage.js +0 -136
  80. package/src/apis/changeThreadColor.js +0 -116
  81. package/src/apis/comment.js +0 -207
  82. package/src/apis/createAITheme.js +0 -129
  83. package/src/apis/createNewGroup.js +0 -79
  84. package/src/apis/createPoll.js +0 -73
  85. package/src/apis/deleteMessage.js +0 -44
  86. package/src/apis/deleteThread.js +0 -52
  87. package/src/apis/e2ee.js +0 -17
  88. package/src/apis/editMessage.js +0 -70
  89. package/src/apis/emoji.js +0 -124
  90. package/src/apis/fetchThemeData.js +0 -82
  91. package/src/apis/follow.js +0 -81
  92. package/src/apis/forwardMessage.js +0 -52
  93. package/src/apis/friend.js +0 -243
  94. package/src/apis/gcmember.js +0 -122
  95. package/src/apis/gcname.js +0 -123
  96. package/src/apis/gcrule.js +0 -119
  97. package/src/apis/getAccess.js +0 -111
  98. package/src/apis/getBotInfo.js +0 -88
  99. package/src/apis/getBotInitialData.js +0 -43
  100. package/src/apis/getFriendsList.js +0 -79
  101. package/src/apis/getMessage.js +0 -423
  102. package/src/apis/getTheme.js +0 -95
  103. package/src/apis/getThemeInfo.js +0 -116
  104. package/src/apis/getThreadHistory.js +0 -239
  105. package/src/apis/getThreadInfo.js +0 -267
  106. package/src/apis/getThreadList.js +0 -232
  107. package/src/apis/getThreadPictures.js +0 -58
  108. package/src/apis/getUserID.js +0 -117
  109. package/src/apis/getUserInfo.js +0 -513
  110. package/src/apis/getUserInfoV2.js +0 -146
  111. package/src/apis/handleMessageRequest.js +0 -50
  112. package/src/apis/httpPost.js +0 -89
  113. package/src/apis/httpPostFormData.js +0 -69
  114. package/src/apis/listenMqtt.js +0 -1236
  115. package/src/apis/listenSpeed.js +0 -179
  116. package/src/apis/logout.js +0 -87
  117. package/src/apis/markAsDelivered.js +0 -47
  118. package/src/apis/markAsReadAll.js +0 -40
  119. package/src/apis/markAsSeen.js +0 -70
  120. package/src/apis/mqttDeltaValue.js +0 -278
  121. package/src/apis/muteThread.js +0 -45
  122. package/src/apis/nickname.js +0 -132
  123. package/src/apis/notes.js +0 -163
  124. package/src/apis/pinMessage.js +0 -150
  125. package/src/apis/produceMetaTheme.js +0 -180
  126. package/src/apis/realtime.js +0 -182
  127. package/src/apis/removeUserFromGroup.js +0 -117
  128. package/src/apis/resolvePhotoUrl.js +0 -58
  129. package/src/apis/searchForThread.js +0 -154
  130. package/src/apis/sendMessage.js +0 -354
  131. package/src/apis/sendMessageMqtt.js +0 -249
  132. package/src/apis/sendTypingIndicator.js +0 -91
  133. package/src/apis/setMessageReaction.js +0 -27
  134. package/src/apis/setMessageReactionMqtt.js +0 -61
  135. package/src/apis/setThreadTheme.js +0 -260
  136. package/src/apis/setThreadThemeMqtt.js +0 -94
  137. package/src/apis/share.js +0 -107
  138. package/src/apis/shareContact.js +0 -66
  139. package/src/apis/stickers.js +0 -257
  140. package/src/apis/story.js +0 -181
  141. package/src/apis/theme.js +0 -233
  142. package/src/apis/unfriend.js +0 -47
  143. package/src/apis/unsendMessage.js +0 -17
  144. package/src/engine/client.js +0 -92
  145. package/src/engine/models/buildAPI.js +0 -152
  146. package/src/engine/models/loginHelper.js +0 -519
  147. package/src/engine/models/setOptions.js +0 -88
  148. package/src/security/e2ee.js +0 -109
  149. package/src/types/index.d.ts +0 -498
  150. package/src/utils/antiSuspension.js +0 -506
  151. package/src/utils/auth-helpers.js +0 -149
  152. package/src/utils/autoReLogin.js +0 -336
  153. package/src/utils/axios.js +0 -436
  154. package/src/utils/cache.js +0 -54
  155. package/src/utils/clients.js +0 -282
  156. package/src/utils/constants.js +0 -410
  157. package/src/utils/formatters/data/formatAttachment.js +0 -370
  158. package/src/utils/formatters/data/formatDelta.js +0 -109
  159. package/src/utils/formatters/index.js +0 -159
  160. package/src/utils/formatters/value/formatCookie.js +0 -91
  161. package/src/utils/formatters/value/formatDate.js +0 -36
  162. package/src/utils/formatters/value/formatID.js +0 -16
  163. package/src/utils/formatters.js +0 -1373
  164. package/src/utils/headers.js +0 -230
  165. package/src/utils/index.js +0 -153
  166. package/src/utils/monitoring.js +0 -333
  167. package/src/utils/rateLimiter.js +0 -319
  168. package/src/utils/tokenRefresh.js +0 -657
  169. package/src/utils/user-agents.js +0 -238
  170. package/src/utils/validation.js +0 -157
@@ -1,249 +0,0 @@
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
- };
@@ -1,91 +0,0 @@
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
- };
@@ -1,27 +0,0 @@
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
- };
@@ -1,61 +0,0 @@
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
- };
@@ -1,260 +0,0 @@
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
- };