@dongdev/fca-unofficial 0.0.6 → 0.0.7

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/index.js CHANGED
@@ -2,307 +2,357 @@
2
2
 
3
3
  const utils = require("./utils");
4
4
  const log = require("npmlog");
5
-
6
5
  let checkVerified = null;
7
-
8
6
  const defaultLogRecordSize = 100;
9
7
  log.maxRecordSize = defaultLogRecordSize;
10
-
8
+ const Boolean_Option = [
9
+ "online",
10
+ "selfListen",
11
+ "listenEvents",
12
+ "updatePresence",
13
+ "forceLogin",
14
+ "autoMarkDelivery",
15
+ "autoMarkRead",
16
+ "listenTyping",
17
+ "autoReconnect",
18
+ "emitReady",
19
+ ];
11
20
  function setOptions(globalOptions, options) {
12
- Object.keys(options).map(function (key) {
13
- switch (key) {
14
- case 'online':
15
- globalOptions.online = Boolean(options.online);
16
- break;
17
- case 'logLevel':
18
- log.level = options.logLevel;
19
- globalOptions.logLevel = options.logLevel;
20
- break;
21
- case 'logRecordSize':
22
- log.maxRecordSize = options.logRecordSize;
23
- globalOptions.logRecordSize = options.logRecordSize;
24
- break;
25
- case 'selfListen':
26
- globalOptions.selfListen = Boolean(options.selfListen);
27
- break;
28
- case 'selfListenEvent':
29
- globalOptions.selfListenEvent = options.selfListenEvent;
30
- break;
31
- case 'listenEvents':
32
- globalOptions.listenEvents = Boolean(options.listenEvents);
33
- break;
34
- case 'pageID':
35
- globalOptions.pageID = options.pageID.toString();
36
- break;
37
- case 'updatePresence':
38
- globalOptions.updatePresence = Boolean(options.updatePresence);
39
- break;
40
- case 'forceLogin':
41
- globalOptions.forceLogin = Boolean(options.forceLogin);
42
- break;
43
- case 'userAgent':
44
- globalOptions.userAgent = options.userAgent;
45
- break;
46
- case 'autoMarkDelivery':
47
- globalOptions.autoMarkDelivery = Boolean(options.autoMarkDelivery);
48
- break;
49
- case 'autoMarkRead':
50
- globalOptions.autoMarkRead = Boolean(options.autoMarkRead);
51
- break;
52
- case 'listenTyping':
53
- globalOptions.listenTyping = Boolean(options.listenTyping);
54
- break;
55
- case 'proxy':
56
- if (typeof options.proxy != "string") {
57
- delete globalOptions.proxy;
58
- utils.setProxy();
59
- } else {
60
- globalOptions.proxy = options.proxy;
61
- utils.setProxy(globalOptions.proxy);
62
- }
63
- break;
64
- case 'autoReconnect':
65
- globalOptions.autoReconnect = Boolean(options.autoReconnect);
66
- break;
67
- case 'emitReady':
68
- globalOptions.emitReady = Boolean(options.emitReady);
69
- break;
70
- default:
71
- log.warn("setOptions", "Unrecognized option given to setOptions: " + key);
72
- break;
73
- }
74
- });
21
+ Object.keys(options).map(function(key) {
22
+ switch (Boolean_Option.includes(key)) {
23
+ case true: {
24
+ globalOptions[key] = Boolean(options[key]);
25
+ break;
26
+ }
27
+ case false: {
28
+ switch (key) {
29
+ case "pauseLog": {
30
+ if (options.pauseLog) log.pause();
31
+ else log.resume();
32
+ break;
33
+ }
34
+ case "logLevel": {
35
+ log.level = options.logLevel;
36
+ globalOptions.logLevel = options.logLevel;
37
+ break;
38
+ }
39
+ case "logRecordSize": {
40
+ log.maxRecordSize = options.logRecordSize;
41
+ globalOptions.logRecordSize = options.logRecordSize;
42
+ break;
43
+ }
44
+ case "pageID": {
45
+ globalOptions.pageID = options.pageID.toString();
46
+ break;
47
+ }
48
+ case "userAgent": {
49
+ globalOptions.userAgent =
50
+ options.userAgent ||
51
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36";
52
+ break;
53
+ }
54
+ case "proxy": {
55
+ if (typeof options.proxy != "string") {
56
+ delete globalOptions.proxy;
57
+ utils.setProxy();
58
+ } else {
59
+ globalOptions.proxy = options.proxy;
60
+ utils.setProxy(globalOptions.proxy);
61
+ }
62
+ break;
63
+ }
64
+ default: {
65
+ log.warn(
66
+ "setOptions",
67
+ "Unrecognized option given to setOptions: " + key
68
+ );
69
+ break;
70
+ }
71
+ }
72
+ break;
73
+ }
74
+ }
75
+ });
75
76
  }
76
-
77
77
  function buildAPI(globalOptions, html, jar) {
78
- const maybeCookie = jar.getCookies("https://www.facebook.com").filter(function (val) {
79
- return val.cookieString().split("=")[0] === "c_user";
80
- });
81
-
82
- const objCookie = jar.getCookies("https://www.facebook.com").reduce(function (obj, val) {
83
- obj[val.cookieString().split("=")[0]] = val.cookieString().split("=")[1];
84
- return obj;
85
- }, {});
86
-
87
- if (maybeCookie.length === 0) {
88
- 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." };
89
- }
90
-
91
- if (html.indexOf("/checkpoint/block/?next") > -1) {
92
- log.warn("login", "Checkpoint detected. Please log in with a browser to verify.");
93
- }
94
-
95
- const userID = maybeCookie[0].cookieString().split("=")[1].toString();
96
- const i_userID = objCookie.i_user || null;
97
- log.info("login", `Logged in as ${userID}`);
98
-
99
- try {
100
- clearInterval(checkVerified);
101
- } catch (_) { }
102
-
103
- const clientID = (Math.random() * 2147483648 | 0).toString(16);
104
-
105
-
106
- const oldFBMQTTMatch = html.match(/irisSeqID:"(.+?)",appID:219994525426954,endpoint:"(.+?)"/);
107
- let mqttEndpoint, region, fb_dtsg, irisSeqID;
108
- try {
109
- const endpointMatch = html.match(/"endpoint":"([^"]+)"/);
110
- if (endpointMatch) {
111
- mqttEndpoint = endpointMatch[1].replace(/\\\//g, '/');
112
- const url = new URL(mqttEndpoint);
113
- region = url.searchParams.get('region')?.toUpperCase() || "PRN";
114
- }
115
- log.info('login', `Sever region ${region}`);
116
- } catch (e) {
117
- log.warning('login', 'Not MQTT endpoint');
118
- }
119
- const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
120
- if (tokenMatch) {
121
- fb_dtsg = tokenMatch[1];
122
- }
123
-
124
- // All data available to api functions
125
- const ctx = {
126
- userID: userID,
127
- i_userID: i_userID,
128
- jar: jar,
129
- clientID: clientID,
130
- globalOptions: globalOptions,
131
- loggedIn: true,
132
- access_token: 'NONE',
133
- clientMutationId: 0,
134
- mqttClient: undefined,
135
- lastSeqId: irisSeqID,
136
- syncToken: undefined,
137
- mqttEndpoint,
138
- region,
139
- firstListen: true,
140
- fb_dtsg
141
- };
142
-
143
- const api = {
144
- setOptions: setOptions.bind(null, globalOptions),
145
- getAppState: function getAppState() {
146
- const appState = utils.getAppState(jar);
147
- // filter duplicate
148
- return appState.filter((item, index, self) => self.findIndex((t) => { return t.key === item.key }) === index);
149
- }
150
- };
151
-
152
- const defaultFuncs = utils.makeDefaults(html, i_userID || userID, ctx);
153
- require('fs').readdirSync(__dirname + '/src/').filter((v) => v.endsWith('.js')).map(function (v) {
154
- api[v.replace('.js', '')] = require('./src/' + v)(defaultFuncs, api, ctx);
155
- });
156
- api.listen = api.listenMqtt;
157
-
158
- return [ctx, defaultFuncs, api];
78
+ const maybeCookie = jar
79
+ .getCookies("https://www.facebook.com")
80
+ .filter(function(val) {
81
+ return val.cookieString().split("=")[0] === "c_user";
82
+ });
83
+ const objCookie = jar
84
+ .getCookies("https://www.facebook.com")
85
+ .reduce(function(obj, val) {
86
+ obj[val.cookieString().split("=")[0]] = val.cookieString().split("=")[1];
87
+ return obj;
88
+ }, {});
89
+ if (maybeCookie.length === 0) {
90
+ throw {
91
+ error:
92
+ "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.",
93
+ };
94
+ }
95
+ if (html.indexOf("/checkpoint/block/?next") > -1) {
96
+ log.warn(
97
+ "login",
98
+ "Checkpoint detected. Please log in with a browser to verify."
99
+ );
100
+ }
101
+ const userID = maybeCookie[0]
102
+ .cookieString()
103
+ .split("=")[1]
104
+ .toString();
105
+ const i_userID = objCookie.i_user || null;
106
+ log.info("login", `Logged in as ${userID}`);
107
+ try {
108
+ clearInterval(checkVerified);
109
+ } catch (_) {}
110
+ const clientID = ((Math.random() * 2147483648) | 0).toString(16);
111
+ let mqttEndpoint, region, fb_dtsg, irisSeqID;
112
+ try {
113
+ const endpointMatch = html.match(/"endpoint":"([^"]+)"/);
114
+ if (endpointMatch) {
115
+ mqttEndpoint = endpointMatch[1].replace(/\\\//g, "/");
116
+ const url = new URL(mqttEndpoint);
117
+ region = url.searchParams.get("region")?.toUpperCase() || "PRN";
118
+ }
119
+ log.info("login", `Sever region ${region}`);
120
+ } catch (e) {
121
+ log.warning("login", "Not MQTT endpoint");
122
+ }
123
+ const tokenMatch = html.match(/DTSGInitialData.*?token":"(.*?)"/);
124
+ if (tokenMatch) {
125
+ fb_dtsg = tokenMatch[1];
126
+ }
127
+ const ctx = {
128
+ userID: userID,
129
+ i_userID: i_userID,
130
+ jar: jar,
131
+ clientID: clientID,
132
+ globalOptions: globalOptions,
133
+ loggedIn: true,
134
+ access_token: "NONE",
135
+ clientMutationId: 0,
136
+ mqttClient: undefined,
137
+ lastSeqId: irisSeqID,
138
+ syncToken: undefined,
139
+ mqttEndpoint,
140
+ region,
141
+ firstListen: true,
142
+ fb_dtsg,
143
+ };
144
+ const api = {
145
+ setOptions: setOptions.bind(null, globalOptions),
146
+ getAppState: function getAppState() {
147
+ const appState = utils.getAppState(jar);
148
+ return appState.filter(
149
+ (item, index, self) =>
150
+ self.findIndex((t) => {
151
+ return t.key === item.key;
152
+ }) === index
153
+ );
154
+ },
155
+ };
156
+ const defaultFuncs = utils.makeDefaults(html, i_userID || userID, ctx);
157
+ require("fs")
158
+ .readdirSync(__dirname + "/src/")
159
+ .filter((v) => v.endsWith(".js"))
160
+ .map(function(v) {
161
+ api[v.replace(".js", "")] = require("./src/" + v)(defaultFuncs, api, ctx);
162
+ });
163
+ api.listen = api.listenMqtt;
164
+ setInterval(async () => {
165
+ api
166
+ .refreshFb_dtsg()
167
+ .then(() => {
168
+ console.log("Successfully refreshed fb_dtsg");
169
+ })
170
+ .catch((err) => {
171
+ console.error("An error occurred while refreshing fb_dtsg", err);
172
+ });
173
+ }, 1000 * 60 * 60 * 48);
174
+ return [ctx, defaultFuncs, api];
159
175
  }
160
-
161
- // Helps the login
162
- function loginHelper(appState, email, password, globalOptions, callback, prCallback) {
163
- let mainPromise = null;
164
- const jar = utils.getJar();
165
-
166
- // If we're given an appState we loop through it and save each cookie
167
- // back into the jar.
168
- if (appState) {
169
- // check and convert cookie to appState
170
- if (utils.getType(appState) === 'Array' && appState.some(c => c.name)) {
171
- appState = appState.map(c => {
172
- c.key = c.name;
173
- delete c.name;
174
- return c;
175
- })
176
- }
177
- else if (utils.getType(appState) === 'String') {
178
- const arrayAppState = [];
179
- appState.split(';').forEach(c => {
180
- const [key, value] = c.split('=');
181
-
182
- arrayAppState.push({
183
- key: (key || "").trim(),
184
- value: (value || "").trim(),
185
- domain: "facebook.com",
186
- path: "/",
187
- expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 365
188
- });
189
- });
190
- appState = arrayAppState;
191
- }
192
-
193
- appState.map(function (c) {
194
- const str = c.key + "=" + c.value + "; expires=" + c.expires + "; domain=" + c.domain + "; path=" + c.path + ";";
195
- jar.setCookie(str, "http://" + c.domain);
196
- });
197
-
198
- // Load the main page.
199
- mainPromise = utils
200
- .get('https://www.facebook.com/', jar, null, globalOptions, { noRef: true })
201
- .then(utils.saveCookies(jar));
202
- } else {
203
- if (email) {
204
- throw { error: "Currently, the login method by email and password is no longer supported, please use the login method by appState" };
205
- }
206
- else {
207
- throw { error: "No appState given." };
208
- }
209
- }
210
-
211
- let ctx = null;
212
- let _defaultFuncs = null;
213
- let api = null;
214
-
215
- mainPromise = mainPromise
216
- .then(function (res) {
217
- // Hacky check for the redirection that happens on some ISPs, which doesn't return statusCode 3xx
218
- const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
219
- const redirect = reg.exec(res.body);
220
- if (redirect && redirect[1]) {
221
- return utils
222
- .get(redirect[1], jar, null, globalOptions)
223
- .then(utils.saveCookies(jar));
224
- }
225
- return res;
226
- })
227
- .then(function (res) {
228
- const html = res.body;
229
- const stuff = buildAPI(globalOptions, html, jar);
230
- ctx = stuff[0];
231
- _defaultFuncs = stuff[1];
232
- api = stuff[2];
233
- return res;
234
- });
235
-
236
- // given a pageID we log in as a page
237
- if (globalOptions.pageID) {
238
- mainPromise = mainPromise
239
- .then(function () {
240
- return utils
241
- .get('https://www.facebook.com/' + ctx.globalOptions.pageID + '/messages/?section=messages&subsection=inbox', ctx.jar, null, globalOptions);
242
- })
243
- .then(function (resData) {
244
- let url = utils.getFrom(resData.body, 'window.location.replace("https:\\/\\/www.facebook.com\\', '");').split('\\').join('');
245
- url = url.substring(0, url.length - 1);
246
-
247
- return utils
248
- .get('https://www.facebook.com' + url, ctx.jar, null, globalOptions);
249
- });
250
- }
251
-
252
- // At the end we call the callback or catch an exception
253
- mainPromise
254
- .then(function () {
255
- log.info("login", 'Done logging in.');
256
- return callback(null, api);
257
- })
258
- .catch(function (e) {
259
- log.error("login", e.error || e);
260
- callback(e);
261
- });
176
+ function loginHelper(
177
+ appState,
178
+ email,
179
+ password,
180
+ globalOptions,
181
+ callback,
182
+ prCallback
183
+ ) {
184
+ let mainPromise = null;
185
+ const jar = utils.getJar();
186
+ if (appState) {
187
+ if (utils.getType(appState) === "Array" && appState.some((c) => c.name)) {
188
+ appState = appState.map((c) => {
189
+ c.key = c.name;
190
+ delete c.name;
191
+ return c;
192
+ });
193
+ } else if (utils.getType(appState) === "String") {
194
+ const arrayAppState = [];
195
+ appState.split(";").forEach((c) => {
196
+ const [key, value] = c.split("=");
197
+ arrayAppState.push({
198
+ key: (key || "").trim(),
199
+ value: (value || "").trim(),
200
+ domain: "facebook.com",
201
+ path: "/",
202
+ expires: new Date().getTime() + 1000 * 60 * 60 * 24 * 365,
203
+ });
204
+ });
205
+ appState = arrayAppState;
206
+ }
207
+ appState.map(function(c) {
208
+ const str =
209
+ c.key +
210
+ "=" +
211
+ c.value +
212
+ "; expires=" +
213
+ c.expires +
214
+ "; domain=" +
215
+ c.domain +
216
+ "; path=" +
217
+ c.path +
218
+ ";";
219
+ jar.setCookie(str, "http://" + c.domain);
220
+ });
221
+ mainPromise = utils
222
+ .get("https://www.facebook.com/", jar, null, globalOptions, {
223
+ noRef: true,
224
+ })
225
+ .then(utils.saveCookies(jar));
226
+ } else {
227
+ if (email) {
228
+ throw {
229
+ error:
230
+ "Currently, the login method by email and password is no longer supported, please use the login method by appState",
231
+ };
232
+ } else {
233
+ throw { error: "No appState given." };
234
+ }
235
+ }
236
+ let ctx = null;
237
+ let _defaultFuncs = null;
238
+ let api = null;
239
+ mainPromise = mainPromise
240
+ .then(function(res) {
241
+ const reg = /<meta http-equiv="refresh" content="0;url=([^"]+)[^>]+>/;
242
+ const redirect = reg.exec(res.body);
243
+ if (redirect && redirect[1]) {
244
+ return utils
245
+ .get(redirect[1], jar, null, globalOptions)
246
+ .then(utils.saveCookies(jar));
247
+ }
248
+ return res;
249
+ })
250
+ .then(function(res) {
251
+ if (res.body.indexOf("checkpoint") > -1) {
252
+ log.warn(
253
+ "login",
254
+ "Checkpoint detected. Please log in with a browser to verify."
255
+ );
256
+ }
257
+ const html = res.body;
258
+ const stuff = buildAPI(globalOptions, html, jar);
259
+ ctx = stuff[0];
260
+ _defaultFuncs = stuff[1];
261
+ api = stuff[2];
262
+ return res;
263
+ });
264
+ if (globalOptions.pageID) {
265
+ mainPromise = mainPromise
266
+ .then(function() {
267
+ return utils.get(
268
+ "https://www.facebook.com/" +
269
+ ctx.globalOptions.pageID +
270
+ "/messages/?section=messages&subsection=inbox",
271
+ ctx.jar,
272
+ null,
273
+ globalOptions
274
+ );
275
+ })
276
+ .then(function(resData) {
277
+ let url = utils
278
+ .getFrom(
279
+ resData.body,
280
+ 'window.location.replace("https:\\/\\/www.facebook.com\\',
281
+ '");'
282
+ )
283
+ .split("\\")
284
+ .join("");
285
+ url = url.substring(0, url.length - 1);
286
+ return utils.get(
287
+ "https://www.facebook.com" + url,
288
+ ctx.jar,
289
+ null,
290
+ globalOptions
291
+ );
292
+ });
293
+ }
294
+ mainPromise
295
+ .then(function() {
296
+ log.info("login", "Done logging in.");
297
+ return callback(null, api);
298
+ })
299
+ .catch(function(e) {
300
+ log.error("login", e.error || e);
301
+ callback(e);
302
+ });
262
303
  }
263
-
264
304
  function login(loginData, options, callback) {
265
- if (utils.getType(options) === 'Function' || utils.getType(options) === 'AsyncFunction') {
266
- callback = options;
267
- options = {};
268
- }
269
-
270
- const globalOptions = {
271
- selfListen: false,
272
- selfListenEvent: false,
273
- listenEvents: false,
274
- listenTyping: false,
275
- updatePresence: false,
276
- forceLogin: false,
277
- autoMarkDelivery: true,
278
- autoMarkRead: false,
279
- autoReconnect: true,
280
- logRecordSize: defaultLogRecordSize,
281
- online: true,
282
- emitReady: false,
283
- userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
284
- };
285
-
286
- setOptions(globalOptions, options);
287
-
288
- let prCallback = null;
289
- if (utils.getType(callback) !== "Function" && utils.getType(callback) !== "AsyncFunction") {
290
- let rejectFunc = null;
291
- let resolveFunc = null;
292
- var returnPromise = new Promise(function (resolve, reject) {
293
- resolveFunc = resolve;
294
- rejectFunc = reject;
295
- });
296
- prCallback = function (error, api) {
297
- if (error) {
298
- return rejectFunc(error);
299
- }
300
- return resolveFunc(api);
301
- };
302
- callback = prCallback;
303
- }
304
- loginHelper(loginData.appState, loginData.email, loginData.password, globalOptions, callback, prCallback);
305
- return returnPromise;
305
+ if (
306
+ utils.getType(options) === "Function" ||
307
+ utils.getType(options) === "AsyncFunction"
308
+ ) {
309
+ callback = options;
310
+ options = {};
311
+ }
312
+ const globalOptions = {
313
+ selfListen: false,
314
+ selfListenEvent: false,
315
+ listenEvents: false,
316
+ listenTyping: false,
317
+ updatePresence: false,
318
+ forceLogin: false,
319
+ autoMarkDelivery: true,
320
+ autoMarkRead: false,
321
+ autoReconnect: true,
322
+ logRecordSize: defaultLogRecordSize,
323
+ online: true,
324
+ emitReady: false,
325
+ userAgent:
326
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
327
+ };
328
+ setOptions(globalOptions, options);
329
+ let prCallback = null;
330
+ if (
331
+ utils.getType(callback) !== "Function" &&
332
+ utils.getType(callback) !== "AsyncFunction"
333
+ ) {
334
+ let rejectFunc = null;
335
+ let resolveFunc = null;
336
+ var returnPromise = new Promise(function(resolve, reject) {
337
+ resolveFunc = resolve;
338
+ rejectFunc = reject;
339
+ });
340
+ prCallback = function(error, api) {
341
+ if (error) {
342
+ return rejectFunc(error);
343
+ }
344
+ return resolveFunc(api);
345
+ };
346
+ callback = prCallback;
347
+ }
348
+ loginHelper(
349
+ loginData.appState,
350
+ loginData.email,
351
+ loginData.password,
352
+ globalOptions,
353
+ callback,
354
+ prCallback
355
+ );
356
+ return returnPromise;
306
357
  }
307
-
308
- module.exports = login;
358
+ module.exports = login;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dongdev/fca-unofficial",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "A Facebook chat API without XMPP, will not be deprecated after April 30th, 2015.",
5
5
  "main": "index.js",
6
6
  "repository": {
@@ -4,78 +4,63 @@ const utils = require("../utils");
4
4
  const log = require("npmlog");
5
5
 
6
6
  module.exports = function (defaultFuncs, api, ctx) {
7
- /**
8
- * Refreshes the fb_dtsg and jazoest values.
9
- * @param {Function} callback
10
- * @returns {Promise}
11
- * @description if you don't update the value of fb_dtsg and jazoest for a long time an error "Please try closing and re-opening your browser window" will appear
12
- * @description you should refresh it every 48h or less
13
- */
14
- return function refreshFb_dtsg(obj, callback) {
15
- let resolveFunc = function () { };
16
- let rejectFunc = function () { };
17
- const returnPromise = new Promise(function (resolve, reject) {
18
- resolveFunc = resolve;
19
- rejectFunc = reject;
20
- });
21
-
22
- if (utils.getType(obj) === "Function" || utils.getType(obj) === "AsyncFunction") {
23
- callback = obj;
24
- obj = {};
25
- }
26
-
27
- if (!obj) {
28
- obj = {};
29
- }
30
-
31
- if (utils.getType(obj) !== "Object") {
32
- throw new utils.CustomError("the first parameter must be an object or a callback function");
33
- }
34
-
35
- if (!callback) {
36
- callback = function (err, friendList) {
37
- if (err) {
38
- return rejectFunc(err);
39
- }
40
- resolveFunc(friendList);
41
- };
42
- }
43
-
44
- if (Object.keys(obj).length == 0) {
45
- utils
46
- .get('https://m.facebook.com/', ctx.jar, null, ctx.globalOptions, { noRef: true })
47
- .then(function (resData) {
48
- const html = resData.body;
49
- const fb_dtsg = utils.getFrom(html, 'name="fb_dtsg" value="', '"');
50
- const jazoest = utils.getFrom(html, 'name="jazoest" value="', '"');
51
- if (!fb_dtsg) {
52
- throw new utils.CustomError("Could not find fb_dtsg in HTML after requesting https://www.facebook.com/");
53
- }
54
- ctx.fb_dtsg = fb_dtsg;
55
- ctx.jazoest = jazoest;
56
- callback(null, {
57
- data: {
58
- fb_dtsg: fb_dtsg,
59
- jazoest: jazoest
60
- },
61
- message: "refreshed fb_dtsg and jazoest"
62
- });
63
- })
64
- .catch(function (err) {
65
- log.error("refreshFb_dtsg", err);
66
- return callback(err);
67
- });
68
- }
69
- else {
70
- Object.keys(obj).forEach(function (key) {
71
- ctx[key] = obj[key];
72
- });
73
- callback(null, {
74
- data: obj,
75
- message: "refreshed " + Object.keys(obj).join(", ")
76
- });
77
- }
78
-
79
- return returnPromise;
80
- };
81
- };
7
+ return function refreshFb_dtsg(obj, callback) {
8
+ let resolveFunc, rejectFunc;
9
+ const returnPromise = new Promise((resolve, reject) => {
10
+ resolveFunc = resolve;
11
+ rejectFunc = reject;
12
+ });
13
+ if (
14
+ utils.getType(obj) === "Function" ||
15
+ utils.getType(obj) === "AsyncFunction"
16
+ ) {
17
+ callback = obj;
18
+ obj = {};
19
+ }
20
+ if (!obj) obj = {};
21
+ if (utils.getType(obj) !== "Object") {
22
+ throw new utils.CustomError(
23
+ "The first parameter must be an object or a callback function"
24
+ );
25
+ }
26
+ if (!callback) {
27
+ callback = (err, data) => (err ? rejectFunc(err) : resolveFunc(data));
28
+ }
29
+ if (Object.keys(obj).length === 0) {
30
+ utils
31
+ .get("https://www.facebook.com/", ctx.jar, null, ctx.globalOptions, {
32
+ noRef: true,
33
+ })
34
+ .then((resData) => {
35
+ const fb_dtsg = utils.getFrom(
36
+ resData.body,
37
+ '["DTSGInitData",[],{"token":"',
38
+ '","'
39
+ );
40
+ const jazoest = utils.getFrom(resData.body, "jazoest=", '",');
41
+ if (!fb_dtsg) {
42
+ throw new utils.CustomError(
43
+ "Could not find fb_dtsg in HTML after requesting Facebook."
44
+ );
45
+ }
46
+ ctx.fb_dtsg = fb_dtsg;
47
+ ctx.jazoest = jazoest;
48
+ callback(null, {
49
+ data: { fb_dtsg, jazoest },
50
+ message: "Refreshed fb_dtsg and jazoest",
51
+ });
52
+ })
53
+ .catch((err) => {
54
+ log.error("refreshFb_dtsg", err);
55
+ callback(err);
56
+ });
57
+ } else {
58
+ Object.assign(ctx, obj);
59
+ callback(null, {
60
+ data: obj,
61
+ message: "Refreshed " + Object.keys(obj).join(", "),
62
+ });
63
+ }
64
+ return returnPromise;
65
+ };
66
+ };
@@ -0,0 +1,49 @@
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 shareContact(text, senderID, threadID, callback) {
8
+ if (!text) {
9
+ text = "";
10
+ }
11
+ var resolveFunc = function () { };
12
+ var rejectFunc = function () { };
13
+ var returnPromise = new Promise(function (resolve, reject) {
14
+ resolveFunc = resolve;
15
+ rejectFunc = reject;
16
+ });
17
+ if (!callback) {
18
+ callback = function (err, data) {
19
+ if (err) return rejectFunc(err);
20
+ resolveFunc(data);
21
+ data
22
+ };
23
+ }
24
+ let count_req = 0
25
+ var form = JSON.stringify({
26
+ "app_id": "2220391788200892",
27
+ "payload": JSON.stringify({
28
+ tasks: [{
29
+ label: '359',
30
+ payload: JSON.stringify({
31
+ "contact_id": senderID,
32
+ "sync_group": 1,
33
+ "text": text || "",
34
+ "thread_id": threadID
35
+ }),
36
+ queue_name: 'messenger_contact_sharing',
37
+ task_id: Math.random() * 1001 << 0,
38
+ failure_count: null,
39
+ }],
40
+ epoch_id: utils.generateOfflineThreadingID(),
41
+ version_id: '7214102258676893',
42
+ }),
43
+ "request_id": ++count_req,
44
+ "type": 3
45
+ });
46
+ mqttClient.publish('/ls_req', form);
47
+ return returnPromise;
48
+ };
49
+ };
package/utils.js CHANGED
@@ -1,4 +1,3 @@
1
- /* eslint-disable no-prototype-builtins */
2
1
  "use strict";
3
2
 
4
3
  let request = promisifyPromise(require("request").defaults({ jar: true, proxy: process.env.FB_PROXY }));