fca-nx 6.6.6
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.
- package/LICENCE +21 -0
- package/README.md +446 -0
- package/e2ee/config.json +0 -0
- package/e2ee/crypto.js +173 -0
- package/e2ee/index.js +1032 -0
- package/e2ee/proto/ArmadilloApplication.proto +281 -0
- package/e2ee/proto/ArmadilloICDC.proto +14 -0
- package/e2ee/proto/ConsumerApplication.proto +232 -0
- package/e2ee/proto/MessageApplication.proto +82 -0
- package/e2ee/proto/MessageTransport.proto +77 -0
- package/e2ee/proto/WACommon.proto +66 -0
- package/e2ee/proto/WAMediaTransport.proto +176 -0
- package/e2ee/protocol.js +196 -0
- package/e2ee/ratchet.js +219 -0
- package/e2ee/store.js +182 -0
- package/e2ee/vendor/fb-e2ee.cjs +9159 -0
- package/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
- package/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
- package/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
- package/e2ee/vendor/proto/MessageApplication.proto +82 -0
- package/e2ee/vendor/proto/MessageTransport.proto +77 -0
- package/e2ee/vendor/proto/WACommon.proto +66 -0
- package/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
- package/func/checkUpdate.js +7 -0
- package/func/logAdapter.js +33 -0
- package/func/logger.js +134 -0
- package/index.js +22 -0
- package/module/config.js +45 -0
- package/module/login.js +183 -0
- package/module/loginHelper.js +1382 -0
- package/module/options.js +52 -0
- package/package.json +101 -0
- package/src/api/action/addExternalModule.js +25 -0
- package/src/api/action/addFriend.js +145 -0
- package/src/api/action/changeAvatar.js +137 -0
- package/src/api/action/changeBio.js +75 -0
- package/src/api/action/changeCover.js +277 -0
- package/src/api/action/enableAutoSaveAppState.js +73 -0
- package/src/api/action/getCurrentUserID.js +7 -0
- package/src/api/action/handleFriendRequest.js +57 -0
- package/src/api/action/logout.js +76 -0
- package/src/api/action/refreshFb_dtsg.js +48 -0
- package/src/api/action/setPostReaction.js +106 -0
- package/src/api/action/unfriend.js +54 -0
- package/src/api/http/httpGet.js +46 -0
- package/src/api/http/httpPost.js +52 -0
- package/src/api/http/postFormData.js +47 -0
- package/src/api/messaging/addUserToGroup.js +68 -0
- package/src/api/messaging/changeAdminStatus.js +126 -0
- package/src/api/messaging/changeArchivedStatus.js +55 -0
- package/src/api/messaging/changeBlockedStatus.js +48 -0
- package/src/api/messaging/changeGroupImage.js +91 -0
- package/src/api/messaging/changeNickname.js +70 -0
- package/src/api/messaging/changeThreadColor.js +79 -0
- package/src/api/messaging/changeThreadEmoji.js +111 -0
- package/src/api/messaging/createNewGroup.js +88 -0
- package/src/api/messaging/createPoll.js +46 -0
- package/src/api/messaging/createThemeAI.js +98 -0
- package/src/api/messaging/deleteMessage.js +136 -0
- package/src/api/messaging/deleteThread.js +56 -0
- package/src/api/messaging/editMessage.js +90 -0
- package/src/api/messaging/forwardAttachment.js +57 -0
- package/src/api/messaging/forwardMessage.js +134 -0
- package/src/api/messaging/getEmojiUrl.js +29 -0
- package/src/api/messaging/getFriendsList.js +82 -0
- package/src/api/messaging/getMessage.js +829 -0
- package/src/api/messaging/getThemePictures.js +62 -0
- package/src/api/messaging/handleMessageRequest.js +65 -0
- package/src/api/messaging/markAsDelivered.js +57 -0
- package/src/api/messaging/markAsRead.js +88 -0
- package/src/api/messaging/markAsReadAll.js +49 -0
- package/src/api/messaging/markAsSeen.js +61 -0
- package/src/api/messaging/muteThread.js +50 -0
- package/src/api/messaging/pinMessage.js +115 -0
- package/src/api/messaging/removeUserFromGroup.js +62 -0
- package/src/api/messaging/resolvePhotoUrl.js +43 -0
- package/src/api/messaging/scheduler.js +264 -0
- package/src/api/messaging/searchForThread.js +53 -0
- package/src/api/messaging/sendBroadcast.js +93 -0
- package/src/api/messaging/sendMessage.js +269 -0
- package/src/api/messaging/sendTypingIndicator.js +74 -0
- package/src/api/messaging/sessionGuard.js +208 -0
- package/src/api/messaging/setMessageReaction.js +95 -0
- package/src/api/messaging/setTitle.js +124 -0
- package/src/api/messaging/shareContact.js +49 -0
- package/src/api/messaging/threadColors.js +128 -0
- package/src/api/messaging/unsendMessage.js +81 -0
- package/src/api/messaging/uploadAttachment.js +523 -0
- package/src/api/socket/OldMessage.js +186 -0
- package/src/api/socket/core/connectMqtt.js +320 -0
- package/src/api/socket/core/emitAuth.js +103 -0
- package/src/api/socket/core/getSeqID.js +338 -0
- package/src/api/socket/core/getTaskResponseData.js +25 -0
- package/src/api/socket/core/parseDelta.js +387 -0
- package/src/api/socket/detail/buildStream.js +215 -0
- package/src/api/socket/detail/constants.js +28 -0
- package/src/api/socket/e2ee/crypto.js +173 -0
- package/src/api/socket/e2ee/e2ee/crypto.js +173 -0
- package/src/api/socket/e2ee/e2ee/index.js +421 -0
- package/src/api/socket/e2ee/e2ee/proto/ArmadilloApplication.proto +281 -0
- package/src/api/socket/e2ee/e2ee/proto/ArmadilloICDC.proto +14 -0
- package/src/api/socket/e2ee/e2ee/proto/ConsumerApplication.proto +232 -0
- package/src/api/socket/e2ee/e2ee/proto/MessageApplication.proto +82 -0
- package/src/api/socket/e2ee/e2ee/proto/MessageTransport.proto +77 -0
- package/src/api/socket/e2ee/e2ee/proto/WACommon.proto +66 -0
- package/src/api/socket/e2ee/e2ee/proto/WAMediaTransport.proto +176 -0
- package/src/api/socket/e2ee/e2ee/protocol.js +196 -0
- package/src/api/socket/e2ee/e2ee/ratchet.js +219 -0
- package/src/api/socket/e2ee/e2ee/store.js +182 -0
- package/src/api/socket/e2ee/e2ee/vendor/fb-e2ee.cjs +9162 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/MessageApplication.proto +82 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/MessageTransport.proto +77 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/WACommon.proto +66 -0
- package/src/api/socket/e2ee/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
- package/src/api/socket/e2ee/index.js +437 -0
- package/src/api/socket/e2ee/proto/ArmadilloApplication.proto +281 -0
- package/src/api/socket/e2ee/proto/ArmadilloICDC.proto +14 -0
- package/src/api/socket/e2ee/proto/ConsumerApplication.proto +232 -0
- package/src/api/socket/e2ee/proto/MessageApplication.proto +82 -0
- package/src/api/socket/e2ee/proto/MessageTransport.proto +77 -0
- package/src/api/socket/e2ee/proto/WACommon.proto +66 -0
- package/src/api/socket/e2ee/proto/WAMediaTransport.proto +176 -0
- package/src/api/socket/e2ee/protocol.js +196 -0
- package/src/api/socket/e2ee/ratchet.js +219 -0
- package/src/api/socket/e2ee/store.js +182 -0
- package/src/api/socket/e2ee/vendor/fb-e2ee.cjs +9162 -0
- package/src/api/socket/e2ee/vendor/proto/ArmadilloApplication.proto +281 -0
- package/src/api/socket/e2ee/vendor/proto/ArmadilloICDC.proto +14 -0
- package/src/api/socket/e2ee/vendor/proto/ConsumerApplication.proto +232 -0
- package/src/api/socket/e2ee/vendor/proto/MessageApplication.proto +82 -0
- package/src/api/socket/e2ee/vendor/proto/MessageTransport.proto +77 -0
- package/src/api/socket/e2ee/vendor/proto/WACommon.proto +66 -0
- package/src/api/socket/e2ee/vendor/proto/WAMediaTransport.proto +176 -0
- package/src/api/socket/listenE2EE.js +75 -0
- package/src/api/socket/listenMqtt.js +551 -0
- package/src/api/socket/middleware/index.js +216 -0
- package/src/api/socket/sendMessage.js +309 -0
- package/src/api/socket/sendMessageMqtt.js +69 -0
- package/src/api/threads/getThreadHistory.js +664 -0
- package/src/api/threads/getThreadInfo.js +296 -0
- package/src/api/threads/getThreadList.js +293 -0
- package/src/api/threads/getThreadPictures.js +78 -0
- package/src/api/users/getUserID.js +65 -0
- package/src/api/users/getUserInfo.js +402 -0
- package/src/api/users/getUserInfoV2.js +911 -0
- package/src/app/MessengerBot.js +209 -0
- package/src/app/MessengerContext.js +32 -0
- package/src/app/createFcaClient.js +139 -0
- package/src/app/threadInfoRealtimeSync.js +284 -0
- package/src/core/sendReqMqtt.js +96 -0
- package/src/database/helpers.js +53 -0
- package/src/database/models/index.js +88 -0
- package/src/database/models/thread.js +50 -0
- package/src/database/models/user.js +46 -0
- package/src/database/threadData.js +94 -0
- package/src/database/userData.js +98 -0
- package/src/remote/remoteClient.js +123 -0
- package/src/utils/broadcast.js +51 -0
- package/src/utils/client.js +10 -0
- package/src/utils/clientIdentity.js +118 -0
- package/src/utils/constants.js +23 -0
- package/src/utils/cookies.js +68 -0
- package/src/utils/format/attachment.js +357 -0
- package/src/utils/format/cookie.js +9 -0
- package/src/utils/format/date.js +50 -0
- package/src/utils/format/decode.js +44 -0
- package/src/utils/format/delta.js +194 -0
- package/src/utils/format/ids.js +64 -0
- package/src/utils/format/index.js +64 -0
- package/src/utils/format/message.js +88 -0
- package/src/utils/format/presence.js +132 -0
- package/src/utils/format/readTyp.js +44 -0
- package/src/utils/format/thread.js +42 -0
- package/src/utils/format/utils.js +141 -0
- package/src/utils/headers.js +124 -0
- package/src/utils/logger.js +144 -0
- package/src/utils/loginParser/autoLogin.js +125 -0
- package/src/utils/loginParser/helpers.js +43 -0
- package/src/utils/loginParser/index.js +10 -0
- package/src/utils/loginParser/parseAndCheckLogin.js +220 -0
- package/src/utils/loginParser/textUtils.js +28 -0
- package/src/utils/request/client.js +26 -0
- package/src/utils/request/config.js +29 -0
- package/src/utils/request/defaults.js +46 -0
- package/src/utils/request/helpers.js +46 -0
- package/src/utils/request/index.js +17 -0
- package/src/utils/request/methods.js +163 -0
- package/src/utils/request/proxy.js +46 -0
- package/src/utils/request/retry.js +77 -0
- package/src/utils/request/sanitize.js +49 -0
- package/src/utils/utils.js +686 -0
- package/src/utils/versionCheck.js +47 -0
- package/src/vendor/fca-unofficial/index.js +11 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { generateOfflineThreadingID } = require("../../utils/format");
|
|
4
|
+
const log = require("../../../func/logAdapter");
|
|
5
|
+
|
|
6
|
+
module.exports = function (defaultFuncs, api, ctx) {
|
|
7
|
+
return function unsendMessage(messageID, threadID, callback) {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
if (!ctx.mqttClient) {
|
|
10
|
+
const err = new Error("Not connected to MQTT");
|
|
11
|
+
callback?.(err);
|
|
12
|
+
return reject(err);
|
|
13
|
+
}
|
|
14
|
+
const reqID = ++ctx.wsReqNumber;
|
|
15
|
+
const taskID = ++ctx.wsTaskNumber;
|
|
16
|
+
const taskPayload = {
|
|
17
|
+
message_id: messageID,
|
|
18
|
+
thread_key: threadID,
|
|
19
|
+
sync_group: 1,
|
|
20
|
+
};
|
|
21
|
+
const task = {
|
|
22
|
+
failure_count: null,
|
|
23
|
+
label: "33",
|
|
24
|
+
payload: JSON.stringify(taskPayload),
|
|
25
|
+
queue_name: "unsend_message",
|
|
26
|
+
task_id: taskID,
|
|
27
|
+
};
|
|
28
|
+
const content = {
|
|
29
|
+
app_id: "2220391788200892",
|
|
30
|
+
payload: JSON.stringify({
|
|
31
|
+
tasks: [task],
|
|
32
|
+
epoch_id: parseInt(generateOfflineThreadingID()),
|
|
33
|
+
version_id: "25393437286970779",
|
|
34
|
+
}),
|
|
35
|
+
request_id: reqID,
|
|
36
|
+
type: 3,
|
|
37
|
+
};
|
|
38
|
+
try {
|
|
39
|
+
ctx.mqttClient.publish("/ls_req", JSON.stringify(content), {
|
|
40
|
+
qos: 1,
|
|
41
|
+
retain: false
|
|
42
|
+
});
|
|
43
|
+
} catch (err) {
|
|
44
|
+
log.error("unsendMessage (MQTT publish failed)", err);
|
|
45
|
+
callback?.(err);
|
|
46
|
+
return reject(err);
|
|
47
|
+
}
|
|
48
|
+
const handleRes = (topic, message) => {
|
|
49
|
+
if (topic !== "/ls_resp") return;
|
|
50
|
+
let jsonMsg;
|
|
51
|
+
try {
|
|
52
|
+
jsonMsg = JSON.parse(message.toString());
|
|
53
|
+
jsonMsg.payload = JSON.parse(jsonMsg.payload);
|
|
54
|
+
} catch (err) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (jsonMsg.request_id !== reqID) return;
|
|
58
|
+
ctx.mqttClient.removeListener("message", handleRes);
|
|
59
|
+
try {
|
|
60
|
+
const msgID = jsonMsg.payload.step?.[1]?.[2]?.[2]?.[1]?.[2];
|
|
61
|
+
const msgReplace = jsonMsg.payload.step?.[1]?.[2]?.[2]?.[1]?.[4];
|
|
62
|
+
if (msgID && msgReplace) {
|
|
63
|
+
const bodies = {
|
|
64
|
+
body: msgReplace,
|
|
65
|
+
messageID: msgID
|
|
66
|
+
};
|
|
67
|
+
callback?.(null, bodies);
|
|
68
|
+
return resolve(bodies);
|
|
69
|
+
} else {
|
|
70
|
+
callback?.(null, { success: true });
|
|
71
|
+
return resolve({ success: true });
|
|
72
|
+
}
|
|
73
|
+
} catch (err) {
|
|
74
|
+
callback?.(null, { success: true });
|
|
75
|
+
return resolve({ success: true });
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
ctx.mqttClient.on("message", handleRes);
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
};
|
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const axios = require("axios");
|
|
4
|
+
const { wrapper } = require("axios-cookiejar-support");
|
|
5
|
+
const { CookieJar } = require("tough-cookie");
|
|
6
|
+
const FormData = require("form-data");
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
const path = require("path");
|
|
9
|
+
const stream = require("stream");
|
|
10
|
+
const { URL } = require("url");
|
|
11
|
+
const log = require("../../../func/logAdapter");
|
|
12
|
+
const { getIdentity } = require("../../utils/clientIdentity");
|
|
13
|
+
|
|
14
|
+
// Resolved from the same centralized identity as every other subsystem
|
|
15
|
+
// (HTTP requests, MQTT) so upload requests never claim a different Chrome
|
|
16
|
+
// version/sec-ch-ua than the rest of the session. Do not hard-code a
|
|
17
|
+
// separate browser version here. This part is stateless/pure, so it's safe
|
|
18
|
+
// to keep at module scope - it's read-only and identical for every session
|
|
19
|
+
// using the default identity.
|
|
20
|
+
const DEFAULT_IDENTITY = getIdentity();
|
|
21
|
+
const DEFAULT_UA = DEFAULT_IDENTITY.userAgent;
|
|
22
|
+
|
|
23
|
+
const TOKEN_CACHE_TTL = 5 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
// NOTE ON SESSION ISOLATION:
|
|
26
|
+
// Previously `http` (the axios instance), `cookieJar`, and `tokenCache` were
|
|
27
|
+
// module-level `let` variables. Since a Node `require()` cache is a
|
|
28
|
+
// singleton, every account/session that called this module's exported
|
|
29
|
+
// factory in the same process was silently sharing (and overwriting) the
|
|
30
|
+
// SAME axios instance, cookie jar, and cached fb_dtsg/lsd tokens. Logging in
|
|
31
|
+
// a second account would clobber the first account's cookie jar and token
|
|
32
|
+
// cache mid-session - the same class of bug as the shared CookieJar issue
|
|
33
|
+
// fixed in module/loginHelper.js, but specific to the upload path.
|
|
34
|
+
//
|
|
35
|
+
// Fix: every piece of session-scoped state now lives on a `sess` object
|
|
36
|
+
// created fresh inside the exported factory (one per login()/session) and
|
|
37
|
+
// is passed explicitly to the helper functions below instead of being read
|
|
38
|
+
// from module scope.
|
|
39
|
+
|
|
40
|
+
function cleanJSON(x) {
|
|
41
|
+
if (typeof x !== "string") return x;
|
|
42
|
+
const s = x.replace(/^for\s*\(;;\);\s*/i, "");
|
|
43
|
+
try { return JSON.parse(s); } catch { return s; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function pick(re, html, i = 1) {
|
|
47
|
+
const m = html && html.match(re);
|
|
48
|
+
return m ? m[i] : "";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function getFrom(html, a, b) {
|
|
52
|
+
const i = html.indexOf(a);
|
|
53
|
+
if (i < 0) return;
|
|
54
|
+
const start = i + a.length;
|
|
55
|
+
const j = html.indexOf(b, start);
|
|
56
|
+
return j < 0 ? undefined : html.slice(start, j);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function respFinalUrl(res) {
|
|
60
|
+
return (res && (res.url || res.requestUrl)) || "";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function detectCheckpoint(res) {
|
|
64
|
+
const url = String(respFinalUrl(res) || "");
|
|
65
|
+
const body = typeof res?.body === "string" ? res.body : "";
|
|
66
|
+
const hit =
|
|
67
|
+
/\/checkpoint\//i.test(url) ||
|
|
68
|
+
/(?:href|action)\s*=\s*["']https?:\/\/[^"']*\/checkpoint\//i.test(body) ||
|
|
69
|
+
/"checkpoint"|checkpoint_title|checkpointMain|id="checkpoint"/i.test(body) ||
|
|
70
|
+
(/login\.php/i.test(url) && /checkpoint/i.test(body));
|
|
71
|
+
return { hit, url: url || (body.match(/https?:\/\/[^"']*\/checkpoint\/[^"'<>]*/i)?.[0] || "") };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function checkpointError(res) {
|
|
75
|
+
const d = detectCheckpoint(res);
|
|
76
|
+
if (!d.hit) return null;
|
|
77
|
+
const e = new Error("Checkpoint required");
|
|
78
|
+
e.code = "CHECKPOINT";
|
|
79
|
+
e.checkpoint = true;
|
|
80
|
+
e.url = d.url || "https://www.facebook.com/checkpoint/";
|
|
81
|
+
e.status = res?.statusCode || res?.status;
|
|
82
|
+
return e;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function httpGet(sess, pageUrl, ua, headers = {}) {
|
|
86
|
+
const host = new URL(pageUrl).hostname;
|
|
87
|
+
const referer = `https://${host}/`;
|
|
88
|
+
const baseHeaders = {
|
|
89
|
+
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
|
90
|
+
"Accept-Language": DEFAULT_IDENTITY.acceptLanguage,
|
|
91
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
92
|
+
"Cache-Control": "max-age=0",
|
|
93
|
+
Connection: "keep-alive",
|
|
94
|
+
Host: host,
|
|
95
|
+
Origin: `https://${host}`,
|
|
96
|
+
Referer: referer,
|
|
97
|
+
"Sec-Ch-Prefers-Color-Scheme": "dark",
|
|
98
|
+
"Sec-Ch-Ua": DEFAULT_IDENTITY.secChUa,
|
|
99
|
+
"Sec-Ch-Ua-Full-Version-List": DEFAULT_IDENTITY.secChUaFullVersionList,
|
|
100
|
+
"Sec-Ch-Ua-Mobile": DEFAULT_IDENTITY.secChUaMobile,
|
|
101
|
+
"Sec-Ch-Ua-Model": '""',
|
|
102
|
+
"Sec-Ch-Ua-Platform": DEFAULT_IDENTITY.secChUaPlatform,
|
|
103
|
+
"Sec-Ch-Ua-Platform-Version": DEFAULT_IDENTITY.secChUaPlatformVersion,
|
|
104
|
+
"Sec-Fetch-Dest": "document",
|
|
105
|
+
"Sec-Fetch-Mode": "navigate",
|
|
106
|
+
"Sec-Fetch-Site": "same-origin",
|
|
107
|
+
"Sec-Fetch-User": "?1",
|
|
108
|
+
"Upgrade-Insecure-Requests": "1",
|
|
109
|
+
"User-Agent": ua || DEFAULT_UA,
|
|
110
|
+
"x-fb-rlafr": "0"
|
|
111
|
+
};
|
|
112
|
+
const res = await sess.http.get(pageUrl, {
|
|
113
|
+
headers: { ...baseHeaders, ...headers },
|
|
114
|
+
timeout: 30000
|
|
115
|
+
});
|
|
116
|
+
const cp = checkpointError(res);
|
|
117
|
+
if (cp) throw cp;
|
|
118
|
+
return typeof res.data === "string" ? res.data : String(res.data || "");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function getTokens(sess, ua, forceRefresh = false) {
|
|
122
|
+
const now = Date.now();
|
|
123
|
+
const cache = sess.tokenCache;
|
|
124
|
+
if (!forceRefresh && cache.data && (now - cache.time) < TOKEN_CACHE_TTL) {
|
|
125
|
+
return cache.data;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
const html = await httpGet(sess, "https://www.facebook.com/", ua, { Referer: "https://www.facebook.com/" });
|
|
129
|
+
const fb_dtsg = getFrom(html, '"DTSGInitData",[],{"token":"', '",') || html.match(/name="fb_dtsg"\s+value="([^"]+)"/)?.[1] || "";
|
|
130
|
+
const jazoest = getFrom(html, 'name="jazoest" value="', '"') || getFrom(html, "jazoest=", '",') || html.match(/name="jazoest"\s+value="([^"]+)"/)?.[1] || "";
|
|
131
|
+
const lsd = getFrom(html, '["LSD",[],{"token":"', '"}') || html.match(/name="lsd"\s+value="([^"]+)"/)?.[1] || "";
|
|
132
|
+
const spin_r = pick(/"__spin_r":(\d+)/, html) || "";
|
|
133
|
+
const spin_t = pick(/"__spin_t":(\d+)/, html) || "";
|
|
134
|
+
const rev = pick(/"__rev":(\d+)/, html) || "";
|
|
135
|
+
|
|
136
|
+
if (!fb_dtsg || !lsd) {
|
|
137
|
+
// Cố gắng fallback nếu regex fail, nhưng thường là do cookie die
|
|
138
|
+
if (!cache.data) throw new Error("Failed to fetch fb_dtsg or LSD from Facebook");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
cache.data = { lsd, fb_dtsg, jazoest, spin_r, spin_t, rev };
|
|
142
|
+
cache.time = now;
|
|
143
|
+
return cache.data;
|
|
144
|
+
} catch (e) {
|
|
145
|
+
if (cache.data) {
|
|
146
|
+
log.warn("[uploadAttachment] Token fetch failed, using cached tokens: " + (e.message || e));
|
|
147
|
+
return cache.data;
|
|
148
|
+
}
|
|
149
|
+
throw e;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function getType(obj) { return Object.prototype.toString.call(obj).slice(8, -1); }
|
|
154
|
+
function isReadableStream(obj) { return obj instanceof stream.Readable && (getType(obj._read) === "Function" || getType(obj._read) === "AsyncFunction") && getType(obj._readableState) === "Object"; }
|
|
155
|
+
function fromBuffer(buf) { return stream.Readable.from(buf); }
|
|
156
|
+
function parseDataUrl(s) { const m = /^data:([^;,]+)?(;base64)?,(.*)$/i.exec(s); if (!m) return null; const mime = m[1] || "application/octet-stream"; const isB64 = !!m[2]; const data = isB64 ? Buffer.from(m[3], "base64") : Buffer.from(decodeURIComponent(m[3]), "utf8"); return { mime, data }; }
|
|
157
|
+
|
|
158
|
+
function filenameFromUrl(u, headers) {
|
|
159
|
+
try {
|
|
160
|
+
const urlObj = new URL(u);
|
|
161
|
+
let filename = path.basename(urlObj.pathname) || `file-${Date.now()}`;
|
|
162
|
+
const cd = headers && (headers["content-disposition"] || headers["Content-Disposition"]);
|
|
163
|
+
if (cd) {
|
|
164
|
+
const m = /filename\*?=(?:UTF-8''|")?([^";\n]+)/i.exec(cd);
|
|
165
|
+
if (m) filename = decodeURIComponent(m[1].replace(/"/g, ""));
|
|
166
|
+
}
|
|
167
|
+
return filename;
|
|
168
|
+
} catch {
|
|
169
|
+
return `file-${Date.now()}`;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async function normalizeOne(sess, input, ua) {
|
|
174
|
+
if (!input) throw new Error("Invalid input");
|
|
175
|
+
if (Buffer.isBuffer(input)) return { stream: fromBuffer(input), filename: `file-${Date.now()}.bin`, contentType: "application/octet-stream" };
|
|
176
|
+
if (typeof input === "string") {
|
|
177
|
+
if (/^https?:\/\//i.test(input)) {
|
|
178
|
+
const resp = await sess.http.get(input, {
|
|
179
|
+
headers: {
|
|
180
|
+
"User-Agent": ua,
|
|
181
|
+
Accept: "*/*",
|
|
182
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
183
|
+
"Cache-Control": "no-cache"
|
|
184
|
+
},
|
|
185
|
+
timeout: 30000,
|
|
186
|
+
responseType: "stream"
|
|
187
|
+
});
|
|
188
|
+
const s = resp.data;
|
|
189
|
+
const filename = filenameFromUrl(input, resp.headers);
|
|
190
|
+
return { stream: s, filename };
|
|
191
|
+
}
|
|
192
|
+
if (input.startsWith("data:")) {
|
|
193
|
+
const p = parseDataUrl(input);
|
|
194
|
+
if (!p) throw new Error("Bad data URL");
|
|
195
|
+
return { stream: fromBuffer(p.data), filename: `file-${Date.now()}`, contentType: p.mime };
|
|
196
|
+
}
|
|
197
|
+
if (fs.existsSync(input) && fs.statSync(input).isFile()) {
|
|
198
|
+
return { stream: fs.createReadStream(input), filename: path.basename(input) };
|
|
199
|
+
}
|
|
200
|
+
throw new Error(`Unsupported string input: ${input}`);
|
|
201
|
+
}
|
|
202
|
+
if (isReadableStream(input)) {
|
|
203
|
+
return { stream: input, filename: `file-${Date.now()}` };
|
|
204
|
+
}
|
|
205
|
+
if (typeof input === "object") {
|
|
206
|
+
if (input.buffer && Buffer.isBuffer(input.buffer)) {
|
|
207
|
+
const filename = input.filename || `file-${Date.now()}.bin`;
|
|
208
|
+
const contentType = input.contentType || "application/octet-stream";
|
|
209
|
+
return { stream: fromBuffer(input.buffer), filename, contentType };
|
|
210
|
+
}
|
|
211
|
+
if (input.data && Buffer.isBuffer(input.data)) {
|
|
212
|
+
const filename = input.filename || `file-${Date.now()}.bin`;
|
|
213
|
+
const contentType = input.contentType || "application/octet-stream";
|
|
214
|
+
return { stream: fromBuffer(input.data), filename, contentType };
|
|
215
|
+
}
|
|
216
|
+
if (input.stream && isReadableStream(input.stream)) {
|
|
217
|
+
const filename = input.filename || `file-${Date.now()}`;
|
|
218
|
+
const contentType = input.contentType;
|
|
219
|
+
return { stream: input.stream, filename, contentType };
|
|
220
|
+
}
|
|
221
|
+
if (input.url) {
|
|
222
|
+
return normalizeOne(sess, String(input.url), ua);
|
|
223
|
+
}
|
|
224
|
+
if (input.path && fs.existsSync(input.path) && fs.statSync(input.path).isFile()) {
|
|
225
|
+
return { stream: fs.createReadStream(input.path), filename: input.filename || path.basename(input.path), contentType: input.contentType };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
throw new Error("Unrecognized input");
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function mapAttachmentDetails(data) {
|
|
232
|
+
const out = [];
|
|
233
|
+
if (!data || typeof data !== "object") return out;
|
|
234
|
+
|
|
235
|
+
const stack = [data];
|
|
236
|
+
while (stack.length) {
|
|
237
|
+
const cur = stack.pop();
|
|
238
|
+
if (!cur || typeof cur !== "object") continue;
|
|
239
|
+
const id = cur.video_id || cur.image_id || cur.audio_id || cur.file_id || cur.fbid || cur.id || cur.upload_id || cur.gif_id;
|
|
240
|
+
const idKey =
|
|
241
|
+
cur.video_id ? "video_id" :
|
|
242
|
+
cur.image_id ? "image_id" :
|
|
243
|
+
cur.audio_id ? "audio_id" :
|
|
244
|
+
cur.file_id ? "file_id" :
|
|
245
|
+
cur.gif_id ? "gif_id" :
|
|
246
|
+
cur.fbid ? "fbid" :
|
|
247
|
+
id ? "id" : null;
|
|
248
|
+
const filename = cur.filename || cur.file_name || cur.name || cur.original_filename;
|
|
249
|
+
const filetype = cur.filetype || cur.mime_type || cur.type || cur.content_type;
|
|
250
|
+
let thumbnail = cur.thumbnail_src || cur.thumbnail_url || cur.preview_url || cur.thumbSrc || cur.thumb_url || cur.image_preview_url || cur.large_preview_url;
|
|
251
|
+
if (!thumbnail) {
|
|
252
|
+
const m = cur.media || cur.thumbnail || cur.thumb || cur.image_data || cur.video_data || cur.preview;
|
|
253
|
+
thumbnail = m?.thumbnail_src || m?.thumbnail_url || m?.src || m?.uri || m?.url;
|
|
254
|
+
}
|
|
255
|
+
if (idKey) {
|
|
256
|
+
const o = {};
|
|
257
|
+
o[idKey] = id;
|
|
258
|
+
if (filename) o.filename = filename;
|
|
259
|
+
if (filetype) o.filetype = filetype;
|
|
260
|
+
if (thumbnail) o.thumbnail_src = thumbnail;
|
|
261
|
+
out.push(o);
|
|
262
|
+
}
|
|
263
|
+
if (Array.isArray(cur)) {
|
|
264
|
+
for (const v of cur) stack.push(v);
|
|
265
|
+
} else {
|
|
266
|
+
for (const k of Object.keys(cur)) stack.push(cur[k]);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (!out.length && data.payload && Array.isArray(data.payload.metadata)) {
|
|
271
|
+
return data.payload.metadata.slice();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function pLimit(n) {
|
|
278
|
+
let active = 0;
|
|
279
|
+
const queue = [];
|
|
280
|
+
const next = () => {
|
|
281
|
+
active--;
|
|
282
|
+
if (queue.length) queue.shift()();
|
|
283
|
+
};
|
|
284
|
+
return fn => new Promise((resolve, reject) => {
|
|
285
|
+
const run = () => {
|
|
286
|
+
active++;
|
|
287
|
+
fn().then(v => { resolve(v); next(); }).catch(e => { reject(e); next(); });
|
|
288
|
+
};
|
|
289
|
+
if (active < n) run(); else queue.push(run);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Hàm upload core xử lý request
|
|
294
|
+
async function singleUpload(sess, urlBase, file, ua, tokens, retries = 2) {
|
|
295
|
+
const form = new FormData();
|
|
296
|
+
// QUAN TRỌNG: Chỉ append file, KHÔNG append fb_dtsg vào body nữa
|
|
297
|
+
form.append("farr", file.stream, { filename: file.filename, contentType: file.contentType });
|
|
298
|
+
|
|
299
|
+
const headers = {
|
|
300
|
+
...form.getHeaders(),
|
|
301
|
+
Accept: "*/*",
|
|
302
|
+
"Accept-Language": DEFAULT_IDENTITY.acceptLanguage,
|
|
303
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
304
|
+
"User-Agent": ua,
|
|
305
|
+
"x-asbd-id": "359341",
|
|
306
|
+
"x-fb-lsd": tokens.lsd || "",
|
|
307
|
+
"x-fb-friendly-name": "MercuryUpload",
|
|
308
|
+
"x-fb-request-analytics-tags": JSON.stringify({
|
|
309
|
+
network_tags: {
|
|
310
|
+
product: "256002347743983",
|
|
311
|
+
purpose: "none",
|
|
312
|
+
request_category: "graphql",
|
|
313
|
+
retry_attempt: "0"
|
|
314
|
+
},
|
|
315
|
+
application_tags: "graphservice"
|
|
316
|
+
}),
|
|
317
|
+
"sec-ch-prefers-color-scheme": "dark",
|
|
318
|
+
"sec-ch-ua": DEFAULT_IDENTITY.secChUa,
|
|
319
|
+
"sec-ch-ua-mobile": DEFAULT_IDENTITY.secChUaMobile,
|
|
320
|
+
"sec-ch-ua-platform": DEFAULT_IDENTITY.secChUaPlatform,
|
|
321
|
+
"sec-fetch-dest": "empty",
|
|
322
|
+
"sec-fetch-mode": "cors",
|
|
323
|
+
"sec-fetch-site": "same-origin",
|
|
324
|
+
Origin: "https://www.facebook.com",
|
|
325
|
+
Referer: "https://www.facebook.com/",
|
|
326
|
+
"x-fb-rlafr": "0",
|
|
327
|
+
Connection: "keep-alive"
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
// Build URL với query string tokens
|
|
331
|
+
const finalUrl = new URL(urlBase);
|
|
332
|
+
finalUrl.searchParams.set("fb_dtsg", tokens.fb_dtsg);
|
|
333
|
+
finalUrl.searchParams.set("jazoest", tokens.jazoest);
|
|
334
|
+
finalUrl.searchParams.set("lsd", tokens.lsd);
|
|
335
|
+
finalUrl.searchParams.set("__aaid", "0");
|
|
336
|
+
finalUrl.searchParams.set("__ccg", "EXCELLENT");
|
|
337
|
+
|
|
338
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
339
|
+
try {
|
|
340
|
+
const res = await sess.http.post(finalUrl.toString(), form, {
|
|
341
|
+
headers,
|
|
342
|
+
timeout: 120000,
|
|
343
|
+
maxContentLength: Infinity,
|
|
344
|
+
maxBodyLength: Infinity
|
|
345
|
+
});
|
|
346
|
+
return res;
|
|
347
|
+
} catch (e) {
|
|
348
|
+
if (attempt === retries) throw e;
|
|
349
|
+
if (e.code === "ETIMEDOUT" || e.code === "ECONNRESET" || (e.response && e.response.status >= 500)) {
|
|
350
|
+
await new Promise(r => setTimeout(r, (attempt + 1) * 1000));
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
throw e;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
module.exports = function (defaultFuncs, api, ctx) {
|
|
359
|
+
const ua = ctx?.options?.userAgent || DEFAULT_UA;
|
|
360
|
+
|
|
361
|
+
// One session object per factory call (i.e. per login()/account), instead
|
|
362
|
+
// of the old module-level `http`/`cookieJar`/`tokenCache` singletons that
|
|
363
|
+
// every session in the process used to share and clobber. `ctx.jar` is
|
|
364
|
+
// itself already per-session (see module/loginHelper.js), so reusing it
|
|
365
|
+
// here (instead of creating yet another jar) also keeps upload requests
|
|
366
|
+
// and the rest of the session's HTTP traffic consistent with each other.
|
|
367
|
+
const sessionJar = ctx.jar instanceof CookieJar ? ctx.jar : new CookieJar();
|
|
368
|
+
const sess = {
|
|
369
|
+
http: null,
|
|
370
|
+
tokenCache: { data: null, time: 0 }
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
// Axios instance
|
|
374
|
+
sess.http = wrapper(axios.create({
|
|
375
|
+
timeout: 60000,
|
|
376
|
+
headers: {
|
|
377
|
+
"User-Agent": ua,
|
|
378
|
+
"Accept-Language": DEFAULT_IDENTITY.acceptLanguage,
|
|
379
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
380
|
+
Connection: "keep-alive"
|
|
381
|
+
},
|
|
382
|
+
maxRedirects: 5,
|
|
383
|
+
validateStatus: () => true
|
|
384
|
+
}));
|
|
385
|
+
sess.http.defaults.withCredentials = true;
|
|
386
|
+
sess.http.defaults.jar = sessionJar;
|
|
387
|
+
|
|
388
|
+
async function uploadCore(link, opts, callback) {
|
|
389
|
+
if (typeof opts === "function") { callback = opts; opts = undefined; }
|
|
390
|
+
const options = {
|
|
391
|
+
concurrency: Math.max(1, Math.min(5, Number(opts?.concurrency || 3))),
|
|
392
|
+
mode: opts?.mode === "single" ? "single" : "parallel"
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
let resolveFunc = function () { };
|
|
396
|
+
let rejectFunc = function () { };
|
|
397
|
+
const returnPromise = new Promise(function (resolve, reject) {
|
|
398
|
+
resolveFunc = resolve;
|
|
399
|
+
rejectFunc = reject;
|
|
400
|
+
});
|
|
401
|
+
if (!callback) {
|
|
402
|
+
callback = function (err, data) {
|
|
403
|
+
if (err) return rejectFunc(err);
|
|
404
|
+
resolveFunc(data);
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
(async () => {
|
|
409
|
+
try {
|
|
410
|
+
const inputsArr = Array.isArray(link) ? link : [link];
|
|
411
|
+
if (!inputsArr.length) {
|
|
412
|
+
const e = new Error("No files to upload");
|
|
413
|
+
callback(e);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
let tokens = await getTokens(sess, ua);
|
|
418
|
+
const normAll = await Promise.all(inputsArr.map(x => normalizeOne(sess, x, ua)));
|
|
419
|
+
|
|
420
|
+
// Base QS setup
|
|
421
|
+
const qs = [];
|
|
422
|
+
const userId = (ctx && (ctx.userID || ctx.userId)) ? String(ctx.userID || ctx.userId) : "";
|
|
423
|
+
if (userId) qs.push(`__user=${encodeURIComponent(userId)}`);
|
|
424
|
+
qs.push("__a=1");
|
|
425
|
+
qs.push("dpr=1");
|
|
426
|
+
const reqId = Math.floor(Math.random() * 36 ** 2).toString(36);
|
|
427
|
+
qs.push(`__req=${encodeURIComponent(reqId)}`);
|
|
428
|
+
if (tokens.spin_r) qs.push(`__spin_r=${encodeURIComponent(tokens.spin_r)}`);
|
|
429
|
+
if (tokens.spin_t) qs.push(`__spin_t=${encodeURIComponent(tokens.spin_t)}`);
|
|
430
|
+
if (tokens.rev) qs.push(`__rev=${encodeURIComponent(tokens.rev)}`);
|
|
431
|
+
qs.push("__spin_b=trunk");
|
|
432
|
+
qs.push("__comet_req=15");
|
|
433
|
+
|
|
434
|
+
const baseUrl = `https://www.facebook.com/ajax/mercury/upload.php?${qs.join("&")}`;
|
|
435
|
+
|
|
436
|
+
if (options.mode === "single") {
|
|
437
|
+
const f = normAll[0];
|
|
438
|
+
const res = await singleUpload(sess, baseUrl, f, ua, tokens);
|
|
439
|
+
|
|
440
|
+
const cp = checkpointError(res);
|
|
441
|
+
if (cp) { sess.tokenCache.data = null; throw cp; }
|
|
442
|
+
|
|
443
|
+
const data = cleanJSON(res.data);
|
|
444
|
+
const ids = mapAttachmentDetails(data);
|
|
445
|
+
|
|
446
|
+
if (!ids.length) {
|
|
447
|
+
const e = new Error("UploadFb returned no metadata/ids");
|
|
448
|
+
e.code = "NO_METADATA";
|
|
449
|
+
e.status = res.status;
|
|
450
|
+
e.body = typeof data === "string" ? data.slice(0, 500) : data;
|
|
451
|
+
throw e;
|
|
452
|
+
}
|
|
453
|
+
log.info(`[uploadAttachment] success ${ids.length} item(s) status ${res.status}`);
|
|
454
|
+
callback(null, { status: res.status, ids, raw: data });
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Parallel mode
|
|
459
|
+
const limit = pLimit(options.concurrency);
|
|
460
|
+
const tasks = normAll.map(f => () => singleUpload(sess, baseUrl, f, ua, tokens));
|
|
461
|
+
const results = await Promise.all(tasks.map(t => limit(t)));
|
|
462
|
+
|
|
463
|
+
const ids = [];
|
|
464
|
+
const errors = [];
|
|
465
|
+
for (let i = 0; i < results.length; i++) {
|
|
466
|
+
const res = results[i];
|
|
467
|
+
try {
|
|
468
|
+
const cp = checkpointError(res);
|
|
469
|
+
if (cp) { sess.tokenCache.data = null; throw cp; }
|
|
470
|
+
|
|
471
|
+
const data = cleanJSON(res.data);
|
|
472
|
+
const fileIds = mapAttachmentDetails(data);
|
|
473
|
+
if (!fileIds.length) {
|
|
474
|
+
log.warn(`[uploadAttachment] File ${i + 1} returned no metadata/ids`);
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
ids.push(...fileIds);
|
|
478
|
+
} catch (e) {
|
|
479
|
+
errors.push({ index: i, error: e });
|
|
480
|
+
log.error(`[uploadAttachment] Upload ${i + 1} failed: ${e.message || e}`);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
if (ids.length === 0 && errors.length > 0) {
|
|
485
|
+
throw errors[0].error;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
log.info(`[uploadAttachment] success ${ids.length}/${normAll.length} item(s)`);
|
|
489
|
+
callback(null, { status: 200, ids, raw: null, errors: errors.length > 0 ? errors : undefined });
|
|
490
|
+
} catch (e) {
|
|
491
|
+
if (e.code === "CHECKPOINT" || (e.response && [401, 403].includes(e.response.status))) {
|
|
492
|
+
sess.tokenCache.data = null;
|
|
493
|
+
try {
|
|
494
|
+
await getTokens(sess, ua, true);
|
|
495
|
+
log.info("[uploadAttachment] Tokens refreshed after error");
|
|
496
|
+
} catch (refreshErr) {
|
|
497
|
+
log.error("[uploadAttachment] Token refresh failed: " + (refreshErr.message || refreshErr));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
log.error(`[uploadAttachment] error ${e.code || e.status || ""} ${e.message || e}`);
|
|
501
|
+
callback(e);
|
|
502
|
+
}
|
|
503
|
+
})().catch(err => {
|
|
504
|
+
log.error("[uploadAttachment] Unhandled promise rejection: " + (err.message || err));
|
|
505
|
+
rejectFunc(err);
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
return returnPromise;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
return function uploadAttachment(attachments, callback) {
|
|
512
|
+
if (!attachments) throw { error: "Please pass an attachment or an array of attachments." };
|
|
513
|
+
|
|
514
|
+
if (typeof callback === "function") {
|
|
515
|
+
return uploadCore(attachments, { mode: "parallel" }, (err, result) => {
|
|
516
|
+
if (err) return callback(err);
|
|
517
|
+
callback(null, result && Array.isArray(result.ids) ? result.ids : []);
|
|
518
|
+
}).then(result => (result && Array.isArray(result.ids) ? result.ids : []));
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
return uploadCore(attachments, { mode: "parallel" }).then(result => result && Array.isArray(result.ids) ? result.ids : []);
|
|
522
|
+
};
|
|
523
|
+
};
|