shadowx-fca 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,14 +1,6 @@
1
- Here's a comprehensive README.md for your shadowx-fca package:
2
-
3
1
  ```markdown
4
2
  # shadowx-fca
5
-
6
- <div align="center">
7
- <img src="https://img.shields.io/npm/v/shadowx-fca.svg?style=for-the-badge" alt="NPM Version">
8
- <img src="https://img.shields.io/npm/dt/shadowx-fca.svg?style=for-the-badge" alt="NPM Downloads">
9
- <img src="https://img.shields.io/github/license/mueidmursalinrifat/shadowx-fca.svg?style=for-the-badge" alt="License">
10
- <img src="https://img.shields.io/badge/node-%3E%3D14.0.0-brightgreen.svg?style=for-the-badge" alt="Node Version">
11
- </div>
3
+ #Mueid Mursalin Rifat
12
4
 
13
5
  <p align="center">
14
6
  <strong>Unofficial Facebook Chat API for Node.js with Auto-Update System</strong><br>
@@ -51,8 +43,8 @@ npm install shadowx-fca
51
43
 
52
44
  Requirements
53
45
 
54
- · Node.js >= 14.0.0
55
- · npm >= 6.0.0
46
+ · Node.js >= 16.0.0
47
+ · npm >= 7.0.0
56
48
 
57
49
  🚀 Quick Start
58
50
 
package/index.js CHANGED
@@ -3,624 +3,454 @@
3
3
  var utils = require("./utils");
4
4
  var cheerio = require("cheerio");
5
5
  var log = require("npmlog");
6
- var { checkForFCAUpdate } = require("./checkUpdate");
7
- const fs = require('fs');
8
- const path = require('path');
9
-
10
6
  log.maxRecordSize = 100;
11
7
  var checkVerified = null;
12
-
13
8
  const Boolean_Option = ['online', 'selfListen', 'listenEvents', 'updatePresence', 'forceLogin', 'autoMarkDelivery', 'autoMarkRead', 'listenTyping', 'autoReconnect', 'emitReady'];
14
-
15
9
  global.ditconmemay = false;
16
- global.stfcaUpdateChecked = false;
17
-
18
- // Rotating user agents to avoid detection
19
- const USER_AGENTS = [
20
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
21
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
22
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
23
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
24
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
25
- ];
26
-
27
- function getRandomUserAgent() {
28
- return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
29
- }
30
-
31
- // Delay function to avoid rate limiting
32
- function delay(ms) {
33
- return new Promise(resolve => setTimeout(resolve, ms));
34
- }
35
10
 
36
11
  function setOptions(globalOptions, options) {
37
- Object.keys(options).map(function (key) {
38
- switch (Boolean_Option.includes(key)) {
39
- case true: {
40
- globalOptions[key] = Boolean(options[key]);
41
- break;
42
- }
43
- case false: {
44
- switch (key) {
45
- case 'pauseLog': {
46
- if (options.pauseLog) log.pause();
47
- else log.resume();
48
- break;
49
- }
50
- case 'logLevel': {
51
- log.level = options.logLevel;
52
- globalOptions.logLevel = options.logLevel;
53
- break;
54
- }
55
- case 'logRecordSize': {
56
- log.maxRecordSize = options.logRecordSize;
57
- globalOptions.logRecordSize = options.logRecordSize;
58
- break;
59
- }
60
- case 'pageID': {
61
- globalOptions.pageID = options.pageID.toString();
62
- break;
63
- }
64
- case 'userAgent': {
65
- globalOptions.userAgent = options.userAgent || getRandomUserAgent();
66
- break;
67
- }
68
- case 'proxy': {
69
- if (typeof options.proxy != "string") {
70
- delete globalOptions.proxy;
71
- utils.setProxy();
72
- } else {
73
- globalOptions.proxy = options.proxy;
74
- utils.setProxy(globalOptions.proxy);
75
- }
76
- break;
77
- }
78
- case 'delayBetweenRequests': {
79
- globalOptions.delayBetweenRequests = options.delayBetweenRequests || 1000;
80
- break;
81
- }
82
- default: {
83
- log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
84
- break;
85
- }
86
- }
87
- break;
88
- }
89
- }
90
- });
12
+ Object.keys(options).map(function (key) {
13
+ switch (Boolean_Option.includes(key)) {
14
+ case true: {
15
+ globalOptions[key] = Boolean(options[key]);
16
+ break;
17
+ }
18
+ case false: {
19
+ switch (key) {
20
+ case 'pauseLog': {
21
+ if (options.pauseLog) log.pause();
22
+ else log.resume();
23
+ break;
24
+ }
25
+ case 'logLevel': {
26
+ log.level = options.logLevel;
27
+ globalOptions.logLevel = options.logLevel;
28
+ break;
29
+ }
30
+ case 'logRecordSize': {
31
+ log.maxRecordSize = options.logRecordSize;
32
+ globalOptions.logRecordSize = options.logRecordSize;
33
+ break;
34
+ }
35
+ case 'pageID': {
36
+ globalOptions.pageID = options.pageID.toString();
37
+ break;
38
+ }
39
+ case 'userAgent': {
40
+ globalOptions.userAgent = (options.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36');
41
+ break;
42
+ }
43
+ case 'proxy': {
44
+ if (typeof options.proxy != "string") {
45
+ delete globalOptions.proxy;
46
+ utils.setProxy();
47
+ } else {
48
+ globalOptions.proxy = options.proxy;
49
+ utils.setProxy(globalOptions.proxy);
50
+ }
51
+ break;
52
+ }
53
+ default: {
54
+ log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
55
+ break;
56
+ }
57
+ }
58
+ break;
59
+ }
60
+ }
61
+ });
91
62
  }
92
63
 
93
64
  function buildAPI(globalOptions, html, jar) {
94
- let fb_dtsg = null;
95
- let irisSeqID = null;
96
-
97
- function extractFromHTML() {
98
- try {
99
- const $ = cheerio.load(html);
100
- $('script').each((i, script) => {
101
- if (!fb_dtsg) {
102
- const scriptText = $(script).html() || '';
103
- const patterns = [
104
- /\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
105
- /\["DTSGInitData",\[\],{"token":"([^"]+)"/,
106
- /"token":"([^"]+)"/,
107
- /{\\"token\\":\\"([^\\]+)\\"/,
108
- /,\{"token":"([^"]+)"\},\d+\]/,
109
- /"async_get_token":"([^"]+)"/,
110
- /"dtsg":\{"token":"([^"]+)"/,
111
- /DTSGInitialData[^>]+>([^<]+)/
112
- ];
113
- for (const pattern of patterns) {
114
- const match = scriptText.match(pattern);
115
- if (match && match[1]) {
116
- try {
117
- const possibleJson = match[1].replace(/\\"/g, '"');
118
- const parsed = JSON.parse(possibleJson);
119
- fb_dtsg = parsed.token || parsed;
120
- } catch {
121
- fb_dtsg = match[1];
122
- }
123
- if (fb_dtsg) break;
124
- }
125
- }
126
- }
127
- });
128
- if (!fb_dtsg) {
129
- const dtsgInput = $('input[name="fb_dtsg"]').val();
130
- if (dtsgInput) fb_dtsg = dtsgInput;
131
- }
132
- const seqMatches = html.match(/irisSeqID":"([^"]+)"/);
133
- if (seqMatches && seqMatches[1]) {
134
- irisSeqID = seqMatches[1];
135
- }
136
- try {
137
- const jsonMatches = html.match(/\{"dtsg":({[^}]+})/);
138
- if (jsonMatches && jsonMatches[1]) {
139
- const dtsgData = JSON.parse(jsonMatches[1]);
140
- if (dtsgData.token) fb_dtsg = dtsgData.token;
141
- }
142
- } catch { }
143
- if (fb_dtsg) {
144
- log.info("Found fb_dtsg token");
145
- }
146
- } catch (e) {
147
- log.error("Error finding fb_dtsg:", e);
148
- }
149
- }
150
-
151
- extractFromHTML();
152
-
153
- var userID;
154
- var cookies = jar.getCookies("https://www.facebook.com");
155
- var userCookie = cookies.find(cookie => cookie.cookieString().startsWith("c_user="));
156
- var tiktikCookie = cookies.find(cookie => cookie.cookieString().startsWith("i_user="));
157
-
158
- if (!userCookie && !tiktikCookie) {
159
- log.error("Error! Your cookiestate is not valid!");
160
- throw new Error("Invalid appState");
161
- }
162
-
163
- if (html.includes("/checkpoint/block/?next")) {
164
- log.error('error', "Appstate is dead, please refresh it!", 'error');
165
- throw new Error("AppState expired");
166
- }
167
-
168
- userID = (tiktikCookie || userCookie).cookieString().split("=")[1];
169
-
170
- try { clearInterval(checkVerified); } catch (_) { }
171
-
172
- const clientID = (Math.random() * 2147483648 | 0).toString(16);
173
- let mqttEndpoint = `wss://edge-chat.facebook.com/chat?region=pnb&sid=${userID}`;
174
- let region = "PNB";
175
-
176
- try {
177
- const endpointMatch = html.match(/"endpoint":"([^"]+)"/);
178
- if (endpointMatch && endpointMatch.input && endpointMatch.input.includes("601051028565049")) {
179
- log.error(`Login error detected`);
180
- global.ditconmemay = true;
181
- }
182
- if (endpointMatch) {
183
- mqttEndpoint = endpointMatch[1].replace(/\\\//g, '/');
184
- const url = new URL(mqttEndpoint);
185
- region = url.searchParams.get('region')?.toUpperCase() || "PNB";
186
- }
187
- } catch (e) {
188
- log.warn('Using default MQTT endpoint');
189
- }
190
-
191
- log.info('Building API...');
192
-
193
- var ctx = {
194
- userID: userID,
195
- jar: jar,
196
- clientID: clientID,
197
- globalOptions: globalOptions,
198
- loggedIn: true,
199
- access_token: 'NONE',
200
- clientMutationId: 0,
201
- mqttClient: undefined,
202
- lastSeqId: irisSeqID,
203
- syncToken: undefined,
204
- mqttEndpoint: mqttEndpoint,
205
- region: region,
206
- firstListen: true,
207
- fb_dtsg: fb_dtsg,
208
- req_ID: 0,
209
- callback_Task: {},
210
- wsReqNumber: 0,
211
- wsTaskNumber: 0,
212
- reqCallbacks: {},
213
- threadTypes: {}
214
- };
215
-
216
- let config = { enableTypingIndicator: false, typingDuration: 4000 };
217
-
218
- try {
219
- const rootConfigPath = path.join(process.cwd(), 'config.json');
220
- if (fs.existsSync(rootConfigPath)) {
221
- const rootConfig = JSON.parse(fs.readFileSync(rootConfigPath, 'utf8'));
222
- if (rootConfig && typeof rootConfig === 'object') {
223
- if (typeof rootConfig.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = rootConfig.enableTypingIndicator;
224
- if (typeof rootConfig.typingDuration !== 'undefined') config.typingDuration = rootConfig.typingDuration;
225
- }
226
- }
227
-
228
- const fcaConfigPath = path.join(__dirname, 'config.json');
229
- if (fs.existsSync(fcaConfigPath)) {
230
- const fcaConfig = JSON.parse(fs.readFileSync(fcaConfigPath, 'utf8'));
231
- if (fcaConfig && typeof fcaConfig === 'object') {
232
- if (typeof fcaConfig.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = fcaConfig.enableTypingIndicator;
233
- if (typeof fcaConfig.typingDuration !== 'undefined') config.typingDuration = fcaConfig.typingDuration;
234
- }
235
- }
236
-
237
- if (global.GoatBot && global.GoatBot.config) {
238
- if (typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = global.GoatBot.config.enableTypingIndicator;
239
- if (typeof global.GoatBot.config.typingDuration !== 'undefined') config.typingDuration = global.GoatBot.config.typingDuration;
240
- }
241
- } catch (e) {
242
- log.warn('Error loading config.json:', e.message);
243
- }
244
-
245
- const refreshFcaConfig = () => {
246
- try {
247
- const updatedConfig = { enableTypingIndicator: false, typingDuration: 4000 };
248
-
249
- if (fs.existsSync(path.join(process.cwd(), 'config.json'))) {
250
- const rootConfig = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'config.json'), 'utf8'));
251
- if (rootConfig && typeof rootConfig === 'object') {
252
- if (typeof rootConfig.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = rootConfig.enableTypingIndicator;
253
- if (typeof rootConfig.typingDuration !== 'undefined') updatedConfig.typingDuration = rootConfig.typingDuration;
254
- }
255
- }
256
-
257
- if (fs.existsSync(path.join(__dirname, 'config.json'))) {
258
- const fcaConfig = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8'));
259
- if (fcaConfig && typeof fcaConfig === 'object') {
260
- if (typeof fcaConfig.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = fcaConfig.enableTypingIndicator;
261
- if (typeof fcaConfig.typingDuration !== 'undefined') updatedConfig.typingDuration = fcaConfig.typingDuration;
262
- }
263
- }
264
-
265
- if (global.GoatBot && global.GoatBot.config) {
266
- if (typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = global.GoatBot.config.enableTypingIndicator;
267
- if (typeof global.GoatBot.config.typingDuration !== 'undefined') updatedConfig.typingDuration = global.GoatBot.config.typingDuration;
268
- }
269
-
270
- ctx.config = updatedConfig;
271
- config = updatedConfig;
272
- } catch (e) {
273
- log.warn('Failed to refresh fca config:', e.message);
274
- }
275
- };
276
-
277
- refreshFcaConfig();
278
- ctx.refreshFcaConfig = refreshFcaConfig;
279
- if (global.GoatBot) {
280
- global.GoatBot.refreshFcaConfig = refreshFcaConfig;
281
- }
282
-
283
- ctx.config = config;
284
-
285
- var api = {
286
- setOptions: setOptions.bind(null, globalOptions),
287
- getAppState: () => utils.getAppState(jar),
288
- postFormData: (url, body) => utils.makeDefaults(html, userID, ctx).postFormData(url, ctx.jar, body)
289
- };
290
-
291
- var defaultFuncs = utils.makeDefaults(html, userID, ctx);
292
- api.postFormData = function (url, body) {
293
- return defaultFuncs.postFormData(url, ctx.jar, body);
294
- };
295
-
296
- api.getFreshDtsg = async function () {
297
- try {
298
- await delay(globalOptions.delayBetweenRequests || 1000);
299
- const res = await defaultFuncs.get('https://www.facebook.com/', jar, null, globalOptions);
300
- const $ = cheerio.load(res.body);
301
- let newDtsg;
302
- const patterns = [
303
- /\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
304
- /\["DTSGInitData",\[\],{"token":"([^"]+)"/,
305
- /"token":"([^"]+)"/,
306
- /name="fb_dtsg" value="([^"]+)"/
307
- ];
308
-
309
- $('script').each((i, script) => {
310
- if (!newDtsg) {
311
- const scriptText = $(script).html() || '';
312
- for (const pattern of patterns) {
313
- const match = scriptText.match(pattern);
314
- if (match && match[1]) {
315
- newDtsg = match[1];
316
- break;
317
- }
318
- }
319
- }
320
- });
321
-
322
- if (!newDtsg) {
323
- newDtsg = $('input[name="fb_dtsg"]').val();
324
- }
325
-
326
- return newDtsg;
327
- } catch (e) {
328
- log.error("Error getting fresh dtsg:", e.message);
329
- return null;
330
- }
331
- };
332
-
333
- // Load API modules
334
- const srcPath = path.join(__dirname, 'src');
335
- if (fs.existsSync(srcPath)) {
336
- fs.readdirSync(srcPath).filter(v => v.endsWith('.js')).forEach(v => {
337
- api[v.replace('.js', '')] = require(`./src/${v}`)(utils.makeDefaults(html, userID, ctx), api, ctx);
338
- });
339
- }
340
-
341
- // Store original sendMessage as the primary method
342
- const originalSendMessage = api.sendMessage;
343
-
344
- // Wrap sendMessage to use OldMessage as fallback on error
345
- api.sendMessage = async function(msg, threadID, callback, replyToMessage, isSingleUser) {
346
- try {
347
- return await originalSendMessage(msg, threadID, callback, replyToMessage, isSingleUser);
348
- } catch (error) {
349
- log.warn('sendMessage failed, using OldMessage fallback:', error.message);
350
- return api.OldMessage(msg, threadID, callback, replyToMessage, isSingleUser);
351
- }
352
- };
353
-
354
- // Provide explicit method for DM sending using OldMessage
355
- api.sendMessageDM = function(msg, threadID, callback, replyToMessage) {
356
- return api.OldMessage(msg, threadID, callback, replyToMessage, true);
357
- };
358
-
359
- api.listen = api.listenMqtt;
360
-
361
- return {
362
- ctx,
363
- defaultFuncs,
364
- api
365
- };
65
+ let fb_dtsg = null;
66
+ let irisSeqID = null;
67
+ function extractFromHTML() {
68
+ try {
69
+ const $ = cheerio.load(html);
70
+ $('script').each((i, script) => {
71
+ if (!fb_dtsg) {
72
+ const scriptText = $(script).html() || '';
73
+ const patterns = [
74
+ /\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
75
+ /\["DTSGInitData",\[\],{"token":"([^"]+)"/,
76
+ /"token":"([^"]+)"/,
77
+ /{\\"token\\":\\"([^\\]+)\\"/,
78
+ /,\{"token":"([^"]+)"\},\d+\]/,
79
+ /"async_get_token":"([^"]+)"/,
80
+ /"dtsg":\{"token":"([^"]+)"/,
81
+ /DTSGInitialData[^>]+>([^<]+)/
82
+ ];
83
+ for (const pattern of patterns) {
84
+ const match = scriptText.match(pattern);
85
+ if (match && match[1]) {
86
+ try {
87
+ const possibleJson = match[1].replace(/\\"/g, '"');
88
+ const parsed = JSON.parse(possibleJson);
89
+ fb_dtsg = parsed.token || parsed;
90
+ } catch {
91
+ fb_dtsg = match[1];
92
+ }
93
+ if (fb_dtsg) break;
94
+ }
95
+ }
96
+ }
97
+ });
98
+ if (!fb_dtsg) {
99
+ const dtsgInput = $('input[name="fb_dtsg"]').val();
100
+ if (dtsgInput) fb_dtsg = dtsgInput;
101
+ }
102
+ const seqMatches = html.match(/irisSeqID":"([^"]+)"/);
103
+ if (seqMatches && seqMatches[1]) {
104
+ irisSeqID = seqMatches[1];
105
+ }
106
+ try {
107
+ const jsonMatches = html.match(/\{"dtsg":({[^}]+})/);
108
+ if (jsonMatches && jsonMatches[1]) {
109
+ const dtsgData = JSON.parse(jsonMatches[1]);
110
+ if (dtsgData.token) fb_dtsg = dtsgData.token;
111
+ }
112
+ } catch { }
113
+ if (fb_dtsg) {
114
+ log.info("✅ | Found fb_Dtsg");
115
+ }
116
+ } catch (e) {
117
+ console.log("Error finding fb_dtsg:", e);
118
+ }
119
+ }
120
+ extractFromHTML();
121
+ var userID;
122
+ var cookies = jar.getCookies("https://www.facebook.com");
123
+ var userCookie = cookies.find(cookie => cookie.cookieString().startsWith("c_user="));
124
+ var tiktikCookie = cookies.find(cookie => cookie.cookieString().startsWith("i_user="));
125
+ if (!userCookie && !tiktikCookie) {
126
+ return log.error('login', "No cookie found for user, please check login information again");
127
+ }
128
+ if (html.includes("/checkpoint/block/?next")) {
129
+ return log.error('login', "Appstate dead, please replace with a new one!", 'error');
130
+ }
131
+ userID = (tiktikCookie || userCookie).cookieString().split("=")[1];
132
+
133
+ try { clearInterval(checkVerified); } catch (_) { }
134
+ const clientID = (Math.random() * 2147483648 | 0).toString(16);
135
+ let mqttEndpoint = `wss://edge-chat.facebook.com/chat?region=prn&sid=${userID}`;
136
+ let region = "PRN";
137
+
138
+ try {
139
+ const endpointMatch = html.match(/"endpoint":"([^"]+)"/);
140
+ if (endpointMatch.input.includes("601051028565049")) {
141
+ console.log(`login error due to automatic account`);
142
+ ditconmemay = true;
143
+ }
144
+ if (endpointMatch) {
145
+ mqttEndpoint = endpointMatch[1].replace(/\\\//g, '/');
146
+ const url = new URL(mqttEndpoint);
147
+ region = url.searchParams.get('region')?.toUpperCase() || "PRN";
148
+ }
149
+ } catch (e) {
150
+ console.log('Using default MQTT endpoint');
151
+ }
152
+ var ctx = {
153
+ userID: userID,
154
+ jar: jar,
155
+ clientID: clientID,
156
+ globalOptions: globalOptions,
157
+ loggedIn: true,
158
+ access_token: 'NONE',
159
+ clientMutationId: 0,
160
+ mqttClient: undefined,
161
+ lastSeqId: irisSeqID,
162
+ syncToken: undefined,
163
+ mqttEndpoint: mqttEndpoint,
164
+ region: region,
165
+ firstListen: true,
166
+ fb_dtsg: fb_dtsg,
167
+ req_ID: 0,
168
+ callback_Task: {},
169
+ wsReqNumber: 0,
170
+ wsTaskNumber: 0,
171
+ reqCallbacks: {}
172
+ };
173
+ var api = {
174
+ setOptions: setOptions.bind(null, globalOptions),
175
+ getAppState: () => utils.getAppState(jar),
176
+ postFormData: (url, body) => utils.makeDefaults(html, userID, ctx).postFormData(url, ctx.jar, body)
177
+ };
178
+ var defaultFuncs = utils.makeDefaults(html, userID, ctx);
179
+ api.postFormData = function (url, body) {
180
+ return defaultFuncs.postFormData(url, ctx.jar, body);
181
+ };
182
+ api.getFreshDtsg = async function () {
183
+ try {
184
+ const res = await defaultFuncs.get('https://www.facebook.com/', jar, null, globalOptions);
185
+ const $ = cheerio.load(res.body);
186
+ let newDtsg;
187
+ const patterns = [
188
+ /\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
189
+ /\["DTSGInitData",\[\],{"token":"([^"]+)"/,
190
+ /"token":"([^"]+)"/,
191
+ /name="fb_dtsg" value="([^"]+)"/
192
+ ];
193
+
194
+ $('script').each((i, script) => {
195
+ if (!newDtsg) {
196
+ const scriptText = $(script).html() || '';
197
+ for (const pattern of patterns) {
198
+ const match = scriptText.match(pattern);
199
+ if (match && match[1]) {
200
+ newDtsg = match[1];
201
+ break;
202
+ }
203
+ }
204
+ }
205
+ });
206
+
207
+ if (!newDtsg) {
208
+ newDtsg = $('input[name="fb_dtsg"]').val();
209
+ }
210
+
211
+ return newDtsg;
212
+ } catch (e) {
213
+ console.log("Error getting fresh dtsg:", e);
214
+ return null;
215
+ }
216
+ };
217
+
218
+ require('fs').readdirSync(__dirname + '/src/').filter(v => v.endsWith('.js')).forEach(v => { api[v.replace('.js', '')] = require(`./src/${v}`)(utils.makeDefaults(html, userID, ctx), api, ctx); });
219
+ api.listen = api.listenMqtt;
220
+ return {
221
+ ctx,
222
+ defaultFuncs,
223
+ api
224
+ };
366
225
  }
367
226
 
368
227
  function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
369
- return async function (res) {
370
- try {
371
- const html = res.body;
372
- const $ = cheerio.load(html);
373
- let arr = [];
374
- $("#login_form input").each((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
375
- arr = arr.filter(v => v.val && v.val.length);
376
- let form = utils.arrToForm(arr);
377
- form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
378
- form.lgndim = Buffer.from(JSON.stringify({ w: 1440, h: 900, aw: 1440, ah: 834, c: 24 })).toString('base64');
379
- form.email = email;
380
- form.pass = password;
381
- form.default_persistent = '0';
382
- form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
383
- form.locale = 'en_US';
384
- form.timezone = '240';
385
- form.lgnjs = Math.floor(Date.now() / 1000);
386
-
387
- const willBeCookies = html.split("\"_js_");
388
- willBeCookies.slice(1).forEach(val => {
389
- const cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
390
- jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
391
- });
392
-
393
- log.info("Logging in with email/password...");
394
- await delay(2000); // Delay to avoid rate limiting
395
-
396
- const loginRes = await utils.post(
397
- "https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110",
398
- jar,
399
- form,
400
- loginOptions
401
- );
402
-
403
- await utils.saveCookies(jar)(loginRes);
404
- const headers = loginRes.headers;
405
-
406
- if (!headers.location) {
407
- throw new Error("Wrong username/password or account locked.");
408
- }
409
-
410
- if (headers.location.includes('https://www.facebook.com/checkpoint/')) {
411
- log.info("login", "Login approval required. Checking checkpoint...");
412
- const checkpointRes = await utils.get(headers.location, jar, null, loginOptions);
413
- await utils.saveCookies(jar)(checkpointRes);
414
- const checkpointHtml = checkpointRes.body;
415
- const $ = cheerio.load(checkpointHtml);
416
- let checkpointForm = [];
417
- $("form input").each((i, v) => checkpointForm.push({ val: $(v).val(), name: $(v).attr("name") }));
418
- checkpointForm = checkpointForm.filter(v => v.val && v.val.length);
419
- const form = utils.arrToForm(checkpointForm);
420
-
421
- if (checkpointHtml.includes("checkpoint/?next")) {
422
- return new Promise((resolve, reject) => {
423
- const submit2FA = async (code) => {
424
- try {
425
- form.approvals_code = code;
426
- form['submit[Continue]'] = $("#checkpointSubmitButton").html();
427
- const approvalRes = await utils.post(
428
- "https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
429
- jar,
430
- form,
431
- loginOptions
432
- );
433
- await utils.saveCookies(jar)(approvalRes);
434
- const approvalError = $("#approvals_code").parent().attr("data-xui-error");
435
- if (approvalError) throw new Error("Invalid 2FA code.");
436
- form.name_action_selected = 'dont_save';
437
- const finalRes = await utils.post(
438
- "https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
439
- jar,
440
- form,
441
- loginOptions
442
- );
443
- await utils.saveCookies(jar)(finalRes);
444
- const appState = utils.getAppState(jar);
445
- resolve(await loginHelper(appState, email, password, loginOptions, callback));
446
- } catch (error) {
447
- reject(error);
448
- }
449
- };
450
- throw {
451
- error: 'login-approval',
452
- continue: submit2FA
453
- };
454
- });
455
- }
456
-
457
- if (!loginOptions.forceLogin) {
458
- throw new Error("Couldn't login. Facebook might have blocked this account or requires verification.");
459
- }
460
-
461
- form['submit[This was me]'] = checkpointHtml.includes("Suspicious Login Attempt") ? "This was me" : "This Is Okay";
462
- await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
463
- form.name_action_selected = 'save_device';
464
- const reviewRes = await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
465
- const appState = utils.getAppState(jar);
466
- return await loginHelper(appState, email, password, loginOptions, callback);
467
- }
468
-
469
- await utils.get('https://www.facebook.com/', jar, null, loginOptions);
470
- return await utils.saveCookies(jar);
471
- } catch (error) {
472
- log.error("Login error:", error.message);
473
- callback(error);
474
- }
475
- };
228
+ return async function (res) {
229
+ try {
230
+ const html = res.body;
231
+ const $ = cheerio.load(html);
232
+ let arr = [];
233
+ $("#login_form input").each((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
234
+ arr = arr.filter(v => v.val && v.val.length);
235
+ let form = utils.arrToForm(arr);
236
+ form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
237
+ form.lgndim = Buffer.from(JSON.stringify({ w: 1440, h: 900, aw: 1440, ah: 834, c: 24 })).toString('base64');
238
+ form.email = email;
239
+ form.pass = password;
240
+ form.default_persistent = '0';
241
+ form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
242
+ form.locale = 'en_US';
243
+ form.timezone = '240';
244
+ form.lgnjs = Math.floor(Date.now() / 1000);
245
+ const willBeCookies = html.split("\"_js_");
246
+ willBeCookies.slice(1).forEach(val => {
247
+ const cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
248
+ jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
249
+ });
250
+ log.info("login", "Logging in...");
251
+ const loginRes = await utils.post(
252
+ "https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110",
253
+ jar,
254
+ form,
255
+ loginOptions
256
+ );
257
+ await utils.saveCookies(jar)(loginRes);
258
+ const headers = loginRes.headers;
259
+ if (!headers.location) throw new Error("Wrong username/password.");
260
+ if (headers.location.includes('https://www.facebook.com/checkpoint/')) {
261
+ log.info("login", "You have login approvals turned on.");
262
+ const checkpointRes = await utils.get(headers.location, jar, null, loginOptions);
263
+ await utils.saveCookies(jar)(checkpointRes);
264
+ const checkpointHtml = checkpointRes.body;
265
+ const $ = cheerio.load(checkpointHtml);
266
+ let checkpointForm = [];
267
+ $("form input").each((i, v) => checkpointForm.push({ val: $(v).val(), name: $(v).attr("name") }));
268
+ checkpointForm = checkpointForm.filter(v => v.val && v.val.length);
269
+ const form = utils.arrToForm(checkpointForm);
270
+ if (checkpointHtml.includes("checkpoint/?next")) {
271
+ return new Promise((resolve, reject) => {
272
+ const submit2FA = async (code) => {
273
+ try {
274
+ form.approvals_code = code;
275
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
276
+ const approvalRes = await utils.post(
277
+ "https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
278
+ jar,
279
+ form,
280
+ loginOptions
281
+ );
282
+ await utils.saveCookies(jar)(approvalRes);
283
+ const approvalError = $("#approvals_code").parent().attr("data-xui-error");
284
+ if (approvalError) throw new Error("Invalid 2FA code.");
285
+ form.name_action_selected = 'dont_save';
286
+ const finalRes = await utils.post(
287
+ "https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
288
+ jar,
289
+ form,
290
+ loginOptions
291
+ );
292
+ await utils.saveCookies(jar)(finalRes);
293
+ const appState = utils.getAppState(jar);
294
+ resolve(await loginHelper(appState, email, password, loginOptions, callback));
295
+ } catch (error) {
296
+ reject(error);
297
+ }
298
+ };
299
+ throw {
300
+ error: 'login-approval',
301
+ continue: submit2FA
302
+ };
303
+ });
304
+ }
305
+ if (!loginOptions.forceLogin) throw new Error("Couldn't login. Facebook might have blocked this account.");
306
+ form['submit[This was me]'] = checkpointHtml.includes("Suspicious Login Attempt") ? "This was me" : "This Is Okay";
307
+ await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
308
+ form.name_action_selected = 'save_device';
309
+ const reviewRes = await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
310
+ const appState = utils.getAppState(jar);
311
+ return await loginHelper(appState, email, password, loginOptions, callback);
312
+ }
313
+ await utils.get('https://www.facebook.com/', jar, null, loginOptions);
314
+ return await utils.saveCookies(jar);
315
+ } catch (error) {
316
+ callback(error);
317
+ }
318
+ };
476
319
  }
477
320
 
478
- function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
479
- let mainPromise = null;
480
- const jar = utils.getJar();
481
-
482
- if (appState) {
483
- try {
484
- if (typeof appState === 'string') {
485
- appState = JSON.parse(appState);
486
- }
487
- } catch (e) {
488
- return callback(new Error("Failed to parse appState: " + e.message));
489
- }
490
-
491
- try {
492
- appState.forEach(c => {
493
- const str = `${c.key}=${c.value}; ${c.expires ? 'expires=' + c.expires + ';' : ''} domain=${c.domain}; path=${c.path};`;
494
- jar.setCookie(str, "http://" + c.domain);
495
- });
496
-
497
- mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
498
- .then(utils.saveCookies(jar));
499
- } catch (e) {
500
- log.error("Error setting cookies:", e.message);
501
- return callback(new Error("Failed to set appState cookies"));
502
- }
503
- } else {
504
- mainPromise = utils
505
- .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
506
- .then(utils.saveCookies(jar))
507
- .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
508
- .then(() => utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar)));
509
- }
510
-
511
- function handleRedirect(res) {
512
- const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
513
- const redirect = reg.exec(res.body);
514
- if (redirect && redirect[1]) {
515
- return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
516
- }
517
- return res;
518
- }
519
-
520
- let ctx, api;
521
- mainPromise = mainPromise
522
- .then(handleRedirect)
523
- .then(res => {
524
- const mobileAgentRegex = /MPageLoadClientMetrics/gs;
525
- if (!mobileAgentRegex.test(res.body)) {
526
- globalOptions.userAgent = getRandomUserAgent();
527
- return utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
528
- }
529
- return res;
530
- })
531
- .then(handleRedirect)
532
- .then(res => {
533
- const html = res.body;
534
- const Obj = buildAPI(globalOptions, html, jar);
535
- ctx = Obj.ctx;
536
- api = Obj.api;
537
- return res;
538
- });
539
321
 
540
- if (globalOptions.pageID) {
541
- mainPromise = mainPromise
542
- .then(() => utils.get(`https://www.facebook.com/${globalOptions.pageID}/messages/?section=messages&subsection=inbox`, jar, null, globalOptions))
543
- .then(resData => {
544
- let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
545
- url = url.substring(0, url.length - 1);
546
- return utils.get('https://www.facebook.com' + url, jar, null, globalOptions);
547
- });
548
- }
549
-
550
- mainPromise
551
- .then(async () => {
552
- log.info('Login successful');
553
- callback(null, api);
554
- })
555
- .catch(e => {
556
- log.error("Login helper error:", e.message);
557
- callback(e);
558
- });
322
+ function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
323
+ let mainPromise = null;
324
+ const jar = utils.getJar();
325
+ if (appState) {
326
+ try {
327
+ appState = JSON.parse(appState);
328
+ } catch (e) {
329
+ try {
330
+ appState = appState;
331
+ } catch (e) {
332
+ return callback(new Error("Failed to parse appState"));
333
+ }
334
+ }
335
+
336
+ try {
337
+ appState.forEach(c => {
338
+ const str = `${c.key}=${c.value}; expires=${c.expires}; domain=${c.domain}; path=${c.path};`;
339
+ jar.setCookie(str, "http://" + c.domain);
340
+ });
341
+
342
+ mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
343
+ .then(utils.saveCookies(jar));
344
+ } catch (e) {
345
+ process.exit(0);
346
+ }
347
+ } else {
348
+ mainPromise = utils
349
+ .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
350
+ .then(utils.saveCookies(jar))
351
+ .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
352
+ .then(() => utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar)));
353
+ }
354
+
355
+ function handleRedirect(res) {
356
+ const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
357
+ const redirect = reg.exec(res.body);
358
+ if (redirect && redirect[1]) {
359
+ return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
360
+ }
361
+ return res;
362
+ }
363
+
364
+ let ctx, api;
365
+ mainPromise = mainPromise
366
+ .then(handleRedirect)
367
+ .then(res => {
368
+ const mobileAgentRegex = /MPageLoadClientMetrics/gs;
369
+ if (!mobileAgentRegex.test(res.body)) {
370
+ globalOptions.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36";
371
+ return utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
372
+ }
373
+ return res;
374
+ })
375
+ .then(handleRedirect)
376
+ .then(res => {
377
+ const html = res.body;
378
+ const Obj = buildAPI(globalOptions, html, jar);
379
+ ctx = Obj.ctx;
380
+ api = Obj.api;
381
+ return res;
382
+ });
383
+
384
+ if (globalOptions.pageID) {
385
+ mainPromise = mainPromise
386
+ .then(() => utils.get(`https://www.facebook.com/${globalOptions.pageID}/messages/?section=messages&subsection=inbox`, jar, null, globalOptions))
387
+ .then(resData => {
388
+ let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
389
+ url = url.substring(0, url.length - 1);
390
+ return utils.get('https://www.facebook.com' + url, jar, null, globalOptions);
391
+ });
392
+ }
393
+
394
+ mainPromise
395
+ .then(async () => {
396
+ log.info('Login successful');
397
+ callback(null, api);
398
+ })
399
+ .catch(e => {
400
+ callback(e);
401
+ });
559
402
  }
560
403
 
561
- function login(loginData, options, callback) {
562
- // Check for updates (non-blocking, only once per session)
563
- if (!global.stfcaUpdateChecked) {
564
- global.stfcaUpdateChecked = true;
565
- checkForFCAUpdate().catch(err => {
566
- // Silently ignore update check errors to not block login
567
- });
568
- }
569
-
570
- if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
571
- callback = options;
572
- options = {};
573
- }
574
404
 
575
- var globalOptions = {
576
- selfListen: false,
577
- listenEvents: true,
578
- listenTyping: false,
579
- updatePresence: false,
580
- forceLogin: false,
581
- autoMarkDelivery: false,
582
- autoMarkRead: false,
583
- autoReconnect: true,
584
- logRecordSize: 100,
585
- online: false,
586
- emitReady: false,
587
- delayBetweenRequests: 1500,
588
- userAgent: getRandomUserAgent()
589
- };
590
-
591
- var prCallback = null;
592
- if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
593
- var rejectFunc = null;
594
- var resolveFunc = null;
595
- var returnPromise = new Promise(function (resolve, reject) {
596
- resolveFunc = resolve;
597
- rejectFunc = reject;
598
- });
599
- prCallback = function (error, api) {
600
- if (error) return rejectFunc(error);
601
- return resolveFunc(api);
602
- };
603
- callback = prCallback;
604
- }
605
-
606
- // Handle different login methods
607
- if (loginData.appState) {
608
- setOptions(globalOptions, options);
609
- loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
610
- } else if (loginData.email && loginData.password) {
611
- setOptions(globalOptions, {
612
- forceLogin: true,
613
- userAgent: getRandomUserAgent(),
614
- delayBetweenRequests: 1500
615
- });
616
- loginHelper(null, loginData.email, loginData.password, globalOptions, callback, prCallback);
617
- } else {
618
- const error = new Error("Invalid login data. Provide either appState or email/password");
619
- if (callback) callback(error);
620
- else throw error;
621
- }
622
-
623
- return returnPromise;
405
+ function login(loginData, options, callback) {
406
+ if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
407
+ callback = options;
408
+ options = {};
409
+ }
410
+
411
+ var globalOptions = {
412
+ selfListen: false,
413
+ listenEvents: false,
414
+ listenTyping: false,
415
+ updatePresence: false,
416
+ forceLogin: false,
417
+ autoMarkDelivery: false,
418
+ autoMarkRead: false,
419
+ autoReconnect: true,
420
+ logRecordSize: 100,
421
+ online: true,
422
+ emitReady: false,
423
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
424
+ };
425
+
426
+ var prCallback = null;
427
+ if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
428
+ var rejectFunc = null;
429
+ var resolveFunc = null;
430
+ var returnPromise = new Promise(function (resolve, reject) {
431
+ resolveFunc = resolve;
432
+ rejectFunc = reject;
433
+ });
434
+ prCallback = function (error, api) {
435
+ if (error) return rejectFunc(error);
436
+ return resolveFunc(api);
437
+ };
438
+ callback = prCallback;
439
+ }
440
+
441
+ if (loginData.email && loginData.password) {
442
+ setOptions(globalOptions, {
443
+ logLevel: "silent",
444
+ forceLogin: true,
445
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
446
+ });
447
+ loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
448
+ } else if (loginData.appState) {
449
+ setOptions(globalOptions, options);
450
+ return loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
451
+ }
452
+ return returnPromise;
624
453
  }
625
454
 
626
- module.exports = login;
455
+
456
+ module.exports = login;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shadowx-fca",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "Unofficial Facebook Chat API for Node.js with Auto-Update System - modify by Mueid Mursalin Rifat",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -0,0 +1,129 @@
1
+ /**
2
+ * @by Allou Mohamed
3
+ * do not remove the author name to get more updates
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const utils = require("../utils");
9
+
10
+ module.exports = function (defaultFuncs, api, ctx) {
11
+ return function createAITheme(prompt, numThemes, callback) {
12
+ if (typeof numThemes === 'function') {
13
+ callback = numThemes;
14
+ numThemes = 3;
15
+ }
16
+ if (typeof numThemes !== 'number' || numThemes < 1) {
17
+ numThemes = 3;
18
+ }
19
+ if (numThemes > 10) {
20
+ numThemes = 10;
21
+ }
22
+
23
+ const form = {
24
+ av: ctx.i_userID || ctx.userID,
25
+ qpl_active_flow_ids: "25308101,25309433,521482085",
26
+ fb_api_caller_class: "RelayModern",
27
+ fb_api_req_friendly_name: "useGenerateAIThemeMutation",
28
+ variables: JSON.stringify({
29
+ input: {
30
+ client_mutation_id: "1",
31
+ actor_id: ctx.i_userID || ctx.userID,
32
+ bypass_cache: true,
33
+ caller: "MESSENGER",
34
+ num_themes: numThemes,
35
+ prompt: prompt
36
+ }
37
+ }),
38
+ server_timestamps: true,
39
+ doc_id: "23873748445608673",
40
+ fb_api_analytics_tags: JSON.stringify([
41
+ "qpl_active_flow_ids=25308101,25309433,521482085"
42
+ ]),
43
+ fb_dtsg: ctx.fb_dtsg
44
+ };
45
+
46
+ const extractUrl = (obj) => {
47
+ if (!obj) return null;
48
+ if (typeof obj === 'string') return obj;
49
+ return obj.uri || obj.url || null;
50
+ };
51
+
52
+ const normalizeTheme = (theme) => {
53
+ const normalized = { ...theme };
54
+
55
+ let lightUrl = null;
56
+ let darkUrl = null;
57
+
58
+ const previewUrls = theme.preview_image_urls || theme.preview_images || theme.preview_urls;
59
+
60
+ if (previewUrls) {
61
+ if (typeof previewUrls === 'string') {
62
+ lightUrl = darkUrl = previewUrls;
63
+ } else if (Array.isArray(previewUrls)) {
64
+ lightUrl = extractUrl(previewUrls[0]) || null;
65
+ darkUrl = extractUrl(previewUrls[1]) || lightUrl;
66
+ } else if (typeof previewUrls === 'object') {
67
+ lightUrl = extractUrl(previewUrls.light_mode) || extractUrl(previewUrls.light) || null;
68
+ darkUrl = extractUrl(previewUrls.dark_mode) || extractUrl(previewUrls.dark) || null;
69
+ }
70
+ }
71
+
72
+ if (!lightUrl && theme.background_asset && theme.background_asset.image) {
73
+ lightUrl = extractUrl(theme.background_asset.image);
74
+ }
75
+ if (!lightUrl && theme.icon_asset && theme.icon_asset.image) {
76
+ lightUrl = extractUrl(theme.icon_asset.image);
77
+ }
78
+
79
+ if (!darkUrl && theme.alternative_themes && theme.alternative_themes.length > 0) {
80
+ const darkTheme = theme.alternative_themes[0];
81
+ if (darkTheme.background_asset && darkTheme.background_asset.image) {
82
+ darkUrl = extractUrl(darkTheme.background_asset.image);
83
+ }
84
+ if (!darkUrl && darkTheme.icon_asset && darkTheme.icon_asset.image) {
85
+ darkUrl = extractUrl(darkTheme.icon_asset.image);
86
+ }
87
+ }
88
+
89
+ if (lightUrl && !darkUrl) {
90
+ darkUrl = lightUrl;
91
+ } else if (darkUrl && !lightUrl) {
92
+ lightUrl = darkUrl;
93
+ }
94
+
95
+ if (lightUrl || darkUrl) {
96
+ normalized.preview_image_urls = {
97
+ light_mode: lightUrl,
98
+ dark_mode: darkUrl
99
+ };
100
+ }
101
+
102
+ return normalized;
103
+ };
104
+
105
+ const promise = defaultFuncs
106
+ .post("https://web.facebook.com/api/graphql/", ctx.jar, form)
107
+ .then(utils.parseAndCheckLogin(ctx, defaultFuncs))
108
+ .then(resData => {
109
+ if (resData.errors) {
110
+ throw resData.errors;
111
+ }
112
+ const themes = resData.data.xfb_generate_ai_themes_from_prompt.themes;
113
+ return themes.map(normalizeTheme);
114
+ });
115
+
116
+ if (callback) {
117
+ promise.then(data => callback(null, data)).catch(err => {
118
+ utils.error("createAITheme", err.message || err);
119
+ callback(err);
120
+ });
121
+ return;
122
+ }
123
+
124
+ return promise.catch(err => {
125
+ utils.error("createAITheme", err.message || err);
126
+ throw err;
127
+ });
128
+ };
129
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ var utils = require("../utils");
4
+ var log = require("npmlog");
5
+
6
+ module.exports = function (defaultFuncs, api, ctx) {
7
+ return function postFormData(url, form, callback) {
8
+ var resolveFunc = function () {};
9
+ var rejectFunc = function () {};
10
+
11
+ var returnPromise = new Promise(function (resolve, reject) {
12
+ resolveFunc = resolve;
13
+ rejectFunc = reject;
14
+ });
15
+
16
+ if (
17
+ !callback &&
18
+ (utils.getType(form) == "Function" ||
19
+ utils.getType(form) == "AsyncFunction")
20
+ ) {
21
+ callback = form;
22
+ form = {};
23
+ }
24
+
25
+ form = form || {};
26
+
27
+ callback =
28
+ callback ||
29
+ function (err, data) {
30
+ if (err) return rejectFunc(err);
31
+ resolveFunc(data);
32
+ };
33
+
34
+ defaultFuncs
35
+ .postFormData(url, ctx.jar, form, {})
36
+ .then(function (resData) {
37
+ callback(null, resData.body.toString());
38
+ })
39
+ .catch(function (err) {
40
+ log.error("postFormData", err);
41
+ return callback(err);
42
+ });
43
+
44
+ return returnPromise;
45
+ };
46
+ };