fca-nx 6.6.7 → 6.6.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fca-nx",
3
- "version": "6.6.7",
3
+ "version": "6.6.9",
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",
@@ -1,55 +1,60 @@
1
+ /**
2
+ * Send a friend request to a Facebook user.
3
+ */
4
+
1
5
  "use strict";
2
6
 
3
7
  const log = require("../../../func/logAdapter");
4
8
  const { parseAndCheckLogin } = require("../../utils/client");
5
9
  const { formatID } = require("../../utils/format");
6
10
 
7
- module.exports = function(defaultFuncs, api, ctx) {
11
+ module.exports = function (defaultFuncs, api, ctx) {
8
12
  return function addFriend(userID, callback) {
9
- let resolveFunc = function() {};
10
- let rejectFunc = function() {};
13
+ let resolveFunc;
14
+ let rejectFunc;
11
15
 
12
- const returnPromise = new Promise(function(resolve, reject) {
16
+ const returnPromise = new Promise(function (resolve, reject) {
13
17
  resolveFunc = resolve;
14
18
  rejectFunc = reject;
15
19
  });
16
20
 
17
- if (typeof callback !== "function") {
18
- callback = function(err, data) {
19
- if (err) {
20
- return rejectFunc(err);
21
- }
22
-
21
+ const handleCallback = (err, data) => {
22
+ if (typeof callback === "function") {
23
+ callback(err, data);
24
+ }
25
+ if (err) {
26
+ rejectFunc(err);
27
+ } else {
23
28
  resolveFunc(data);
24
- };
25
- }
29
+ }
30
+ };
26
31
 
27
32
  /*
28
33
  * Validate user ID
29
34
  */
35
+ let targetID;
30
36
  try {
31
- userID = formatID(userID);
37
+ targetID = formatID(userID);
32
38
  } catch (err) {
33
- return callback(err);
39
+ handleCallback(err);
40
+ return returnPromise;
34
41
  }
35
42
 
36
- if (!userID) {
37
- return callback(
38
- new Error("Invalid user ID")
39
- );
43
+ if (!targetID) {
44
+ handleCallback(new Error("Invalid user ID"));
45
+ return returnPromise;
40
46
  }
41
47
 
42
- if (String(userID) === String(ctx.userID)) {
43
- return callback(
44
- new Error("You cannot send a friend request to yourself")
45
- );
48
+ if (String(targetID) === String(ctx.userID)) {
49
+ handleCallback(new Error("You cannot send a friend request to yourself"));
50
+ return returnPromise;
46
51
  }
47
52
 
48
53
  /*
49
- * Facebook friend request endpoint
54
+ * Facebook friend request payload
50
55
  */
51
56
  const form = {
52
- uid: String(userID),
57
+ uid: String(targetID),
53
58
  viewer_id: String(ctx.userID),
54
59
  source: "profile_button",
55
60
  ref: "profile",
@@ -63,81 +68,42 @@ module.exports = function(defaultFuncs, api, ctx) {
63
68
  ctx.jar,
64
69
  form
65
70
  )
66
- .then(
67
- parseAndCheckLogin(ctx, defaultFuncs)
68
- )
69
- .then(function(resData) {
70
- /*
71
- * Facebook may return different response
72
- * structures depending on the account/session.
73
- */
71
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
72
+ .then(function (resData) {
74
73
  if (!resData) {
75
- throw new Error(
76
- "Empty response from Facebook"
77
- );
74
+ throw new Error("Empty response from Facebook");
78
75
  }
79
76
 
80
- if (
81
- resData.error ||
82
- resData.errors ||
83
- resData.errorDescription
84
- ) {
77
+ if (resData.error || resData.errors || resData.errorDescription) {
85
78
  throw resData;
86
79
  }
87
80
 
88
- /*
89
- * Some responses contain:
90
- *
91
- * payload.error
92
- * payload.err
93
- * payload.success
94
- */
95
81
  const payload = resData.payload;
96
82
 
97
83
  if (payload) {
98
- if (
99
- payload.error ||
100
- payload.err
101
- ) {
84
+ if (payload.error || payload.err) {
102
85
  throw payload;
103
86
  }
104
87
 
105
- if (
106
- payload.errorDescription
107
- ) {
108
- throw new Error(
109
- payload.errorDescription
110
- );
88
+ if (payload.errorDescription) {
89
+ throw new Error(payload.errorDescription);
111
90
  }
112
91
  }
113
92
 
114
- return resData;
115
- })
116
- .then(function(resData) {
117
- /*
118
- * Return a simple result instead of
119
- * exposing Facebook's whole response.
120
- */
121
93
  const result = {
122
94
  success: true,
123
- userID: String(userID),
95
+ userID: String(targetID),
124
96
  response: resData
125
97
  };
126
98
 
127
- return callback(
128
- null,
129
- result
130
- );
99
+ return handleCallback(null, result);
131
100
  })
132
- .catch(function(err) {
133
- log.error(
134
- "addFriend",
135
- err
136
- );
137
-
138
- return callback(err);
101
+ .catch(function (err) {
102
+ log.error("addFriend", err?.message || err);
103
+ return handleCallback(err);
139
104
  });
140
105
 
141
106
  return returnPromise;
142
107
  };
143
108
  };
109
+
@@ -1,3 +1,7 @@
1
+ /**d
2
+ * Change Facebook Profile Cover Photo via GraphQL Mutation.
3
+ */
4
+
1
5
  "use strict";
2
6
 
3
7
  const log = require("../../../func/logAdapter");
@@ -5,13 +9,14 @@ const { isReadableStream } = require("../../utils/constants");
5
9
  const { parseAndCheckLogin } = require("../../utils/client");
6
10
  const { getType } = require("../../utils/format");
7
11
 
8
- module.exports = function(defaultFuncs, api, ctx) {
9
-
12
+ module.exports = function (defaultFuncs, api, ctx) {
10
13
  function handleUpload(image, callback) {
14
+ const userID = ctx.i_userID || ctx.userID;
15
+
11
16
  const form = {
12
- profile_id: ctx.i_userID || ctx.userID,
17
+ profile_id: userID,
13
18
  photo_source: 57,
14
- av: ctx.i_userID || ctx.userID,
19
+ av: userID,
15
20
  file: image
16
21
  };
17
22
 
@@ -22,255 +27,135 @@ module.exports = function(defaultFuncs, api, ctx) {
22
27
  form,
23
28
  {}
24
29
  )
25
- .then(
26
- parseAndCheckLogin(ctx, defaultFuncs)
27
- )
28
- .then(function(resData) {
29
- if (
30
- !resData ||
31
- resData.error ||
32
- resData.errors ||
33
- !resData.payload
34
- ) {
35
- throw resData || new Error(
36
- "Cover image upload failed"
37
- );
30
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
31
+ .then(function (resData) {
32
+ if (!resData || resData.error || resData.errors || !resData.payload) {
33
+ throw resData || new Error("Cover image upload failed");
38
34
  }
39
35
 
40
36
  if (!resData.payload.fbid) {
41
- throw new Error(
42
- "Facebook did not return photo ID"
43
- );
37
+ throw new Error("Facebook did not return photo ID");
44
38
  }
45
39
 
46
40
  callback(null, resData);
47
41
  })
48
- .catch(function(err) {
42
+ .catch(function (err) {
49
43
  log.error("handleCoverUpload", err);
50
44
  callback(err);
51
45
  });
52
46
  }
53
47
 
54
- return function changeCover(
55
- image,
56
- callback
57
- ) {
58
-
59
- let resolveFunc = function() {};
60
- let rejectFunc = function() {};
48
+ return function changeCover(image, callback) {
49
+ let resolveFunc;
50
+ let rejectFunc;
61
51
 
62
- const returnPromise = new Promise(
63
- function(resolve, reject) {
64
- resolveFunc = resolve;
65
- rejectFunc = reject;
66
- }
67
- );
52
+ const returnPromise = new Promise(function (resolve, reject) {
53
+ resolveFunc = resolve;
54
+ rejectFunc = reject;
55
+ });
68
56
 
69
- /*
70
- * Callback handling
71
- */
72
57
  if (
73
58
  !callback &&
74
- (
75
- getType(image) === "Function" ||
76
- getType(image) === "AsyncFunction"
77
- )
59
+ (getType(image) === "Function" || getType(image) === "AsyncFunction")
78
60
  ) {
79
61
  callback = image;
80
62
  image = null;
81
63
  }
82
64
 
83
- if (!callback) {
84
- callback = function(err, data) {
85
- if (err) {
86
- return rejectFunc(err);
87
- }
88
-
65
+ const handleCallback = (err, data) => {
66
+ if (typeof callback === "function") {
67
+ callback(err, data);
68
+ }
69
+ if (err) {
70
+ rejectFunc(err);
71
+ } else {
89
72
  resolveFunc(data);
90
- };
91
- }
73
+ }
74
+ };
92
75
 
93
- /*
94
- * Validate image
95
- */
96
76
  if (!isReadableStream(image)) {
97
- return callback(
98
- new Error(
99
- "Image is not a readable stream"
100
- )
101
- );
77
+ handleCallback(new Error("Image is not a readable stream"));
78
+ return returnPromise;
102
79
  }
103
80
 
104
- /*
105
- * Upload cover image
106
- */
107
- handleUpload(
108
- image,
109
- function(err, payload) {
110
-
111
- if (err) {
112
- return callback(err);
113
- }
114
-
115
- const userID =
116
- ctx.i_userID ||
117
- ctx.userID;
118
-
119
- const photoID =
120
- payload?.payload?.fbid;
121
-
122
- if (!photoID) {
123
- return callback(
124
- new Error(
125
- "Cover photo ID not found"
126
- )
127
- );
128
- }
129
-
130
- /*
131
- * ProfileCometCoverPhotoUpdateMutation
132
- */
133
- const variables = {
134
- input: {
135
- attribution_id_v2:
136
- `ProfileCometCollectionRoot.react,` +
137
- `comet.profile.collection.photos_by,unexpected,` +
138
- `${Date.now()},770083,,;` +
139
-
140
- `ProfileCometCollectionRoot.react,` +
141
- `comet.profile.collection.photos_albums,unexpected,` +
142
- `${Date.now()},470774,,;` +
143
-
144
- `ProfileCometCollectionRoot.react,` +
145
- `comet.profile.collection.photos,unexpected,` +
146
- `${Date.now()},94740,,;` +
147
-
148
- `ProfileCometCollectionRoot.react,` +
149
- `comet.profile.collection.saved_reels_on_profile,unexpected,` +
150
- `${Date.now()},89669,,;` +
151
-
152
- `ProfileCometCollectionRoot.react,` +
153
- `comet.profile.collection.reels_tab,unexpected,` +
154
- `${Date.now()},152201,,`,
155
-
156
- cover_photo_id: String(photoID),
81
+ handleUpload(image, function (err, payload) {
82
+ if (err) {
83
+ return handleCallback(err);
84
+ }
157
85
 
158
- focus: {
159
- x: 0.5,
160
- y: 1
161
- },
86
+ const userID = ctx.i_userID || ctx.userID;
87
+ const photoID = payload?.payload?.fbid;
162
88
 
163
- target_user_id: String(userID),
164
- actor_id: String(userID),
89
+ if (!photoID) {
90
+ return handleCallback(new Error("Cover photo ID not found"));
91
+ }
165
92
 
166
- client_mutation_id:
167
- Math.round(
168
- Math.random() * 19
169
- ).toString()
93
+ const variables = {
94
+ input: {
95
+ attribution_id_v2:
96
+ `ProfileCometCollectionRoot.react,` +
97
+ `comet.profile.collection.photos_by,unexpected,` +
98
+ `${Date.now()},770083,,;` +
99
+ `ProfileCometCollectionRoot.react,` +
100
+ `comet.profile.collection.photos_albums,unexpected,` +
101
+ `${Date.now()},470774,,;` +
102
+ `ProfileCometCollectionRoot.react,` +
103
+ `comet.profile.collection.photos,unexpected,` +
104
+ `${Date.now()},94740,,;` +
105
+ `ProfileCometCollectionRoot.react,` +
106
+ `comet.profile.collection.saved_reels_on_profile,unexpected,` +
107
+ `${Date.now()},89669,,;` +
108
+ `ProfileCometCollectionRoot.react,` +
109
+ `comet.profile.collection.reels_tab,unexpected,` +
110
+ `${Date.now()},152201,,`,
111
+
112
+ cover_photo_id: String(photoID),
113
+ focus: {
114
+ x: 0.5,
115
+ y: 1
170
116
  },
117
+ target_user_id: String(userID),
118
+ actor_id: String(userID),
119
+ client_mutation_id: Math.round(Math.random() * 19).toString()
120
+ },
121
+ scale: 1,
122
+ contextualProfileContext: null
123
+ };
171
124
 
172
- scale: 1,
173
- contextualProfileContext: null
174
- };
175
-
176
- const form = {
177
- av: String(userID),
178
-
179
- fb_api_req_friendly_name:
180
- "ProfileCometCoverPhotoUpdateMutation",
181
-
182
- fb_api_caller_class:
183
- "RelayModern",
184
-
185
- doc_id:
186
- "8247793861913071",
187
-
188
- server_timestamps: true,
189
-
190
- variables:
191
- JSON.stringify(variables)
192
- };
193
-
194
- defaultFuncs
195
- .post(
196
- "https://www.facebook.com/api/graphql/",
197
- ctx.jar,
198
- form
199
- )
200
- .then(
201
- parseAndCheckLogin(
202
- ctx,
203
- defaultFuncs
204
- )
205
- )
206
- .then(function(resData) {
207
-
208
- if (
209
- !resData ||
210
- resData.error ||
211
- resData.errors
212
- ) {
213
- throw resData || new Error(
214
- "Cover photo update failed"
215
- );
216
- }
217
-
218
- /*
219
- * Facebook response
220
- */
221
- const coverURL =
222
- resData
223
- ?.data
224
- ?.user_update_cover_photo
225
- ?.user
226
- ?.cover_photo
227
- ?.photo
228
- ?.url;
229
-
230
- /*
231
- * কিছু response array আকারে আসতে পারে
232
- */
233
- const finalData =
234
- Array.isArray(resData)
235
- ? resData[0]
236
- : resData;
237
-
238
- const url =
239
- coverURL ||
240
- finalData
241
- ?.data
242
- ?.user_update_cover_photo
243
- ?.user
244
- ?.cover_photo
245
- ?.photo
246
- ?.url;
247
-
248
- if (!url) {
249
- /*
250
- * Mutation সফল হলেও URL না দিলে
251
- * পুরো response return করছি।
252
- */
253
- return callback(
254
- null,
255
- finalData
256
- );
257
- }
258
-
259
- return callback(
260
- null,
261
- url
262
- );
263
- })
264
- .catch(function(err) {
265
- log.error(
266
- "changeCover",
267
- err
268
- );
125
+ const form = {
126
+ av: String(userID),
127
+ fb_api_req_friendly_name: "ProfileCometCoverPhotoUpdateMutation",
128
+ fb_api_caller_class: "RelayModern",
129
+ doc_id: "8247793861913071",
130
+ server_timestamps: true,
131
+ variables: JSON.stringify(variables)
132
+ };
269
133
 
270
- return callback(err);
271
- });
272
- }
273
- );
134
+ defaultFuncs
135
+ .post("https://www.facebook.com/api/graphql/", ctx.jar, form)
136
+ .then(parseAndCheckLogin(ctx, defaultFuncs))
137
+ .then(function (resData) {
138
+ if (!resData || resData.error || resData.errors) {
139
+ throw resData || new Error("Cover photo update failed");
140
+ }
141
+
142
+ const finalData = Array.isArray(resData) ? resData[0] : resData;
143
+
144
+ const coverURL =
145
+ finalData?.data?.user_update_cover_photo?.user?.cover_photo?.photo?.url ||
146
+ resData?.data?.user_update_cover_photo?.user?.cover_photo?.photo?.url;
147
+
148
+ if (!coverURL) {
149
+ return handleCallback(null, finalData);
150
+ }
151
+
152
+ return handleCallback(null, coverURL);
153
+ })
154
+ .catch(function (err) {
155
+ log.error("changeCover", err?.message || err);
156
+ return handleCallback(err);
157
+ });
158
+ });
274
159
 
275
160
  return returnPromise;
276
161
  };
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Modified by Xalman
3
+ * HTTP Get Helper Function with Clean Promise & Callback Handling
4
+ */
5
+
1
6
  "use strict";
2
7
 
3
8
  const { getType } = require("../../utils/format");
@@ -5,14 +10,15 @@ const { get } = require("../../utils/request");
5
10
 
6
11
  const httpGetFactory = function (defaultFuncs, api, ctx) {
7
12
  return function httpGet(url, form, callback, notAPI) {
8
- let resolveFunc = () => { };
9
- let rejectFunc = () => { };
13
+ let resolveFunc;
14
+ let rejectFunc;
10
15
 
11
16
  const returnPromise = new Promise((resolve, reject) => {
12
17
  resolveFunc = resolve;
13
18
  rejectFunc = reject;
14
19
  });
15
20
 
21
+ // Handle optional 'form' parameter when callback is passed as second argument
16
22
  if (
17
23
  !callback &&
18
24
  (getType(form) === "Function" || getType(form) === "AsyncFunction")
@@ -23,20 +29,34 @@ const httpGetFactory = function (defaultFuncs, api, ctx) {
23
29
 
24
30
  form = form || {};
25
31
 
26
- callback =
27
- callback ||
28
- function (err, data) {
29
- if (err) return rejectFunc(err);
32
+ const handleCallback = (err, data) => {
33
+ if (typeof callback === "function") {
34
+ callback(err, data);
35
+ }
36
+ if (err) {
37
+ rejectFunc(err);
38
+ } else {
30
39
  resolveFunc(data);
31
- };
40
+ }
41
+ };
32
42
 
33
- const executor = notAPI ? get : defaultFuncs.get;
43
+ const executor = notAPI ? get : (defaultFuncs?.get || get);
34
44
 
35
- executor(url, ctx.jar, form)
36
- .then((resData) => callback(null, resData.data))
37
- .catch(function (err) {
38
- console.error("httpGet", err);
39
- return callback(err);
45
+ executor(url, ctx.jar, form, ctx.globalOptions || {})
46
+ .then((resData) => {
47
+ let data = resData?.data ?? resData;
48
+ if (typeof data === "object") {
49
+ try {
50
+ data = JSON.stringify(data, null, 2);
51
+ } catch {
52
+ // Retain object if stringify fails
53
+ }
54
+ }
55
+ handleCallback(null, data);
56
+ })
57
+ .catch((err) => {
58
+ console.error("httpGet error:", err?.message || err);
59
+ handleCallback(err, null);
40
60
  });
41
61
 
42
62
  return returnPromise;
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Modified by Xalman
3
+ * HTTP Post Helper Function with Clean Promise/Callback Handling
4
+ */
5
+
1
6
  "use strict";
2
7
 
3
8
  const { post } = require("../../utils/request");
@@ -13,6 +18,7 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
13
18
  rejectFunc = reject;
14
19
  });
15
20
 
21
+ // Callback parameter handling
16
22
  if (
17
23
  !callback &&
18
24
  (getType(form) === "Function" || getType(form) === "AsyncFunction")
@@ -21,12 +27,14 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
21
27
  form = {};
22
28
  }
23
29
 
30
+ if (typeof callback !== "function") {
31
+ callback = () => {};
32
+ }
33
+
24
34
  form = form || {};
25
35
 
26
36
  const handleCallback = (err, data) => {
27
- if (typeof callback === "function") {
28
- callback(err, data);
29
- }
37
+ callback(err, data);
30
38
  if (err) {
31
39
  rejectFunc(err);
32
40
  } else {
@@ -34,18 +42,23 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
34
42
  }
35
43
  };
36
44
 
37
- const executor = notAPI ? post : defaultFuncs.post;
45
+ const executor = notAPI ? post : (defaultFuncs?.post || post);
38
46
 
39
- executor(url, ctx.jar, form, ctx.globalOptions)
47
+ // Dynamic execution
48
+ executor(url, ctx.jar, form, ctx.globalOptions || {})
40
49
  .then((resData) => {
41
- let data = resData.data;
50
+ let data = resData?.data ?? resData;
42
51
  if (typeof data === "object") {
43
- data = JSON.stringify(data, null, 2);
52
+ try {
53
+ data = JSON.stringify(data, null, 2);
54
+ } catch {
55
+ // retain object if JSON stringify fails
56
+ }
44
57
  }
45
58
  handleCallback(null, data);
46
59
  })
47
60
  .catch((err) => {
48
- console.error("httpPost error:", err);
61
+ console.error("httpPost error:", err?.message || err);
49
62
  handleCallback(err, null);
50
63
  });
51
64
 
@@ -54,3 +67,4 @@ const httpPostFactory = function (defaultFuncs, api, ctx) {
54
67
  };
55
68
 
56
69
  module.exports = httpPostFactory;
70
+
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Create by Donix-VN (DongDev)
2
+ * Created by Donix-VN (DongDev)
3
3
  * Modified by MueidMursalinRifat & Xalman
4
4
  * Send a message using MQTT.
5
5
  * @param {string|object} msg - The message object or text to send.
@@ -171,12 +171,12 @@ module.exports = function (defaultFuncs, api, ctx) {
171
171
  metadata_dataclass: JSON.stringify({ media_accessibility_metadata: { alt_text: null } })
172
172
  };
173
173
 
174
- // --- FIX: TEXT EFFECTS SUPPORT ---
174
+ // --- TEXT EFFECTS SUPPORT FOR MQTT ---
175
175
  if (m.text_effect_ids) {
176
176
  let effectArray = [];
177
177
  if (Array.isArray(m.text_effect_ids)) {
178
178
  effectArray = m.text_effect_ids;
179
- } else if (typeof m.text_effect_ids === "string") {
179
+ } else if (typeof m.text_effect_ids === "string" || typeof m.text_effect_ids === "number") {
180
180
  effectArray = [m.text_effect_ids];
181
181
  }
182
182
  if (effectArray.length > 0) {
@@ -2,9 +2,10 @@
2
2
  /**
3
3
  * Fetches MQTT sync sequence ID from GraphQL and starts listenMqtt.
4
4
  * Handles retries and auto re-login via fca-config.json when session expires.
5
+ * Fixed by Xalman: Added fb_dtsg/jazoest payload & 1357032 Object error fallback.
5
6
  */
6
7
  const { getType } = require("../../../utils/format");
7
- const { parseAndCheckLogin, saveCookies } = require("../../../utils/client");
8
+ const { parseAndCheckLogin } = require("../../../utils/client");
8
9
  const path = require("path");
9
10
  const loginHelper = require("../../../../module/loginHelper");
10
11
 
@@ -69,21 +70,14 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
69
70
  if (typeof result.cookies === "string") {
70
71
  cookiePairs = normalizeCookieHeaderString(result.cookies);
71
72
  }
72
- // If cookies is an array, convert to pairs
73
73
  else if (Array.isArray(result.cookies)) {
74
74
  cookiePairs = result.cookies.map(c => {
75
- if (typeof c === "string") {
76
- // Already in "key=value" format
77
- return c;
78
- } else if (c && typeof c === "object") {
79
- // Object format {key, value} or {name, value}
80
- return `${c.key || c.name}=${c.value}`;
81
- }
75
+ if (typeof c === "string") return c;
76
+ if (c && typeof c === "object") return `${c.key || c.name}=${c.value}`;
82
77
  return null;
83
78
  }).filter(Boolean);
84
79
  }
85
80
 
86
- // Also check for cookie field (alternative field name)
87
81
  if (cookiePairs.length === 0 && result.cookie) {
88
82
  if (typeof result.cookie === "string") {
89
83
  cookiePairs = normalizeCookieHeaderString(result.cookie);
@@ -99,7 +93,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
99
93
  if (cookiePairs.length > 0 || result.uid) {
100
94
  logger(`getSeqID: auto re-login successful! UID: ${result.uid}, Cookies: ${cookiePairs.length}`, "info");
101
95
 
102
- // Apply cookies to ctx.jar using setJarFromPairs approach
103
96
  if (ctx.jar && cookiePairs.length > 0) {
104
97
  const expires = new Date(Date.now() + 31536e6).toUTCString();
105
98
  for (const kv of cookiePairs) {
@@ -117,23 +110,11 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
117
110
  logger(`getSeqID: applied ${cookiePairs.length} API cookies to jar`, "info");
118
111
  }
119
112
 
120
- // Now refresh web session to get proper web cookies
121
113
  logger("getSeqID: refreshing web session after API login...", "info");
122
114
  try {
123
115
  const { get } = require("../../../utils/request");
124
116
  const { saveCookies: saveWebCookies } = require("../../../utils/client");
125
117
 
126
- // NOTE: cookies are applied to ctx.jar only (above), not to any
127
- // process-wide/global jar. Each login/session now owns its own
128
- // CookieJar (see module/loginHelper.js); writing this account's
129
- // cookies into a shared global jar would leak them into any other
130
- // account/session running in the same process and corrupt both
131
- // sessions' identity - exactly the kind of bug that produces
132
- // random/abnormal logouts when running more than one account.
133
-
134
- // Fetch Facebook to refresh and get web session cookies
135
- // Do this multiple times to ensure session is fully established
136
- // Try both m.facebook.com and www.facebook.com
137
118
  let webResponse = null;
138
119
  let htmlContent = "";
139
120
  const htmlUID = body => {
@@ -143,10 +124,8 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
143
124
  const isValidUID = uid => uid && uid !== "0" && /^\d+$/.test(uid) && parseInt(uid, 10) > 0;
144
125
  const urlsToTry = ["https://m.facebook.com/", "https://www.facebook.com/"];
145
126
 
146
- // Try refreshing up to 3 times to get valid session
147
127
  for (let attempt = 0; attempt < 3; attempt++) {
148
128
  try {
149
- // Try m.facebook.com first (mobile version often works better for API login)
150
129
  const urlToUse = attempt === 0 ? urlsToTry[0] : urlsToTry[attempt % urlsToTry.length];
151
130
  logger(`getSeqID: Refreshing ${urlToUse} (attempt ${attempt + 1}/3)...`, "info");
152
131
 
@@ -155,7 +134,6 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
155
134
  await saveWebCookies(ctx.jar)(webResponse);
156
135
  htmlContent = typeof webResponse.data === "string" ? webResponse.data : String(webResponse.data || "");
157
136
 
158
- // Check if HTML contains valid USER_ID
159
137
  const htmlUserID = htmlUID(htmlContent);
160
138
  if (isValidUID(htmlUserID)) {
161
139
  logger(`getSeqID: Found valid USER_ID in HTML from ${urlToUse}: ${htmlUserID}`, "info");
@@ -174,20 +152,16 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
174
152
  }
175
153
 
176
154
  if (webResponse && webResponse.data) {
177
- // Get updated cookies from jar
178
155
  const updatedCookies = await ctx.jar.getCookies("https://www.facebook.com");
179
156
  logger(`getSeqID: refreshed session, now have ${updatedCookies.length} web cookies`, "info");
180
157
 
181
- // Check HTML for USER_ID
182
158
  const htmlUserID = htmlUID(htmlContent);
183
159
  if (!isValidUID(htmlUserID)) {
184
160
  logger("getSeqID: WARNING - HTML does not show valid USER_ID after refresh. Session may not be fully established.", "warn");
185
161
  }
186
162
 
187
- // Update ctx state
188
163
  if (ctx) {
189
164
  ctx.loggedIn = true;
190
- // Use USER_ID from HTML if available, otherwise from API response
191
165
  if (isValidUID(htmlUserID)) {
192
166
  ctx.userID = htmlUserID;
193
167
  logger(`getSeqID: Updated ctx.userID from HTML: ${htmlUserID}`, "info");
@@ -203,7 +177,7 @@ async function tryAutoLogin(logger, config, ctx, defaultFuncs) {
203
177
  logger(`getSeqID: web session refresh failed - ${refreshErr && refreshErr.message ? refreshErr.message : String(refreshErr)}`, "warn");
204
178
  }
205
179
 
206
- return { ...result, cookies };
180
+ return { ...result, cookies: parseCookieString(result.cookies || result.cookie) };
207
181
  }
208
182
  }
209
183
 
@@ -223,25 +197,61 @@ module.exports = function createGetSeqID(deps) {
223
197
  const RETRY_DELAY = 2000;
224
198
  ctx.t_mqttCalled = false;
225
199
 
200
+ // Ensure essential tokens are injected into GraphQL Batch Payload
201
+ if (!form) {
202
+ form = {
203
+ av: ctx.globalOptions.pageID || ctx.userID,
204
+ fb_dtsg: ctx.fb_dtsg,
205
+ jazoest: ctx.jazoest,
206
+ queries: JSON.stringify({
207
+ o0: {
208
+ doc_id: "3336396659757871",
209
+ query_params: {
210
+ limit: 1,
211
+ before: null,
212
+ tags: ["INBOX", "PENDING", "OTHER"],
213
+ includeDeliveryReceipts: false,
214
+ includeSeqID: true
215
+ }
216
+ }
217
+ })
218
+ };
219
+ } else {
220
+ if (!form.fb_dtsg && ctx.fb_dtsg) form.fb_dtsg = ctx.fb_dtsg;
221
+ if (!form.jazoest && ctx.jazoest) form.jazoest = ctx.jazoest;
222
+ }
223
+
226
224
  return defaultFuncs
227
225
  .post("https://www.facebook.com/api/graphqlbatch/", ctx.jar, form)
228
226
  .then(parseAndCheckLogin(ctx, defaultFuncs))
229
227
  .then(async resData => {
230
- // Better error handling: check what we actually got
228
+ // Safe check for non-array responses (such as Error Objects from FB)
231
229
  if (getType(resData) !== "Array") {
232
- // Log what we actually received for debugging
233
- logger(`getSeqID: Unexpected response type: ${getType(resData)}, value: ${JSON.stringify(resData).substring(0, 200)}`, "warn");
234
-
235
- // If parseAndCheckLogin returned an error object, check if it's an auth error
230
+ logger(`getSeqID: Response is not Array, received: ${getType(resData)}`, "warn");
231
+
232
+ // Handle Facebook GraphQL 1357032 or transient error responses without triggering re-login
236
233
  if (resData && typeof resData === "object") {
237
- const errorMsg = resData.error || resData.message || "";
234
+ const errCode = resData.error || resData.errorCode;
235
+ const errorMsg = resData.errorSummary || resData.message || "";
236
+
237
+ if (errCode === 1357032 || /Something Went Wrong/i.test(errorMsg)) {
238
+ logger("getSeqID: FB returned error 1357032. Using fallback seqID and continuing to MQTT.", "warn");
239
+ ctx.lastSeqId = ctx.lastSeqId || "0";
240
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
241
+ return;
242
+ }
243
+
238
244
  if (/Not logged in|login|blocked|401|403|checkpoint/i.test(errorMsg)) {
239
245
  throw { error: "Not logged in", originalResponse: resData };
240
246
  }
241
247
  }
242
-
243
- throw { error: "Not logged in", originalResponse: resData };
248
+
249
+ // Fallback if it's an unrecognized object
250
+ ctx.lastSeqId = ctx.lastSeqId || "0";
251
+ listenMqtt(defaultFuncs, api, ctx, globalCallback);
252
+ return;
244
253
  }
254
+
245
255
  if (!Array.isArray(resData) || !resData.length) return;
246
256
  const lastRes = resData[resData.length - 1];
247
257
  if (lastRes && lastRes.successful_results === 0) return;
@@ -251,7 +261,7 @@ module.exports = function createGetSeqID(deps) {
251
261
  ctx.lastSeqId = syncSeqId;
252
262
  logger("mqtt getSeqID ok -> listenMqtt()", "info");
253
263
  } else {
254
- ctx.lastSeqId = ctx.lastSeqId || 0;
264
+ ctx.lastSeqId = ctx.lastSeqId || "0";
255
265
  logger("getSeqID: sync_sequence_id not found, fallback lastSeqId=" + ctx.lastSeqId, "warn");
256
266
  }
257
267
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
@@ -260,11 +270,6 @@ module.exports = function createGetSeqID(deps) {
260
270
  const detail = (err && err.detail && err.detail.message) ? ` | detail=${err.detail.message}` : "";
261
271
  const msg = ((err && err.error) || (err && err.message) || String(err || "")) + detail;
262
272
 
263
- // Check if this is a CONFIRMED auth-related error (session actually
264
- // rejected) versus a transient network problem. Only confirmed auth
265
- // errors should ever lead to emitAuth() / auto-login; a timeout or
266
- // connection reset is not evidence the session is invalid and must
267
- // not be treated as a logout.
268
273
  const isAuthError = /Not logged in|no sync_sequence_id found|blocked the login|401|403/i.test(msg);
269
274
  const netCode = err?.code || err?.originalError?.code || "";
270
275
  const isNetworkError = !isAuthError && (
@@ -279,23 +284,16 @@ module.exports = function createGetSeqID(deps) {
279
284
  await new Promise(resolve => setTimeout(resolve, delay));
280
285
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
281
286
  }
282
- // Exhausted retries on a network error - this is NOT a confirmed
283
- // auth failure, so we do not call emitAuth()/tear down the
284
- // session. Surface it and let the caller's own reconnect/backoff
285
- // logic (see connectMqtt.js) decide whether to keep trying.
286
- logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now (session left intact): ${msg}`, "error");
287
+ logger(`getSeqID: network error persisted after ${MAX_RETRIES} retries, giving up for now: ${msg}`, "error");
287
288
  return;
288
289
  }
289
290
 
290
- // For confirmed auth errors, try retry + auto-login
291
291
  if (isAuthError) {
292
- // Retry logic with increasing delay
293
292
  if (retryCount < MAX_RETRIES) {
294
- const delay = RETRY_DELAY * (retryCount + 1); // Increasing delay: 2s, 4s, 6s
293
+ const delay = RETRY_DELAY * (retryCount + 1);
295
294
  logger(`getSeqID: retry ${retryCount + 1}/${MAX_RETRIES} after ${delay}ms... (error: ${msg})`, "warn");
296
295
  await new Promise(resolve => setTimeout(resolve, delay));
297
296
 
298
- // Before retrying, try to refresh the session if this is the first retry
299
297
  if (retryCount === 0 && ctx.loggedIn) {
300
298
  try {
301
299
  logger("getSeqID: refreshing session before retry...", "info");
@@ -310,19 +308,16 @@ module.exports = function createGetSeqID(deps) {
310
308
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, retryCount + 1);
311
309
  }
312
310
 
313
- // All retries failed, try auto-login
314
311
  logger("getSeqID: all retries failed, attempting auto re-login...", "warn");
315
312
  const config = getConfig();
316
313
  const loginResult = await tryAutoLogin(logger, config, ctx, defaultFuncs);
317
314
 
318
315
  if (loginResult) {
319
- // Wait longer after auto-login to ensure session is ready
320
316
  logger("getSeqID: retrying with new session...", "info");
321
- await new Promise(resolve => setTimeout(resolve, 3000)); // Increased delay to 3s
317
+ await new Promise(resolve => setTimeout(resolve, 3000));
322
318
  return getSeqID(defaultFuncs, api, ctx, globalCallback, form, 0);
323
319
  }
324
320
 
325
- // Determine the auth error type
326
321
  if (/blocked/i.test(msg)) {
327
322
  return emitAuth(ctx, api, globalCallback, "login_blocked", msg);
328
323
  }
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Fixed and Optimized listenMqtt.js
3
+ * Prevents MQTT loop hangs, fixes heartbeat ping leaks, and cleans up event listeners.
4
+ */
5
+
1
6
  "use strict";
2
7
 
3
8
  const mqtt = require("mqtt");
@@ -76,12 +81,12 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
76
81
  function postSafe(...args) {
77
82
  return rawPost(...args).catch(err => {
78
83
  const msg = (err && err.error) || (err && err.message) || String(err || "");
79
- if (/Not logged in|blocked the login/i.test(msg)) {
84
+ if (/Not logged in|blocked the login|Checkpoint/i.test(msg)) {
80
85
  emitAuth(
81
86
  ctx,
82
87
  api,
83
88
  globalCallback,
84
- /blocked/i.test(msg) ? "login_blocked" : "not_logged_in",
89
+ /blocked|checkpoint/i.test(msg) ? "login_blocked" : "not_logged_in",
85
90
  msg
86
91
  );
87
92
  }
@@ -112,6 +117,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
112
117
 
113
118
  const form = {
114
119
  av: ctx.globalOptions.pageID || ctx.userID,
120
+ fb_dtsg: ctx.fb_dtsg,
121
+ jazoest: ctx.jazoest,
115
122
  queries: JSON.stringify({
116
123
  o0: {
117
124
  doc_id: "3336396659757871",
@@ -178,6 +185,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
178
185
  stopHeartbeat();
179
186
  if (!isConnected()) return;
180
187
 
188
+ lastPongTime = Date.now();
189
+
181
190
  heartbeatTimer = setInterval(() => {
182
191
  if (!isConnected()) {
183
192
  stopHeartbeat();
@@ -192,7 +201,7 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
192
201
  }
193
202
 
194
203
  try {
195
- ctx.mqttClient.publish("/ping", "{}", { qos: 0 });
204
+ ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
196
205
  logger("mqtt heartbeat sent", "debug");
197
206
  } catch (err) {
198
207
  logger(`mqtt heartbeat error: ${err.message}`, "warn");
@@ -381,6 +390,40 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
381
390
  }
382
391
  }
383
392
 
393
+ function attachClientListeners() {
394
+ if (!ctx.mqttClient) return;
395
+
396
+ ctx.mqttClient.removeAllListeners("pong");
397
+ ctx.mqttClient.removeAllListeners("close");
398
+ ctx.mqttClient.removeAllListeners("error");
399
+
400
+ ctx.mqttClient.on("pong", () => {
401
+ lastPongTime = Date.now();
402
+ logger("mqtt pong received", "debug");
403
+ });
404
+
405
+ ctx.mqttClient.once("close", () => {
406
+ logger("mqtt connection closed", "warn");
407
+ stopHeartbeat();
408
+ if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
409
+ if (!isReconnecting) {
410
+ isReconnecting = true;
411
+ delayedReconnect();
412
+ }
413
+ }
414
+ });
415
+
416
+ ctx.mqttClient.once("error", (err) => {
417
+ logger(`mqtt error: ${err.message}`, "error");
418
+ if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
419
+ if (!isReconnecting) {
420
+ isReconnecting = true;
421
+ forceCycle();
422
+ }
423
+ }
424
+ });
425
+ }
426
+
384
427
  return function (callback) {
385
428
  class MessageEmitter extends EventEmitter {
386
429
  stopListening(callback2) {
@@ -464,34 +507,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
464
507
  } else {
465
508
  logger("mqtt starting listenMqtt", "info");
466
509
  listenMqtt(defaultFuncs, api, ctx, globalCallback);
467
-
468
- if (isConnected()) {
469
- startHeartbeat();
470
-
471
- ctx.mqttClient.on("pong", () => {
472
- lastPongTime = Date.now();
473
- logger("mqtt pong received", "debug");
474
- });
475
-
476
- ctx.mqttClient.on("close", () => {
477
- logger("mqtt connection closed", "warn");
478
- stopHeartbeat();
479
- if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
480
- isReconnecting = true;
481
- delayedReconnect();
482
- }
483
- });
484
-
485
- ctx.mqttClient.on("error", (err) => {
486
- logger(`mqtt error: ${err.message}`, "error");
487
- if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
488
- if (!isReconnecting) {
489
- isReconnecting = true;
490
- forceCycle();
491
- }
492
- }
493
- });
494
- }
510
+ attachClientListeners();
511
+ startHeartbeat();
495
512
  }
496
513
 
497
514
  api.stopListening = msgEmitter.stopListening;