fca-nx 6.7.2 → 6.7.3

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/README.md CHANGED
@@ -138,6 +138,30 @@ api.stopAutoSave();
138
138
  api.sendMessage("Hello world!", threadID);
139
139
 
140
140
  ```
141
+ ### Message Effects
142
+ ```javascript
143
+ api.sendMessage(
144
+ {
145
+ body: "I love you! ❤️",
146
+ textEffect: "love"
147
+ },
148
+ threadID
149
+ );
150
+ ```
151
+
152
+ Built-in effect names are `heart`, `hearts`, `love`, `gift`, `present`, `fire`,
153
+ `flame`, `confetti`, `confecti`, `party`, `sparkles`, `sparkle`, `star`, and
154
+ `magic`. You can also pass a custom numeric effect ID:
155
+
156
+ ```javascript
157
+ api.sendMessage({ body: "Party time!", effect: "confetti" }, threadID);
158
+ api.sendMessage({ body: "Custom effect", textEffect: 27 }, threadID);
159
+ ```
160
+
161
+ The aliases `textEffect`, `text_effect`, `effect`, `effectName`, and their
162
+ snake/camel-case ID variants are accepted. Effects are applied through both
163
+ the MQTT sender and the legacy fallback sender.
164
+
141
165
  ### Send Attachment
142
166
  ```javascript
143
167
  const fs = require("fs");
@@ -1412,8 +1412,17 @@ function loginHelper(appState, Cookie, email, password, globalOptions, callback)
1412
1412
 
1413
1413
  // listenMqtt override with fca-nx version (better MQTT stability)
1414
1414
  try {
1415
- api.listenMqtt = require("../src/api/socket/listenMqtt")(defaultFuncs, api, ctxMain);
1416
- api.listen = api.listenMqtt;
1415
+ const stableListenMqtt = require("../src/api/socket/listenMqtt")(defaultFuncs, api, ctxMain);
1416
+ // Keep the raw MQTT listener behind the combined listener. The
1417
+ // E2EE bridge is installed above, but replacing api.listenMqtt here
1418
+ // used to silently discard it, so only group messages arriving over
1419
+ // plain MQTT reached bot handlers.
1420
+ api._listenMqttRaw = stableListenMqtt;
1421
+ if (typeof api.listenE2EE === "function") {
1422
+ api.listenMqtt = api.listen = api.listenE2EE;
1423
+ } else {
1424
+ api.listenMqtt = api.listen = stableListenMqtt;
1425
+ }
1417
1426
  } catch (e) {
1418
1427
  logger(`listenMqtt fca-nx override failed (non-fatal): ${e && e.message ? e.message : String(e)}`, "warn");
1419
1428
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.7.2",
3
+ "version": "6.7.3",
4
4
  "description": "Facebook Messenger API for Node.js — Fast, Secure, and Feature-Rich",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -6,7 +6,9 @@
6
6
 
7
7
  const log = require("../../../func/logAdapter");
8
8
  const { parseAndCheckLogin } = require("../../utils/client");
9
- const { formatID } = require("../../utils/format");
9
+ const { formatID, getSignatureID } = require("../../utils/format");
10
+
11
+ const FRIEND_REQUEST_DOC_ID = "FriendingCometFriendRequestSendMutation";
10
12
 
11
13
  module.exports = function (defaultFuncs, api, ctx) {
12
14
  return function addFriend(userID, callback) {
@@ -50,51 +52,128 @@ module.exports = function (defaultFuncs, api, ctx) {
50
52
  return returnPromise;
51
53
  }
52
54
 
53
- /*
54
- * Facebook friend request payload
55
- */
56
- const form = {
57
- uid: String(targetID),
58
- viewer_id: String(ctx.userID),
59
- source: "profile_button",
60
- ref: "profile",
61
- floc: "profile",
62
- nctr: "profile"
55
+ const sendRequest = async function () {
56
+ // Facebook retired the old /ajax/friends/requests/send/ action. The
57
+ // profile button now uses this Relay mutation instead.
58
+ if (!ctx.fb_dtsg && typeof api?.refreshFb_dtsg === "function") {
59
+ try {
60
+ await api.refreshFb_dtsg();
61
+ } catch (_) {
62
+ // The request below will return the actionable Facebook error.
63
+ }
64
+ }
65
+
66
+ const actorID = String(ctx.i_userID || ctx.userID);
67
+ const form = {
68
+ av: actorID,
69
+ __aaid: "0",
70
+ __user: actorID,
71
+ __a: "1",
72
+ __req: getSignatureID(),
73
+ __hs: "20353.HYP:comet_pkg.2.1...0",
74
+ dpr: "1",
75
+ __ccg: "EXCELLENT",
76
+ __rev: "1027405870",
77
+ __s: getSignatureID(),
78
+ __hsi: "7552782279085106329",
79
+ __comet_req: "15",
80
+ fb_dtsg: ctx.fb_dtsg,
81
+ jazoest: ctx.ttstamp || ctx.jazoest,
82
+ lsd: ctx.fb_dtsg,
83
+ __spin_r: "1027405870",
84
+ __spin_b: "trunk",
85
+ __spin_t: String(Date.now()),
86
+ __crn: "comet.fbweb.CometFriendingRoute",
87
+ fb_api_caller_class: "RelayModern",
88
+ fb_api_req_friendly_name: "FriendingCometFriendRequestSendMutation",
89
+ server_timestamps: true,
90
+ doc_id: "24614631718227645",
91
+ variables: JSON.stringify({
92
+ input: {
93
+ click_correlation_id: String(Date.now()),
94
+ click_proof_validation_result: JSON.stringify({ validated: true }),
95
+ friend_requestee_ids: [String(targetID)],
96
+ friending_channel: "FRIENDS_HOME_MAIN",
97
+ warn_ack_for_ids: [],
98
+ actor_id: actorID,
99
+ client_mutation_id: String(Math.floor(Math.random() * 100000))
100
+ },
101
+ scale: 1
102
+ })
103
+ };
104
+
105
+ return defaultFuncs
106
+ .post(
107
+ "https://www.facebook.com/api/graphql/",
108
+ ctx.jar,
109
+ form
110
+ )
111
+ .then(parseAndCheckLogin(ctx, defaultFuncs));
63
112
  };
64
113
 
65
- defaultFuncs
66
- .post(
67
- "https://www.facebook.com/ajax/friends/requests/send/",
68
- ctx.jar,
69
- form
70
- )
71
- .then(parseAndCheckLogin(ctx, defaultFuncs))
114
+ sendRequest()
72
115
  .then(function (resData) {
73
116
  if (!resData) {
74
117
  throw new Error("Empty response from Facebook");
75
118
  }
76
119
 
77
- if (resData.error || resData.errors || resData.errorDescription) {
78
- throw resData;
120
+ const payload = resData.payload || resData.data || resData;
121
+ const errorValue =
122
+ resData.error ||
123
+ resData.errors ||
124
+ resData.errorDescription ||
125
+ payload?.error ||
126
+ payload?.err ||
127
+ payload?.errorDescription ||
128
+ payload?.message;
129
+ if (errorValue) {
130
+ const error = new Error(
131
+ typeof errorValue === "string"
132
+ ? errorValue
133
+ : errorValue.message || JSON.stringify(errorValue)
134
+ );
135
+ error.error = errorValue;
136
+ error.res = resData;
137
+ throw error;
79
138
  }
80
139
 
81
- const payload = resData.payload;
82
-
83
- if (payload) {
84
- if (payload.error || payload.err) {
85
- throw payload;
140
+ const findRequestID = value => {
141
+ if (!value || typeof value !== "object") return null;
142
+ for (const key of ["friend_request_id", "friendRequestId", "request_id"]) {
143
+ if (value[key]) return String(value[key]);
86
144
  }
87
-
88
- if (payload.errorDescription) {
89
- throw new Error(payload.errorDescription);
145
+ for (const child of Object.values(value)) {
146
+ const nested = findRequestID(child);
147
+ if (nested) return nested;
90
148
  }
149
+ return null;
150
+ };
151
+
152
+ const response = Array.isArray(resData) ? resData[0] : resData;
153
+ const data = response?.data?.friend_request_send ||
154
+ response?.friend_request_send;
155
+ const requestee = Array.isArray(data?.friend_requestees)
156
+ ? data.friend_requestees[0]
157
+ : null;
158
+ const requestID = findRequestID(payload);
159
+ if (!requestee && !requestID) {
160
+ throw new Error("No friend request data received");
91
161
  }
92
162
 
93
163
  const result = {
94
- success: true,
95
- userID: String(targetID),
96
- response: resData
164
+ success: requestee
165
+ ? requestee.friendship_status === "OUTGOING_REQUEST"
166
+ : true,
167
+ userID: requestee?.id || String(targetID)
97
168
  };
169
+ if (requestee) {
170
+ result.friendshipStatus = requestee.friendship_status || null;
171
+ result.actionTitle = requestee.profile_action?.title?.text || null;
172
+ }
173
+ if (requestID) {
174
+ result.requestID = requestID;
175
+ result.response = response;
176
+ }
98
177
 
99
178
  return handleCallback(null, result);
100
179
  })
@@ -3,10 +3,14 @@
3
3
  var utils = require("../../utils/utils");
4
4
  var logger = require("../../utils/logger");
5
5
  var bluebird = require("bluebird");
6
+ var { getTextEffectId } = require("../../utils/textEffects");
6
7
 
7
8
  var allowedProperties = {
8
9
  attachment: true, url: true, sticker: true, emoji: true,
9
- emojiSize: true, body: true, mentions: true, location: true,
10
+ emojiSize: true, body: true, mentions: true, location: true, text_effect_ids: true,
11
+ textEffect: true, text_effect: true, text_effect_id: true, textEffectId: true,
12
+ textEffectID: true, effect: true, effect_id: true, effectID: true,
13
+ text_effect_name: true, effectName: true, effect_name: true,
10
14
  };
11
15
 
12
16
  module.exports = function (defaultFuncs, api, ctx) {
@@ -134,6 +138,8 @@ module.exports = function (defaultFuncs, api, ctx) {
134
138
 
135
139
  var form = {};
136
140
  if (msg.body) form.body = msg.body;
141
+ var textEffectId = getTextEffectId(msg);
142
+ if (textEffectId) form.text_effect_id = textEffectId;
137
143
 
138
144
  if (msg.mentions && Array.isArray(msg.mentions)) {
139
145
  form.body = msg.body || "";
@@ -170,10 +170,20 @@ module.exports = function createListenMqtt(deps) {
170
170
  mqttClient.end(true);
171
171
  }
172
172
  } catch (_) { }
173
- return emitAuth(ctx, api, globalCallback,
174
- /blocked/i.test(msg) ? "login_blocked" : "not_logged_in",
175
- msg
176
- );
173
+ if (/blocked/i.test(msg)) {
174
+ return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
175
+ }
176
+
177
+ // Auth responses can race with the shared cookie refresh triggered by
178
+ // another request. Treat a plain 401/403/"Not logged in" MQTT error as
179
+ // recoverable instead of emitting account_inactive and permanently
180
+ // setting ctx._ending. The close handler/scheduler will establish a
181
+ // fresh MQTT connection with the refreshed session.
182
+ logger(`mqtt transient auth error; reconnecting without logging out: ${msg}`, "warn");
183
+ if (!ctx._ending && ctx.globalOptions.autoReconnect) {
184
+ scheduleReconnect();
185
+ }
186
+ return;
177
187
  }
178
188
  logger(`mqtt error: ${msg}`, "error");
179
189
  try {
@@ -44,7 +44,11 @@ module.exports = function (defaultFuncs, api, ctx) {
44
44
  };
45
45
 
46
46
  // Start regular MQTT listener
47
- var mqttEmitter = (api._listenMqttRaw || api.listenMqtt)(globalCallback);
47
+ var mqttListener = api._listenMqttRaw || api.listenMqtt;
48
+ if (typeof mqttListener !== "function") {
49
+ throw new Error("listenE2EE: MQTT listener is not available");
50
+ }
51
+ var mqttEmitter = mqttListener(globalCallback);
48
52
  api._mqttEmitter = mqttEmitter;
49
53
 
50
54
  // [Fixed by xalman] Hook E2EE incoming messages (FCA-NX native Noise WebSocket).
@@ -82,12 +82,17 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
82
82
  function postSafe(...args) {
83
83
  return rawPost(...args).catch(err => {
84
84
  const msg = (err && err.error) || (err && err.message) || String(err || "");
85
- if (/Not logged in|blocked the login|Checkpoint/i.test(msg)) {
85
+ // A single request can briefly see an expired web session while
86
+ // another request is refreshing the shared cookie jar. Do not
87
+ // tear down the live MQTT session for that recoverable case;
88
+ // the shared auto-login promise handles the HTTP request and
89
+ // MQTT reconnects itself if the socket also needs refreshing.
90
+ if (/blocked the login|Checkpoint/i.test(msg)) {
86
91
  emitAuth(
87
92
  ctx,
88
93
  api,
89
94
  globalCallback,
90
- /blocked|checkpoint/i.test(msg) ? "login_blocked" : "not_logged_in",
95
+ /blocked|checkpoint/i.test(msg) ? "login_blocked" : "auth_error",
91
96
  msg
92
97
  );
93
98
  }
@@ -2,11 +2,15 @@
2
2
 
3
3
  var utils = require("../../utils/utils");
4
4
  var logger = require("../../utils/logger");
5
+ var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
5
6
 
6
7
  var ALLOWED = {
7
8
  attachment: true, url: true, sticker: true, emoji: true,
8
9
  emojiSize: true, body: true, mentions: true, location: true,
9
- replyToMessage: true, forwardAttachmentIds: true
10
+ replyToMessage: true, forwardAttachmentIds: true, text_effect_ids: true,
11
+ textEffect: true, text_effect: true, text_effect_id: true,
12
+ textEffectId: true, textEffectID: true, effect: true, effect_id: true,
13
+ effectID: true, text_effect_name: true, effectName: true, effect_name: true
10
14
  };
11
15
 
12
16
  var EMOJI_SIZES = { small: 1, medium: 2, large: 3 };
@@ -132,6 +136,11 @@ module.exports = function (defaultFuncs, api, ctx) {
132
136
  var mentionData = buildMentionData(msg, baseBody);
133
137
  if (mentionData) payload0.mention_data = mentionData;
134
138
 
139
+ var textEffectId = getTextEffectId(msg);
140
+ if (textEffectId) payload0.text_effect_id = textEffectId;
141
+ var effectArray = getTextEffectIds(msg);
142
+ if (effectArray.length) payload0.text_effect_ids = effectArray;
143
+
135
144
  if (msg.sticker) { payload0.send_type = 2; payload0.sticker_id = msg.sticker; }
136
145
  if (msg.emoji) { payload0.send_type = 1; payload0.text = msg.emoji; payload0.hot_emoji_size = toEmojiSize(msg.emojiSize); }
137
146
 
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  var utils = require("../../utils/utils");
4
+ var { getTextEffectId, getTextEffectIds } = require("../../utils/textEffects");
4
5
 
5
6
  module.exports = function (defaultFuncs, api, ctx) {
6
7
  return function sendMessageMqtt(msg, threadID, callback, replyToMessage) {
@@ -33,6 +34,11 @@ module.exports = function (defaultFuncs, api, ctx) {
33
34
  multitab_env: 0
34
35
  };
35
36
 
37
+ var textEffectId = getTextEffectId(msg);
38
+ if (textEffectId) payload0.text_effect_id = textEffectId;
39
+ var effectArray = getTextEffectIds(msg);
40
+ if (effectArray.length) payload0.text_effect_ids = effectArray;
41
+
36
42
  if (msg.sticker) { payload0.send_type = 2; payload0.sticker_id = msg.sticker; }
37
43
  if (replyToMessage || msg.replyToMessage) {
38
44
  payload0.reply_metadata = {
@@ -1,8 +1,39 @@
1
1
  "use strict";
2
2
  const { parseAndCheckLogin } = require("../../utils/client.js");
3
3
  const logger = require("../../../func/logger");
4
- const DOC_ID = "24418640587785718";
5
- const FRIENDLY_NAME = "CometHovercardQueryRendererQuery";
4
+
5
+ const DOC_IDS = [
6
+ {
7
+ id: "2399631849267992",
8
+ name: "CometUserProfileCoverPhotoQuery",
9
+ hasCover: true
10
+ },
11
+ {
12
+ id: "5009315269112105",
13
+ name: "CometProfilePhotoGridQuery",
14
+ hasCover: true
15
+ },
16
+ {
17
+ id: "24418640587785718",
18
+ name: "CometHovercardQueryRendererQuery",
19
+ hasCover: false
20
+ },
21
+ {
22
+ id: "6003371686559437",
23
+ name: "CometProfileInfoRendererQuery",
24
+ hasCover: true
25
+ },
26
+ {
27
+ id: "6184020922587885",
28
+ name: "CometProfilePageQuery",
29
+ hasCover: true
30
+ },
31
+ {
32
+ id: "5069749766627730",
33
+ name: "CometActorProfilePictureQuery",
34
+ hasCover: false
35
+ }
36
+ ];
6
37
  const CALLER_CLASS = "RelayModern";
7
38
 
8
39
  function toJSONMaybe(data) {
@@ -33,6 +64,32 @@ function usernameFromUrl(raw) {
33
64
  return null;
34
65
  }
35
66
 
67
+ function extractPhotoUrl(photo, depth = 0) {
68
+ if (!photo || depth > 4) return null;
69
+ if (typeof photo === "string") {
70
+ return /^https?:\/\//i.test(photo) ? photo : null;
71
+ }
72
+ if (typeof photo !== "object") return null;
73
+
74
+ // Facebook has returned direct URLs as well as nested image/photo objects
75
+ // from Comet hovercards. Walk only the known media keys and prefer direct
76
+ // URL fields before descending into nested containers.
77
+ for (const key of [
78
+ "source",
79
+ "uri",
80
+ "url",
81
+ "image",
82
+ "photo",
83
+ "media",
84
+ "cover_photo",
85
+ "coverPhoto"
86
+ ]) {
87
+ const value = extractPhotoUrl(photo[key], depth + 1);
88
+ if (value) return value;
89
+ }
90
+ return null;
91
+ }
92
+
36
93
  function pickMeta(user) {
37
94
  let friendshipStatus = null;
38
95
  let gender = null;
@@ -57,6 +114,20 @@ function pickMeta(user) {
57
114
  return { friendshipStatus, gender, shortName };
58
115
  }
59
116
 
117
+ function extractCoverPhoto(user) {
118
+ const cover = user?.cover_photo;
119
+ if (!cover) return null;
120
+ if (typeof cover === "string") return cover;
121
+ return cover.source?.uri ||
122
+ cover.source ||
123
+ cover.uri ||
124
+ cover.photo?.image?.uri ||
125
+ cover.photo?.image?.url ||
126
+ cover.image?.uri ||
127
+ cover.image?.url ||
128
+ cover.photo?.url ||
129
+ null;
130
+ }
60
131
  function normalizeUser(user) {
61
132
  if (!user) return null;
62
133
  const meta = pickMeta(user);
@@ -66,8 +137,10 @@ function normalizeUser(user) {
66
137
  name: user.name || null,
67
138
  firstName: meta.shortName || null,
68
139
  vanity,
69
- thumbSrc: user.profile_picture?.uri || null,
70
- coverPhoto: user.cover_photo?.source || user.cover_photo?.uri || null,
140
+ thumbSrc: extractProfilePicture(user),
141
+ coverPhoto: extractPhotoUrl(
142
+ user.cover_photo || user.coverPhoto || user.profile_cover_photo
143
+ ),
71
144
  profileUrl: user.profile_url || user.url || null,
72
145
  gender: meta.gender || null,
73
146
  type: user.__typename || "User",
@@ -136,26 +209,47 @@ function formatUser(user, id) {
136
209
  module.exports = function (defaultFuncs, api, ctx) {
137
210
  async function fetchOne(userID) {
138
211
  const id = String(userID);
139
- const variables = {
140
- actionBarRenderLocation: "WWW_COMET_HOVERCARD",
141
- context: "DEFAULT",
142
- entityID: id,
143
- scale: 1,
144
- __relay_internal__pv__WorkCometIsEmployeeGKProviderrelayprovider: false
145
- };
146
- const form = {
147
- av: String(ctx?.userID || ""),
148
- fb_api_caller_class: CALLER_CLASS,
149
- fb_api_req_friendly_name: FRIENDLY_NAME,
150
- server_timestamps: true,
151
- doc_id: DOC_ID,
152
- variables: JSON.stringify(variables)
153
- };
154
- const response = await defaultFuncs.post("https://www.facebook.com/api/graphql/", ctx.jar, form).then(parseAndCheckLogin(ctx, defaultFuncs));
155
- const parsed = toJSONMaybe(response) || response;
156
- const root = Array.isArray(parsed)? parsed[0] : parsed;
157
- const user = root?.data?.node?.comet_hovercard_renderer?.user || null;
158
- return normalizeUser(user);
212
+ let bestUser = null;
213
+ for (const doc of DOC_IDS) {
214
+ const variables = doc.name === "CometHovercardQueryRendererQuery"
215
+ ? {
216
+ actionBarRenderLocation: "WWW_COMET_HOVERCARD",
217
+ context: "DEFAULT",
218
+ entityID: id,
219
+ scale: 1,
220
+ __relay_internal__pv__WorkCometIsEmployeeGKProviderrelayprovider: false
221
+ }
222
+ : { userID: id, scale: 1 };
223
+ const form = {
224
+ av: String(ctx?.userID || ""),
225
+ fb_api_caller_class: CALLER_CLASS,
226
+ fb_api_req_friendly_name: doc.name,
227
+ server_timestamps: true,
228
+ doc_id: doc.id,
229
+ variables: JSON.stringify(variables)
230
+ };
231
+ try {
232
+ const response = await defaultFuncs.post("https://www.facebook.com/api/graphql/", ctx.jar, form)
233
+ .then(parseAndCheckLogin(ctx, defaultFuncs));
234
+ const parsed = toJSONMaybe(response) || response;
235
+ const root = Array.isArray(parsed) ? parsed[0] : parsed;
236
+ const normalized = normalizeUser(findUser(root));
237
+ if (!normalized?.id) continue;
238
+ if (!bestUser) {
239
+ bestUser = normalized;
240
+ } else {
241
+ for (const field of ["thumbSrc", "profileUrl", "vanity", "coverPhoto", "firstName", "gender"]) {
242
+ if (!bestUser[field] && normalized[field]) bestUser[field] = normalized[field];
243
+ }
244
+ if (normalized.isVerified) bestUser.isVerified = true;
245
+ if (normalized.isFriend) bestUser.isFriend = true;
246
+ }
247
+ if (doc.hasCover && bestUser.coverPhoto) break;
248
+ } catch (error) {
249
+ logger(`getUserInfoV2 ${doc.id}: ${error.message || error}`, "warn");
250
+ }
251
+ }
252
+ return bestUser;
159
253
  }
160
254
 
161
255
  async function fetchLegacy(userIDs) {
@@ -180,7 +274,7 @@ module.exports = function (defaultFuncs, api, ctx) {
180
274
  lastName: nameParts.length > 1? nameParts.slice(1).join(" ") : null,
181
275
  vanity: profile.vanity || null,
182
276
  thumbSrc: null,
183
- coverPhoto: profile.cover_photo || null, // FIX: legacy teo add
277
+ coverPhoto: extractPhotoUrl(profile.cover_photo),
184
278
  profileUrl: profile.uri || `https://www.facebook.com/profile.php?id=${id}`,
185
279
  gender: profile.gender === 1? "male" : profile.gender === 2? "female" : "no specific gender",
186
280
  type: profile.type || "User",
@@ -219,7 +313,7 @@ module.exports = function (defaultFuncs, api, ctx) {
219
313
  callback(error);
220
314
  returnPromise;
221
315
  }
222
- (async () => {
316
+ (async () => {
223
317
  try {
224
318
  const retObj = {};
225
319
  const results = await Promise.allSettled(ids.map(fetchOne));
@@ -265,6 +359,28 @@ module.exports = function (defaultFuncs, api, ctx) {
265
359
  return callback(null, retObj);
266
360
  }
267
361
  })();
268
- returnPromise;
362
+ return returnPromise;
269
363
  };
270
364
  };
365
+
366
+ module.exports._private = {
367
+ extractPhotoUrl,
368
+ normalizeUser
369
+ };
370
+
371
+ function findUser(root) {
372
+ return root?.data?.node?.comet_hovercard_renderer?.user ||
373
+ root?.data?.node?.user ||
374
+ root?.data?.node ||
375
+ root?.data?.user ||
376
+ root?.data?.viewer ||
377
+ null;
378
+ }
379
+
380
+ function extractProfilePicture(user) {
381
+ return user?.profile_picture?.uri ||
382
+ user?.profilePicture?.uri ||
383
+ user?.profile_picture?.source?.uri ||
384
+ user?.profile_picture?.source ||
385
+ null;
386
+ }
@@ -14,12 +14,86 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
14
14
  const { buildUrl, headerOf, formatCookie } = helpers;
15
15
 
16
16
  return async function maybeAutoLogin(resData, resConfig) {
17
- if (ctx.auto_login) {
18
- const e = new Error("Not logged in. Auto login already in progress.");
19
- e.error = "Not logged in.";
20
- e.res = resData;
21
- throw e;
17
+ const retryAfterLogin = async function () {
18
+ if (!resConfig) {
19
+ const e = new Error(
20
+ "Not logged in. Auto login successful but cannot retry request."
21
+ );
22
+ e.error = "Not logged in.";
23
+ e.res = resData;
24
+ throw e;
25
+ }
26
+
27
+ const url = buildUrl(resConfig);
28
+ const method = String(resConfig?.method || "GET").toUpperCase();
29
+ const ctype = String(headerOf(resConfig?.headers, "content-type") || "").toLowerCase();
30
+ const isMultipart = ctype.includes("multipart/form-data");
31
+ const payload = resConfig?.data;
32
+ const params = resConfig?.params;
33
+
34
+ try {
35
+ let newData;
36
+ if (method === "GET") {
37
+ newData = await http.get(url, ctx.jar, params || null, ctx.globalOptions, ctx);
38
+ } else if (isMultipart) {
39
+ newData = await http.postFormData(url, ctx.jar, payload, params, ctx.globalOptions, ctx);
40
+ } else {
41
+ newData = await http.post(url, ctx.jar, payload, ctx.globalOptions, ctx);
42
+ }
43
+ return await parseAndCheckLogin(ctx, http)(newData);
44
+ } catch (retryErr) {
45
+ if (
46
+ retryErr?.code === "ERR_INVALID_CHAR" ||
47
+ (retryErr?.message && retryErr.message.includes("Invalid character in header"))
48
+ ) {
49
+ logger(
50
+ `Auto login retry failed: Invalid header detected. Error: ${retryErr.message}`,
51
+ "error"
52
+ );
53
+ const e = new Error("Not logged in. Auto login retry failed due to invalid header.");
54
+ e.error = "Not logged in.";
55
+ e.res = resData;
56
+ e.originalError = retryErr;
57
+ throw e;
58
+ }
59
+ logger(
60
+ `Auto login retry failed: ${
61
+ retryErr && retryErr.message ? retryErr.message : String(retryErr)
62
+ }`,
63
+ "error"
64
+ );
65
+ const e = new Error("Not logged in. Auto login retry failed.");
66
+ e.error = "Not logged in.";
67
+ e.res = resData;
68
+ e.originalError = retryErr;
69
+ throw e;
70
+ }
71
+ };
72
+
73
+ // Several requests can discover an expired session at the same time when
74
+ // many users interact with the bot. They must share one recovery attempt;
75
+ // rejecting all followers as "already in progress" creates an auth storm
76
+ // and can make the MQTT session look logged out.
77
+ if (ctx._autoLoginPromise) {
78
+ let ok;
79
+ try {
80
+ ok = await ctx._autoLoginPromise;
81
+ } catch (autoLoginErr) {
82
+ const e = new Error("Not logged in. Auto login failed.");
83
+ e.error = "Not logged in.";
84
+ e.res = resData;
85
+ e.originalError = autoLoginErr;
86
+ throw e;
87
+ }
88
+ if (!ok) {
89
+ const e = new Error("Not logged in. Auto login failed.");
90
+ e.error = "Not logged in.";
91
+ e.res = resData;
92
+ throw e;
93
+ }
94
+ return retryAfterLogin();
22
95
  }
96
+
23
97
  if (typeof ctx.performAutoLogin !== "function") {
24
98
  const e = new Error("Not logged in. Auto login function not available.");
25
99
  e.error = "Not logged in.";
@@ -31,68 +105,16 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
31
105
  logger("Login session expired, attempting auto login...", "warn");
32
106
  emit("sessionExpired", { res: resData });
33
107
 
108
+ const autoLoginPromise = Promise.resolve().then(() => ctx.performAutoLogin());
109
+ ctx._autoLoginPromise = autoLoginPromise;
110
+
34
111
  try {
35
- const ok = await ctx.performAutoLogin();
112
+ const ok = await autoLoginPromise;
36
113
  if (ok) {
37
114
  logger("Auto login successful! Retrying request...", "info");
38
115
  emit("autoLoginSuccess", { res: resData });
39
- ctx.auto_login = false;
40
-
41
- if (resConfig) {
42
- const url = buildUrl(resConfig);
43
- const method = String(resConfig?.method || "GET").toUpperCase();
44
- const ctype = String(headerOf(resConfig?.headers, "content-type") || "").toLowerCase();
45
- const isMultipart = ctype.includes("multipart/form-data");
46
- const payload = resConfig?.data;
47
- const params = resConfig?.params;
48
-
49
- try {
50
- let newData;
51
- if (method === "GET") {
52
- newData = await http.get(url, ctx.jar, params || null, ctx.globalOptions, ctx);
53
- } else if (isMultipart) {
54
- newData = await http.postFormData(url, ctx.jar, payload, params, ctx.globalOptions, ctx);
55
- } else {
56
- newData = await http.post(url, ctx.jar, payload, ctx.globalOptions, ctx);
57
- }
58
- return await parseAndCheckLogin(ctx, http)(newData);
59
- } catch (retryErr) {
60
- if (
61
- retryErr?.code === "ERR_INVALID_CHAR" ||
62
- (retryErr?.message && retryErr.message.includes("Invalid character in header"))
63
- ) {
64
- logger(
65
- `Auto login retry failed: Invalid header detected. Error: ${retryErr.message}`,
66
- "error"
67
- );
68
- const e = new Error("Not logged in. Auto login retry failed due to invalid header.");
69
- e.error = "Not logged in.";
70
- e.res = resData;
71
- e.originalError = retryErr;
72
- throw e;
73
- }
74
- logger(
75
- `Auto login retry failed: ${
76
- retryErr && retryErr.message ? retryErr.message : String(retryErr)
77
- }`,
78
- "error"
79
- );
80
- const e = new Error("Not logged in. Auto login retry failed.");
81
- e.error = "Not logged in.";
82
- e.res = resData;
83
- e.originalError = retryErr;
84
- throw e;
85
- }
86
- } else {
87
- const e = new Error(
88
- "Not logged in. Auto login successful but cannot retry request."
89
- );
90
- e.error = "Not logged in.";
91
- e.res = resData;
92
- throw e;
93
- }
116
+ return retryAfterLogin();
94
117
  } else {
95
- ctx.auto_login = false;
96
118
  const e = new Error("Not logged in. Auto login failed.");
97
119
  e.error = "Not logged in.";
98
120
  e.res = resData;
@@ -100,7 +122,6 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
100
122
  throw e;
101
123
  }
102
124
  } catch (autoLoginErr) {
103
- ctx.auto_login = false;
104
125
  if (autoLoginErr.error === "Not logged in.") {
105
126
  throw autoLoginErr;
106
127
  }
@@ -116,6 +137,11 @@ function createMaybeAutoLogin(ctx, http, helpers, emit, parseAndCheckLogin) {
116
137
  e.originalError = autoLoginErr;
117
138
  emit("autoLoginFailed", { error: e, res: resData });
118
139
  throw e;
140
+ } finally {
141
+ ctx.auto_login = false;
142
+ if (ctx._autoLoginPromise === autoLoginPromise) {
143
+ ctx._autoLoginPromise = null;
144
+ }
119
145
  }
120
146
  };
121
147
  }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+
3
+ const TEXT_EFFECTS = Object.freeze({
4
+ hearts: "1",
5
+ heart: "1",
6
+ love: "1",
7
+ gift: "2",
8
+ present: "2",
9
+ box: "2",
10
+ giftbox: "2",
11
+ fire: "3",
12
+ flame: "3",
13
+ hot: "3",
14
+ confetti: "4",
15
+ confecti: "4",
16
+ party: "4",
17
+ celebrate: "4",
18
+ celebration: "4",
19
+ sparkles: "5",
20
+ sparkle: "5",
21
+ star: "5",
22
+ stars: "5",
23
+ magic: "5"
24
+ });
25
+
26
+ const EFFECT_PROPERTIES = [
27
+ "textEffect",
28
+ "text_effect",
29
+ "text_effect_id",
30
+ "textEffectId",
31
+ "textEffectID",
32
+ "effect",
33
+ "effect_id",
34
+ "effectID",
35
+ "text_effect_name",
36
+ "effectName",
37
+ "effect_name"
38
+ ];
39
+
40
+ function toTextEffectId(effect) {
41
+ if (effect === null || effect === undefined) return null;
42
+ if (typeof effect === "number" && Number.isFinite(effect)) return String(effect);
43
+ if (typeof effect !== "string") return null;
44
+
45
+ const value = effect.trim();
46
+ if (!value) return null;
47
+ return TEXT_EFFECTS[value.toLowerCase()] || value;
48
+ }
49
+
50
+ function getTextEffectId(message) {
51
+ if (!message || typeof message !== "object") return null;
52
+ for (const property of EFFECT_PROPERTIES) {
53
+ if (message[property] !== undefined && message[property] !== null) {
54
+ const effectID = toTextEffectId(message[property]);
55
+ if (effectID) return effectID;
56
+ }
57
+ }
58
+
59
+ const rawIDs = Array.isArray(message.text_effect_ids)
60
+ ? message.text_effect_ids
61
+ : [message.text_effect_ids];
62
+ for (const rawID of rawIDs) {
63
+ const effectID = toTextEffectId(rawID);
64
+ if (effectID) return effectID;
65
+ }
66
+ return null;
67
+ }
68
+
69
+ function getTextEffectIds(message) {
70
+ if (!message || typeof message !== "object") return [];
71
+ const rawIDs = Array.isArray(message.text_effect_ids)
72
+ ? message.text_effect_ids
73
+ : [message.text_effect_ids];
74
+ return rawIDs
75
+ .map(toTextEffectId)
76
+ .filter(Boolean);
77
+ }
78
+
79
+ module.exports = {
80
+ EFFECT_PROPERTIES,
81
+ TEXT_EFFECTS,
82
+ getTextEffectId,
83
+ getTextEffectIds,
84
+ toTextEffectId
85
+ };