stfca 1.0.0

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 (82) hide show
  1. package/LICENSE-MIT +4 -0
  2. package/README.md +325 -0
  3. package/index.d.ts +615 -0
  4. package/index.js +1 -0
  5. package/module/config.js +33 -0
  6. package/module/login.js +48 -0
  7. package/module/loginHelper.js +722 -0
  8. package/module/options.js +44 -0
  9. package/package.json +69 -0
  10. package/src/api/action/addExternalModule.js +25 -0
  11. package/src/api/action/changeAvatar.js +137 -0
  12. package/src/api/action/changeBio.js +75 -0
  13. package/src/api/action/getCurrentUserID.js +7 -0
  14. package/src/api/action/handleFriendRequest.js +57 -0
  15. package/src/api/action/logout.js +76 -0
  16. package/src/api/action/refreshFb_dtsg.js +71 -0
  17. package/src/api/action/setPostReaction.js +106 -0
  18. package/src/api/action/unfriend.js +54 -0
  19. package/src/api/http/httpGet.js +46 -0
  20. package/src/api/http/httpPost.js +52 -0
  21. package/src/api/http/postFormData.js +47 -0
  22. package/src/api/messaging/addUserToGroup.js +68 -0
  23. package/src/api/messaging/changeAdminStatus.js +122 -0
  24. package/src/api/messaging/changeArchivedStatus.js +55 -0
  25. package/src/api/messaging/changeBlockedStatus.js +48 -0
  26. package/src/api/messaging/changeGroupImage.js +90 -0
  27. package/src/api/messaging/changeNickname.js +70 -0
  28. package/src/api/messaging/changeThreadColor.js +79 -0
  29. package/src/api/messaging/changeThreadEmoji.js +106 -0
  30. package/src/api/messaging/createNewGroup.js +88 -0
  31. package/src/api/messaging/createPoll.js +43 -0
  32. package/src/api/messaging/deleteMessage.js +56 -0
  33. package/src/api/messaging/deleteThread.js +56 -0
  34. package/src/api/messaging/editMessage.js +68 -0
  35. package/src/api/messaging/forwardAttachment.js +51 -0
  36. package/src/api/messaging/getEmojiUrl.js +29 -0
  37. package/src/api/messaging/getFriendsList.js +82 -0
  38. package/src/api/messaging/getMessage.js +829 -0
  39. package/src/api/messaging/handleMessageRequest.js +65 -0
  40. package/src/api/messaging/markAsDelivered.js +57 -0
  41. package/src/api/messaging/markAsRead.js +88 -0
  42. package/src/api/messaging/markAsReadAll.js +49 -0
  43. package/src/api/messaging/markAsSeen.js +61 -0
  44. package/src/api/messaging/muteThread.js +50 -0
  45. package/src/api/messaging/removeUserFromGroup.js +105 -0
  46. package/src/api/messaging/resolvePhotoUrl.js +43 -0
  47. package/src/api/messaging/searchForThread.js +52 -0
  48. package/src/api/messaging/sendMessage.js +379 -0
  49. package/src/api/messaging/sendMessageMqtt.js +323 -0
  50. package/src/api/messaging/sendTypingIndicator.js +67 -0
  51. package/src/api/messaging/setMessageReaction.js +75 -0
  52. package/src/api/messaging/setTitle.js +119 -0
  53. package/src/api/messaging/shareContact.js +49 -0
  54. package/src/api/messaging/threadColors.js +128 -0
  55. package/src/api/messaging/unsendMessage.js +81 -0
  56. package/src/api/messaging/uploadAttachment.js +95 -0
  57. package/src/api/socket/core/connectMqtt.js +179 -0
  58. package/src/api/socket/core/getSeqID.js +25 -0
  59. package/src/api/socket/core/getTaskResponseData.js +22 -0
  60. package/src/api/socket/core/markDelivery.js +12 -0
  61. package/src/api/socket/core/parseDelta.js +351 -0
  62. package/src/api/socket/detail/buildStream.js +208 -0
  63. package/src/api/socket/detail/constants.js +24 -0
  64. package/src/api/socket/listenMqtt.js +133 -0
  65. package/src/api/threads/getThreadHistory.js +664 -0
  66. package/src/api/threads/getThreadInfo.js +358 -0
  67. package/src/api/threads/getThreadList.js +248 -0
  68. package/src/api/threads/getThreadPictures.js +78 -0
  69. package/src/api/users/getUserID.js +65 -0
  70. package/src/api/users/getUserInfo.js +319 -0
  71. package/src/api/users/getUserInfoV2.js +133 -0
  72. package/src/core/sendReqMqtt.js +63 -0
  73. package/src/database/models/index.js +49 -0
  74. package/src/database/models/thread.js +31 -0
  75. package/src/database/models/user.js +32 -0
  76. package/src/database/threadData.js +98 -0
  77. package/src/database/userData.js +89 -0
  78. package/src/utils/client.js +214 -0
  79. package/src/utils/constants.js +23 -0
  80. package/src/utils/format.js +1111 -0
  81. package/src/utils/headers.js +41 -0
  82. package/src/utils/request.js +215 -0
@@ -0,0 +1,379 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { Readable } = require("stream");
4
+ const log = require("npmlog");
5
+ const allowedProperties = {
6
+ attachment: true,
7
+ url: true,
8
+ sticker: true,
9
+ emoji: true,
10
+ emojiSize: true,
11
+ body: true,
12
+ mentions: true,
13
+ location: true,
14
+ asPage: true
15
+ };
16
+ const { isReadableStream } = require("../../utils/constants");
17
+ const { parseAndCheckLogin } = require("../../utils/client");
18
+ const { getType, generateThreadingID, generateTimestampRelative, generateOfflineThreadingID, getSignatureID } = require("../../utils/format");
19
+
20
+ module.exports = function (defaultFuncs, api, ctx) {
21
+ function toReadable(input) {
22
+ if (isReadableStream(input)) return input;
23
+ if (Buffer.isBuffer(input)) return Readable.from(input);
24
+ if (typeof input === "string" && fs.existsSync(input) && fs.statSync(input).isFile()) return fs.createReadStream(path.resolve(input));
25
+ throw { error: "Unsupported attachment input. Use stream/buffer/filepath." };
26
+ }
27
+
28
+ function uploadAttachment(attachments, callback) {
29
+ const uploads = [];
30
+ for (let i = 0; i < attachments.length; i++) {
31
+ if (!isReadableStream(attachments[i])) throw { error: "Attachment should be a readable stream and not " + getType(attachments[i]) + "." };
32
+ const form = { upload_1024: attachments[i], voice_clip: "true" };
33
+ uploads.push(
34
+ defaultFuncs
35
+ .postFormData("https://upload.facebook.com/ajax/mercury/upload.php", ctx.jar, form, {}, {})
36
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
37
+ .then(resData => {
38
+ if (resData.error) throw resData;
39
+ return resData.payload.metadata[0];
40
+ })
41
+ );
42
+ }
43
+ Promise.all(uploads)
44
+ .then(resData => callback(null, resData))
45
+ .catch(err => {
46
+ log.error("uploadAttachment", err);
47
+ callback(err);
48
+ });
49
+ }
50
+
51
+ function getUrl(url, callback) {
52
+ const form = { image_height: 960, image_width: 960, uri: url };
53
+ defaultFuncs
54
+ .post("https://www.facebook.com/message_share_attachment/fromURI/", ctx.jar, form)
55
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
56
+ .then(resData => {
57
+ if (resData.error) return callback(resData);
58
+ if (!resData.payload) return callback({ error: "Invalid url" });
59
+ callback(null, resData.payload.share_data.share_params);
60
+ })
61
+ .catch(err => {
62
+ log.error("getUrl", err);
63
+ callback(err);
64
+ });
65
+ }
66
+
67
+ function sleep(ms) {
68
+ return new Promise(r => setTimeout(r, ms));
69
+ }
70
+
71
+ async function postWithRetry(url, jar, form, tries = 3) {
72
+ let lastErr;
73
+ for (let i = 0; i < tries; i++) {
74
+ try {
75
+ const res = await defaultFuncs.post(url, jar, form).then(parseAndCheckLogin(ctx, defaultFuncs));
76
+ if (res && !res.error) return res;
77
+ lastErr = res;
78
+ if (res && (res.error === 1545003 || res.error === 368)) await sleep(500 * (i + 1));
79
+ else break;
80
+ } catch (e) {
81
+ lastErr = e;
82
+ await sleep(500 * (i + 1));
83
+ }
84
+ }
85
+ throw lastErr || { error: "Send failed" };
86
+ }
87
+
88
+ function applyPageAuthor(form, msg) {
89
+ const pageID = msg && msg.asPage ? msg.asPage : ctx.globalOptions.pageID;
90
+ if (!pageID) return;
91
+ form["author"] = "fbid:" + pageID;
92
+ form["specific_to_list[1]"] = "fbid:" + pageID;
93
+ form["creator_info[creatorID]"] = ctx.userID;
94
+ form["creator_info[creatorType]"] = "direct_admin";
95
+ form["creator_info[labelType]"] = "sent_message";
96
+ form["creator_info[pageID]"] = pageID;
97
+ form["request_user_id"] = pageID;
98
+ form["creator_info[profileURI]"] = "https://www.facebook.com/profile.php?id=" + ctx.userID;
99
+ }
100
+
101
+ function applyMentions(msg, form) {
102
+ if (!msg.mentions || !msg.mentions.length) return;
103
+ let body = typeof msg.body === "string" ? msg.body : "";
104
+ const need = [];
105
+ for (const m of msg.mentions) {
106
+ const tag = String(m.tag || "");
107
+ if (tag && !body.includes(tag)) need.push(tag);
108
+ }
109
+ if (need.length) body = (body ? body + " " : "") + need.join(" ");
110
+ const emptyChar = "\u200E";
111
+ form["body"] = emptyChar + body;
112
+ let searchFrom = 0;
113
+ msg.mentions.forEach((m, i) => {
114
+ const tag = String(m.tag || "");
115
+ const from = typeof m.fromIndex === "number" ? m.fromIndex : searchFrom;
116
+ const off = Math.max(0, body.indexOf(tag, from));
117
+ form[`profile_xmd[${i}][offset]`] = off + 1;
118
+ form[`profile_xmd[${i}][length]`] = tag.length;
119
+ form[`profile_xmd[${i}][id]`] = m.id || 0;
120
+ form[`profile_xmd[${i}][type]`] = "p";
121
+ searchFrom = off + tag.length;
122
+ });
123
+ }
124
+
125
+ function finalizeHasAttachment(form) {
126
+ const keys = ["image_ids", "gif_ids", "file_ids", "video_ids", "audio_ids", "sticker_id", "shareable_attachment[share_params]"];
127
+ form.has_attachment = keys.some(k => k in form && (Array.isArray(form[k]) ? form[k].length > 0 : !!form[k]));
128
+ }
129
+
130
+ function extractMessageInfo(resData, fallbackThreadID) {
131
+ let messageID = null;
132
+ let threadFBID = null;
133
+ let timestamp = null;
134
+ const actions = resData && resData.payload && Array.isArray(resData.payload.actions) ? resData.payload.actions : null;
135
+ if (actions && actions.length) {
136
+ const v = actions.find(x => x && x.message_id) || actions[0];
137
+ messageID = v && v.message_id ? v.message_id : null;
138
+ threadFBID = (v && (v.thread_fbid || v.thread_id)) || fallbackThreadID || null;
139
+ timestamp = v && v.timestamp ? v.timestamp : null;
140
+ }
141
+ if (!messageID) messageID = (resData && resData.payload && resData.payload.message_id) || resData.message_id || null;
142
+ if (!threadFBID) threadFBID = (resData && resData.payload && resData.payload.thread_id) || fallbackThreadID || null;
143
+ if (!timestamp) timestamp = (resData && resData.timestamp) || Date.now();
144
+ if (!messageID) return null;
145
+ return { threadID: threadFBID, messageID, timestamp };
146
+ }
147
+
148
+ function sendContent(form, threadID, isSingleUser, messageAndOTID, callback) {
149
+ if (getType(threadID) === "Array") {
150
+ for (let i = 0; i < threadID.length; i++) form["specific_to_list[" + i + "]"] = "fbid:" + threadID[i];
151
+ form["specific_to_list[" + threadID.length + "]"] = "fbid:" + ctx.userID;
152
+ form["client_thread_id"] = "root:" + messageAndOTID;
153
+ } else {
154
+ if (isSingleUser) {
155
+ form["specific_to_list[0]"] = "fbid:" + threadID;
156
+ form["specific_to_list[1]"] = "fbid:" + ctx.userID;
157
+ form["other_user_fbid"] = threadID;
158
+ } else {
159
+ form["thread_fbid"] = threadID;
160
+ }
161
+ }
162
+ postWithRetry("https://www.facebook.com/messaging/send/", ctx.jar, form)
163
+ .then(resData => {
164
+ if (!resData) return callback({ error: "Send message failed." });
165
+ if (resData.error) {
166
+ if (resData.error === 1545012) log.warn("sendMessage", "Got error 1545012. This might mean that you're not part of the conversation " + threadID);
167
+ else log.error("sendMessage", resData);
168
+ return callback(resData);
169
+ }
170
+ const info = extractMessageInfo(resData, getType(threadID) === "Array" ? null : String(threadID));
171
+ if (!info) return callback({ error: "Cannot parse message info." });
172
+ callback(null, info);
173
+ })
174
+ .catch(err => {
175
+ log.error("sendMessage", err);
176
+ if (getType(err) === "Object" && err.error === "Not logged in.") ctx.loggedIn = false;
177
+ callback(err);
178
+ });
179
+ }
180
+
181
+ function sendOnce(baseForm, threadID, isSingleUser) {
182
+ const otid = generateOfflineThreadingID();
183
+ const form = { ...baseForm, offline_threading_id: otid, message_id: otid };
184
+ return new Promise((resolve, reject) => {
185
+ sendContent(form, threadID, isSingleUser, otid, (err, info) => (err ? reject(err) : resolve(info)));
186
+ });
187
+ }
188
+
189
+ function send(form, threadID, messageAndOTID, callback, isGroup) {
190
+ if (getType(threadID) === "Array") return sendContent(form, threadID, false, messageAndOTID, callback);
191
+ if (getType(isGroup) === "Boolean") return sendContent(form, threadID, !isGroup, messageAndOTID, callback);
192
+ sendOnce(form, threadID, false)
193
+ .then(info => callback(null, info))
194
+ .catch(() => {
195
+ sendOnce(form, threadID, true)
196
+ .then(info => callback(null, info))
197
+ .catch(err => callback(err));
198
+ });
199
+ }
200
+
201
+ function handleUrl(msg, form, callback, cb) {
202
+ if (msg.url) {
203
+ form["shareable_attachment[share_type]"] = "100";
204
+ getUrl(msg.url, function (err, params) {
205
+ if (err) return callback(err);
206
+ form["shareable_attachment[share_params]"] = params;
207
+ cb();
208
+ });
209
+ } else cb();
210
+ }
211
+
212
+ function handleLocation(msg, form, callback, cb) {
213
+ if (msg.location) {
214
+ if (msg.location.latitude == null || msg.location.longitude == null) return callback({ error: "location property needs both latitude and longitude" });
215
+ form["location_attachment[coordinates][latitude]"] = msg.location.latitude;
216
+ form["location_attachment[coordinates][longitude]"] = msg.location.longitude;
217
+ form["location_attachment[is_current_location]"] = !!msg.location.current;
218
+ }
219
+ cb();
220
+ }
221
+
222
+ function handleSticker(msg, form, callback, cb) {
223
+ if (msg.sticker) form["sticker_id"] = msg.sticker;
224
+ cb();
225
+ }
226
+
227
+ function handleEmoji(msg, form, callback, cb) {
228
+ if (msg.emojiSize != null && msg.emoji == null) return callback({ error: "emoji property is empty" });
229
+ if (msg.emoji) {
230
+ if (msg.emojiSize == null) msg.emojiSize = "medium";
231
+ if (msg.emojiSize !== "small" && msg.emojiSize !== "medium" && msg.emojiSize !== "large") return callback({ error: "emojiSize property is invalid" });
232
+ if (form["body"] != null && form["body"] !== "") return callback({ error: "body is not empty" });
233
+ form["body"] = msg.emoji;
234
+ form["tags[0]"] = "hot_emoji_size:" + msg.emojiSize;
235
+ }
236
+ cb();
237
+ }
238
+
239
+ function splitAttachments(list) {
240
+ if (!Array.isArray(list)) list = [list];
241
+ const ids = [];
242
+ const streams = [];
243
+ for (const a of list) {
244
+ if (Array.isArray(a) && /_id$/.test(a[0])) {
245
+ ids.push([a[0], String(a[1])]);
246
+ continue;
247
+ }
248
+ if (a && typeof a === "object") {
249
+ if (a.id && a.type && /_id$/.test(a.type)) {
250
+ ids.push([a.type, String(a.id)]);
251
+ continue;
252
+ }
253
+ const k = Object.keys(a || {}).find(x => /_id$/.test(x));
254
+ if (k) {
255
+ ids.push([k, String(a[k])]);
256
+ continue;
257
+ }
258
+ }
259
+ streams.push(toReadable(a));
260
+ }
261
+ return { ids, streams };
262
+ }
263
+
264
+ function handleAttachment(msg, form, callback, cb) {
265
+ if (!msg.attachment) return cb();
266
+ form["image_ids"] = [];
267
+ form["gif_ids"] = [];
268
+ form["file_ids"] = [];
269
+ form["video_ids"] = [];
270
+ form["audio_ids"] = [];
271
+ const { ids, streams } = splitAttachments(msg.attachment);
272
+ for (const [type, id] of ids) form[`${type}s`].push(id);
273
+ if (!streams.length) return cb();
274
+ uploadAttachment(streams, function (err, files) {
275
+ if (err) return callback(err);
276
+ files.forEach(function (file) {
277
+ const type = Object.keys(file)[0];
278
+ form[type + "s"].push(file[type]);
279
+ });
280
+ cb();
281
+ });
282
+ }
283
+
284
+ function handleMention(msg, form, callback, cb) {
285
+ try {
286
+ applyMentions(msg, form);
287
+ cb();
288
+ } catch (e) {
289
+ callback(e);
290
+ }
291
+ }
292
+
293
+ return function sendMessage(msg, threadID, callback, replyToMessage, isGroup) {
294
+ const isFn = v => typeof v === "function";
295
+ const isStr = v => typeof v === "string";
296
+
297
+ if (typeof isGroup === "undefined") isGroup = null;
298
+ if (!callback && (getType(threadID) === "Function" || getType(threadID) === "AsyncFunction")) return threadID({ error: "Pass a threadID as a second argument." });
299
+
300
+ if (isStr(callback) && isFn(replyToMessage)) {
301
+ const t = callback;
302
+ callback = replyToMessage;
303
+ replyToMessage = t;
304
+ } else if (!replyToMessage && isStr(callback)) {
305
+ replyToMessage = callback;
306
+ callback = null;
307
+ }
308
+
309
+ let resolveFunc = function () { };
310
+ let rejectFunc = function () { };
311
+ const returnPromise = new Promise(function (resolve, reject) {
312
+ resolveFunc = resolve;
313
+ rejectFunc = reject;
314
+ });
315
+ if (!callback) {
316
+ callback = function (err, data) {
317
+ if (err) return rejectFunc(err);
318
+ resolveFunc(data);
319
+ };
320
+ }
321
+ const msgType = getType(msg);
322
+ const threadIDType = getType(threadID);
323
+ const messageIDType = getType(replyToMessage);
324
+ if (msgType !== "String" && msgType !== "Object") return callback({ error: "Message should be of type string or object and not " + msgType + "." });
325
+ if (threadIDType !== "Array" && threadIDType !== "Number" && threadIDType !== "String") return callback({ error: "ThreadID should be of type number, string, or array and not " + threadIDType + "." });
326
+ if (replyToMessage && messageIDType !== "String") return callback({ error: "MessageID should be of type string and not " + threadIDType + "." });
327
+ if (msgType === "String") msg = { body: msg };
328
+ const disallowedProperties = Object.keys(msg).filter(prop => !allowedProperties[prop]);
329
+ if (disallowedProperties.length > 0) return callback({ error: "Disallowed props: `" + disallowedProperties.join(", ") + "`" });
330
+ const messageAndOTID = generateOfflineThreadingID();
331
+ const form = {
332
+ client: "mercury",
333
+ action_type: "ma-type:user-generated-message",
334
+ author: "fbid:" + ctx.userID,
335
+ timestamp: Date.now(),
336
+ timestamp_absolute: "Today",
337
+ timestamp_relative: generateTimestampRelative(),
338
+ timestamp_time_passed: "0",
339
+ is_unread: false,
340
+ is_cleared: false,
341
+ is_forward: false,
342
+ is_filtered_content: false,
343
+ is_filtered_content_bh: false,
344
+ is_filtered_content_account: false,
345
+ is_filtered_content_quasar: false,
346
+ is_filtered_content_invalid_app: false,
347
+ is_spoof_warning: false,
348
+ source: "source:chat:web",
349
+ "source_tags[0]": "source:chat",
350
+ body: msg.body ? msg.body.toString() : "",
351
+ html_body: false,
352
+ ui_push_phase: "V3",
353
+ status: "0",
354
+ offline_threading_id: messageAndOTID,
355
+ message_id: messageAndOTID,
356
+ threading_id: generateThreadingID(ctx.clientID),
357
+ ephemeral_ttl_mode: "0",
358
+ manual_retry_cnt: "0",
359
+ signatureID: getSignatureID(),
360
+ replied_to_message_id: replyToMessage ? replyToMessage.toString() : ""
361
+ };
362
+ applyPageAuthor(form, msg);
363
+ handleLocation(msg, form, callback, () =>
364
+ handleSticker(msg, form, callback, () =>
365
+ handleAttachment(msg, form, callback, () =>
366
+ handleUrl(msg, form, callback, () =>
367
+ handleEmoji(msg, form, callback, () =>
368
+ handleMention(msg, form, callback, () => {
369
+ finalizeHasAttachment(form);
370
+ send(form, threadID, messageAndOTID, callback, isGroup);
371
+ })
372
+ )
373
+ )
374
+ )
375
+ )
376
+ );
377
+ return returnPromise;
378
+ };
379
+ };
@@ -0,0 +1,323 @@
1
+
2
+ var log = require("npmlog");
3
+ var bluebird = require("bluebird");
4
+ const { parseAndCheckLogin } = require("../../utils/client");
5
+ const { getType } = require("../../utils/format");
6
+ const { isReadableStream } = require("../../utils/constants");
7
+ module.exports = function(defaultFuncs, api, ctx) {
8
+ function uploadAttachment(attachments, callback) {
9
+ callback = callback || function() {};
10
+ var uploads = [];
11
+
12
+ // create an array of promises
13
+ for (var i = 0; i < attachments.length; i++) {
14
+ if (!isReadableStream(attachments[i])) {
15
+ throw {
16
+ error:
17
+ "Attachment should be a readable stream and not " +
18
+ getType(attachments[i]) +
19
+ "."
20
+ };
21
+ }
22
+
23
+ var form = {
24
+ upload_1024: attachments[i],
25
+ voice_clip: "true"
26
+ };
27
+
28
+ uploads.push(
29
+ defaultFuncs
30
+ .postFormData(
31
+ "https://upload.facebook.com/ajax/mercury/upload.php",
32
+ ctx.jar,
33
+ form,
34
+ {}
35
+ )
36
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
37
+ .then(function(resData) {
38
+ if (resData.error) {
39
+ throw resData;
40
+ }
41
+
42
+ // We have to return the data unformatted unless we want to change it
43
+ // back in sendMessage.
44
+ return resData.payload.metadata[0];
45
+ })
46
+ );
47
+ }
48
+
49
+ // resolve all promises
50
+ bluebird
51
+ .all(uploads)
52
+ .then(function(resData) {
53
+ callback(null, resData);
54
+ })
55
+ .catch(function(err) {
56
+ log.error("uploadAttachment", err);
57
+ return callback(err);
58
+ });
59
+ }
60
+
61
+ let variance = 0;
62
+ const epoch_id = () =>
63
+ Math.floor(Date.now() * (4194304 + (variance = (variance + 0.1) % 5)));
64
+ const emojiSizes = {
65
+ small: 1,
66
+ medium: 2,
67
+ large: 3
68
+ };
69
+
70
+ function handleEmoji(msg, form, callback, cb) {
71
+ if (msg.emojiSize != null && msg.emoji == null) {
72
+ return callback({ error: "emoji property is empty" });
73
+ }
74
+ if (msg.emoji) {
75
+ if (!msg.emojiSize) {
76
+ msg.emojiSize = "small";
77
+ }
78
+ if (
79
+ msg.emojiSize !== "small" &&
80
+ msg.emojiSize !== "medium" &&
81
+ msg.emojiSize !== "large" &&
82
+ (isNaN(msg.emojiSize) || msg.emojiSize < 1 || msg.emojiSize > 3)
83
+ ) {
84
+ return callback({ error: "emojiSize property is invalid" });
85
+ }
86
+
87
+ form.payload.tasks[0].payload.send_type = 1;
88
+ form.payload.tasks[0].payload.text = msg.emoji;
89
+ form.payload.tasks[0].payload.hot_emoji_size = !isNaN(msg.emojiSize)
90
+ ? msg.emojiSize
91
+ : emojiSizes[msg.emojiSize];
92
+ }
93
+ cb();
94
+ }
95
+
96
+ function handleSticker(msg, form, callback, cb) {
97
+ if (msg.sticker) {
98
+ form.payload.tasks[0].payload.send_type = 2;
99
+ form.payload.tasks[0].payload.sticker_id = msg.sticker;
100
+ }
101
+ cb();
102
+ }
103
+
104
+ function handleAttachment(msg, form, callback, cb) {
105
+ if (msg.attachment) {
106
+ form.payload.tasks[0].payload.send_type = 3;
107
+ form.payload.tasks[0].payload.attachment_fbids = [];
108
+ if (form.payload.tasks[0].payload.text == "")
109
+ form.payload.tasks[0].payload.text = null;
110
+ if (getType(msg.attachment) !== "Array") {
111
+ msg.attachment = [msg.attachment];
112
+ }
113
+
114
+ uploadAttachment(msg.attachment, function(err, files) {
115
+ if (err) {
116
+ return callback(err);
117
+ }
118
+
119
+ files.forEach(function(file) {
120
+ var key = Object.keys(file);
121
+ var type = key[0]; // image_id, file_id, etc
122
+ form.payload.tasks[0].payload.attachment_fbids.push(file[type]); // push the id
123
+ });
124
+ cb();
125
+ });
126
+ } else {
127
+ cb();
128
+ }
129
+ }
130
+
131
+ function handleMention(msg, form, callback, cb) {
132
+ if (msg.mentions) {
133
+ form.payload.tasks[0].payload.send_type = 1;
134
+
135
+ const arrayIds = [];
136
+ const arrayOffsets = [];
137
+ const arrayLengths = [];
138
+ const mention_types = [];
139
+
140
+ for (let i = 0; i < msg.mentions.length; i++) {
141
+ const mention = msg.mentions[i];
142
+
143
+ const tag = mention.tag;
144
+ if (typeof tag !== "string") {
145
+ return callback({ error: "Mention tags must be strings." });
146
+ }
147
+
148
+ const offset = msg.body.indexOf(tag, mention.fromIndex || 0);
149
+
150
+ if (offset < 0) {
151
+ log.warn(
152
+ "handleMention",
153
+ 'Mention for "' + tag + '" not found in message string.'
154
+ );
155
+ }
156
+
157
+ if (mention.id == null) {
158
+ log.warn("handleMention", "Mention id should be non-null.");
159
+ }
160
+
161
+ const id = mention.id || 0;
162
+ arrayIds.push(id);
163
+ arrayOffsets.push(offset);
164
+ arrayLengths.push(tag.length);
165
+ mention_types.push("p");
166
+ }
167
+
168
+ form.payload.tasks[0].payload.mention_data = {
169
+ mention_ids: arrayIds.join(","),
170
+ mention_offsets: arrayOffsets.join(","),
171
+ mention_lengths: arrayLengths.join(","),
172
+ mention_types: mention_types.join(",")
173
+ };
174
+ }
175
+ cb();
176
+ }
177
+
178
+ function handleLocation(msg, form, callback, cb) {
179
+ // this is not working yet
180
+ if (msg.location) {
181
+ if (msg.location.latitude == null || msg.location.longitude == null) {
182
+ return callback({
183
+ error: "location property needs both latitude and longitude"
184
+ });
185
+ }
186
+
187
+ form.payload.tasks[0].payload.send_type = 1;
188
+ form.payload.tasks[0].payload.location_data = {
189
+ coordinates: {
190
+ latitude: msg.location.latitude,
191
+ longitude: msg.location.longitude
192
+ },
193
+ is_current_location: !!msg.location.current,
194
+ is_live_location: !!msg.location.live
195
+ };
196
+ }
197
+
198
+ cb();
199
+ }
200
+
201
+ function send(form, threadID, callback, replyToMessage) {
202
+ if (replyToMessage) {
203
+ form.payload.tasks[0].payload.reply_metadata = {
204
+ reply_source_id: replyToMessage,
205
+ reply_source_type: 1,
206
+ reply_type: 0
207
+ };
208
+ }
209
+ const mqttClient = ctx.mqttClient;
210
+ form.payload.tasks.forEach(task => {
211
+ task.payload = JSON.stringify(task.payload);
212
+ });
213
+ form.payload = JSON.stringify(form.payload);
214
+ console.log(global.jsonStringifyColor(form, null, 2));
215
+
216
+ return mqttClient.publish("/ls_req", JSON.stringify(form), function(
217
+ err,
218
+ data
219
+ ) {
220
+ if (err) {
221
+ console.error("Error publishing message: ", err);
222
+ callback(err);
223
+ } else {
224
+ console.log("Message published successfully with data: ", data);
225
+ callback(null, data);
226
+ }
227
+ });
228
+ }
229
+
230
+ return function sendMessageMqtt(msg, threadID, callback, replyToMessage) {
231
+ if (
232
+ !callback &&
233
+ (getType(threadID) === "Function" ||
234
+ getType(threadID) === "AsyncFunction")
235
+ ) {
236
+ return threadID({ error: "Pass a threadID as a second argument." });
237
+ }
238
+ if (!replyToMessage && getType(callback) === "String") {
239
+ replyToMessage = callback;
240
+ callback = function() {};
241
+ }
242
+
243
+ if (!callback) {
244
+ callback = function(err, friendList) {};
245
+ }
246
+
247
+ var msgType = getType(msg);
248
+ var threadIDType = getType(threadID);
249
+ var messageIDType = getType(replyToMessage);
250
+
251
+ if (msgType !== "String" && msgType !== "Object") {
252
+ return callback({
253
+ error:
254
+ "Message should be of type string or object and not " + msgType + "."
255
+ });
256
+ }
257
+
258
+ if (msgType === "String") {
259
+ msg = { body: msg };
260
+ }
261
+
262
+ const timestamp = Date.now();
263
+ // get full date time
264
+ const epoch = timestamp << 22;
265
+ //const otid = epoch + 0; // TODO replace with randomInt(0, 2**22)
266
+ const otid = epoch + Math.floor(Math.random() * 4194304);
267
+
268
+ const form = {
269
+ app_id: "2220391788200892",
270
+ payload: {
271
+ tasks: [
272
+ {
273
+ label: "46",
274
+ payload: {
275
+ thread_id: threadID.toString(),
276
+ otid: otid.toString(),
277
+ source: 0,
278
+ send_type: 1,
279
+ sync_group: 1,
280
+ text:
281
+ msg.body != null && msg.body != undefined
282
+ ? msg.body.toString()
283
+ : "",
284
+ initiating_source: 1,
285
+ skip_url_preview_gen: 0
286
+ },
287
+ queue_name: threadID.toString(),
288
+ task_id: 0,
289
+ failure_count: null
290
+ },
291
+ {
292
+ label: "21",
293
+ payload: {
294
+ thread_id: threadID.toString(),
295
+ last_read_watermark_ts: Date.now(),
296
+ sync_group: 1
297
+ },
298
+ queue_name: threadID.toString(),
299
+ task_id: 1,
300
+ failure_count: null
301
+ }
302
+ ],
303
+ epoch_id: epoch_id(),
304
+ version_id: "6120284488008082",
305
+ data_trace_id: null
306
+ },
307
+ request_id: 1,
308
+ type: 3
309
+ };
310
+
311
+ handleEmoji(msg, form, callback, function() {
312
+ handleLocation(msg, form, callback, function() {
313
+ handleMention(msg, form, callback, function() {
314
+ handleSticker(msg, form, callback, function() {
315
+ handleAttachment(msg, form, callback, function() {
316
+ send(form, threadID, callback, replyToMessage);
317
+ });
318
+ });
319
+ });
320
+ });
321
+ });
322
+ };
323
+ };