@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,154 +0,0 @@
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
- };
@@ -1,354 +0,0 @@
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
- };