sagor-fca 0.0.16 → 0.0.17

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.
Files changed (78) hide show
  1. package/index.js +509 -554
  2. package/package.json +30 -31
  3. package/src/OldMessage.js +357 -0
  4. package/src/addExternalModule.js +15 -4
  5. package/src/addUserToGroup.js +57 -19
  6. package/src/changeAdminStatus.js +91 -35
  7. package/src/changeArchivedStatus.js +26 -12
  8. package/src/changeAvatar.js +136 -0
  9. package/src/changeAvatarV2.js +86 -0
  10. package/src/changeAvt.js +85 -0
  11. package/src/changeBio.js +27 -15
  12. package/src/changeBlockedStatus.js +22 -9
  13. package/src/changeBlockedStatusMqtt.js +80 -0
  14. package/src/changeCover.js +72 -0
  15. package/src/changeGroupImage.js +56 -26
  16. package/src/changeName.js +79 -0
  17. package/src/changeNickname.js +29 -13
  18. package/src/changeThreadColor.js +23 -19
  19. package/src/changeThreadEmoji.js +26 -12
  20. package/src/changeUsername.js +59 -0
  21. package/src/createCommentPost.js +230 -0
  22. package/src/createNewGroup.js +36 -18
  23. package/src/createPoll.js +29 -17
  24. package/src/createPost.js +276 -0
  25. package/src/deleteMessage.js +26 -14
  26. package/src/deleteThread.js +27 -13
  27. package/src/editMessage.js +68 -0
  28. package/src/editMessageOld.js +67 -0
  29. package/src/follow.js +74 -0
  30. package/src/forwardAttachment.js +29 -16
  31. package/src/friendList.js +91 -0
  32. package/src/getAccess.js +112 -0
  33. package/src/getAvatarUser.js +78 -0
  34. package/src/getEmojiUrl.js +10 -8
  35. package/src/getFriendsList.js +25 -15
  36. package/src/getMessage.js +847 -0
  37. package/src/getRegion.js +7 -0
  38. package/src/getThreadHistory.js +241 -98
  39. package/src/getThreadInfo.js +221 -274
  40. package/src/getThreadTheme.js +82 -0
  41. package/src/getUID.js +119 -0
  42. package/src/httpGet.js +49 -47
  43. package/src/httpPost.js +48 -47
  44. package/src/listenMqtt.js +711 -671
  45. package/src/logout.js +24 -17
  46. package/src/metaTheme.js +190 -0
  47. package/src/note.js +228 -0
  48. package/src/refreshFb_dtsg.js +89 -0
  49. package/src/removeSuspiciousAccount.js +79 -0
  50. package/src/removeUserFromGroup.js +50 -16
  51. package/src/resolvePhotoUrl.js +23 -14
  52. package/src/searchForThread.js +24 -13
  53. package/src/searchFriends.js +139 -0
  54. package/src/searchStickers.js +53 -0
  55. package/src/sendFriendRequest.js +113 -0
  56. package/src/sendMessage.js +253 -533
  57. package/src/sendMessageMqtt.js +322 -0
  58. package/src/sendTypingIndicator.js +45 -70
  59. package/src/setActiveStatus.js +93 -0
  60. package/src/setMessageReaction.js +38 -19
  61. package/src/setMessageReactionMqtt.js +62 -0
  62. package/src/setPostReaction.js +75 -26
  63. package/src/setProfileLock.js +98 -0
  64. package/src/setStoryReaction.js +134 -0
  65. package/src/setStorySeen.js +109 -0
  66. package/src/setThreadTheme.js +103 -0
  67. package/src/setTitle.js +39 -19
  68. package/src/shareContact.js +110 -0
  69. package/src/shareLink.js +59 -0
  70. package/src/stopListenMqtt.js +23 -0
  71. package/src/storyManager.js +358 -0
  72. package/src/suggestFriend.js +133 -0
  73. package/src/threadColors.js +97 -7
  74. package/src/unfriend.js +21 -11
  75. package/src/unsendMessage.js +16 -10
  76. package/src/uploadAttachment.js +93 -0
  77. package/utils.js +2802 -1034
  78. package/.github/workflows/main.yml +0 -22
package/index.js CHANGED
@@ -3,595 +3,550 @@
3
3
  var utils = require("./utils");
4
4
  var cheerio = require("cheerio");
5
5
  var log = require("npmlog");
6
-
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ /*var { getThemeColors } = require("../../func/utils/log.js");
9
+ var logger = require("../../func/utils/log.js");
10
+ var { cra, cv, cb, co } = getThemeColors();*/
11
+ log.maxRecordSize = 100;
7
12
  var checkVerified = null;
8
-
9
- var defaultLogRecordSize = 100;
10
- log.maxRecordSize = defaultLogRecordSize;
13
+ const Boolean_Option = ['online', 'selfListen', 'listenEvents', 'updatePresence', 'forceLogin', 'autoMarkDelivery', 'autoMarkRead', 'listenTyping', 'autoReconnect', 'emitReady'];
14
+ global.ditconmemay = false;
11
15
 
12
16
  function setOptions(globalOptions, options) {
13
- Object.keys(options).map(function (key) {
14
- switch (key) {
15
- case 'pauseLog':
16
- if (options.pauseLog) log.pause();
17
- break;
18
- case 'online':
19
- globalOptions.online = Boolean(options.online);
20
- break;
21
- case 'logLevel':
22
- log.level = options.logLevel;
23
- globalOptions.logLevel = options.logLevel;
24
- break;
25
- case 'logRecordSize':
26
- log.maxRecordSize = options.logRecordSize;
27
- globalOptions.logRecordSize = options.logRecordSize;
28
- break;
29
- case 'selfListen':
30
- globalOptions.selfListen = Boolean(options.selfListen);
31
- break;
32
- case 'listenEvents':
33
- globalOptions.listenEvents = Boolean(options.listenEvents);
34
- break;
35
- case 'pageID':
36
- globalOptions.pageID = options.pageID.toString();
37
- break;
38
- case 'updatePresence':
39
- globalOptions.updatePresence = Boolean(options.updatePresence);
40
- break;
41
- case 'forceLogin':
42
- globalOptions.forceLogin = Boolean(options.forceLogin);
43
- break;
44
- case 'userAgent':
45
- globalOptions.userAgent = options.userAgent;
46
- break;
47
- case 'autoMarkDelivery':
48
- globalOptions.autoMarkDelivery = Boolean(options.autoMarkDelivery);
49
- break;
50
- case 'autoMarkRead':
51
- globalOptions.autoMarkRead = Boolean(options.autoMarkRead);
52
- break;
53
- case 'listenTyping':
54
- globalOptions.listenTyping = Boolean(options.listenTyping);
55
- break;
56
- case 'proxy':
57
- if (typeof options.proxy != "string") {
58
- delete globalOptions.proxy;
59
- utils.setProxy();
60
- }
61
- else {
62
- globalOptions.proxy = options.proxy;
63
- utils.setProxy(globalOptions.proxy);
17
+ Object.keys(options).map(function (key) {
18
+ switch (Boolean_Option.includes(key)) {
19
+ case true: {
20
+ globalOptions[key] = Boolean(options[key]);
21
+ break;
22
+ }
23
+ case false: {
24
+ switch (key) {
25
+ case 'pauseLog': {
26
+ if (options.pauseLog) log.pause();
27
+ else log.resume();
28
+ break;
29
+ }
30
+ case 'logLevel': {
31
+ log.level = options.logLevel;
32
+ globalOptions.logLevel = options.logLevel;
33
+ break;
34
+ }
35
+ case 'logRecordSize': {
36
+ log.maxRecordSize = options.logRecordSize;
37
+ globalOptions.logRecordSize = options.logRecordSize;
38
+ break;
39
+ }
40
+ case 'pageID': {
41
+ globalOptions.pageID = options.pageID.toString();
42
+ break;
43
+ }
44
+ case 'userAgent': {
45
+ 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');
46
+ break;
47
+ }
48
+ case 'proxy': {
49
+ if (typeof options.proxy != "string") {
50
+ delete globalOptions.proxy;
51
+ utils.setProxy();
52
+ } else {
53
+ globalOptions.proxy = options.proxy;
54
+ utils.setProxy(globalOptions.proxy);
55
+ }
56
+ break;
57
+ }
58
+ default: {
59
+ log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
60
+ break;
61
+ }
62
+ }
63
+ break;
64
+ }
64
65
  }
65
- break;
66
- case 'autoReconnect':
67
- globalOptions.autoReconnect = Boolean(options.autoReconnect);
68
- break;
69
- case 'emitReady':
70
- globalOptions.emitReady = Boolean(options.emitReady);
71
- break;
72
- default:
73
- log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
74
- break;
75
- }
76
- });
66
+ });
77
67
  }
78
68
 
79
69
  function buildAPI(globalOptions, html, jar) {
80
- var maybeCookie = jar.getCookies("https://www.facebook.com").filter(function (val) {
81
- return val.cookieString().split("=")[0] === "c_user";
82
- });
83
-
84
- var objCookie = jar.getCookies("https://www.facebook.com").reduce(function (obj, val) {
85
- obj[val.cookieString().split("=")[0]] = val.cookieString().split("=")[1];
86
- return obj;
87
- }, {});
88
-
89
- if (maybeCookie.length === 0) throw { error: "Error retrieving userID. This can be caused by a lot of things, including getting blocked by Facebook for logging in from an unknown location. Try logging in with a browser to verify." };
90
-
91
- if (html.indexOf("/checkpoint/block/?next") > -1) log.warn("login", "Checkpoint detected. Please log in with a browser to verify.");
92
-
93
- var userID = maybeCookie[0].cookieString().split("=")[1].toString();
94
- // var i_userID = objCookie.i_user || null;
95
- log.info("login", `Logged in as ${userID}`);
96
-
97
- try {
98
- clearInterval(checkVerified);
99
- }
100
- catch (_) { }
101
-
102
- var clientID = (Math.random() * 2147483648 | 0).toString(16);
103
-
104
- let oldFBMQTTMatch = html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/);
105
- let mqttEndpoint = null;
106
- let region = null;
107
- let irisSeqID = null;
108
- var noMqttData = null;
109
-
110
- if (oldFBMQTTMatch) {
111
- irisSeqID = oldFBMQTTMatch[1];
112
- mqttEndpoint = oldFBMQTTMatch[2];
113
- region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
114
- log.info("login", `Got this account's message region: ${region}`);
115
- }
116
- else {
117
- let newFBMQTTMatch = html.match(/{"app_id":"219994525426954","endpoint":"(.+?)","iris_seq_id":"(.+?)"}/);
118
- // html.match(/"appID":219994525426954,"endpoint":"(.+?)","pollingEndpoint":"(.+?)","subscribedTopics":\[\]/);
119
- if (newFBMQTTMatch) {
120
- irisSeqID = newFBMQTTMatch[2];
121
- mqttEndpoint = newFBMQTTMatch[1].replace(/\\\//g, "/");
122
- region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
123
- log.info("login", `Got this account's message region: ${region}`);
70
+ let fb_dtsg = null;
71
+ let irisSeqID = null;
72
+ function extractFromHTML() {
73
+ try {
74
+ const $ = cheerio.load(html);
75
+ $('script').each((i, script) => {
76
+ if (!fb_dtsg) {
77
+ const scriptText = $(script).html() || '';
78
+ const patterns = [
79
+ /\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
80
+ /\["DTSGInitData",\[\],{"token":"([^"]+)"/,
81
+ /"token":"([^"]+)"/,
82
+ /{\\"token\\":\\"([^\\]+)\\"/,
83
+ /,\{"token":"([^"]+)"\},\d+\]/,
84
+ /"async_get_token":"([^"]+)"/,
85
+ /"dtsg":\{"token":"([^"]+)"/,
86
+ /DTSGInitialData[^>]+>([^<]+)/
87
+ ];
88
+ for (const pattern of patterns) {
89
+ const match = scriptText.match(pattern);
90
+ if (match && match[1]) {
91
+ try {
92
+ const possibleJson = match[1].replace(/\\"/g, '"');
93
+ const parsed = JSON.parse(possibleJson);
94
+ fb_dtsg = parsed.token || parsed;
95
+ } catch {
96
+ fb_dtsg = match[1];
97
+ }
98
+ if (fb_dtsg) break;
99
+ }
100
+ }
101
+ }
102
+ });
103
+ if (!fb_dtsg) {
104
+ const dtsgInput = $('input[name="fb_dtsg"]').val();
105
+ if (dtsgInput) fb_dtsg = dtsgInput;
106
+ }
107
+ const seqMatches = html.match(/irisSeqID":"([^"]+)"/);
108
+ if (seqMatches && seqMatches[1]) {
109
+ irisSeqID = seqMatches[1];
110
+ }
111
+ try {
112
+ const jsonMatches = html.match(/\{"dtsg":({[^}]+})/);
113
+ if (jsonMatches && jsonMatches[1]) {
114
+ const dtsgData = JSON.parse(jsonMatches[1]);
115
+ if (dtsgData.token) fb_dtsg = dtsgData.token;
116
+ }
117
+ } catch { }
118
+ if (fb_dtsg) {
119
+ // console.log("Found fb_dtsg!");
120
+ }
121
+ } catch (e) {
122
+ console.log("Error finding fb_dtsg:", e);
123
+ }
124
124
  }
125
- else {
126
- let legacyFBMQTTMatch = html.match(/(\["MqttWebConfig",\[\],{fbid:")(.+?)(",appID:219994525426954,endpoint:")(.+?)(",pollingEndpoint:")(.+?)(3790])/);
127
- if (legacyFBMQTTMatch) {
128
- mqttEndpoint = legacyFBMQTTMatch[4];
129
- region = new URL(mqttEndpoint).searchParams.get("region").toUpperCase();
130
- log.warn("login", `Cannot get sequence ID with new RegExp. Fallback to old RegExp (without seqID)...`);
131
- log.info("login", `Got this account's message region: ${region}`);
132
- log.info("login", `[Unused] Polling endpoint: ${legacyFBMQTTMatch[6]}`);
133
- }
134
- else {
135
- log.warn("login", "Cannot get MQTT region & sequence ID.");
136
- noMqttData = html;
137
- }
125
+ extractFromHTML();
126
+ var userID;
127
+ var cookies = jar.getCookies("https://www.facebook.com");
128
+ var userCookie = cookies.find(cookie => cookie.cookieString().startsWith("c_user="));
129
+ var tiktikCookie = cookies.find(cookie => cookie.cookieString().startsWith("i_user="));
130
+ if (!userCookie && !tiktikCookie) {
131
+ return log.error("Error! Your cookiestate is not valid!");
138
132
  }
139
- }
140
-
141
- // All data available to api functions
142
- var ctx = {
143
- userID: userID,
144
- jar: jar,
145
- clientID: clientID,
146
- globalOptions: globalOptions,
147
- loggedIn: true,
148
- access_token: 'NONE',
149
- clientMutationId: 0,
150
- mqttClient: undefined,
151
- lastSeqId: irisSeqID,
152
- syncToken: undefined,
153
- mqttEndpoint,
154
- region,
155
- firstListen: true
156
- };
157
-
158
- var api = {
159
- setOptions: setOptions.bind(null, globalOptions),
160
- getAppState: function getAppState() {
161
- return utils.getAppState(jar);
133
+ if (html.includes("/checkpoint/block/?next")) {
134
+ return log.error('error', "Appstate is dead rechange it!", 'error');
135
+ }
136
+ userID = (tiktikCookie || userCookie).cookieString().split("=")[1];
137
+
138
+ try { clearInterval(checkVerified); } catch (_) { }
139
+ const clientID = (Math.random() * 2147483648 | 0).toString(16);
140
+ let mqttEndpoint = `wss://edge-chat.facebook.com/chat?region=pnb&sid=${userID}`;
141
+ let region = "PNB";
142
+
143
+ try {
144
+ const endpointMatch = html.match(/"endpoint":"([^"]+)"/);
145
+ if (endpointMatch.input.includes("601051028565049")) {
146
+ console.log(`login error.`);
147
+ ditconmemay = true;
148
+ }
149
+ if (endpointMatch) {
150
+ mqttEndpoint = endpointMatch[1].replace(/\\\//g, '/');
151
+ const url = new URL(mqttEndpoint);
152
+ region = url.searchParams.get('region')?.toUpperCase() || "PNB";
153
+ }
154
+ } catch (e) {
155
+ console.log('Using default MQTT endpoint');
162
156
  }
163
- };
157
+ console.log('SAGOR-FCA: Logging in...');
158
+ var ctx = {
159
+ userID: userID,
160
+ jar: jar,
161
+ clientID: clientID,
162
+ globalOptions: globalOptions,
163
+ loggedIn: true,
164
+ access_token: 'NONE',
165
+ clientMutationId: 0,
166
+ mqttClient: undefined,
167
+ lastSeqId: irisSeqID,
168
+ syncToken: undefined,
169
+ mqttEndpoint: mqttEndpoint,
170
+ region: region,
171
+ firstListen: true,
172
+ fb_dtsg: fb_dtsg,
173
+ req_ID: 0,
174
+ callback_Task: {},
175
+ wsReqNumber: 0,
176
+ wsTaskNumber: 0,
177
+ reqCallbacks: {},
178
+ threadTypes: {}
179
+ };
180
+ let config = { enableTypingIndicator: false, typingDuration: 4000 };
181
+ try {
182
+ const rootConfigPath = path.join(process.cwd(), 'config.json');
183
+ if (fs.existsSync(rootConfigPath)) {
184
+ const rootConfig = JSON.parse(fs.readFileSync(rootConfigPath, 'utf8'));
185
+ if (rootConfig && typeof rootConfig === 'object') {
186
+ if (typeof rootConfig.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = rootConfig.enableTypingIndicator;
187
+ if (typeof rootConfig.typingDuration !== 'undefined') config.typingDuration = rootConfig.typingDuration;
188
+ }
189
+ }
164
190
 
165
- if (noMqttData) api["htmlData"] = noMqttData;
191
+ const fcaConfigPath = path.join(__dirname, 'config.json');
192
+ if (fs.existsSync(fcaConfigPath)) {
193
+ const fcaConfig = JSON.parse(fs.readFileSync(fcaConfigPath, 'utf8'));
194
+ if (fcaConfig && typeof fcaConfig === 'object') {
195
+ if (typeof fcaConfig.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = fcaConfig.enableTypingIndicator;
196
+ if (typeof fcaConfig.typingDuration !== 'undefined') config.typingDuration = fcaConfig.typingDuration;
197
+ }
198
+ }
166
199
 
167
- const apiFuncNames = [
168
- 'addExternalModule',
169
- 'addUserToGroup',
170
- 'changeAdminStatus',
171
- 'changeArchivedStatus',
172
- 'changeBio',
173
- 'changeBlockedStatus',
174
- 'changeGroupImage',
175
- 'changeNickname',
176
- 'changeThreadColor',
177
- 'changeThreadEmoji',
178
- 'createNewGroup',
179
- 'createPoll',
180
- 'deleteMessage',
181
- 'deleteThread',
182
- 'forwardAttachment',
183
- 'getCurrentUserID',
184
- 'getEmojiUrl',
185
- 'getFriendsList',
186
- 'getThreadHistory',
187
- 'getThreadInfo',
188
- 'getThreadList',
189
- 'getThreadPictures',
190
- 'getUserID',
191
- 'getUserInfo',
192
- 'handleMessageRequest',
193
- 'listenMqtt',
194
- 'logout',
195
- 'markAsDelivered',
196
- 'markAsRead',
197
- 'markAsReadAll',
198
- 'markAsSeen',
199
- 'muteThread',
200
- 'removeUserFromGroup',
201
- 'resolvePhotoUrl',
202
- 'searchForThread',
203
- 'sendMessage',
204
- 'sendTypingIndicator',
205
- 'setMessageReaction',
206
- 'setTitle',
207
- 'threadColors',
208
- 'unsendMessage',
209
- 'unfriend',
200
+ if (global.GoatBot && global.GoatBot.config) {
201
+ if (typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') config.enableTypingIndicator = global.GoatBot.config.enableTypingIndicator;
202
+ if (typeof global.GoatBot.config.typingDuration !== 'undefined') config.typingDuration = global.GoatBot.config.typingDuration;
203
+ }
204
+ } catch (e) {
205
+ console.log('Error loading config.json:', e);
206
+ }
210
207
 
211
- // HTTP
212
- 'httpGet',
213
- 'httpPost',
208
+ const refreshFcaConfig = () => {
209
+ try {
210
+ const updatedConfig = { enableTypingIndicator: false, typingDuration: 4000 };
211
+
212
+ if (fs.existsSync(path.join(process.cwd(), 'config.json'))) {
213
+ const rootConfig = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'config.json'), 'utf8'));
214
+ if (rootConfig && typeof rootConfig === 'object') {
215
+ if (typeof rootConfig.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = rootConfig.enableTypingIndicator;
216
+ if (typeof rootConfig.typingDuration !== 'undefined') updatedConfig.typingDuration = rootConfig.typingDuration;
217
+ }
218
+ }
219
+
220
+ if (fs.existsSync(path.join(__dirname, 'config.json'))) {
221
+ const fcaConfig = JSON.parse(fs.readFileSync(path.join(__dirname, 'config.json'), 'utf8'));
222
+ if (fcaConfig && typeof fcaConfig === 'object') {
223
+ if (typeof fcaConfig.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = fcaConfig.enableTypingIndicator;
224
+ if (typeof fcaConfig.typingDuration !== 'undefined') updatedConfig.typingDuration = fcaConfig.typingDuration;
225
+ }
226
+ }
227
+
228
+ if (global.GoatBot && global.GoatBot.config) {
229
+ if (typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') updatedConfig.enableTypingIndicator = global.GoatBot.config.enableTypingIndicator;
230
+ if (typeof global.GoatBot.config.typingDuration !== 'undefined') updatedConfig.typingDuration = global.GoatBot.config.typingDuration;
231
+ }
232
+
233
+ ctx.config = updatedConfig;
234
+ config = updatedConfig;
235
+ if (global.GoatBot) global.GoatBot.config = global.GoatBot.config || {};
236
+ if (global.GoatBot && typeof global.GoatBot.config.enableTypingIndicator !== 'undefined') {
237
+ global.GoatBot.config.enableTypingIndicator = updatedConfig.enableTypingIndicator;
238
+ }
239
+ if (global.GoatBot && typeof global.GoatBot.config.typingDuration !== 'undefined') {
240
+ global.GoatBot.config.typingDuration = updatedConfig.typingDuration;
241
+ }
242
+ } catch (e) {
243
+ console.log('Failed to refresh fca config:', e);
244
+ }
245
+ };
214
246
 
215
- // Deprecated features
216
- "getThreadListDeprecated",
217
- 'getThreadHistoryDeprecated',
218
- 'getThreadInfoDeprecated',
219
- ];
247
+ refreshFcaConfig();
248
+ ctx.refreshFcaConfig = refreshFcaConfig;
249
+ if (global.GoatBot) {
250
+ global.GoatBot.refreshFcaConfig = refreshFcaConfig;
251
+ }
220
252
 
221
- var defaultFuncs = utils.makeDefaults(html, userID, ctx);
253
+ ctx.config = config;
254
+ var api = {
255
+ setOptions: setOptions.bind(null, globalOptions),
256
+ getAppState: () => utils.getAppState(jar),
257
+ postFormData: (url, body) => utils.makeDefaults(html, userID, ctx).postFormData(url, ctx.jar, body)
258
+ };
259
+ var defaultFuncs = utils.makeDefaults(html, userID, ctx);
260
+ api.postFormData = function (url, body) {
261
+ return defaultFuncs.postFormData(url, ctx.jar, body);
262
+ };
263
+ api.getFreshDtsg = async function () {
264
+ try {
265
+ const res = await defaultFuncs.get('https://www.facebook.com/', jar, null, globalOptions);
266
+ const $ = cheerio.load(res.body);
267
+ let newDtsg;
268
+ const patterns = [
269
+ /\["DTSGInitialData",\[\],{"token":"([^"]+)"}]/,
270
+ /\["DTSGInitData",\[\],{"token":"([^"]+)"/,
271
+ /"token":"([^"]+)"/,
272
+ /name="fb_dtsg" value="([^"]+)"/
273
+ ];
274
+
275
+ $('script').each((i, script) => {
276
+ if (!newDtsg) {
277
+ const scriptText = $(script).html() || '';
278
+ for (const pattern of patterns) {
279
+ const match = scriptText.match(pattern);
280
+ if (match && match[1]) {
281
+ newDtsg = match[1];
282
+ break;
283
+ }
284
+ }
285
+ }
286
+ });
222
287
 
223
- // Load all api functions in a loop
224
- apiFuncNames.map(v => api[v] = require('./src/' + v)(defaultFuncs, api, ctx));
288
+ if (!newDtsg) {
289
+ newDtsg = $('input[name="fb_dtsg"]').val();
290
+ }
225
291
 
226
- return [ctx, defaultFuncs, api];
292
+ return newDtsg;
293
+ } catch (e) {
294
+ console.log("Error getting fresh dtsg:", e);
295
+ return null;
296
+ }
297
+ };
298
+ 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); });
299
+
300
+ const originalSendMessage = api.sendMessage;
301
+
302
+ api.sendMessage = async function(msg, threadID, callback, replyToMessage, isSingleUser) {
303
+ try {
304
+ return await originalSendMessage(msg, threadID, callback, replyToMessage, isSingleUser);
305
+ } catch (error) {
306
+ console.log('sendMessage failed, using OldMessage fallback:', error.message);
307
+ return api.OldMessage(msg, threadID, callback, replyToMessage, isSingleUser);
308
+ }
309
+ };
310
+
311
+ api.sendMessageDM = function(msg, threadID, callback, replyToMessage) {
312
+ return api.OldMessage(msg, threadID, callback, replyToMessage, true);
313
+ };
314
+
315
+ api.listen = api.listenMqtt;
316
+ return {
317
+ ctx,
318
+ defaultFuncs,
319
+ api
320
+ };
227
321
  }
228
322
 
229
323
  function makeLogin(jar, email, password, loginOptions, callback, prCallback) {
230
- return function (res) {
231
- var html = res.body;
232
- var $ = cheerio.load(html);
233
- var arr = [];
234
-
235
- // This will be empty, but just to be sure we leave it
236
- $("#login_form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
237
-
238
- arr = arr.filter(function (v) {
239
- return v.val && v.val.length;
240
- });
241
-
242
- var form = utils.arrToForm(arr);
243
- form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
244
- form.lgndim = Buffer.from("{\"w\":1440,\"h\":900,\"aw\":1440,\"ah\":834,\"c\":24}").toString('base64');
245
- form.email = email;
246
- form.pass = password;
247
- form.default_persistent = '0';
248
- form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
249
- form.locale = 'en_US';
250
- form.timezone = '240';
251
- form.lgnjs = ~~(Date.now() / 1000);
252
-
253
-
254
- // Getting cookies from the HTML page... (kill me now plz)
255
- // we used to get a bunch of cookies in the headers of the response of the
256
- // request, but FB changed and they now send those cookies inside the JS.
257
- // They run the JS which then injects the cookies in the page.
258
- // The "solution" is to parse through the html and find those cookies
259
- // which happen to be conveniently indicated with a _js_ in front of their
260
- // variable name.
261
- //
262
- // ---------- Very Hacky Part Starts -----------------
263
- var willBeCookies = html.split("\"_js_");
264
- willBeCookies.slice(1).map(function (val) {
265
- var cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
266
- jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
267
- });
268
- // ---------- Very Hacky Part Ends -----------------
269
-
270
- log.info("login", "Logging in...");
271
- return utils
272
- .post("https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110", jar, form, loginOptions)
273
- .then(utils.saveCookies(jar))
274
- .then(function (res) {
275
- var headers = res.headers;
276
- if (!headers.location) throw { error: "Wrong username/password." };
277
-
278
- // This means the account has login approvals turned on.
279
- if (headers.location.indexOf('https://www.facebook.com/checkpoint/') > -1) {
280
- log.info("login", "You have login approvals turned on.");
281
- var nextURL = 'https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php';
282
-
283
- return utils
284
- .get(headers.location, jar, null, loginOptions)
285
- .then(utils.saveCookies(jar))
286
- .then(function (res) {
287
- var html = res.body;
288
- // Make the form in advance which will contain the fb_dtsg and nh
289
- var $ = cheerio.load(html);
290
- var arr = [];
291
- $("form input").map((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
292
-
293
- arr = arr.filter(function (v) {
294
- return v.val && v.val.length;
295
- });
296
-
297
- var form = utils.arrToForm(arr);
298
- if (html.indexOf("checkpoint/?next") > -1) {
299
- setTimeout(() => {
300
- checkVerified = setInterval((_form) => { }, 5000, {
301
- fb_dtsg: form.fb_dtsg,
302
- jazoest: form.jazoest,
303
- dpr: 1
304
- });
305
- }, 2500);
306
- throw {
307
- error: 'login-approval',
308
- continue: function submit2FA(code) {
309
- form.approvals_code = code;
310
- form['submit[Continue]'] = $("#checkpointSubmitButton").html(); //'Continue';
311
- var prResolve = null;
312
- var prReject = null;
313
- var rtPromise = new Promise(function (resolve, reject) {
314
- prResolve = resolve;
315
- prReject = reject;
316
- });
317
- if (typeof code == "string") {
318
- utils
319
- .post(nextURL, jar, form, loginOptions)
320
- .then(utils.saveCookies(jar))
321
- .then(function (res) {
322
- var $ = cheerio.load(res.body);
323
- var error = $("#approvals_code").parent().attr("data-xui-error");
324
- if (error) {
325
- throw {
326
- error: 'login-approval',
327
- errordesc: "Invalid 2FA code.",
328
- lerror: error,
329
- continue: submit2FA
330
- };
331
- }
332
- })
333
- .then(function () {
334
- // Use the same form (safe I hope)
335
- delete form.no_fido;
336
- delete form.approvals_code;
337
- form.name_action_selected = 'dont_save'; //'save_device';
338
-
339
- return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
340
- })
341
- .then(function (res) {
342
- var headers = res.headers;
343
- if (!headers.location && res.body.indexOf('Review Recent Login') > -1) throw { error: "Something went wrong with login approvals." };
344
-
345
- var appState = utils.getAppState(jar);
346
-
347
- if (callback === prCallback) {
348
- callback = function (err, api) {
349
- if (err) return prReject(err);
350
- return prResolve(api);
351
- };
352
- }
353
-
354
- // Simply call loginHelper because all it needs is the jar
355
- // and will then complete the login process
356
- return loginHelper(appState, email, password, loginOptions, callback);
357
- })
358
- .catch(function (err) {
359
- // Check if using Promise instead of callback
360
- if (callback === prCallback) prReject(err);
361
- else callback(err);
362
- });
363
- }
364
- else {
365
- utils
366
- .post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions, null, { "Referer": "https://www.facebook.com/checkpoint/?next" })
367
- .then(utils.saveCookies(jar))
368
- .then(res => {
369
- try {
370
- JSON.parse(res.body.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, ""));
371
- }
372
- catch (ex) {
373
- clearInterval(checkVerified);
374
- log.info("login", "Verified from browser. Logging in...");
375
- if (callback === prCallback) {
376
- callback = function (err, api) {
377
- if (err) return prReject(err);
378
- return prResolve(api);
379
- };
380
- }
381
- return loginHelper(utils.getAppState(jar), email, password, loginOptions, callback);
382
- }
383
- })
384
- .catch(ex => {
385
- log.error("login", ex);
386
- if (callback === prCallback) prReject(ex);
387
- else callback(ex);
388
- });
389
- }
390
- return rtPromise;
391
- }
392
- };
393
- }
394
- else {
395
- if (!loginOptions.forceLogin) throw { error: "Couldn't login. Facebook might have blocked this account. Please login with a browser or enable the option 'forceLogin' and try again." };
396
-
397
- if (html.indexOf("Suspicious Login Attempt") > -1) form['submit[This was me]'] = "This was me";
398
- else form['submit[This Is Okay]'] = "This Is Okay";
399
-
400
- return utils
401
- .post(nextURL, jar, form, loginOptions)
402
- .then(utils.saveCookies(jar))
403
- .then(function () {
404
- // Use the same form (safe I hope)
405
- form.name_action_selected = 'save_device';
406
-
407
- return utils.post(nextURL, jar, form, loginOptions).then(utils.saveCookies(jar));
408
- })
409
- .then(function (res) {
410
- var headers = res.headers;
411
-
412
- if (!headers.location && res.body.indexOf('Review Recent Login') > -1) throw { error: "Something went wrong with review recent login." };
413
-
414
- var appState = utils.getAppState(jar);
415
-
416
- // Simply call loginHelper because all it needs is the jar
417
- // and will then complete the login process
418
- return loginHelper(appState, email, password, loginOptions, callback);
419
- })
420
- .catch(e => callback(e));
421
- }
324
+ return async function (res) {
325
+ try {
326
+ const html = res.body;
327
+ const $ = cheerio.load(html);
328
+ let arr = [];
329
+ $("#login_form input").each((i, v) => arr.push({ val: $(v).val(), name: $(v).attr("name") }));
330
+ arr = arr.filter(v => v.val && v.val.length);
331
+ let form = utils.arrToForm(arr);
332
+ form.lsd = utils.getFrom(html, "[\"LSD\",[],{\"token\":\"", "\"}");
333
+ form.lgndim = Buffer.from(JSON.stringify({ w: 1440, h: 900, aw: 1440, ah: 834, c: 24 })).toString('base64');
334
+ form.email = email;
335
+ form.pass = password;
336
+ form.default_persistent = '0';
337
+ form.lgnrnd = utils.getFrom(html, "name=\"lgnrnd\" value=\"", "\"");
338
+ form.locale = 'en_US';
339
+ form.timezone = '240';
340
+ form.lgnjs = Math.floor(Date.now() / 1000);
341
+ const willBeCookies = html.split("\"_js_");
342
+ willBeCookies.slice(1).forEach(val => {
343
+ const cookieData = JSON.parse("[\"" + utils.getFrom(val, "", "]") + "]");
344
+ jar.setCookie(utils.formatCookie(cookieData, "facebook"), "https://www.facebook.com");
422
345
  });
346
+ console.log("SAGOR-FCA: Logging in...");
347
+ const loginRes = await utils.post(
348
+ "https://www.facebook.com/login/device-based/regular/login/?login_attempt=1&lwv=110",
349
+ jar,
350
+ form,
351
+ loginOptions
352
+ );
353
+ await utils.saveCookies(jar)(loginRes);
354
+ const headers = loginRes.headers;
355
+ if (!headers.location) throw new Error("Wrong username/password.");
356
+ if (headers.location.includes('https://www.facebook.com/checkpoint/')) {
357
+ log.info("login", "You have login approvals turned on.");
358
+ const checkpointRes = await utils.get(headers.location, jar, null, loginOptions);
359
+ await utils.saveCookies(jar)(checkpointRes);
360
+ const checkpointHtml = checkpointRes.body;
361
+ const $ = cheerio.load(checkpointHtml);
362
+ let checkpointForm = [];
363
+ $("form input").each((i, v) => checkpointForm.push({ val: $(v).val(), name: $(v).attr("name") }));
364
+ checkpointForm = checkpointForm.filter(v => v.val && v.val.length);
365
+ const form = utils.arrToForm(checkpointForm);
366
+ if (checkpointHtml.includes("checkpoint/?next")) {
367
+ return new Promise((resolve, reject) => {
368
+ const submit2FA = async (code) => {
369
+ try {
370
+ form.approvals_code = code;
371
+ form['submit[Continue]'] = $("#checkpointSubmitButton").html();
372
+ const approvalRes = await utils.post(
373
+ "https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
374
+ jar,
375
+ form,
376
+ loginOptions
377
+ );
378
+ await utils.saveCookies(jar)(approvalRes);
379
+ const approvalError = $("#approvals_code").parent().attr("data-xui-error");
380
+ if (approvalError) throw new Error("Invalid 2FA code.");
381
+ form.name_action_selected = 'dont_save';
382
+ const finalRes = await utils.post(
383
+ "https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php",
384
+ jar,
385
+ form,
386
+ loginOptions
387
+ );
388
+ await utils.saveCookies(jar)(finalRes);
389
+ const appState = utils.getAppState(jar);
390
+ resolve(await loginHelper(appState, email, password, loginOptions, callback));
391
+ } catch (error) {
392
+ reject(error);
393
+ }
394
+ };
395
+ throw {
396
+ error: 'login-approval',
397
+ continue: submit2FA
398
+ };
399
+ });
400
+ }
401
+ if (!loginOptions.forceLogin) throw new Error("Couldn't login. Facebook might have blocked this account.");
402
+ form['submit[This was me]'] = checkpointHtml.includes("Suspicious Login Attempt") ? "This was me" : "This Is Okay";
403
+ await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
404
+ form.name_action_selected = 'save_device';
405
+ const reviewRes = await utils.post("https://www.facebook.com/checkpoint/?next=https%3A%2F%2Fwww.facebook.com%2Fhome.php", jar, form, loginOptions);
406
+ const appState = utils.getAppState(jar);
407
+ return await loginHelper(appState, email, password, loginOptions, callback);
408
+ }
409
+ await utils.get('https://www.facebook.com/', jar, null, loginOptions);
410
+ return await utils.saveCookies(jar);
411
+ } catch (error) {
412
+ callback(error);
423
413
  }
424
-
425
- return utils.get('https://www.facebook.com/', jar, null, loginOptions).then(utils.saveCookies(jar));
426
- });
427
- };
414
+ };
428
415
  }
429
416
 
430
- // Helps the login
431
- function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
432
- var mainPromise = null;
433
- var jar = utils.getJar();
434
-
435
- // If we're given an appState we loop through it and save each cookie
436
- // back into the jar.
437
- if (appState) {
438
- // check and convert cookie to appState
439
- if (utils.getType(appState) === 'Array' && appState.some(c => c.name)) {
440
- appState = appState.map(c => {
441
- c.key = c.name;
442
- delete c.name;
443
- return c;
444
- });
445
- }
446
- else if (utils.getType(appState) === 'String') {
447
- const arrayAppState = [];
448
- appState.split(';').forEach(c => {
449
- const [key, value] = c.split('=');
450
417
 
451
- arrayAppState.push({
452
- key: (key || "").trim(),
453
- value: (value || "").trim(),
454
- domain: "facebook.com",
455
- path: "/",
456
- expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 365
457
- });
458
- });
459
- appState = arrayAppState;
460
- }
418
+ function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
419
+ let mainPromise = null;
420
+ const jar = utils.getJar();
421
+ if (appState) {
422
+ try {
423
+ appState = JSON.parse(appState);
424
+ } catch (e) {
425
+ try {
426
+ appState = appState;
427
+ } catch (e) {
428
+ return callback(new Error("Failed to parse appState"));
429
+ }
430
+ }
461
431
 
462
- appState.map(function (c) {
463
- const str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
464
- jar.setCookie(str, "http://" + c.domain);
465
- });
432
+ try {
433
+ appState.forEach(c => {
434
+ const str = `${c.key}=${c.value}; expires=${c.expires}; domain=${c.domain}; path=${c.path};`;
435
+ jar.setCookie(str, "http://" + c.domain);
436
+ });
466
437
 
467
- // Load the main page.
468
- mainPromise = utils.get('https://mbasic.facebook.com/a/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
469
- } else {
470
- // Open the main page, then we login with the given credentials and finally
471
- // load the main page again (it'll give us some IDs that we need)
472
- mainPromise = utils
473
- .get("https://mbasic.facebook.com/a/", null, null, globalOptions, { noRef: true })
474
- .then(utils.saveCookies(jar))
475
- .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
476
- .then(function () {
477
- return utils.get('https://mbasic.facebook.com/a/', jar, null, globalOptions).then(utils.saveCookies(jar));
478
- });
479
- }
438
+ mainPromise = utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
439
+ .then(utils.saveCookies(jar));
440
+ } catch (e) {
441
+ process.exit(0);
442
+ }
443
+ } else {
444
+ mainPromise = utils
445
+ .get("https://www.facebook.com/", null, null, globalOptions, { noRef: true })
446
+ .then(utils.saveCookies(jar))
447
+ .then(makeLogin(jar, email, password, globalOptions, callback, prCallback))
448
+ .then(() => utils.get('https://www.facebook.com/', jar, null, globalOptions).then(utils.saveCookies(jar)));
449
+ }
480
450
 
451
+ function handleRedirect(res) {
452
+ const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
453
+ const redirect = reg.exec(res.body);
454
+ if (redirect && redirect[1]) {
455
+ return utils.get(redirect[1], jar, null, globalOptions).then(utils.saveCookies(jar));
456
+ }
457
+ return res;
458
+ }
481
459
 
482
- let redirectArr = [1, "https://m.facebook.com/"];
483
- let ctx;
484
- let api;
485
- function checkAndFixErr(res) {
486
- const reg_antierr = /This browser is not supported/gs;
487
- if (reg_antierr.test(res.body)) {
488
- const Data = JSON.stringify(res.body);
489
- const Dt_Check = Data.split('2Fhome.php&amp;gfid=')[1];
490
- if (Dt_Check == undefined) return res;
491
- const fid = Dt_Check.split("\\\\")[0];
492
- if (Dt_Check == undefined || Dt_Check == "") return res;
493
- const final_fid = fid.split(`\\`)[0];
494
- if (final_fid == undefined || final_fid == '') return res;
495
- const redirectlink = redirectArr[1] + "a/preferences.php?basic_site_devices=m_basic&uri=" + encodeURIComponent("https://m.facebook.com/home.php") + "&gfid=" + final_fid;
496
- return utils.get(redirectlink, jar, null, globalOptions).then(utils.saveCookies(jar));
497
- }
498
- else return res;
499
- }
500
- function redirect(res) {
501
- const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
502
- redirectArr = reg.exec(res.body);
503
- if (redirectArr && redirectArr[1]) return utils.get(redirectArr[1], jar, null, globalOptions).then(utils.saveCookies(jar));
504
- return res;
505
- }
460
+ let ctx, api;
461
+ mainPromise = mainPromise
462
+ .then(handleRedirect)
463
+ .then(res => {
464
+ const mobileAgentRegex = /MPageLoadClientMetrics/gs;
465
+ if (!mobileAgentRegex.test(res.body)) {
466
+ 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";
467
+ return utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
468
+ }
469
+ return res;
470
+ })
471
+ .then(handleRedirect)
472
+ .then(res => {
473
+ const html = res.body;
474
+ const Obj = buildAPI(globalOptions, html, jar);
475
+ ctx = Obj.ctx;
476
+ api = Obj.api;
477
+ return res;
478
+ });
479
+
480
+ if (globalOptions.pageID) {
481
+ mainPromise = mainPromise
482
+ .then(() => utils.get(`https://www.facebook.com/${globalOptions.pageID}/messages/?section=messages&subsection=inbox`, jar, null, globalOptions))
483
+ .then(resData => {
484
+ let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
485
+ url = url.substring(0, url.length - 1);
486
+ return utils.get('https://www.facebook.com' + url, jar, null, globalOptions);
487
+ });
488
+ }
506
489
 
507
- // At the end we call the callback or catch an exception
508
- mainPromise = mainPromise
509
- .then(res => redirect(res))
510
- .then(res => checkAndFixErr(res))
511
- //fix via login with defaut UA return WWW.facebook.com not m.facebook.com
512
- .then(function (res) {
513
- const Regex_Via = /MPageLoadClientMetrics/gs; //default for normal account, can easily get region, without this u can't get region in some case but u can run normal
514
- if (!Regex_Via.test(res.body)) {
515
- //www.facebook.com
516
- globalOptions.userAgent = "Mozilla/5.0 (Linux; Android 14; SM-A055F Build/UP1A.231005.007; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/130.0.6723.86 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/461.0.0.47.85;] ";
517
- return utils.get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true }).then(utils.saveCookies(jar));
518
- }
519
- else return res;
520
- })
521
- .then(res => redirect(res))
522
- .then(res => checkAndFixErr(res))
523
- .then(function (res) {
524
- const html = res.body;
525
- const stuff = buildAPI(globalOptions, html, jar);
526
- ctx = stuff[0];
527
- api = stuff[2];
528
- return res;
529
- });
490
+ mainPromise
491
+ .then(async () => {
492
+ console.log('SAGOR-FCA: Connected ✔');
493
+ console.log('SAGOR-FCA: Listening...');
494
+ callback(null, api);
495
+ })
496
+ .catch(e => {
497
+ callback(e);
498
+ });
499
+ }
530
500
 
531
- // given a pageID we log in as a page
532
- if (globalOptions.pageID) {
533
- mainPromise = mainPromise
534
- .then(function () {
535
- return utils.get('https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx.jar, null, globalOptions);
536
- })
537
- .then(function (resData) {
538
- let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
539
- url = url.substring(0, url.length - 1);
540
- return utils.get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
541
- });
542
- }
543
501
 
544
- // At the end we call the callback or catch an exception
545
- mainPromise
546
- .then(function () {
547
- log.info("login", 'Done logging in.');
548
- return callback(null, api);
549
- })
550
- .catch(function (e) {
551
- log.error("login", e.error || e);
552
- callback(e);
553
- });
554
- }
555
502
  function login(loginData, options, callback) {
556
- if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
557
- callback = options;
558
- options = {};
559
- }
503
+ if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
504
+ callback = options;
505
+ options = {};
506
+ }
560
507
 
561
- var globalOptions = {
562
- pauseLog: false,
563
- selfListen: false,
564
- listenEvents: true,
565
- listenTyping: false,
566
- updatePresence: false,
567
- forceLogin: false,
568
- autoMarkDelivery: false,
569
- autoMarkRead: false,
570
- autoReconnect: true,
571
- logRecordSize: defaultLogRecordSize,
572
- online: false,
573
- emitReady: false,
574
- userAgent: "Mozilla/5.0 (Linux; Android 14; SM-A055F Build/UP1A.231005.007; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/130.0.6723.86 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/461.0.0.47.85;] "
575
- };
508
+ var globalOptions = {
509
+ selfListen: false,
510
+ listenEvents: true,
511
+ listenTyping: false,
512
+ updatePresence: false,
513
+ forceLogin: false,
514
+ autoMarkDelivery: false,
515
+ autoMarkRead: false,
516
+ autoReconnect: true,
517
+ logRecordSize: 100,
518
+ online: false,
519
+ emitReady: false,
520
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
521
+ };
576
522
 
577
- setOptions(globalOptions, options);
523
+ var prCallback = null;
524
+ if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
525
+ var rejectFunc = null;
526
+ var resolveFunc = null;
527
+ var returnPromise = new Promise(function (resolve, reject) {
528
+ resolveFunc = resolve;
529
+ rejectFunc = reject;
530
+ });
531
+ prCallback = function (error, api) {
532
+ if (error) return rejectFunc(error);
533
+ return resolveFunc(api);
534
+ };
535
+ callback = prCallback;
536
+ }
578
537
 
579
- var prCallback = null;
580
- if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
581
- var rejectFunc = null;
582
- var resolveFunc = null;
583
- var returnPromise = new Promise(function (resolve, reject) {
584
- resolveFunc = resolve;
585
- rejectFunc = reject;
586
- });
587
- prCallback = function (error, api) {
588
- if (error) return rejectFunc(error);
589
- return resolveFunc(api);
590
- };
591
- callback = prCallback;
592
- }
593
- loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
594
- return returnPromise;
538
+ if (loginData.email && loginData.password) {
539
+ setOptions(globalOptions, {
540
+ logLevel: "silent",
541
+ forceLogin: true,
542
+ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
543
+ });
544
+ loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
545
+ } else if (loginData.appState) {
546
+ setOptions(globalOptions, options);
547
+ return loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
548
+ }
549
+ return returnPromise;
595
550
  }
596
551
 
597
- module.exports = login;
552
+ module.exports = login;