@cexy/hoonfca 1.0.7 → 2.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 (191) hide show
  1. package/LICENSE +3 -0
  2. package/README.md +100 -632
  3. package/examples/login-with-cookies.js +102 -0
  4. package/examples/verify.js +70 -0
  5. package/index.js +2 -8
  6. package/package.json +83 -61
  7. package/src/{api/action → apis}/addExternalModule.js +24 -25
  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/apis/changeThreadEmoji.js +53 -0
  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/{api/users → apis}/getUserInfoV2.js +146 -134
  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/{api/messaging → apis}/markAsRead.js +99 -88
  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 -23
  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 +214 -99
  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/CHANGELOG.md +0 -181
  110. package/DOCS.md +0 -2636
  111. package/LICENSE-MIT +0 -21
  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,154 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+
5
+ module.exports = (defaultFuncs, api, ctx) => {
6
+ return async function searchForThread(searchQuery, callback) {
7
+ let resolveFunc = () => {};
8
+ let rejectFunc = () => {};
9
+ const returnPromise = new Promise((resolve, reject) => {
10
+ resolveFunc = resolve;
11
+ rejectFunc = reject;
12
+ });
13
+
14
+ // Store original callback if provided
15
+ const originalCallback = callback;
16
+
17
+ // Always use a wrapped callback that settles the promise
18
+ callback = (err, result) => {
19
+ if (originalCallback) {
20
+ originalCallback(err, result);
21
+ }
22
+ if (err) return rejectFunc(err);
23
+ resolveFunc(result);
24
+ };
25
+
26
+ if (!searchQuery || typeof searchQuery !== 'string') {
27
+ const error = { error: "searchForThread: searchQuery parameter must be a non-empty string" };
28
+ utils.error("searchForThread", error);
29
+ callback(error);
30
+ return returnPromise;
31
+ }
32
+
33
+ try {
34
+ // Strategy 1: Use GraphQL-based getThreadList and filter locally
35
+ // This bypasses checkpoint issues entirely
36
+ utils.log("searchForThread", "Using GraphQL-based search (bypasses checkpoints)");
37
+
38
+ try {
39
+ // Use getThreadList to fetch threads from INBOX
40
+ // This ensures consistent behavior and avoids tag parameter issues
41
+ const threads = await api.getThreadList(100, null, ["INBOX"]);
42
+
43
+ if (!threads || threads.length === 0) {
44
+ utils.warn("searchForThread", "No threads available in INBOX, trying legacy method");
45
+ throw new Error("No threads available from GraphQL");
46
+ }
47
+
48
+ utils.log("searchForThread", `Retrieved ${threads.length} threads from GraphQL`);
49
+
50
+ // Filter threads by search query (case-insensitive, partial match)
51
+ const searchLower = searchQuery.toLowerCase().trim();
52
+ const matchedThreads = threads.filter(thread => {
53
+ // Search in thread name
54
+ if (thread.threadName && thread.threadName.toLowerCase().includes(searchLower)) {
55
+ return true;
56
+ }
57
+
58
+ // Search in thread ID (exact or partial match)
59
+ if (thread.threadID && thread.threadID.toString().includes(searchQuery)) {
60
+ return true;
61
+ }
62
+
63
+ // Search in participant names
64
+ if (thread.userInfo && Array.isArray(thread.userInfo)) {
65
+ return thread.userInfo.some(user =>
66
+ user.name && user.name.toLowerCase().includes(searchLower)
67
+ );
68
+ }
69
+
70
+ return false;
71
+ });
72
+
73
+ if (matchedThreads.length === 0) {
74
+ callback({
75
+ error: `Could not find thread matching "${searchQuery}".`,
76
+ details: "No threads match your search query. Try a different search term."
77
+ });
78
+ return returnPromise;
79
+ }
80
+
81
+ utils.log("searchForThread", `Found ${matchedThreads.length} matching thread(s) using GraphQL method`);
82
+ callback(null, matchedThreads);
83
+ return returnPromise;
84
+
85
+ } catch (graphqlError) {
86
+ utils.warn("searchForThread", "GraphQL method failed, falling back to legacy AJAX endpoint");
87
+ utils.error("searchForThread GraphQL error", graphqlError);
88
+
89
+ // Strategy 2: Fallback to legacy AJAX endpoint (may trigger checkpoints)
90
+ const form = {
91
+ client: "web_messenger",
92
+ query: searchQuery,
93
+ offset: 0,
94
+ limit: 21,
95
+ index: "fbid"
96
+ };
97
+
98
+ const res = await defaultFuncs.post(
99
+ "https://www.facebook.com/ajax/mercury/search_threads.php",
100
+ ctx.jar,
101
+ form
102
+ ).then(utils.parseAndCheckLogin(ctx, defaultFuncs));
103
+
104
+ if (!res) {
105
+ const error = {
106
+ error: "Account checkpoint required - searchForThread is restricted until verification",
107
+ details: "Please verify your account on facebook.com. This function requires additional permissions.",
108
+ errorCode: 1357004,
109
+ errorType: 'CHECKPOINT'
110
+ };
111
+ callback(error);
112
+ return returnPromise;
113
+ }
114
+
115
+ if (res.error) {
116
+ throw res;
117
+ }
118
+
119
+ // Support both legacy payload.threads (object map) and newer payload.mercury_payload.threads (array)
120
+ let threadsData = res.payload?.mercury_payload?.threads || res.payload?.threads;
121
+
122
+ if (!threadsData) {
123
+ callback({
124
+ error: `Could not find thread "${searchQuery}".`,
125
+ details: "The thread may not exist or access may be restricted."
126
+ });
127
+ return returnPromise;
128
+ }
129
+
130
+ // Convert legacy object format to array if needed
131
+ if (!Array.isArray(threadsData)) {
132
+ threadsData = Object.values(threadsData);
133
+ }
134
+
135
+ const threads = threadsData.map(utils.formatThread);
136
+ utils.log("searchForThread", `Found ${threads.length} thread(s) using legacy AJAX method`);
137
+ callback(null, threads);
138
+ }
139
+ } catch (err) {
140
+ // Enhanced error handling for checkpoint errors
141
+ if (err.errorCode === 1357004 || err.errorType === 'CHECKPOINT') {
142
+ err.error = "Account checkpoint required - searchForThread is restricted until verification";
143
+ err.friendlyMessage = "Your account requires verification on facebook.com before using search features";
144
+ } else if (err.error && typeof err.error === 'string' && err.error.includes('checkpoint')) {
145
+ err.friendlyMessage = "Account checkpoint required - searchForThread is restricted until verification";
146
+ }
147
+
148
+ utils.error("searchForThread", err);
149
+ callback(err);
150
+ }
151
+
152
+ return returnPromise;
153
+ };
154
+ };
@@ -0,0 +1,354 @@
1
+ "use strict";
2
+
3
+ const utils = require('../utils');
4
+ const e2ee = require('../security/e2ee');
5
+ const { globalAntiSuspension } = require('../utils/antiSuspension');
6
+
7
+ const allowedProperties = {
8
+ attachment: true,
9
+ url: true,
10
+ sticker: true,
11
+ emoji: true,
12
+ emojiSize: true,
13
+ body: true,
14
+ mentions: true,
15
+ location: true,
16
+ };
17
+
18
+ module.exports = (defaultFuncs, api, ctx) => {
19
+ function getThreadCache() {
20
+ if (!ctx.threadTypeCache) ctx.threadTypeCache = Object.create(null);
21
+ return ctx.threadTypeCache;
22
+ }
23
+
24
+ async function isGroupThread(threadID, explicitIsGroup) {
25
+ if (utils.getType(explicitIsGroup) === "Boolean") return !!explicitIsGroup;
26
+ const tid = threadID.toString();
27
+ const cache = getThreadCache();
28
+ if (Object.prototype.hasOwnProperty.call(cache, tid)) return !!cache[tid];
29
+ try {
30
+ const info = await api.getThreadInfo(tid);
31
+ cache[tid] = !!info.isGroup;
32
+ return !!info.isGroup;
33
+ } catch (_) {
34
+ const fallback = tid.length >= 16;
35
+ cache[tid] = fallback;
36
+ return fallback;
37
+ }
38
+ }
39
+
40
+ function detectAttachmentType(attachment) {
41
+ const path = attachment.path || '';
42
+ const ext = path.toLowerCase().split('.').pop();
43
+
44
+ const audioTypes = ['mp3', 'wav', 'aac', 'm4a', 'ogg', 'opus', 'flac'];
45
+ const videoTypes = ['mp4', 'mov', 'avi', 'mkv', 'webm', 'wmv', 'flv'];
46
+ const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
47
+
48
+ if (audioTypes.includes(ext)) return { voice_clip: "true" };
49
+ if (videoTypes.includes(ext)) return { video: "true" };
50
+ if (imageTypes.includes(ext)) return { image: "true" };
51
+ return { file: "true" };
52
+ }
53
+
54
+ async function uploadSingleAttachment(attachment, threadIDHint) {
55
+ if (!utils.isReadableStream(attachment)) {
56
+ throw new Error("Attachment should be a readable stream and not " + utils.getType(attachment) + ".");
57
+ }
58
+ const uploadType = detectAttachmentType(attachment);
59
+ const oksir = await defaultFuncs.postFormData(
60
+ "https://upload.facebook.com/ajax/mercury/upload.php",
61
+ ctx.jar,
62
+ { upload_1024: attachment, ...uploadType },
63
+ {},
64
+ { ...ctx, requestThreadID: threadIDHint }
65
+ ).then(utils.parseAndCheckLogin(ctx, defaultFuncs));
66
+
67
+ if (oksir.error) throw new Error(JSON.stringify(oksir));
68
+ return oksir.payload.metadata[0];
69
+ }
70
+
71
+ async function uploadAttachment(attachments, threadIDHint) {
72
+ const CONCURRENT_UPLOADS = 3;
73
+ const uploads = [];
74
+ for (let i = 0; i < attachments.length; i += CONCURRENT_UPLOADS) {
75
+ const batch = attachments.slice(i, i + CONCURRENT_UPLOADS);
76
+ const results = await Promise.all(batch.map(a => uploadSingleAttachment(a, threadIDHint)));
77
+ uploads.push(...results);
78
+ if (i + CONCURRENT_UPLOADS < attachments.length) {
79
+ await globalAntiSuspension.addSmartDelay();
80
+ }
81
+ }
82
+ return uploads;
83
+ }
84
+
85
+ async function getUrl(url) {
86
+ const resData = await defaultFuncs.post(
87
+ "https://www.facebook.com/message_share_attachment/fromURI/",
88
+ ctx.jar,
89
+ { image_height: 960, image_width: 960, uri: url }
90
+ ).then(utils.parseAndCheckLogin(ctx, defaultFuncs));
91
+ if (!resData || resData.error || !resData.payload) throw new Error("Invalid url");
92
+ return resData.payload.share_data.share_params;
93
+ }
94
+
95
+ async function sendContent(form, threadID, isSingleUser, messageAndOTID) {
96
+ if (utils.getType(threadID) === "Array") {
97
+ for (let i = 0; i < threadID.length; i++) {
98
+ form["specific_to_list[" + i + "]"] = "fbid:" + threadID[i];
99
+ }
100
+ form["specific_to_list[" + threadID.length + "]"] = "fbid:" + ctx.userID;
101
+ form["client_thread_id"] = "root:" + messageAndOTID;
102
+ utils.log("sendMessage", "Sending message to multiple users: " + threadID);
103
+ } else {
104
+ if (isSingleUser) {
105
+ form["specific_to_list[0]"] = "fbid:" + threadID;
106
+ form["specific_to_list[1]"] = "fbid:" + ctx.userID;
107
+ form["other_user_fbid"] = threadID;
108
+ form["client_thread_id"] = "root:" + messageAndOTID;
109
+ } else {
110
+ form["thread_fbid"] = threadID;
111
+ }
112
+ }
113
+
114
+ if (ctx.globalOptions.pageID) {
115
+ form["author"] = "fbid:" + ctx.globalOptions.pageID;
116
+ form["specific_to_list[1]"] = "fbid:" + ctx.globalOptions.pageID;
117
+ form["creator_info[creatorID]"] = ctx.userID;
118
+ form["creator_info[creatorType]"] = "direct_admin";
119
+ form["creator_info[labelType]"] = "sent_message";
120
+ form["creator_info[pageID]"] = ctx.globalOptions.pageID;
121
+ form["request_user_id"] = ctx.globalOptions.pageID;
122
+ form["creator_info[profileURI]"] = "https://www.facebook.com/profile.php?id=" + ctx.userID;
123
+ }
124
+
125
+ const resData = await defaultFuncs.post(
126
+ "https://www.facebook.com/messaging/send/",
127
+ ctx.jar,
128
+ form,
129
+ { ...ctx, requestThreadID: threadID }
130
+ ).then(utils.parseAndCheckLogin(ctx, defaultFuncs));
131
+
132
+ if (!resData) throw new Error("Send message failed.");
133
+ if (resData.error) {
134
+ if (resData.error === 1545012) {
135
+ utils.warn("sendMessage", "Got error 1545012. This might mean that you're not part of the conversation " + threadID);
136
+ }
137
+ // Check for suspension signals in error
138
+ globalAntiSuspension.detectSuspensionSignal(String(resData.error) + ' ' + JSON.stringify(resData));
139
+ throw new Error(JSON.stringify(resData));
140
+ }
141
+
142
+ const messageInfo = resData.payload.actions.reduce((p, v) => {
143
+ return { threadID: v.thread_fbid, messageID: v.message_id, timestamp: v.timestamp } || p;
144
+ }, null);
145
+ return messageInfo;
146
+ }
147
+
148
+ return async (msg, threadID, callback, replyToMessage, isGroup) => {
149
+ if (!callback && (utils.getType(threadID) === "Function" || utils.getType(threadID) === "AsyncFunction")) {
150
+ throw new Error("Pass a threadID as a second argument.");
151
+ }
152
+ if (!replyToMessage && utils.getType(callback) === "String") {
153
+ replyToMessage = callback;
154
+ callback = undefined;
155
+ }
156
+
157
+ let resolveFunc = () => {};
158
+ let rejectFunc = () => {};
159
+ let returnPromise = new Promise((resolve, reject) => {
160
+ resolveFunc = resolve;
161
+ rejectFunc = reject;
162
+ });
163
+
164
+ if (!callback) {
165
+ callback = (err, data) => {
166
+ if (err) return rejectFunc(err);
167
+ resolveFunc(data);
168
+ };
169
+ }
170
+
171
+ let msgType = utils.getType(msg);
172
+ let threadIDType = utils.getType(threadID);
173
+ let messageIDType = utils.getType(replyToMessage);
174
+
175
+ if (msgType !== "String" && msgType !== "Object") {
176
+ return callback(new Error("Message should be of type string or object and not " + msgType + "."));
177
+ }
178
+ if (threadIDType !== "Array" && threadIDType !== "Number" && threadIDType !== "String") {
179
+ return callback(new Error("ThreadID should be of type number, string, or array and not " + threadIDType + "."));
180
+ }
181
+ if (replyToMessage && messageIDType !== 'String') {
182
+ return callback(new Error("MessageID should be of type string and not " + messageIDType + "."));
183
+ }
184
+
185
+ if (!ctx.validator.isValidMessage(msg)) {
186
+ return callback(new Error("Invalid message content"));
187
+ }
188
+ const threadIDs = Array.isArray(threadID) ? threadID : [threadID];
189
+ if (!ctx.validator.validateIDArray(threadIDs, ctx.validator.isValidThreadID)) {
190
+ return callback(new Error("Invalid thread ID(s)"));
191
+ }
192
+
193
+ if (msgType === "String") msg = { body: msg };
194
+
195
+ let disallowedProperties = Object.keys(msg).filter(prop => !allowedProperties[prop]);
196
+ if (disallowedProperties.length > 0) {
197
+ return callback(new Error("Dissallowed props: `" + disallowedProperties.join(", ") + "`"));
198
+ }
199
+
200
+ try {
201
+ let messageAndOTID = utils.generateOfflineThreadingID();
202
+ let form = {
203
+ client: "mercury",
204
+ action_type: "ma-type:user-generated-message",
205
+ author: "fbid:" + ctx.userID,
206
+ timestamp: Date.now(),
207
+ timestamp_absolute: "Today",
208
+ timestamp_relative: utils.generateTimestampRelative(),
209
+ timestamp_time_passed: "0",
210
+ is_unread: false,
211
+ is_cleared: false,
212
+ is_forward: false,
213
+ is_filtered_content: false,
214
+ is_filtered_content_bh: false,
215
+ is_filtered_content_account: false,
216
+ is_filtered_content_quasar: false,
217
+ is_filtered_content_invalid_app: false,
218
+ is_spoof_warning: false,
219
+ source: "source:chat:web",
220
+ "source_tags[0]": "source:chat",
221
+ ...(msg.body && { body: msg.body }),
222
+ html_body: false,
223
+ ui_push_phase: "V3",
224
+ status: "0",
225
+ offline_threading_id: messageAndOTID,
226
+ message_id: messageAndOTID,
227
+ threading_id: utils.generateThreadingID(ctx.clientID),
228
+ "ephemeral_ttl_mode:": "0",
229
+ manual_retry_cnt: "0",
230
+ has_attachment: !!(msg.attachment || msg.url || msg.sticker),
231
+ signatureID: utils.getSignatureID(),
232
+ ...(replyToMessage && { replied_to_message_id: replyToMessage })
233
+ };
234
+
235
+ if (msg.location) {
236
+ if (!msg.location.latitude || !msg.location.longitude) {
237
+ return callback(new Error("location property needs both latitude and longitude"));
238
+ }
239
+ form["location_attachment[coordinates][latitude]"] = msg.location.latitude;
240
+ form["location_attachment[coordinates][longitude]"] = msg.location.longitude;
241
+ form["location_attachment[is_current_location]"] = !!msg.location.current;
242
+ }
243
+ if (msg.sticker) form["sticker_id"] = msg.sticker;
244
+ if (msg.attachment) {
245
+ form.image_ids = [];
246
+ form.gif_ids = [];
247
+ form.file_ids = [];
248
+ form.video_ids = [];
249
+ form.audio_ids = [];
250
+ if (utils.getType(msg.attachment) !== "Array") msg.attachment = [msg.attachment];
251
+ const files = await uploadAttachment(msg.attachment, threadID);
252
+ files.forEach(file => {
253
+ const type = Object.keys(file)[0];
254
+ form["" + type + "s"].push(file[type]);
255
+ });
256
+ }
257
+ if (msg.url) {
258
+ form["shareable_attachment[share_type]"] = "100";
259
+ const params = await getUrl(msg.url);
260
+ form["shareable_attachment[share_params]"] = params;
261
+ }
262
+ if (msg.emoji) {
263
+ if (!msg.emojiSize) msg.emojiSize = "medium";
264
+ if (msg.emojiSize !== "small" && msg.emojiSize !== "medium" && msg.emojiSize !== "large") {
265
+ return callback(new Error("emojiSize property is invalid"));
266
+ }
267
+ if (form.body && form.body !== "") return callback(new Error("body is not empty"));
268
+ form.body = msg.emoji;
269
+ form["tags[0]"] = "hot_emoji_size:" + msg.emojiSize;
270
+ }
271
+ if (msg.mentions) {
272
+ for (let i = 0; i < msg.mentions.length; i++) {
273
+ const mention = msg.mentions[i];
274
+ const tag = mention.tag;
275
+ if (typeof tag !== "string") return callback(new Error("Mention tags must be strings."));
276
+ const offset = msg.body.indexOf(tag, mention.fromIndex || 0);
277
+ if (offset < 0) utils.warn("handleMention", 'Mention for "' + tag + '" not found in message string.');
278
+ if (!mention.id) utils.warn("handleMention", "Mention id should be non-null.");
279
+ const id = mention.id || 0;
280
+ const emptyChar = '\u200E';
281
+ form["body"] = emptyChar + msg.body;
282
+ form["profile_xmd[" + i + "][offset]"] = offset + 1;
283
+ form["profile_xmd[" + i + "][length]"] = tag.length;
284
+ form["profile_xmd[" + i + "][id]"] = id;
285
+ form["profile_xmd[" + i + "][type]"] = "p";
286
+ }
287
+ }
288
+
289
+ const isSingleUser = !(await isGroupThread(threadID, isGroup));
290
+
291
+ // Late E2EE encryption for plain text only
292
+ try {
293
+ const isPlainText = !!form.body && !msg.mentions && !msg.sticker && !msg.emoji && !msg.url && !msg.attachment;
294
+ if (isPlainText && e2ee.isEnabled(ctx) && e2ee.hasPeer(ctx, threadID) && !isSingleUser) {
295
+ form.body = e2ee.encrypt(ctx, threadID, form.body);
296
+ }
297
+ } catch (_) {}
298
+
299
+ // ── Optimised anti-suspension send flow ───────────────────────────────
300
+ // Step 1: enforce thread throttle (single delay — no stacking).
301
+ await globalAntiSuspension.prepareBeforeMessage(threadID, msg.body || '');
302
+
303
+ // Step 2: start typing indicator BEFORE the typing delay so the delay
304
+ // is "hidden" inside the visible typing indicator — zero extra latency.
305
+ let typingStarted = false;
306
+ let typingTimeout;
307
+ const shouldSimulateTyping = ctx.globalOptions && ctx.globalOptions.simulateTyping && api.sendTypingIndicator;
308
+ if (shouldSimulateTyping) {
309
+ try {
310
+ await api.sendTypingIndicator(true, threadID);
311
+ typingStarted = true;
312
+
313
+ // Typing delay runs while the indicator is already showing.
314
+ const msgLen = (msg.body || '').length;
315
+ const typingMs = await globalAntiSuspension.simulateTyping(threadID, msgLen);
316
+ await new Promise(resolve => setTimeout(resolve, typingMs));
317
+
318
+ typingTimeout = setTimeout(() => {
319
+ if (typingStarted) {
320
+ try { api.sendTypingIndicator(false, threadID); } catch (_) {}
321
+ typingStarted = false;
322
+ }
323
+ }, 10000);
324
+ } catch (_) {}
325
+ }
326
+
327
+ // Step 3: send.
328
+ try {
329
+ const result = await sendContent(form, threadID, isSingleUser, messageAndOTID);
330
+ callback(null, result);
331
+ } catch (primaryErr) {
332
+ // Fallback to MQTT for group threads or when HTTP send fails.
333
+ if (api.sendMessageMqtt) {
334
+ try {
335
+ const mqttRes = await api.sendMessageMqtt(msg, threadID, replyToMessage);
336
+ callback(null, mqttRes);
337
+ } catch (fallbackErr) {
338
+ callback(primaryErr);
339
+ }
340
+ } else {
341
+ callback(primaryErr);
342
+ }
343
+ } finally {
344
+ if (typingTimeout) clearTimeout(typingTimeout);
345
+ if (typingStarted) {
346
+ try { await api.sendTypingIndicator(false, threadID); } catch (_) {}
347
+ }
348
+ }
349
+ } catch (err) {
350
+ callback(err);
351
+ }
352
+ return returnPromise;
353
+ };
354
+ };