fca-nx 6.6.7 → 6.6.8

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.8",
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) {
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Modified by Xalman
3
+ * Fixed Auto-Logout, MQTT Heartbeat Leak, and Loop Reconnection Bugs.
4
+ */
5
+
1
6
  "use strict";
2
7
 
3
8
  const mqtt = require("mqtt");
@@ -19,7 +24,7 @@ const CYCLE_MS_DEFAULT = 60 * 60 * 1000;
19
24
  const RECONNECT_DELAY_MS_DEFAULT = 3000;
20
25
  const UNSUB_ALL_TIMEOUT_MS = 5000;
21
26
  const MAX_MQTT_RECONNECT_DELAY_MS = 60000;
22
- const MAX_MQTT_RECONNECT_ATTEMPTS = 10;
27
+ const MAX_MQTT_RECONNECT_ATTEMPTS = 15;
23
28
  const HEARTBEAT_INTERVAL_MS = 30000;
24
29
  const HEARTBEAT_TIMEOUT_MS = 10000;
25
30
 
@@ -76,12 +81,13 @@ 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
+ // Handle Auto-Logout and Checkpoint Auth triggers
85
+ if (/Not logged in|blocked the login|Checkpoint|Login approved/i.test(msg)) {
80
86
  emitAuth(
81
87
  ctx,
82
88
  api,
83
89
  globalCallback,
84
- /blocked/i.test(msg) ? "login_blocked" : "not_logged_in",
90
+ /blocked|checkpoint/i.test(msg) ? "login_blocked" : "not_logged_in",
85
91
  msg
86
92
  );
87
93
  }
@@ -110,11 +116,12 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
110
116
  return Promise.resolve();
111
117
  }
112
118
 
119
+ // Updated Doc ID to modern Facebook GraphQL Thread Query Endpoint to avoid logouts
113
120
  const form = {
114
121
  av: ctx.globalOptions.pageID || ctx.userID,
115
122
  queries: JSON.stringify({
116
123
  o0: {
117
- doc_id: "3336396659757871",
124
+ doc_id: "6007624976008514",
118
125
  query_params: {
119
126
  limit: 1,
120
127
  before: null,
@@ -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,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
192
201
  }
193
202
 
194
203
  try {
195
- ctx.mqttClient.publish("/ping", "{}", { qos: 0 });
204
+ // Send standard MQTT ping timestamp packet to keep Facebook connection alive
205
+ ctx.mqttClient.publish("/ping", JSON.stringify({ timestamp: Date.now() }), { qos: 0 });
196
206
  logger("mqtt heartbeat sent", "debug");
197
207
  } catch (err) {
198
208
  logger(`mqtt heartbeat error: ${err.message}`, "warn");
@@ -381,6 +391,41 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
381
391
  }
382
392
  }
383
393
 
394
+ function attachClientListeners() {
395
+ if (!ctx.mqttClient) return;
396
+
397
+ // Clean up prior event listeners to prevent memory leak & double-triggering
398
+ ctx.mqttClient.removeAllListeners("pong");
399
+ ctx.mqttClient.removeAllListeners("close");
400
+ ctx.mqttClient.removeAllListeners("error");
401
+
402
+ ctx.mqttClient.on("pong", () => {
403
+ lastPongTime = Date.now();
404
+ logger("mqtt pong received", "debug");
405
+ });
406
+
407
+ ctx.mqttClient.once("close", () => {
408
+ logger("mqtt connection closed", "warn");
409
+ stopHeartbeat();
410
+ if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
411
+ if (!isReconnecting) {
412
+ isReconnecting = true;
413
+ delayedReconnect();
414
+ }
415
+ }
416
+ });
417
+
418
+ ctx.mqttClient.once("error", (err) => {
419
+ logger(`mqtt error: ${err.message}`, "error");
420
+ if (!ctx._ending && ctx.globalOptions.autoReconnect !== false) {
421
+ if (!isReconnecting) {
422
+ isReconnecting = true;
423
+ forceCycle();
424
+ }
425
+ }
426
+ });
427
+ }
428
+
384
429
  return function (callback) {
385
430
  class MessageEmitter extends EventEmitter {
386
431
  stopListening(callback2) {
@@ -464,34 +509,8 @@ module.exports = function (defaultFuncs, api, ctx, opts) {
464
509
  } else {
465
510
  logger("mqtt starting listenMqtt", "info");
466
511
  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
- }
512
+ attachClientListeners();
513
+ startHeartbeat();
495
514
  }
496
515
 
497
516
  api.stopListening = msgEmitter.stopListening;