@dongdev/fca-unofficial 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/utils.js CHANGED
@@ -1,1500 +1,1387 @@
1
1
  "use strict";
2
-
3
- let request = promisifyPromise(require("request").defaults({ jar: true, proxy: process.env.FB_PROXY }));
4
- const stream = require("stream");
2
+ var url = require("url");
5
3
  const log = require("npmlog");
4
+ const stream = require("stream");
5
+ const bluebird = require("bluebird");
6
6
  const querystring = require("querystring");
7
- const url = require("url");
8
- var bluebird = require("bluebird");
7
+ const request = bluebird.promisify(require("request").defaults({ jar: true }));
9
8
 
10
9
  class CustomError extends Error {
11
- constructor(obj) {
12
- if (typeof obj === 'string')
13
- obj = { message: obj };
14
- if (typeof obj !== 'object' || obj === null)
15
- throw new TypeError('Object required');
16
- obj.message ? super(obj.message) : super();
17
- Object.assign(this, obj);
18
- }
10
+ constructor(obj) {
11
+ if (typeof obj === 'string')
12
+ obj = { message: obj };
13
+ if (typeof obj !== 'object' || obj === null)
14
+ throw new TypeError('Object required');
15
+ obj.message ? super(obj.message) : super();
16
+ Object.assign(this, obj);
17
+ }
19
18
  }
20
19
 
21
- function callbackToPromise(func) {
22
- return function (...args) {
23
- return new Promise((resolve, reject) => {
24
- func(...args, (err, data) => {
25
- if (err)
26
- reject(err);
27
- else
28
- resolve(data);
29
- });
30
- });
31
- };
32
- }
33
-
34
- function isHasCallback(func) {
35
- if (typeof func !== "function")
36
- return false;
37
- return func.toString().split("\n")[0].match(/(callback|cb)\s*\)/) !== null;
38
- }
39
-
40
- // replace for bluebird.promisify (but this only applies best to the `request` package)
41
- function promisifyPromise(promise) {
42
- const keys = Object.keys(promise);
43
- let promise_;
44
- if (
45
- typeof promise === "function"
46
- && isHasCallback(promise)
47
- )
48
- promise_ = callbackToPromise(promise);
49
- else
50
- promise_ = promise;
51
-
52
- for (const key of keys) {
53
- if (!promise[key]?.toString)
54
- continue;
55
-
56
- if (
57
- typeof promise[key] === "function"
58
- && isHasCallback(promise[key])
59
- ) {
60
- promise_[key] = callbackToPromise(promise[key]);
61
- }
62
- else {
63
- promise_[key] = promise[key];
64
- }
65
- }
66
-
67
- return promise_;
20
+ function tryPromise(tryFunc) {
21
+ return new Promise((resolve, reject) => {
22
+ try {
23
+ resolve(tryFunc());
24
+ } catch (error) {
25
+ reject(error);
26
+ }
27
+ });
68
28
  }
69
29
 
70
- // replace for bluebird.delay
71
30
  function delay(ms) {
72
- return new Promise(resolve => setTimeout(resolve, ms));
73
- }
74
-
75
- // replace for bluebird.try
76
- function tryPromise(tryFunc) {
77
- return new Promise((resolve, reject) => {
78
- try {
79
- resolve(tryFunc());
80
- } catch (error) {
81
- reject(error);
82
- }
83
- });
31
+ return new Promise(resolve => setTimeout(resolve, ms));
84
32
  }
85
33
 
86
34
  function setProxy(url) {
87
- if (typeof url == "undefined")
88
- return request = promisifyPromise(require("request").defaults({
89
- jar: true
90
- }));
91
- return request = promisifyPromise(require("request").defaults({
92
- jar: true,
93
- proxy: url
94
- }));
35
+ if (typeof url == "undefined") return request = bluebird.promisify(require("request").defaults({ jar: true }));
36
+ return request = bluebird.promisify(require("request").defaults({ jar: true, proxy: url }));
95
37
  }
96
38
 
97
39
  function getHeaders(url, options, ctx, customHeader) {
98
- const headers = {
99
- "Content-Type": "application/x-www-form-urlencoded",
100
- Referer: "https://www.facebook.com/",
101
- Host: url.replace("https://", "").split("/")[0],
102
- Origin: "https://www.facebook.com",
103
- "User-Agent": options.userAgent,
104
- Connection: "keep-alive",
105
- "sec-fetch-site": "same-origin"
106
- };
107
- if (customHeader) {
108
- Object.assign(headers, customHeader);
109
- }
110
- if (ctx && ctx.region) {
111
- headers["X-MSGR-Region"] = ctx.region;
112
- }
113
-
114
- return headers;
40
+ var headers = {
41
+ "Content-Type": "application/x-www-form-urlencoded",
42
+ Referer: "https://www.facebook.com/",
43
+ Host: url.replace("https://", "").split("/")[0],
44
+ Origin: "https://www.facebook.com",
45
+ "user-agent": (options?.userAgent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36"),
46
+ Connection: "keep-alive",
47
+ "sec-fetch-site": 'same-origin',
48
+ "sec-fetch-mode": 'cors'
49
+ };
50
+ if (customHeader) Object.assign(headers, customHeader);
51
+ if (ctx && ctx.region) headers["X-MSGR-Region"] = ctx.region;
52
+
53
+ return headers;
115
54
  }
116
55
 
117
56
  function isReadableStream(obj) {
118
- return (
119
- obj instanceof stream.Stream &&
120
- (getType(obj._read) === "Function" ||
121
- getType(obj._read) === "AsyncFunction") &&
122
- getType(obj._readableState) === "Object"
123
- );
57
+ return (
58
+ obj instanceof stream.Stream &&
59
+ (getType(obj._read) === "Function" ||
60
+ getType(obj._read) === "AsyncFunction") &&
61
+ getType(obj._readableState) === "Object"
62
+ );
124
63
  }
125
64
 
126
65
  function get(url, jar, qs, options, ctx) {
127
- // I'm still confused about this
128
- if (getType(qs) === "Object") {
129
- for (const prop in qs) {
130
- if (qs.hasOwnProperty(prop) && getType(qs[prop]) === "Object") {
131
- qs[prop] = JSON.stringify(qs[prop]);
132
- }
133
- }
134
- }
135
- const op = {
136
- headers: getHeaders(url, options, ctx),
137
- timeout: 60000,
138
- qs: qs,
139
- url: url,
140
- method: "GET",
141
- jar: jar,
142
- gzip: true
143
- };
144
-
145
- return request(op).then(function (res) {
146
- return Array.isArray(res) ? res[0] : res;
147
- });
66
+ if (getType(qs) === "Object")
67
+ for (var prop in qs)
68
+ if (qs.hasOwnProperty(prop) && getType(qs[prop]) === "Object") qs[prop] = JSON.stringify(qs[prop]);
69
+ var op = {
70
+ headers: getHeaders(url, options, ctx),
71
+ timeout: 60000,
72
+ qs: qs,
73
+ url: url,
74
+ method: "GET",
75
+ jar: jar,
76
+ gzip: true
77
+ };
78
+ return request(op).then(function (res) {
79
+ return res;
80
+ });
81
+ }
82
+
83
+ function get2(url, jar, headers, options, ctx) {
84
+ var op = {
85
+ headers: getHeaders(url, options, ctx, headers),
86
+ timeout: 60000,
87
+ url: url,
88
+ method: "GET",
89
+ jar: jar,
90
+ gzip: true,
91
+ };
92
+
93
+ return request(op).then(function (res) {
94
+ return res[0];
95
+ });
148
96
  }
149
97
 
150
98
  function post(url, jar, form, options, ctx, customHeader) {
151
- const op = {
152
- headers: getHeaders(url, options, ctx, customHeader),
153
- timeout: 60000,
154
- url: url,
155
- method: "POST",
156
- form: form,
157
- jar: jar,
158
- gzip: true
159
- };
160
-
161
- return request(op).then(function (res) {
162
- return Array.isArray(res) ? res[0] : res;
163
- });
99
+ var op = {
100
+ headers: getHeaders(url, options),
101
+ timeout: 60000,
102
+ url: url,
103
+ method: "POST",
104
+ form: form,
105
+ jar: jar,
106
+ gzip: true
107
+ };
108
+ return request(op).then(function (res) {
109
+ return res;
110
+ });
164
111
  }
165
112
 
166
113
  function postFormData(url, jar, form, qs, options, ctx) {
167
- const headers = getHeaders(url, options, ctx);
168
- headers["Content-Type"] = "multipart/form-data";
169
- const op = {
170
- headers: headers,
171
- timeout: 60000,
172
- url: url,
173
- method: "POST",
174
- formData: form,
175
- qs: qs,
176
- jar: jar,
177
- gzip: true
178
- };
179
-
180
- return request(op).then(function (res) {
181
- return Array.isArray(res) ? res[0] : res;
182
- });
114
+ var headers = getHeaders(url, options, ctx);
115
+ headers["Content-Type"] = "multipart/form-data";
116
+ var op = {
117
+ headers: headers,
118
+ timeout: 60000,
119
+ url: url,
120
+ method: "POST",
121
+ formData: form,
122
+ qs: qs,
123
+ jar: jar,
124
+ gzip: true
125
+ };
126
+
127
+ return request(op).then(function (res) {
128
+ return res;
129
+ });
183
130
  }
184
131
 
185
132
  function padZeros(val, len) {
186
- val = String(val);
187
- len = len || 2;
188
- while (val.length < len) val = "0" + val;
189
- return val;
133
+ val = String(val);
134
+ len = len || 2;
135
+ while (val.length < len) val = "0" + val;
136
+ return val;
190
137
  }
191
138
 
192
139
  function generateThreadingID(clientID) {
193
- const k = Date.now();
194
- const l = Math.floor(Math.random() * 4294967295);
195
- const m = clientID;
196
- return "<" + k + ":" + l + "-" + m + "@mail.projektitan.com>";
140
+ var k = Date.now();
141
+ var l = Math.floor(Math.random() * 4294967295);
142
+ var m = clientID;
143
+ return "<" + k + ":" + l + "-" + m + "@mail.projektitan.com>";
197
144
  }
198
145
 
199
146
  function binaryToDecimal(data) {
200
- let ret = "";
201
- while (data !== "0") {
202
- let end = 0;
203
- let fullName = "";
204
- let i = 0;
205
- for (; i < data.length; i++) {
206
- end = 2 * end + parseInt(data[i], 10);
207
- if (end >= 10) {
208
- fullName += "1";
209
- end -= 10;
210
- }
211
- else {
212
- fullName += "0";
213
- }
214
- }
215
- ret = end.toString() + ret;
216
- data = fullName.slice(fullName.indexOf("1"));
217
- }
218
- return ret;
147
+ var ret = "";
148
+ while (data !== "0") {
149
+ var end = 0;
150
+ var fullName = "";
151
+ var i = 0;
152
+ for (; i < data.length; i++) {
153
+ end = 2 * end + parseInt(data[i], 10);
154
+ if (end >= 10) {
155
+ fullName += "1";
156
+ end -= 10;
157
+ } else fullName += "0";
158
+ }
159
+ ret = end.toString() + ret;
160
+ data = fullName.slice(fullName.indexOf("1"));
161
+ }
162
+ return ret;
219
163
  }
220
164
 
221
165
  function generateOfflineThreadingID() {
222
- const ret = Date.now();
223
- const value = Math.floor(Math.random() * 4294967295);
224
- const str = ("0000000000000000000000" + value.toString(2)).slice(-22);
225
- const msgs = ret.toString(2) + str;
226
- return binaryToDecimal(msgs);
166
+ var ret = Date.now();
167
+ var value = Math.floor(Math.random() * 4294967295);
168
+ var str = ("0000000000000000000000" + value.toString(2)).slice(-22);
169
+ var msgs = ret.toString(2) + str;
170
+ return binaryToDecimal(msgs);
227
171
  }
228
172
 
229
- let h;
230
- const i = {};
231
- const j = {
232
- _: "%",
233
- A: "%2",
234
- B: "000",
235
- C: "%7d",
236
- D: "%7b%22",
237
- E: "%2c%22",
238
- F: "%22%3a",
239
- G: "%2c%22ut%22%3a1",
240
- H: "%2c%22bls%22%3a",
241
- I: "%2c%22n%22%3a%22%",
242
- J: "%22%3a%7b%22i%22%3a0%7d",
243
- K: "%2c%22pt%22%3a0%2c%22vis%22%3a",
244
- L: "%2c%22ch%22%3a%7b%22h%22%3a%22",
245
- M: "%7b%22v%22%3a2%2c%22time%22%3a1",
246
- N: ".channel%22%2c%22sub%22%3a%5b",
247
- O: "%2c%22sb%22%3a1%2c%22t%22%3a%5b",
248
- P: "%2c%22ud%22%3a100%2c%22lc%22%3a0",
249
- Q: "%5d%2c%22f%22%3anull%2c%22uct%22%3a",
250
- R: ".channel%22%2c%22sub%22%3a%5b1%5d",
251
- S: "%22%2c%22m%22%3a0%7d%2c%7b%22i%22%3a",
252
- T: "%2c%22blc%22%3a1%2c%22snd%22%3a1%2c%22ct%22%3a",
253
- U: "%2c%22blc%22%3a0%2c%22snd%22%3a1%2c%22ct%22%3a",
254
- V: "%2c%22blc%22%3a0%2c%22snd%22%3a0%2c%22ct%22%3a",
255
- W: "%2c%22s%22%3a0%2c%22blo%22%3a0%7d%2c%22bl%22%3a%7b%22ac%22%3a",
256
- X: "%2c%22ri%22%3a0%7d%2c%22state%22%3a%7b%22p%22%3a0%2c%22ut%22%3a1",
257
- Y:
258
- "%2c%22pt%22%3a0%2c%22vis%22%3a1%2c%22bls%22%3a0%2c%22blc%22%3a0%2c%22snd%22%3a1%2c%22ct%22%3a",
259
- Z:
260
- "%2c%22sb%22%3a1%2c%22t%22%3a%5b%5d%2c%22f%22%3anull%2c%22uct%22%3a0%2c%22s%22%3a0%2c%22blo%22%3a0%7d%2c%22bl%22%3a%7b%22ac%22%3a"
173
+ var h;
174
+ var i = {};
175
+ var j = {
176
+ _: "%",
177
+ A: "%2",
178
+ B: "000",
179
+ C: "%7d",
180
+ D: "%7b%22",
181
+ E: "%2c%22",
182
+ F: "%22%3a",
183
+ G: "%2c%22ut%22%3a1",
184
+ H: "%2c%22bls%22%3a",
185
+ I: "%2c%22n%22%3a%22%",
186
+ J: "%22%3a%7b%22i%22%3a0%7d",
187
+ K: "%2c%22pt%22%3a0%2c%22vis%22%3a",
188
+ L: "%2c%22ch%22%3a%7b%22h%22%3a%22",
189
+ M: "%7b%22v%22%3a2%2c%22time%22%3a1",
190
+ N: ".channel%22%2c%22sub%22%3a%5b",
191
+ O: "%2c%22sb%22%3a1%2c%22t%22%3a%5b",
192
+ P: "%2c%22ud%22%3a100%2c%22lc%22%3a0",
193
+ Q: "%5d%2c%22f%22%3anull%2c%22uct%22%3a",
194
+ R: ".channel%22%2c%22sub%22%3a%5b1%5d",
195
+ S: "%22%2c%22m%22%3a0%7d%2c%7b%22i%22%3a",
196
+ T: "%2c%22blc%22%3a1%2c%22snd%22%3a1%2c%22ct%22%3a",
197
+ U: "%2c%22blc%22%3a0%2c%22snd%22%3a1%2c%22ct%22%3a",
198
+ V: "%2c%22blc%22%3a0%2c%22snd%22%3a0%2c%22ct%22%3a",
199
+ W: "%2c%22s%22%3a0%2c%22blo%22%3a0%7d%2c%22bl%22%3a%7b%22ac%22%3a",
200
+ X: "%2c%22ri%22%3a0%7d%2c%22state%22%3a%7b%22p%22%3a0%2c%22ut%22%3a1",
201
+ Y: "%2c%22pt%22%3a0%2c%22vis%22%3a1%2c%22bls%22%3a0%2c%22blc%22%3a0%2c%22snd%22%3a1%2c%22ct%22%3a",
202
+ Z: "%2c%22sb%22%3a1%2c%22t%22%3a%5b%5d%2c%22f%22%3anull%2c%22uct%22%3a0%2c%22s%22%3a0%2c%22blo%22%3a0%7d%2c%22bl%22%3a%7b%22ac%22%3a"
261
203
  };
262
204
  (function () {
263
- const l = [];
264
- for (const m in j) {
265
- i[j[m]] = m;
266
- l.push(j[m]);
267
- }
268
- l.reverse();
269
- h = new RegExp(l.join("|"), "g");
205
+ var l = [];
206
+ for (var m in j) {
207
+ i[j[m]] = m;
208
+ l.push(j[m]);
209
+ }
210
+ l.reverse();
211
+ h = new RegExp(l.join("|"), "g");
270
212
  })();
271
213
 
272
214
  function presenceEncode(str) {
273
- return encodeURIComponent(str)
274
- .replace(/([_A-Z])|%../g, function (m, n) {
275
- return n ? "%" + n.charCodeAt(0).toString(16) : m;
276
- })
277
- .toLowerCase()
278
- .replace(h, function (m) {
279
- return i[m];
280
- });
215
+ return encodeURIComponent(str)
216
+ .replace(/([_A-Z])|%../g, function (m, n) {
217
+ return n ? "%" + n.charCodeAt(0).toString(16) : m;
218
+ })
219
+ .toLowerCase()
220
+ .replace(h, function (m) {
221
+ return i[m];
222
+ });
281
223
  }
282
224
 
283
- // eslint-disable-next-line no-unused-vars
284
225
  function presenceDecode(str) {
285
- return decodeURIComponent(
286
- str.replace(/[_A-Z]/g, function (m) {
287
- return j[m];
288
- })
289
- );
226
+ return decodeURIComponent(
227
+ str.replace(/[_A-Z]/g, function (/** @type {string | number} */m) {
228
+ return j[m];
229
+ })
230
+ );
290
231
  }
291
232
 
292
233
  function generatePresence(userID) {
293
- const time = Date.now();
294
- return (
295
- "E" +
296
- presenceEncode(
297
- JSON.stringify({
298
- v: 3,
299
- time: parseInt(time / 1000, 10),
300
- user: userID,
301
- state: {
302
- ut: 0,
303
- t2: [],
304
- lm2: null,
305
- uct2: time,
306
- tr: null,
307
- tw: Math.floor(Math.random() * 4294967295) + 1,
308
- at: time
309
- },
310
- ch: {
311
- ["p_" + userID]: 0
312
- }
313
- })
314
- )
315
- );
234
+ var time = Date.now();
235
+ return (
236
+ "E" +
237
+ presenceEncode(
238
+ JSON.stringify({
239
+ v: 3,
240
+ time: parseInt(time / 1000, 10),
241
+ user: userID,
242
+ state: {
243
+ ut: 0,
244
+ t2: [],
245
+ lm2: null,
246
+ uct2: time,
247
+ tr: null,
248
+ tw: Math.floor(Math.random() * 4294967295) + 1,
249
+ at: time
250
+ },
251
+ ch: {
252
+ ["p_" + userID]: 0
253
+ }
254
+ })
255
+ )
256
+ );
316
257
  }
317
258
 
318
259
  function generateAccessiblityCookie() {
319
- const time = Date.now();
320
- return encodeURIComponent(
321
- JSON.stringify({
322
- sr: 0,
323
- "sr-ts": time,
324
- jk: 0,
325
- "jk-ts": time,
326
- kb: 0,
327
- "kb-ts": time,
328
- hcm: 0,
329
- "hcm-ts": time
330
- })
331
- );
260
+ var time = Date.now();
261
+ return encodeURIComponent(
262
+ JSON.stringify({
263
+ sr: 0,
264
+ "sr-ts": time,
265
+ jk: 0,
266
+ "jk-ts": time,
267
+ kb: 0,
268
+ "kb-ts": time,
269
+ hcm: 0,
270
+ "hcm-ts": time
271
+ })
272
+ );
332
273
  }
333
274
 
334
275
  function getGUID() {
335
- /** @type {number} */
336
- let sectionLength = Date.now();
337
- /** @type {string} */
338
- const id = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
339
- /** @type {number} */
340
- const r = Math.floor((sectionLength + Math.random() * 16) % 16);
341
- /** @type {number} */
342
- sectionLength = Math.floor(sectionLength / 16);
343
- /** @type {string} */
344
- const _guid = (c == "x" ? r : (r & 7) | 8).toString(16);
345
- return _guid;
346
- });
347
- return id;
348
- }
276
+ /** @type {number} */
277
+
278
+ var sectionLength = Date.now();
279
+ /** @type {string} */
280
+
281
+ var id = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
282
+ /** @type {number} */
349
283
 
350
- function getExtension(original_extension, fullFileName = "") {
351
- if (original_extension) {
352
- return original_extension;
353
- }
354
- else {
355
- const extension = fullFileName.split(".").pop();
356
- if (extension === fullFileName) {
357
- return "";
358
- }
359
- else {
360
- return extension;
361
- }
362
- }
284
+ var r = Math.floor((sectionLength + Math.random() * 16) % 16);
285
+ /** @type {number} */
286
+
287
+ sectionLength = Math.floor(sectionLength / 16);
288
+ /** @type {string} */
289
+
290
+ var _guid = (c == "x" ? r : (r & 7) | 8).toString(16);
291
+ return _guid;
292
+ });
293
+ return id;
363
294
  }
364
295
 
365
296
  function _formatAttachment(attachment1, attachment2) {
366
- // TODO: THIS IS REALLY BAD
367
- // This is an attempt at fixing Facebook's inconsistencies. Sometimes they give us
368
- // two attachment objects, but sometimes only one. They each contain part of the
369
- // data that you'd want so we merge them for convenience.
370
- // Instead of having a bunch of if statements guarding every access to image_data,
371
- // we set it to empty object and use the fact that it'll return undefined.
372
- const fullFileName = attachment1.filename;
373
- const fileSize = Number(attachment1.fileSize || 0);
374
- const durationVideo = attachment1.genericMetadata ? Number(attachment1.genericMetadata.videoLength) : undefined;
375
- const durationAudio = attachment1.genericMetadata ? Number(attachment1.genericMetadata.duration) : undefined;
376
- const mimeType = attachment1.mimeType;
377
-
378
- attachment2 = attachment2 || { id: "", image_data: {} };
379
- attachment1 = attachment1.mercury || attachment1;
380
- let blob = attachment1.blob_attachment || attachment1.sticker_attachment;
381
- let type =
382
- blob && blob.__typename ? blob.__typename : attachment1.attach_type;
383
- if (!type && attachment1.sticker_attachment) {
384
- type = "StickerAttachment";
385
- blob = attachment1.sticker_attachment;
386
- }
387
- else if (!type && attachment1.extensible_attachment) {
388
- if (
389
- attachment1.extensible_attachment.story_attachment &&
390
- attachment1.extensible_attachment.story_attachment.target &&
391
- attachment1.extensible_attachment.story_attachment.target.__typename &&
392
- attachment1.extensible_attachment.story_attachment.target.__typename === "MessageLocation"
393
- ) {
394
- type = "MessageLocation";
395
- }
396
- else {
397
- type = "ExtensibleAttachment";
398
- }
399
-
400
- blob = attachment1.extensible_attachment;
401
- }
402
- // TODO: Determine whether "sticker", "photo", "file" etc are still used
403
- // KEEP IN SYNC WITH getThreadHistory
404
- switch (type) {
405
- case "sticker":
406
- return {
407
- type: "sticker",
408
- ID: attachment1.metadata.stickerID.toString(),
409
- url: attachment1.url,
410
-
411
- packID: attachment1.metadata.packID.toString(),
412
- spriteUrl: attachment1.metadata.spriteURI,
413
- spriteUrl2x: attachment1.metadata.spriteURI2x,
414
- width: attachment1.metadata.width,
415
- height: attachment1.metadata.height,
416
-
417
- caption: attachment2.caption,
418
- description: attachment2.description,
419
-
420
- frameCount: attachment1.metadata.frameCount,
421
- frameRate: attachment1.metadata.frameRate,
422
- framesPerRow: attachment1.metadata.framesPerRow,
423
- framesPerCol: attachment1.metadata.framesPerCol,
424
-
425
- stickerID: attachment1.metadata.stickerID.toString(), // @Legacy
426
- spriteURI: attachment1.metadata.spriteURI, // @Legacy
427
- spriteURI2x: attachment1.metadata.spriteURI2x // @Legacy
428
- };
429
- case "file":
430
- return {
431
- type: "file",
432
- ID: attachment2.id.toString(),
433
- fullFileName: fullFileName,
434
- filename: attachment1.name,
435
- fileSize: fileSize,
436
- original_extension: getExtension(attachment1.original_extension, fullFileName),
437
- mimeType: mimeType,
438
- url: attachment1.url,
439
-
440
- isMalicious: attachment2.is_malicious,
441
- contentType: attachment2.mime_type,
442
-
443
- name: attachment1.name // @Legacy
444
- };
445
- case "photo":
446
- return {
447
- type: "photo",
448
- ID: attachment1.metadata.fbid.toString(),
449
- filename: attachment1.fileName,
450
- fullFileName: fullFileName,
451
- fileSize: fileSize,
452
- original_extension: getExtension(attachment1.original_extension, fullFileName),
453
- mimeType: mimeType,
454
- thumbnailUrl: attachment1.thumbnail_url,
455
-
456
- previewUrl: attachment1.preview_url,
457
- previewWidth: attachment1.preview_width,
458
- previewHeight: attachment1.preview_height,
459
-
460
- largePreviewUrl: attachment1.large_preview_url,
461
- largePreviewWidth: attachment1.large_preview_width,
462
- largePreviewHeight: attachment1.large_preview_height,
463
-
464
- url: attachment1.metadata.url, // @Legacy
465
- width: attachment1.metadata.dimensions.split(",")[0], // @Legacy
466
- height: attachment1.metadata.dimensions.split(",")[1], // @Legacy
467
- name: fullFileName // @Legacy
468
- };
469
- case "animated_image":
470
- return {
471
- type: "animated_image",
472
- ID: attachment2.id.toString(),
473
- filename: attachment2.filename,
474
- fullFileName: fullFileName,
475
- original_extension: getExtension(attachment2.original_extension, fullFileName),
476
- mimeType: mimeType,
477
-
478
- previewUrl: attachment1.preview_url,
479
- previewWidth: attachment1.preview_width,
480
- previewHeight: attachment1.preview_height,
481
-
482
- url: attachment2.image_data.url,
483
- width: attachment2.image_data.width,
484
- height: attachment2.image_data.height,
485
-
486
- name: attachment1.name, // @Legacy
487
- facebookUrl: attachment1.url, // @Legacy
488
- thumbnailUrl: attachment1.thumbnail_url, // @Legacy
489
- rawGifImage: attachment2.image_data.raw_gif_image, // @Legacy
490
- rawWebpImage: attachment2.image_data.raw_webp_image, // @Legacy
491
- animatedGifUrl: attachment2.image_data.animated_gif_url, // @Legacy
492
- animatedGifPreviewUrl: attachment2.image_data.animated_gif_preview_url, // @Legacy
493
- animatedWebpUrl: attachment2.image_data.animated_webp_url, // @Legacy
494
- animatedWebpPreviewUrl: attachment2.image_data.animated_webp_preview_url // @Legacy
495
- };
496
- case "share":
497
- return {
498
- type: "share",
499
- ID: attachment1.share.share_id.toString(),
500
- url: attachment2.href,
501
-
502
- title: attachment1.share.title,
503
- description: attachment1.share.description,
504
- source: attachment1.share.source,
505
-
506
- image: attachment1.share.media.image,
507
- width: attachment1.share.media.image_size.width,
508
- height: attachment1.share.media.image_size.height,
509
- playable: attachment1.share.media.playable,
510
- duration: attachment1.share.media.duration,
511
-
512
- subattachments: attachment1.share.subattachments,
513
- properties: {},
514
-
515
- animatedImageSize: attachment1.share.media.animated_image_size, // @Legacy
516
- facebookUrl: attachment1.share.uri, // @Legacy
517
- target: attachment1.share.target, // @Legacy
518
- styleList: attachment1.share.style_list // @Legacy
519
- };
520
- case "video":
521
- return {
522
- type: "video",
523
- ID: attachment1.metadata.fbid.toString(),
524
- filename: attachment1.name,
525
- fullFileName: fullFileName,
526
- original_extension: getExtension(attachment1.original_extension, fullFileName),
527
- mimeType: mimeType,
528
- duration: durationVideo,
529
-
530
- previewUrl: attachment1.preview_url,
531
- previewWidth: attachment1.preview_width,
532
- previewHeight: attachment1.preview_height,
533
-
534
- url: attachment1.url,
535
- width: attachment1.metadata.dimensions.width,
536
- height: attachment1.metadata.dimensions.height,
537
-
538
- videoType: "unknown",
539
-
540
- thumbnailUrl: attachment1.thumbnail_url // @Legacy
541
- };
542
- case "error":
543
- return {
544
- type: "error",
545
-
546
- // Save error attachments because we're unsure of their format,
547
- // and whether there are cases they contain something useful for debugging.
548
- attachment1: attachment1,
549
- attachment2: attachment2
550
- };
551
- case "MessageImage":
552
- return {
553
- type: "photo",
554
- ID: blob.legacy_attachment_id,
555
- filename: blob.filename,
556
- fullFileName: fullFileName,
557
- fileSize: fileSize,
558
- original_extension: getExtension(blob.original_extension, fullFileName),
559
- mimeType: mimeType,
560
- thumbnailUrl: blob.thumbnail.uri,
561
-
562
- previewUrl: blob.preview.uri,
563
- previewWidth: blob.preview.width,
564
- previewHeight: blob.preview.height,
565
-
566
- largePreviewUrl: blob.large_preview.uri,
567
- largePreviewWidth: blob.large_preview.width,
568
- largePreviewHeight: blob.large_preview.height,
569
-
570
- url: blob.large_preview.uri, // @Legacy
571
- width: blob.original_dimensions.x, // @Legacy
572
- height: blob.original_dimensions.y, // @Legacy
573
- name: blob.filename // @Legacy
574
- };
575
- case "MessageAnimatedImage":
576
- return {
577
- type: "animated_image",
578
- ID: blob.legacy_attachment_id,
579
- filename: blob.filename,
580
- fullFileName: fullFileName,
581
- original_extension: getExtension(blob.original_extension, fullFileName),
582
- mimeType: mimeType,
583
-
584
- previewUrl: blob.preview_image.uri,
585
- previewWidth: blob.preview_image.width,
586
- previewHeight: blob.preview_image.height,
587
-
588
- url: blob.animated_image.uri,
589
- width: blob.animated_image.width,
590
- height: blob.animated_image.height,
591
-
592
- thumbnailUrl: blob.preview_image.uri, // @Legacy
593
- name: blob.filename, // @Legacy
594
- facebookUrl: blob.animated_image.uri, // @Legacy
595
- rawGifImage: blob.animated_image.uri, // @Legacy
596
- animatedGifUrl: blob.animated_image.uri, // @Legacy
597
- animatedGifPreviewUrl: blob.preview_image.uri, // @Legacy
598
- animatedWebpUrl: blob.animated_image.uri, // @Legacy
599
- animatedWebpPreviewUrl: blob.preview_image.uri // @Legacy
600
- };
601
- case "MessageVideo":
602
- return {
603
- type: "video",
604
- ID: blob.legacy_attachment_id,
605
- filename: blob.filename,
606
- fullFileName: fullFileName,
607
- original_extension: getExtension(blob.original_extension, fullFileName),
608
- fileSize: fileSize,
609
- duration: durationVideo,
610
- mimeType: mimeType,
611
-
612
- previewUrl: blob.large_image.uri,
613
- previewWidth: blob.large_image.width,
614
- previewHeight: blob.large_image.height,
615
-
616
- url: blob.playable_url,
617
- width: blob.original_dimensions.x,
618
- height: blob.original_dimensions.y,
619
-
620
- videoType: blob.video_type.toLowerCase(),
621
-
622
- thumbnailUrl: blob.large_image.uri // @Legacy
623
- };
624
- case "MessageAudio":
625
- return {
626
- type: "audio",
627
- ID: blob.url_shimhash,
628
- filename: blob.filename,
629
- fullFileName: fullFileName,
630
- fileSize: fileSize,
631
- duration: durationAudio,
632
- original_extension: getExtension(blob.original_extension, fullFileName),
633
- mimeType: mimeType,
634
-
635
- audioType: blob.audio_type,
636
- url: blob.playable_url,
637
-
638
- isVoiceMail: blob.is_voicemail
639
- };
640
- case "StickerAttachment":
641
- case "Sticker":
642
- return {
643
- type: "sticker",
644
- ID: blob.id,
645
- url: blob.url,
646
-
647
- packID: blob.pack ? blob.pack.id : null,
648
- spriteUrl: blob.sprite_image,
649
- spriteUrl2x: blob.sprite_image_2x,
650
- width: blob.width,
651
- height: blob.height,
652
-
653
- caption: blob.label,
654
- description: blob.label,
655
-
656
- frameCount: blob.frame_count,
657
- frameRate: blob.frame_rate,
658
- framesPerRow: blob.frames_per_row,
659
- framesPerCol: blob.frames_per_column,
660
-
661
- stickerID: blob.id, // @Legacy
662
- spriteURI: blob.sprite_image, // @Legacy
663
- spriteURI2x: blob.sprite_image_2x // @Legacy
664
- };
665
- case "MessageLocation":
666
- var urlAttach = blob.story_attachment.url;
667
- var mediaAttach = blob.story_attachment.media;
668
-
669
- var u = querystring.parse(url.parse(urlAttach).query).u;
670
- var where1 = querystring.parse(url.parse(u).query).where1;
671
- var address = where1.split(", ");
672
-
673
- var latitude;
674
- var longitude;
675
-
676
- try {
677
- latitude = Number.parseFloat(address[0]);
678
- longitude = Number.parseFloat(address[1]);
679
- } catch (err) {
680
- /* empty */
681
- }
682
-
683
- var imageUrl;
684
- var width;
685
- var height;
686
-
687
- if (mediaAttach && mediaAttach.image) {
688
- imageUrl = mediaAttach.image.uri;
689
- width = mediaAttach.image.width;
690
- height = mediaAttach.image.height;
691
- }
692
-
693
- return {
694
- type: "location",
695
- ID: blob.legacy_attachment_id,
696
- latitude: latitude,
697
- longitude: longitude,
698
- image: imageUrl,
699
- width: width,
700
- height: height,
701
- url: u || urlAttach,
702
- address: where1,
703
-
704
- facebookUrl: blob.story_attachment.url, // @Legacy
705
- target: blob.story_attachment.target, // @Legacy
706
- styleList: blob.story_attachment.style_list // @Legacy
707
- };
708
- case "ExtensibleAttachment":
709
- return {
710
- type: "share",
711
- ID: blob.legacy_attachment_id,
712
- url: blob.story_attachment.url,
713
-
714
- title: blob.story_attachment.title_with_entities.text,
715
- description:
716
- blob.story_attachment.description &&
717
- blob.story_attachment.description.text,
718
- source: blob.story_attachment.source
719
- ? blob.story_attachment.source.text
720
- : null,
721
-
722
- image:
723
- blob.story_attachment.media &&
724
- blob.story_attachment.media.image &&
725
- blob.story_attachment.media.image.uri,
726
- width:
727
- blob.story_attachment.media &&
728
- blob.story_attachment.media.image &&
729
- blob.story_attachment.media.image.width,
730
- height:
731
- blob.story_attachment.media &&
732
- blob.story_attachment.media.image &&
733
- blob.story_attachment.media.image.height,
734
- playable:
735
- blob.story_attachment.media &&
736
- blob.story_attachment.media.is_playable,
737
- duration:
738
- blob.story_attachment.media &&
739
- blob.story_attachment.media.playable_duration_in_ms,
740
- playableUrl:
741
- blob.story_attachment.media == null
742
- ? null
743
- : blob.story_attachment.media.playable_url,
744
-
745
- subattachments: blob.story_attachment.subattachments,
746
- properties: blob.story_attachment.properties.reduce(function (obj, cur) {
747
- obj[cur.key] = cur.value.text;
748
- return obj;
749
- }, {}),
750
-
751
- facebookUrl: blob.story_attachment.url, // @Legacy
752
- target: blob.story_attachment.target, // @Legacy
753
- styleList: blob.story_attachment.style_list // @Legacy
754
- };
755
- case "MessageFile":
756
- return {
757
- type: "file",
758
- ID: blob.message_file_fbid,
759
- fullFileName: fullFileName,
760
- filename: blob.filename,
761
- fileSize: fileSize,
762
- mimeType: blob.mimetype,
763
- original_extension: blob.original_extension || fullFileName.split(".").pop(),
764
-
765
- url: blob.url,
766
- isMalicious: blob.is_malicious,
767
- contentType: blob.content_type,
768
-
769
- name: blob.filename
770
- };
771
- default:
772
- throw new Error(
773
- "unrecognized attach_file of type " +
774
- type +
775
- "`" +
776
- JSON.stringify(attachment1, null, 4) +
777
- " attachment2: " +
778
- JSON.stringify(attachment2, null, 4) +
779
- "`"
780
- );
781
- }
297
+ attachment2 = attachment2 || { id: "", image_data: {} };
298
+ attachment1 = attachment1.mercury ? attachment1.mercury : attachment1;
299
+ var blob = attachment1.blob_attachment;
300
+ var type =
301
+ blob && blob.__typename ? blob.__typename : attachment1.attach_type;
302
+ if (!type && attachment1.sticker_attachment) {
303
+ type = "StickerAttachment";
304
+ blob = attachment1.sticker_attachment;
305
+ } else if (!type && attachment1.extensible_attachment) {
306
+ if (
307
+ attachment1.extensible_attachment.story_attachment &&
308
+ attachment1.extensible_attachment.story_attachment.target &&
309
+ attachment1.extensible_attachment.story_attachment.target.__typename &&
310
+ attachment1.extensible_attachment.story_attachment.target.__typename === "MessageLocation"
311
+ ) type = "MessageLocation";
312
+ else type = "ExtensibleAttachment";
313
+
314
+ blob = attachment1.extensible_attachment;
315
+ }
316
+ switch (type) {
317
+ case "sticker":
318
+ return {
319
+ type: "sticker",
320
+ ID: attachment1.metadata.stickerID.toString(),
321
+ url: attachment1.url,
322
+
323
+ packID: attachment1.metadata.packID.toString(),
324
+ spriteUrl: attachment1.metadata.spriteURI,
325
+ spriteUrl2x: attachment1.metadata.spriteURI2x,
326
+ width: attachment1.metadata.width,
327
+ height: attachment1.metadata.height,
328
+
329
+ caption: attachment2.caption,
330
+ description: attachment2.description,
331
+
332
+ frameCount: attachment1.metadata.frameCount,
333
+ frameRate: attachment1.metadata.frameRate,
334
+ framesPerRow: attachment1.metadata.framesPerRow,
335
+ framesPerCol: attachment1.metadata.framesPerCol,
336
+
337
+ stickerID: attachment1.metadata.stickerID.toString(), // @Legacy
338
+ spriteURI: attachment1.metadata.spriteURI, // @Legacy
339
+ spriteURI2x: attachment1.metadata.spriteURI2x // @Legacy
340
+ };
341
+ case "file":
342
+ return {
343
+ type: "file",
344
+ filename: attachment1.name,
345
+ ID: attachment2.id.toString(),
346
+ url: attachment1.url,
347
+
348
+ isMalicious: attachment2.is_malicious,
349
+ contentType: attachment2.mime_type,
350
+
351
+ name: attachment1.name, // @Legacy
352
+ mimeType: attachment2.mime_type, // @Legacy
353
+ fileSize: attachment2.file_size // @Legacy
354
+ };
355
+ case "photo":
356
+ return {
357
+ type: "photo",
358
+ ID: attachment1.metadata.fbid.toString(),
359
+ filename: attachment1.fileName,
360
+ thumbnailUrl: attachment1.thumbnail_url,
361
+
362
+ previewUrl: attachment1.preview_url,
363
+ previewWidth: attachment1.preview_width,
364
+ previewHeight: attachment1.preview_height,
365
+
366
+ largePreviewUrl: attachment1.large_preview_url,
367
+ largePreviewWidth: attachment1.large_preview_width,
368
+ largePreviewHeight: attachment1.large_preview_height,
369
+
370
+ url: attachment1.metadata.url, // @Legacy
371
+ width: attachment1.metadata.dimensions.split(",")[0], // @Legacy
372
+ height: attachment1.metadata.dimensions.split(",")[1], // @Legacy
373
+ name: attachment1.fileName // @Legacy
374
+ };
375
+ case "animated_image":
376
+ return {
377
+ type: "animated_image",
378
+ ID: attachment2.id.toString(),
379
+ filename: attachment2.filename,
380
+
381
+ previewUrl: attachment1.preview_url,
382
+ previewWidth: attachment1.preview_width,
383
+ previewHeight: attachment1.preview_height,
384
+
385
+ url: attachment2.image_data.url,
386
+ width: attachment2.image_data.width,
387
+ height: attachment2.image_data.height,
388
+
389
+ name: attachment1.name, // @Legacy
390
+ facebookUrl: attachment1.url, // @Legacy
391
+ thumbnailUrl: attachment1.thumbnail_url, // @Legacy
392
+ mimeType: attachment2.mime_type, // @Legacy
393
+ rawGifImage: attachment2.image_data.raw_gif_image, // @Legacy
394
+ rawWebpImage: attachment2.image_data.raw_webp_image, // @Legacy
395
+ animatedGifUrl: attachment2.image_data.animated_gif_url, // @Legacy
396
+ animatedGifPreviewUrl: attachment2.image_data.animated_gif_preview_url, // @Legacy
397
+ animatedWebpUrl: attachment2.image_data.animated_webp_url, // @Legacy
398
+ animatedWebpPreviewUrl: attachment2.image_data.animated_webp_preview_url // @Legacy
399
+ };
400
+ case "share":
401
+ return {
402
+ type: "share",
403
+ ID: attachment1.share.share_id.toString(),
404
+ url: attachment2.href,
405
+
406
+ title: attachment1.share.title,
407
+ description: attachment1.share.description,
408
+ source: attachment1.share.source,
409
+
410
+ image: attachment1.share.media.image,
411
+ width: attachment1.share.media.image_size.width,
412
+ height: attachment1.share.media.image_size.height,
413
+ playable: attachment1.share.media.playable,
414
+ duration: attachment1.share.media.duration,
415
+
416
+ subattachments: attachment1.share.subattachments,
417
+ properties: {},
418
+
419
+ animatedImageSize: attachment1.share.media.animated_image_size, // @Legacy
420
+ facebookUrl: attachment1.share.uri, // @Legacy
421
+ target: attachment1.share.target, // @Legacy
422
+ styleList: attachment1.share.style_list // @Legacy
423
+ };
424
+ case "video":
425
+ return {
426
+ type: "video",
427
+ ID: attachment1.metadata.fbid.toString(),
428
+ filename: attachment1.name,
429
+
430
+ previewUrl: attachment1.preview_url,
431
+ previewWidth: attachment1.preview_width,
432
+ previewHeight: attachment1.preview_height,
433
+
434
+ url: attachment1.url,
435
+ width: attachment1.metadata.dimensions.width,
436
+ height: attachment1.metadata.dimensions.height,
437
+
438
+ duration: attachment1.metadata.duration,
439
+ videoType: "unknown",
440
+
441
+ thumbnailUrl: attachment1.thumbnail_url // @Legacy
442
+ };
443
+ case "error":
444
+ return {
445
+ type: "error",
446
+ attachment1: attachment1,
447
+ attachment2: attachment2
448
+ };
449
+ case "MessageImage":
450
+ return {
451
+ type: "photo",
452
+ ID: blob.legacy_attachment_id,
453
+ filename: blob.filename,
454
+ thumbnailUrl: blob.thumbnail.uri,
455
+
456
+ previewUrl: blob.preview.uri,
457
+ previewWidth: blob.preview.width,
458
+ previewHeight: blob.preview.height,
459
+
460
+ largePreviewUrl: blob.large_preview.uri,
461
+ largePreviewWidth: blob.large_preview.width,
462
+ largePreviewHeight: blob.large_preview.height,
463
+
464
+ url: blob.large_preview.uri, // @Legacy
465
+ width: blob.original_dimensions.x, // @Legacy
466
+ height: blob.original_dimensions.y, // @Legacy
467
+ name: blob.filename // @Legacy
468
+ };
469
+ case "MessageAnimatedImage":
470
+ return {
471
+ type: "animated_image",
472
+ ID: blob.legacy_attachment_id,
473
+ filename: blob.filename,
474
+
475
+ previewUrl: blob.preview_image.uri,
476
+ previewWidth: blob.preview_image.width,
477
+ previewHeight: blob.preview_image.height,
478
+
479
+ url: blob.animated_image.uri,
480
+ width: blob.animated_image.width,
481
+ height: blob.animated_image.height,
482
+
483
+ thumbnailUrl: blob.preview_image.uri, // @Legacy
484
+ name: blob.filename, // @Legacy
485
+ facebookUrl: blob.animated_image.uri, // @Legacy
486
+ rawGifImage: blob.animated_image.uri, // @Legacy
487
+ animatedGifUrl: blob.animated_image.uri, // @Legacy
488
+ animatedGifPreviewUrl: blob.preview_image.uri, // @Legacy
489
+ animatedWebpUrl: blob.animated_image.uri, // @Legacy
490
+ animatedWebpPreviewUrl: blob.preview_image.uri // @Legacy
491
+ };
492
+ case "MessageVideo":
493
+ return {
494
+ type: "video",
495
+ filename: blob.filename,
496
+ ID: blob.legacy_attachment_id,
497
+
498
+ previewUrl: blob.large_image.uri,
499
+ previewWidth: blob.large_image.width,
500
+ previewHeight: blob.large_image.height,
501
+
502
+ url: blob.playable_url,
503
+ width: blob.original_dimensions.x,
504
+ height: blob.original_dimensions.y,
505
+
506
+ duration: blob.playable_duration_in_ms,
507
+ videoType: blob.video_type.toLowerCase(),
508
+
509
+ thumbnailUrl: blob.large_image.uri // @Legacy
510
+ };
511
+ case "MessageAudio":
512
+ return {
513
+ type: "audio",
514
+ filename: blob.filename,
515
+ ID: blob.url_shimhash,
516
+
517
+ audioType: blob.audio_type,
518
+ duration: blob.playable_duration_in_ms,
519
+ url: blob.playable_url,
520
+
521
+ isVoiceMail: blob.is_voicemail
522
+ };
523
+ case "StickerAttachment":
524
+ return {
525
+ type: "sticker",
526
+ ID: blob.id,
527
+ url: blob.url,
528
+
529
+ packID: blob.pack ? blob.pack.id : null,
530
+ spriteUrl: blob.sprite_image,
531
+ spriteUrl2x: blob.sprite_image_2x,
532
+ width: blob.width,
533
+ height: blob.height,
534
+
535
+ caption: blob.label,
536
+ description: blob.label,
537
+
538
+ frameCount: blob.frame_count,
539
+ frameRate: blob.frame_rate,
540
+ framesPerRow: blob.frames_per_row,
541
+ framesPerCol: blob.frames_per_column,
542
+
543
+ stickerID: blob.id, // @Legacy
544
+ spriteURI: blob.sprite_image, // @Legacy
545
+ spriteURI2x: blob.sprite_image_2x // @Legacy
546
+ };
547
+ case "MessageLocation":
548
+ var urlAttach = blob.story_attachment.url;
549
+ var mediaAttach = blob.story_attachment.media;
550
+
551
+ var u = querystring.parse(url.parse(urlAttach).query).u;
552
+ var where1 = querystring.parse(url.parse(u).query).where1;
553
+ var address = where1.split(", ");
554
+
555
+ var latitude;
556
+ var longitude;
557
+
558
+ try {
559
+ latitude = Number.parseFloat(address[0]);
560
+ longitude = Number.parseFloat(address[1]);
561
+ } catch (err) {
562
+ /* empty */
563
+
564
+ }
565
+
566
+ var imageUrl;
567
+ var width;
568
+ var height;
569
+
570
+ if (mediaAttach && mediaAttach.image) {
571
+ imageUrl = mediaAttach.image.uri;
572
+ width = mediaAttach.image.width;
573
+ height = mediaAttach.image.height;
574
+ }
575
+
576
+ return {
577
+ type: "location",
578
+ ID: blob.legacy_attachment_id,
579
+ latitude: latitude,
580
+ longitude: longitude,
581
+ image: imageUrl,
582
+ width: width,
583
+ height: height,
584
+ url: u || urlAttach,
585
+ address: where1,
586
+
587
+ facebookUrl: blob.story_attachment.url, // @Legacy
588
+ target: blob.story_attachment.target, // @Legacy
589
+ styleList: blob.story_attachment.style_list // @Legacy
590
+ };
591
+ case "ExtensibleAttachment":
592
+ return {
593
+ type: "share",
594
+ ID: blob.legacy_attachment_id,
595
+ url: blob.story_attachment.url,
596
+
597
+ title: blob.story_attachment.title_with_entities.text,
598
+ description: blob.story_attachment.description &&
599
+ blob.story_attachment.description.text,
600
+ source: blob.story_attachment.source ? blob.story_attachment.source.text : null,
601
+
602
+ image: blob.story_attachment.media &&
603
+ blob.story_attachment.media.image &&
604
+ blob.story_attachment.media.image.uri,
605
+ width: blob.story_attachment.media &&
606
+ blob.story_attachment.media.image &&
607
+ blob.story_attachment.media.image.width,
608
+ height: blob.story_attachment.media &&
609
+ blob.story_attachment.media.image &&
610
+ blob.story_attachment.media.image.height,
611
+ playable: blob.story_attachment.media &&
612
+ blob.story_attachment.media.is_playable,
613
+ duration: blob.story_attachment.media &&
614
+ blob.story_attachment.media.playable_duration_in_ms,
615
+ playableUrl: blob.story_attachment.media == null ? null : blob.story_attachment.media.playable_url,
616
+
617
+ subattachments: blob.story_attachment.subattachments,
618
+ properties: blob.story_attachment.properties.reduce(function (/** @type {{ [x: string]: any; }} */obj, /** @type {{ key: string | number; value: { text: any; }; }} */cur) {
619
+ obj[cur.key] = cur.value.text;
620
+ return obj;
621
+ }, {}),
622
+
623
+ facebookUrl: blob.story_attachment.url, // @Legacy
624
+ target: blob.story_attachment.target, // @Legacy
625
+ styleList: blob.story_attachment.style_list // @Legacy
626
+ };
627
+ case "MessageFile":
628
+ return {
629
+ type: "file",
630
+ filename: blob.filename,
631
+ ID: blob.message_file_fbid,
632
+
633
+ url: blob.url,
634
+ isMalicious: blob.is_malicious,
635
+ contentType: blob.content_type,
636
+
637
+ name: blob.filename,
638
+ mimeType: "",
639
+ fileSize: -1
640
+ };
641
+ default:
642
+ throw new Error(
643
+ "unrecognized attach_file of type " +
644
+ type +
645
+ "`" +
646
+ JSON.stringify(attachment1, null, 4) +
647
+ " attachment2: " +
648
+ JSON.stringify(attachment2, null, 4) +
649
+ "`"
650
+ );
651
+ }
782
652
  }
783
653
 
784
654
  function formatAttachment(attachments, attachmentIds, attachmentMap, shareMap) {
785
- attachmentMap = shareMap || attachmentMap;
786
- return attachments
787
- ? attachments.map(function (val, i) {
788
- if (
789
- !attachmentMap ||
790
- !attachmentIds ||
791
- !attachmentMap[attachmentIds[i]]
792
- ) {
793
- return _formatAttachment(val);
794
- }
795
- return _formatAttachment(val, attachmentMap[attachmentIds[i]]);
796
- })
797
- : [];
655
+ attachmentMap = shareMap || attachmentMap;
656
+ return attachments ?
657
+ attachments.map(function (i) {
658
+ if (!attachmentMap ||
659
+ !attachmentIds ||
660
+ !attachmentMap[attachmentIds[i]]
661
+ ) {
662
+ return _formatAttachment(val);
663
+ }
664
+ return _formatAttachment(val, attachmentMap[attachmentIds[i]]);
665
+ }) : [];
798
666
  }
799
667
 
800
668
  function formatDeltaMessage(m) {
801
- const md = m.delta.messageMetadata;
802
-
803
- const mdata =
804
- m.delta.data === undefined
805
- ? []
806
- : m.delta.data.prng === undefined
807
- ? []
808
- : JSON.parse(m.delta.data.prng);
809
- const m_id = mdata.map(u => u.i);
810
- const m_offset = mdata.map(u => u.o);
811
- const m_length = mdata.map(u => u.l);
812
- const mentions = {};
813
- for (let i = 0; i < m_id.length; i++) {
814
- mentions[m_id[i]] = m.delta.body.substring(
815
- m_offset[i],
816
- m_offset[i] + m_length[i]
817
- );
818
- }
819
- return {
820
- type: "message",
821
- senderID: formatID(md.actorFbId.toString()),
822
- body: m.delta.body || "",
823
- threadID: formatID(
824
- (md.threadKey.threadFbId || md.threadKey.otherUserFbId).toString()
825
- ),
826
- messageID: md.messageId,
827
- attachments: (m.delta.attachments || []).map(v => _formatAttachment(v)),
828
- mentions: mentions,
829
- timestamp: md.timestamp,
830
- isGroup: !!md.threadKey.threadFbId,
831
- participantIDs: m.delta.participants || (md.cid ? md.cid.canonicalParticipantFbids : []) || []
832
- };
669
+ var md = m.messageMetadata;
670
+ var mdata =
671
+ m.data === undefined ? [] :
672
+ m.data.prng === undefined ? [] :
673
+ JSON.parse(m.data.prng);
674
+ var m_id = mdata.map((/** @type {{ i: any; }} */u) => u.i);
675
+ var m_offset = mdata.map((/** @type {{ o: any; }} */u) => u.o);
676
+ var m_length = mdata.map((/** @type {{ l: any; }} */u) => u.l);
677
+ var mentions = {};
678
+ var body = m.body || "";
679
+ var args = body == "" ? [] : body.trim().split(/\s+/);
680
+ for (var i = 0; i < m_id.length; i++) mentions[m_id[i]] = m.body.substring(m_offset[i], m_offset[i] + m_length[i]);
681
+ return {
682
+ type: "message",
683
+ senderID: formatID(md.actorFbId.toString()),
684
+ threadID: formatID((md.threadKey.threadFbId || md.threadKey.otherUserFbId).toString()),
685
+ messageID: md.messageId,
686
+ args: args,
687
+ body: body,
688
+ attachments: (m.attachments || []).map((/** @type {any} */v) => _formatAttachment(v)),
689
+ mentions: mentions,
690
+ timestamp: md.timestamp,
691
+ isGroup: !!md.threadKey.threadFbId,
692
+ participantIDs: m.participants || []
693
+ };
833
694
  }
834
695
 
835
696
  function formatID(id) {
836
- if (id != undefined && id != null) {
837
- return id.replace(/(fb)?id[:.]/, "");
838
- }
839
- else {
840
- return id;
841
- }
697
+ if (id != undefined && id != null) return id.replace(/(fb)?id[:.]/, "");
698
+ else return id;
842
699
  }
843
700
 
844
701
  function formatMessage(m) {
845
- const originalMessage = m.message ? m.message : m;
846
- const obj = {
847
- type: "message",
848
- senderName: originalMessage.sender_name,
849
- senderID: formatID(originalMessage.sender_fbid.toString()),
850
- participantNames: originalMessage.group_thread_info
851
- ? originalMessage.group_thread_info.participant_names
852
- : [originalMessage.sender_name.split(" ")[0]],
853
- participantIDs: originalMessage.group_thread_info
854
- ? originalMessage.group_thread_info.participant_ids.map(function (v) {
855
- return formatID(v.toString());
856
- })
857
- : [formatID(originalMessage.sender_fbid)],
858
- body: originalMessage.body || "",
859
- threadID: formatID(
860
- (
861
- originalMessage.thread_fbid || originalMessage.other_user_fbid
862
- ).toString()
863
- ),
864
- threadName: originalMessage.group_thread_info
865
- ? originalMessage.group_thread_info.name
866
- : originalMessage.sender_name,
867
- location: originalMessage.coordinates ? originalMessage.coordinates : null,
868
- messageID: originalMessage.mid
869
- ? originalMessage.mid.toString()
870
- : originalMessage.message_id,
871
- attachments: formatAttachment(
872
- originalMessage.attachments,
873
- originalMessage.attachmentIds,
874
- originalMessage.attachment_map,
875
- originalMessage.share_map
876
- ),
877
- timestamp: originalMessage.timestamp,
878
- timestampAbsolute: originalMessage.timestamp_absolute,
879
- timestampRelative: originalMessage.timestamp_relative,
880
- timestampDatetime: originalMessage.timestamp_datetime,
881
- tags: originalMessage.tags,
882
- reactions: originalMessage.reactions ? originalMessage.reactions : [],
883
- isUnread: originalMessage.is_unread
884
- };
885
-
886
- if (m.type === "pages_messaging")
887
- obj.pageID = m.realtime_viewer_fbid.toString();
888
- obj.isGroup = obj.participantIDs.length > 2;
889
-
890
- return obj;
702
+ var originalMessage = m.message ? m.message : m;
703
+ var obj = {
704
+ type: "message",
705
+ senderName: originalMessage.sender_name,
706
+ senderID: formatID(originalMessage.sender_fbid.toString()),
707
+ participantNames: originalMessage.group_thread_info ? originalMessage.group_thread_info.participant_names : [originalMessage.sender_name.split(" ")[0]],
708
+ participantIDs: originalMessage.group_thread_info ?
709
+ originalMessage.group_thread_info.participant_ids.map(function (v) {
710
+ return formatID(v.toString());
711
+ }) : [formatID(originalMessage.sender_fbid)],
712
+ body: originalMessage.body || "",
713
+ threadID: formatID((originalMessage.thread_fbid || originalMessage.other_user_fbid).toString()),
714
+ threadName: originalMessage.group_thread_info ? originalMessage.group_thread_info.name : originalMessage.sender_name,
715
+ location: originalMessage.coordinates ? originalMessage.coordinates : null,
716
+ messageID: originalMessage.mid ? originalMessage.mid.toString() : originalMessage.message_id,
717
+ attachments: formatAttachment(
718
+ originalMessage.attachments,
719
+ originalMessage.attachmentIds,
720
+ originalMessage.attachment_map,
721
+ originalMessage.share_map
722
+ ),
723
+ timestamp: originalMessage.timestamp,
724
+ timestampAbsolute: originalMessage.timestamp_absolute,
725
+ timestampRelative: originalMessage.timestamp_relative,
726
+ timestampDatetime: originalMessage.timestamp_datetime,
727
+ tags: originalMessage.tags,
728
+ reactions: originalMessage.reactions ? originalMessage.reactions : [],
729
+ isUnread: originalMessage.is_unread
730
+ };
731
+ if (m.type === "pages_messaging") obj.pageID = m.realtime_viewer_fbid.toString();
732
+ obj.isGroup = obj.participantIDs.length > 2;
733
+ return obj;
891
734
  }
892
735
 
893
736
  function formatEvent(m) {
894
- const originalMessage = m.message ? m.message : m;
895
- let logMessageType = originalMessage.log_message_type;
896
- let logMessageData;
897
- if (logMessageType === "log:generic-admin-text") {
898
- logMessageData = originalMessage.log_message_data.untypedData;
899
- logMessageType = getAdminTextMessageType(
900
- originalMessage.log_message_data.message_type
901
- );
902
- }
903
- else {
904
- logMessageData = originalMessage.log_message_data;
905
- }
906
-
907
- return Object.assign(formatMessage(originalMessage), {
908
- type: "event",
909
- logMessageType: logMessageType,
910
- logMessageData: logMessageData,
911
- logMessageBody: originalMessage.log_message_body
912
- });
737
+ var originalMessage = m.message ? m.message : m;
738
+ var logMessageType = originalMessage.log_message_type;
739
+ var logMessageData;
740
+ if (logMessageType === "log:generic-admin-text") {
741
+ logMessageData = originalMessage.log_message_data.untypedData;
742
+ logMessageType = getAdminTextMessageType(originalMessage.log_message_data.message_type);
743
+ } else logMessageData = originalMessage.log_message_data;
744
+ return Object.assign(formatMessage(originalMessage), {
745
+ type: "event",
746
+ logMessageType: logMessageType,
747
+ logMessageData: logMessageData,
748
+ logMessageBody: originalMessage.log_message_body
749
+ });
913
750
  }
914
751
 
915
752
  function formatHistoryMessage(m) {
916
- switch (m.action_type) {
917
- case "ma-type:log-message":
918
- return formatEvent(m);
919
- default:
920
- return formatMessage(m);
921
- }
753
+ switch (m.action_type) {
754
+ case "ma-type:log-message":
755
+ return formatEvent(m);
756
+ default:
757
+ return formatMessage(m);
758
+ }
922
759
  }
923
760
 
924
- // Get a more readable message type for AdminTextMessages
925
- function getAdminTextMessageType(type) {
926
- switch (type) {
927
- case "change_thread_theme":
928
- return "log:thread-color";
929
- case "change_thread_icon":
930
- return "log:thread-icon";
931
- case "change_thread_nickname":
932
- return "log:user-nickname";
933
- case "change_thread_admins":
934
- return "log:thread-admins";
935
- case "group_poll":
936
- return "log:thread-poll";
937
- case "change_thread_approval_mode":
938
- return "log:thread-approval-mode";
939
- case "messenger_call_log":
940
- case "participant_joined_group_call":
941
- return "log:thread-call";
942
- default:
943
- return type;
944
- }
761
+ function getAdminTextMessageType(m) {
762
+ switch (m.type) {
763
+ case "joinable_group_link_mode_change":
764
+ return "log:link-status";
765
+ case "magic_words":
766
+ return "log:magic-words";
767
+ case "change_thread_theme":
768
+ return "log:thread-color";
769
+ case "change_thread_icon":
770
+ case "change_thread_quick_reaction":
771
+ return "log:thread-icon";
772
+ case "change_thread_nickname":
773
+ return "log:user-nickname";
774
+ case "change_thread_admins":
775
+ return "log:thread-admins";
776
+ case "group_poll":
777
+ return "log:thread-poll";
778
+ case "change_thread_approval_mode":
779
+ return "log:thread-approval-mode";
780
+ case "messenger_call_log":
781
+ case "participant_joined_group_call":
782
+ return "log:thread-call";
783
+ case "pin_messages_v2":
784
+ return "log:thread-pinned";
785
+ case 'unpin_messages_v2':
786
+ return 'log:unpin-message';
787
+ default:
788
+ return m.type;
789
+ }
945
790
  }
946
791
 
947
792
  function formatDeltaEvent(m) {
948
- let logMessageType;
949
- let logMessageData;
950
-
951
- // log:thread-color => {theme_color}
952
- // log:user-nickname => {participant_id, nickname}
953
- // log:thread-icon => {thread_icon}
954
- // log:thread-name => {name}
955
- // log:subscribe => {addedParticipants - [Array]}
956
- // log:unsubscribe => {leftParticipantFbId}
957
-
958
- switch (m.class) {
959
- case "AdminTextMessage":
960
- logMessageData = m.untypedData;
961
- logMessageType = getAdminTextMessageType(m.type);
962
- break;
963
- case "ThreadName":
964
- logMessageType = "log:thread-name";
965
- logMessageData = { name: m.name };
966
- break;
967
- case "ParticipantsAddedToGroupThread":
968
- logMessageType = "log:subscribe";
969
- logMessageData = { addedParticipants: m.addedParticipants };
970
- break;
971
- case "ParticipantLeftGroupThread":
972
- logMessageType = "log:unsubscribe";
973
- logMessageData = { leftParticipantFbId: m.leftParticipantFbId };
974
- break;
975
- case "ApprovalQueue":
976
- logMessageType = "log:approval-queue";
977
- logMessageData = {
978
- approvalQueue: {
979
- action: m.action,
980
- recipientFbId: m.recipientFbId,
981
- requestSource: m.requestSource,
982
- ...m.messageMetadata
983
- }
984
- };
985
- }
986
-
987
- return {
988
- type: "event",
989
- threadID: formatID(
990
- (
991
- m.messageMetadata.threadKey.threadFbId ||
992
- m.messageMetadata.threadKey.otherUserFbId
993
- ).toString()
994
- ),
995
- messageID: m.messageMetadata.messageId.toString(),
996
- logMessageType: logMessageType,
997
- logMessageData: logMessageData,
998
- logMessageBody: m.messageMetadata.adminText,
999
- timestamp: m.messageMetadata.timestamp,
1000
- author: m.messageMetadata.actorFbId,
1001
- participantIDs: (m.participants || []).map(p => p.toString())
1002
- };
793
+ var logMessageType;
794
+ var logMessageData;
795
+ switch (m.class) {
796
+ case "AdminTextMessage":
797
+ logMessageType = getAdminTextMessageType(m);
798
+ logMessageData = m.untypedData;
799
+ break;
800
+ case "ThreadName":
801
+ logMessageType = "log:thread-name";
802
+ logMessageData = { name: m.name };
803
+ break;
804
+ case "ParticipantsAddedToGroupThread":
805
+ logMessageType = "log:subscribe";
806
+ logMessageData = { addedParticipants: m.addedParticipants };
807
+ break;
808
+ case "ParticipantLeftGroupThread":
809
+ logMessageType = "log:unsubscribe";
810
+ logMessageData = { leftParticipantFbId: m.leftParticipantFbId };
811
+ break;
812
+ case "UserLocation": {
813
+ logMessageType = "log:user-location";
814
+ logMessageData = {
815
+ Image: m.attachments[0].mercury.extensible_attachment.story_attachment.media.image,
816
+ Location: m.attachments[0].mercury.extensible_attachment.story_attachment.target.location_title,
817
+ coordinates: m.attachments[0].mercury.extensible_attachment.story_attachment.target.coordinate,
818
+ url: m.attachments[0].mercury.extensible_attachment.story_attachment.url
819
+ };
820
+ }
821
+ case "ApprovalQueue":
822
+ logMessageType = "log:approval-queue";
823
+ logMessageData = {
824
+ approvalQueue: {
825
+ action: m.action,
826
+ recipientFbId: m.recipientFbId,
827
+ requestSource: m.requestSource,
828
+ ...m.messageMetadata
829
+ }
830
+ };
831
+ }
832
+ return {
833
+ type: "event",
834
+ threadID: formatID((m.messageMetadata.threadKey.threadFbId || m.messageMetadata.threadKey.otherUserFbId).toString()),
835
+ logMessageType: logMessageType,
836
+ logMessageData: logMessageData,
837
+ logMessageBody: m.messageMetadata.adminText,
838
+ author: m.messageMetadata.actorFbId,
839
+ participantIDs: (m?.participants || []).map((e) => e.toString())
840
+ };
1003
841
  }
1004
842
 
1005
843
  function formatTyp(event) {
1006
- return {
1007
- isTyping: !!event.st,
1008
- from: event.from.toString(),
1009
- threadID: formatID(
1010
- (event.to || event.thread_fbid || event.from).toString()
1011
- ),
1012
- // When receiving typ indication from mobile, `from_mobile` isn't set.
1013
- // If it is, we just use that value.
1014
- fromMobile: event.hasOwnProperty("from_mobile") ? event.from_mobile : true,
1015
- userID: (event.realtime_viewer_fbid || event.from).toString(),
1016
- type: "typ"
1017
- };
844
+ return {
845
+ isTyping: !!event.st,
846
+ from: event.from.toString(),
847
+ threadID: formatID((event.to || event.thread_fbid || event.from).toString()),
848
+ fromMobile: event.hasOwnProperty("from_mobile") ? event.from_mobile : true,
849
+ userID: (event.realtime_viewer_fbid || event.from).toString(),
850
+ type: "typ"
851
+ };
1018
852
  }
1019
853
 
1020
854
  function formatDeltaReadReceipt(delta) {
1021
- // otherUserFbId seems to be used as both the readerID and the threadID in a 1-1 chat.
1022
- // In a group chat actorFbId is used for the reader and threadFbId for the thread.
1023
- return {
1024
- reader: (delta.threadKey.otherUserFbId || delta.actorFbId).toString(),
1025
- time: delta.actionTimestampMs,
1026
- threadID: formatID(
1027
- (delta.threadKey.otherUserFbId || delta.threadKey.threadFbId).toString()
1028
- ),
1029
- type: "read_receipt"
1030
- };
855
+ return {
856
+ reader: (delta.threadKey.otherUserFbId || delta.actorFbId).toString(),
857
+ time: delta.actionTimestampMs,
858
+ threadID: formatID((delta.threadKey.otherUserFbId || delta.threadKey.threadFbId).toString()),
859
+ type: "read_receipt"
860
+ };
1031
861
  }
1032
862
 
1033
863
  function formatReadReceipt(event) {
1034
- return {
1035
- reader: event.reader.toString(),
1036
- time: event.time,
1037
- threadID: formatID((event.thread_fbid || event.reader).toString()),
1038
- type: "read_receipt"
1039
- };
864
+ return {
865
+ reader: event.reader.toString(),
866
+ time: event.time,
867
+ threadID: formatID((event.thread_fbid || event.reader).toString()),
868
+ type: "read_receipt"
869
+ };
1040
870
  }
1041
871
 
1042
872
  function formatRead(event) {
1043
- return {
1044
- threadID: formatID(
1045
- (
1046
- (event.chat_ids && event.chat_ids[0]) ||
1047
- (event.thread_fbids && event.thread_fbids[0])
1048
- ).toString()
1049
- ),
1050
- time: event.timestamp,
1051
- type: "read"
1052
- };
873
+ return {
874
+ threadID: formatID(((event.chat_ids && event.chat_ids[0]) || (event.thread_fbids && event.thread_fbids[0])).toString()),
875
+ time: event.timestamp,
876
+ type: "read"
877
+ };
1053
878
  }
1054
879
 
1055
880
  function getFrom(str, startToken, endToken) {
1056
- const start = str.indexOf(startToken) + startToken.length;
1057
- if (start < startToken.length) return "";
1058
-
1059
- const lastHalf = str.substring(start);
1060
- const end = lastHalf.indexOf(endToken);
1061
- if (end === -1) {
1062
- throw new Error(
1063
- "Could not find endTime `" + endToken + "` in the given string."
1064
- );
1065
- }
1066
- return lastHalf.substring(0, end);
881
+ var start = str.indexOf(startToken) + startToken.length;
882
+ if (start < startToken.length) return "";
883
+ var lastHalf = str.substring(start);
884
+ var end = lastHalf.indexOf(endToken);
885
+ if (end === -1) throw Error("Could not find endTime `" + endToken + "` in the given string.");
886
+ return lastHalf.substring(0, end);
887
+ }
888
+
889
+ function getFroms(str, startToken, endToken) {
890
+ let results = [];
891
+ let currentIndex = 0;
892
+ while (true) {
893
+ let start = str.indexOf(startToken, currentIndex);
894
+ if (start === -1) break;
895
+ start += startToken.length;
896
+ let lastHalf = str.substring(start);
897
+ let end = lastHalf.indexOf(endToken);
898
+ if (end === -1) {
899
+ if (results.length === 0) {
900
+ throw Error("Could not find endToken `" + endToken + "` in the given string.");
901
+ }
902
+ break;
903
+ }
904
+ results.push(lastHalf.substring(0, end));
905
+ currentIndex = start + end + endToken.length;
906
+ }
907
+ return results.length === 0 ? "" : results.length === 1 ? results[0] : results;
1067
908
  }
1068
909
 
1069
910
  function makeParsable(html) {
1070
- const withoutForLoop = html.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, "");
1071
-
1072
- // (What the fuck FB, why windows style newlines?)
1073
- // So sometimes FB will send us base multiple objects in the same response.
1074
- // They're all valid JSON, one after the other, at the top level. We detect
1075
- // that and make it parse-able by JSON.parse.
1076
- // Ben - July 15th 2017
1077
- //
1078
- // It turns out that Facebook may insert random number of spaces before
1079
- // next object begins (issue #616)
1080
- // rav_kr - 2018-03-19
1081
- const maybeMultipleObjects = withoutForLoop.split(/\}\r\n *\{/);
1082
- if (maybeMultipleObjects.length === 1) return maybeMultipleObjects;
1083
-
1084
- return "[" + maybeMultipleObjects.join("},{") + "]";
911
+ let withoutForLoop = html.replace(/for\s*\(\s*;\s*;\s*\)\s*;\s*/, "");
912
+ let maybeMultipleObjects = withoutForLoop.split(/\}\r\n *\{/);
913
+ if (maybeMultipleObjects.length === 1) return maybeMultipleObjects;
914
+ return "[" + maybeMultipleObjects.join("},{") + "]";
1085
915
  }
1086
916
 
1087
917
  function arrToForm(form) {
1088
- return arrayToObject(
1089
- form,
1090
- function (v) {
1091
- return v.name;
1092
- },
1093
- function (v) {
1094
- return v.val;
1095
- }
1096
- );
918
+ return arrayToObject(form,
919
+ function (v) {
920
+ return v.name;
921
+ },
922
+ function (v) {
923
+ return v.val;
924
+ }
925
+ );
1097
926
  }
1098
927
 
1099
928
  function arrayToObject(arr, getKey, getValue) {
1100
- return arr.reduce(function (acc, val) {
1101
- acc[getKey(val)] = getValue(val);
1102
- return acc;
1103
- }, {});
929
+ return arr.reduce(function (acc, val) {
930
+ acc[getKey(val)] = getValue(val);
931
+ return acc;
932
+ }, {});
1104
933
  }
1105
934
 
1106
935
  function getSignatureID() {
1107
- return Math.floor(Math.random() * 2147483648).toString(16);
936
+ return Math.floor(Math.random() * 2147483648).toString(16);
1108
937
  }
1109
938
 
1110
939
  function generateTimestampRelative() {
1111
- const d = new Date();
1112
- return d.getHours() + ":" + padZeros(d.getMinutes());
940
+ var d = new Date();
941
+ return d.getHours() + ":" + padZeros(d.getMinutes());
1113
942
  }
1114
943
 
1115
944
  function makeDefaults(html, userID, ctx) {
1116
- let reqCounter = 1;
1117
- const fb_dtsg = getFrom(html, 'name="fb_dtsg" value="', '"');
1118
-
1119
- // @Hack Ok we've done hacky things, this is definitely on top 5.
1120
- // We totally assume the object is flat and try parsing until a }.
1121
- // If it works though it's cool because we get a bunch of extra data things.
1122
- //
1123
- // Update: we don't need this. Leaving it in in case we ever do.
1124
- // Ben - July 15th 2017
1125
-
1126
- // var siteData = getFrom(html, "[\"SiteData\",[],", "},");
1127
- // try {
1128
- // siteData = JSON.parse(siteData + "}");
1129
- // } catch(e) {
1130
- // log.warn("makeDefaults", "Couldn't parse SiteData. Won't have access to some variables.");
1131
- // siteData = {};
1132
- // }
1133
-
1134
- let ttstamp = "2";
1135
- for (let i = 0; i < fb_dtsg.length; i++) {
1136
- ttstamp += fb_dtsg.charCodeAt(i);
1137
- }
1138
- const revision = getFrom(html, 'revision":', ",");
1139
-
1140
- function mergeWithDefaults(obj) {
1141
- // @TODO This is missing a key called __dyn.
1142
- // After some investigation it seems like __dyn is some sort of set that FB
1143
- // calls BitMap. It seems like certain responses have a "define" key in the
1144
- // res.jsmods arrays. I think the code iterates over those and calls `set`
1145
- // on the bitmap for each of those keys. Then it calls
1146
- // bitmap.toCompressedString() which returns what __dyn is.
1147
- //
1148
- // So far the API has been working without this.
1149
- //
1150
- // Ben - July 15th 2017
1151
- const newObj = {
1152
- __user: userID,
1153
- __req: (reqCounter++).toString(36),
1154
- __rev: revision,
1155
- __a: 1,
1156
- // __af: siteData.features,
1157
- fb_dtsg: ctx.fb_dtsg ? ctx.fb_dtsg : fb_dtsg,
1158
- jazoest: ctx.ttstamp ? ctx.ttstamp : ttstamp
1159
- // __spin_r: siteData.__spin_r,
1160
- // __spin_b: siteData.__spin_b,
1161
- // __spin_t: siteData.__spin_t,
1162
- };
1163
-
1164
- // @TODO this is probably not needed.
1165
- // Ben - July 15th 2017
1166
- // if (siteData.be_key) {
1167
- // newObj[siteData.be_key] = siteData.be_mode;
1168
- // }
1169
- // if (siteData.pkg_cohort_key) {
1170
- // newObj[siteData.pkg_cohort_key] = siteData.pkg_cohort;
1171
- // }
1172
-
1173
- if (!obj) return newObj;
1174
-
1175
- for (const prop in obj) {
1176
- if (obj.hasOwnProperty(prop)) {
1177
- if (!newObj[prop]) {
1178
- newObj[prop] = obj[prop];
1179
- }
1180
- }
1181
- }
1182
-
1183
- return newObj;
1184
- }
1185
-
1186
- function postWithDefaults(url, jar, form, ctxx, customHeader = {}) {
1187
- return post(url, jar, mergeWithDefaults(form), ctx.globalOptions, ctxx || ctx, customHeader);
1188
- }
1189
-
1190
- function getWithDefaults(url, jar, qs, ctxx, customHeader = {}) {
1191
- return get(url, jar, mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx, customHeader);
1192
- }
1193
-
1194
- function postFormDataWithDefault(url, jar, form, qs, ctxx) {
1195
- return postFormData(
1196
- url,
1197
- jar,
1198
- mergeWithDefaults(form),
1199
- mergeWithDefaults(qs),
1200
- ctx.globalOptions,
1201
- ctxx || ctx
1202
- );
1203
- }
1204
-
1205
- return {
1206
- get: getWithDefaults,
1207
- post: postWithDefaults,
1208
- postFormData: postFormDataWithDefault
1209
- };
945
+ var reqCounter = 1;
946
+ const fb_dtsg = getFrom(html, '"DTSGInitData",[],{"token":"', '",');
947
+ var ttstamp = "2";
948
+ for (var i = 0; i < fb_dtsg.length; i++) ttstamp += fb_dtsg.charCodeAt(i);
949
+ var revision = getFrom(html, 'revision":', ",");
950
+ function mergeWithDefaults(obj) {
951
+ var newObj = {
952
+ __user: userID,
953
+ __req: (reqCounter++).toString(36),
954
+ __rev: revision,
955
+ __a: 1,
956
+ fb_dtsg: ctx.fb_dtsg ? ctx.fb_dtsg : fb_dtsg,
957
+ jazoest: ctx.ttstamp ? ctx.ttstamp : ttstamp
958
+ };
959
+ if (!obj) return newObj;
960
+ for (var prop in obj)
961
+ if (obj.hasOwnProperty(prop))
962
+ if (!newObj[prop]) newObj[prop] = obj[prop];
963
+ return newObj;
964
+ }
965
+ function postWithDefaults(url, jar, form, ctxx) {
966
+ return post(url, jar, mergeWithDefaults(form), ctx.globalOptions, ctxx || ctx);
967
+ }
968
+ function getWithDefaults(url, jar, qs, ctxx) {
969
+ return get(url, jar, mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx);
970
+ }
971
+ function postFormDataWithDefault(url, jar, form, qs, ctxx) {
972
+ return postFormData(url, jar, mergeWithDefaults(form), mergeWithDefaults(qs), ctx.globalOptions, ctxx || ctx);
973
+ }
974
+ return {
975
+ get: getWithDefaults,
976
+ post: postWithDefaults,
977
+ postFormData: postFormDataWithDefault
978
+ };
1210
979
  }
1211
980
 
1212
981
  function parseAndCheckLogin(ctx, defaultFuncs, retryCount = 0, sourceCall) {
1213
- if (sourceCall === undefined) {
1214
- try {
1215
- throw new Error();
1216
- } catch (e) {
1217
- sourceCall = e;
1218
- }
1219
- }
1220
- return function (data) {
1221
- return tryPromise(function () {
1222
- log.verbose("parseAndCheckLogin", data.body);
1223
- if (data.statusCode >= 500 && data.statusCode < 600) {
1224
- if (retryCount >= 5) {
1225
- throw {
1226
- message: "Request retry failed. Check `res` and `statusCode`.",
1227
- statusCode: data.statusCode,
1228
- res: data.body,
1229
- error: "Request retry failed.",
1230
- sourceCall
1231
- };
1232
- }
1233
- retryCount++;
1234
- const retryTime = Math.floor(Math.random() * 5000);
1235
- log.warn(
1236
- "parseAndCheckLogin",
1237
- `Got status code ${data.statusCode} - Retrying in ${retryTime}ms...`
1238
- );
1239
- if (!data.request) throw new Error("Invalid request object");
1240
- const url = `${data.request.uri.protocol}//${data.request.uri.hostname}${data.request.uri.pathname}`;
1241
- const contentType = data.request.headers?.["content-type"]?.split(";")[0];
1242
- return delay(retryTime)
1243
- .then(() =>
1244
- contentType === "multipart/form-data"
1245
- ? defaultFuncs.postFormData(url, ctx.jar, data.request.formData, {})
1246
- : defaultFuncs.post(url, ctx.jar, data.request.formData)
1247
- )
1248
- .then(parseAndCheckLogin(ctx, defaultFuncs, retryCount, sourceCall));
1249
- }
1250
- if (data.statusCode !== 200) {
1251
- throw {
1252
- message: `parseAndCheckLogin got status code: ${data.statusCode}.`,
1253
- statusCode: data.statusCode,
1254
- res: data.body,
1255
- error: `parseAndCheckLogin got status code: ${data.statusCode}.`,
1256
- sourceCall
1257
- };
1258
- }
1259
- let res;
1260
- try {
1261
- res = JSON.parse(makeParsable(data.body));
1262
- } catch (e) {
1263
- log.error("JSON parsing failed:", data.body);
1264
- throw {
1265
- message: "Failed to parse JSON response.",
1266
- detail: e.message,
1267
- res: data.body,
1268
- error: "JSON.parse error.",
1269
- sourceCall
1270
- };
1271
- }
1272
- if (res.redirect && data.request.method === "GET") {
1273
- return defaultFuncs
1274
- .get(res.redirect, ctx.jar)
1275
- .then(parseAndCheckLogin(ctx, defaultFuncs, undefined, sourceCall));
1276
- }
1277
- if (
1278
- res.jsmods?.require &&
1279
- Array.isArray(res.jsmods.require[0]) &&
1280
- res.jsmods.require[0][0] === "Cookie"
1281
- ) {
1282
- res.jsmods.require[0][3][0] = res.jsmods.require[0][3][0].replace("_js_", "");
1283
- const cookie = formatCookie(res.jsmods.require[0][3], "facebook");
1284
- const cookie2 = formatCookie(res.jsmods.require[0][3], "messenger");
1285
- ctx.jar.setCookie(cookie, "https://www.facebook.com");
1286
- ctx.jar.setCookie(cookie2, "https://www.messenger.com");
1287
- }
1288
- if (res.jsmods?.require) {
1289
- for (const arr of res.jsmods.require) {
1290
- if (arr[0] === "DTSG" && arr[1] === "setToken") {
1291
- ctx.fb_dtsg = arr[3][0];
1292
- ctx.ttstamp = "2" + ctx.fb_dtsg.split("").map(c => c.charCodeAt(0)).join("");
1293
- }
1294
- }
1295
- }
1296
- if (res.error === 1357001) {
1297
- throw {
1298
- message: "Facebook blocked login. Please check your account.",
1299
- error: "Not logged in.",
1300
- res,
1301
- statusCode: data.statusCode,
1302
- sourceCall
1303
- };
1304
- }
1305
- return res;
1306
- });
1307
- };
982
+ if (sourceCall === undefined) {
983
+ try {
984
+ throw new Error();
985
+ } catch (e) {
986
+ sourceCall = e;
987
+ }
988
+ }
989
+ return function (data) {
990
+ return tryPromise(function () {
991
+ log.verbose("parseAndCheckLogin", data.body);
992
+ if (data.statusCode >= 500 && data.statusCode < 600) {
993
+ if (retryCount >= 5) {
994
+ throw {
995
+ message: "Request retry failed. Check `res` and `statusCode`.",
996
+ statusCode: data.statusCode,
997
+ res: data.body,
998
+ error: "Request retry failed.",
999
+ sourceCall
1000
+ };
1001
+ }
1002
+ retryCount++;
1003
+ const retryTime = Math.floor(Math.random() * 5000);
1004
+ log.warn(
1005
+ "parseAndCheckLogin",
1006
+ `Got status code ${data.statusCode} - Retrying in ${retryTime}ms...`
1007
+ );
1008
+ if (!data.request) throw new Error("Invalid request object");
1009
+ const url = `${data.request.uri.protocol}//${data.request.uri.hostname}${data.request.uri.pathname}`;
1010
+ const contentType = data.request.headers?.["content-type"]?.split(";")[0];
1011
+ return delay(retryTime)
1012
+ .then(() =>
1013
+ contentType === "multipart/form-data"
1014
+ ? defaultFuncs.postFormData(url, ctx.jar, data.request.formData, {})
1015
+ : defaultFuncs.post(url, ctx.jar, data.request.formData)
1016
+ )
1017
+ .then(parseAndCheckLogin(ctx, defaultFuncs, retryCount, sourceCall));
1018
+ }
1019
+ if (data.statusCode !== 200) {
1020
+ throw {
1021
+ message: `parseAndCheckLogin got status code: ${data.statusCode}.`,
1022
+ statusCode: data.statusCode,
1023
+ res: data.body,
1024
+ error: `parseAndCheckLogin got status code: ${data.statusCode}.`,
1025
+ sourceCall
1026
+ };
1027
+ }
1028
+ let res;
1029
+ try {
1030
+ res = JSON.parse(makeParsable(data.body));
1031
+ } catch (e) {
1032
+ log.error("JSON parsing failed:", data.body);
1033
+ throw {
1034
+ message: "Failed to parse JSON response.",
1035
+ detail: e.message,
1036
+ res: data.body,
1037
+ error: "JSON.parse error.",
1038
+ sourceCall
1039
+ };
1040
+ }
1041
+ if (res.redirect && data.request.method === "GET") {
1042
+ return defaultFuncs
1043
+ .get(res.redirect, ctx.jar)
1044
+ .then(parseAndCheckLogin(ctx, defaultFuncs, undefined, sourceCall));
1045
+ }
1046
+ if (
1047
+ res.jsmods?.require &&
1048
+ Array.isArray(res.jsmods.require[0]) &&
1049
+ res.jsmods.require[0][0] === "Cookie"
1050
+ ) {
1051
+ res.jsmods.require[0][3][0] = res.jsmods.require[0][3][0].replace("_js_", "");
1052
+ const cookie = formatCookie(res.jsmods.require[0][3], "facebook");
1053
+ const cookie2 = formatCookie(res.jsmods.require[0][3], "messenger");
1054
+ ctx.jar.setCookie(cookie, "https://www.facebook.com");
1055
+ ctx.jar.setCookie(cookie2, "https://www.messenger.com");
1056
+ }
1057
+ if (res.jsmods?.require) {
1058
+ for (const arr of res.jsmods.require) {
1059
+ if (arr[0] === "DTSG" && arr[1] === "setToken") {
1060
+ ctx.fb_dtsg = arr[3][0];
1061
+ ctx.ttstamp = "2" + ctx.fb_dtsg.split("").map(c => c.charCodeAt(0)).join("");
1062
+ }
1063
+ }
1064
+ }
1065
+ if (res.error === 1357001) {
1066
+ if (!ctx.auto_login) {
1067
+ ctx.auto_login = true;
1068
+ auto_login(success => {
1069
+ if (success) {
1070
+ log.info("Auto login successful! Retrying...");
1071
+ ctx.auto_login = false;
1072
+ process.exit(1);
1073
+ } else {
1074
+ ctx.auto_login = false;
1075
+ throw {
1076
+ message: "Facebook blocked login. Please check your account.",
1077
+ error: "Not logged in.",
1078
+ res,
1079
+ statusCode: data.statusCode,
1080
+ sourceCall
1081
+ };
1082
+ }
1083
+ });
1084
+ }
1085
+ }
1086
+ return res;
1087
+ });
1088
+ };
1308
1089
  }
1309
-
1310
- function checkLiveCookie(ctx, defaultFuncs) {
1311
- return defaultFuncs
1312
- .get("https://m.facebook.com/me", ctx.jar)
1313
- .then(function (res) {
1314
- if (res.body.indexOf(ctx.i_userID || ctx.userID) === -1) {
1315
- throw new CustomError({
1316
- message: "Not logged in.",
1317
- error: "Not logged in."
1318
- });
1319
- }
1320
- return true;
1321
- });
1322
- }
1323
-
1324
1090
  function saveCookies(jar) {
1325
- return function (res) {
1326
- const cookies = res.headers["set-cookie"] || [];
1327
- cookies.forEach(function (c) {
1328
- if (c.indexOf(".facebook.com") > -1) {
1329
- jar.setCookie(c, "https://www.facebook.com");
1330
- }
1331
- const c2 = c.replace(/domain=\.facebook\.com/, "domain=.messenger.com");
1332
- jar.setCookie(c2, "https://www.messenger.com");
1333
- });
1334
- return res;
1335
- };
1091
+ return function (res) {
1092
+ var cookies = res.headers["set-cookie"] || [];
1093
+ cookies.forEach(function (c) {
1094
+ if (c.indexOf(".facebook.com") > -1) {
1095
+ jar.setCookie(c, "https://www.facebook.com");
1096
+ jar.setCookie(c.replace(/domain=\.facebook\.com/, "domain=.messenger.com"), "https://www.messenger.com");
1097
+ }
1098
+ });
1099
+ return res;
1100
+ };
1336
1101
  }
1337
1102
 
1338
- const NUM_TO_MONTH = [
1339
- "Jan",
1340
- "Feb",
1341
- "Mar",
1342
- "Apr",
1343
- "May",
1344
- "Jun",
1345
- "Jul",
1346
- "Aug",
1347
- "Sep",
1348
- "Oct",
1349
- "Nov",
1350
- "Dec"
1103
+ var NUM_TO_MONTH = [
1104
+ "Jan",
1105
+ "Feb",
1106
+ "Mar",
1107
+ "Apr",
1108
+ "May",
1109
+ "Jun",
1110
+ "Jul",
1111
+ "Aug",
1112
+ "Sep",
1113
+ "Oct",
1114
+ "Nov",
1115
+ "Dec"
1351
1116
  ];
1352
- const NUM_TO_DAY = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1117
+ var NUM_TO_DAY = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
1118
+
1353
1119
  function formatDate(date) {
1354
- let d = date.getUTCDate();
1355
- d = d >= 10 ? d : "0" + d;
1356
- let h = date.getUTCHours();
1357
- h = h >= 10 ? h : "0" + h;
1358
- let m = date.getUTCMinutes();
1359
- m = m >= 10 ? m : "0" + m;
1360
- let s = date.getUTCSeconds();
1361
- s = s >= 10 ? s : "0" + s;
1362
- return (
1363
- NUM_TO_DAY[date.getUTCDay()] +
1364
- ", " +
1365
- d +
1366
- " " +
1367
- NUM_TO_MONTH[date.getUTCMonth()] +
1368
- " " +
1369
- date.getUTCFullYear() +
1370
- " " +
1371
- h +
1372
- ":" +
1373
- m +
1374
- ":" +
1375
- s +
1376
- " GMT"
1377
- );
1120
+ var d = date.getUTCDate();
1121
+ d = d >= 10 ? d : "0" + d;
1122
+ var h = date.getUTCHours();
1123
+ h = h >= 10 ? h : "0" + h;
1124
+ var m = date.getUTCMinutes();
1125
+ m = m >= 10 ? m : "0" + m;
1126
+ var s = date.getUTCSeconds();
1127
+ s = s >= 10 ? s : "0" + s;
1128
+ return (NUM_TO_DAY[date.getUTCDay()] + ", " + d + " " + NUM_TO_MONTH[date.getUTCMonth()] + " " + date.getUTCFullYear() + " " + h + ":" + m + ":" + s + " GMT");
1378
1129
  }
1379
1130
 
1380
1131
  function formatCookie(arr, url) {
1381
- return (
1382
- arr[0] + "=" + arr[1] + "; Path=" + arr[3] + "; Domain=" + url + ".com"
1383
- );
1132
+ return arr[0] + "=" + arr[1] + "; Path=" + arr[3] + "; Domain=" + url + ".com";
1384
1133
  }
1385
1134
 
1386
1135
  function formatThread(data) {
1387
- return {
1388
- threadID: formatID(data.thread_fbid.toString()),
1389
- participants: data.participants.map(formatID),
1390
- participantIDs: data.participants.map(formatID),
1391
- name: data.name,
1392
- nicknames: data.custom_nickname,
1393
- snippet: data.snippet,
1394
- snippetAttachments: data.snippet_attachments,
1395
- snippetSender: formatID((data.snippet_sender || "").toString()),
1396
- unreadCount: data.unread_count,
1397
- messageCount: data.message_count,
1398
- imageSrc: data.image_src,
1399
- timestamp: data.timestamp,
1400
- serverTimestamp: data.server_timestamp, // what is this?
1401
- muteUntil: data.mute_until,
1402
- isCanonicalUser: data.is_canonical_user,
1403
- isCanonical: data.is_canonical,
1404
- isSubscribed: data.is_subscribed,
1405
- folder: data.folder,
1406
- isArchived: data.is_archived,
1407
- recipientsLoadable: data.recipients_loadable,
1408
- hasEmailParticipant: data.has_email_participant,
1409
- readOnly: data.read_only,
1410
- canReply: data.can_reply,
1411
- cannotReplyReason: data.cannot_reply_reason,
1412
- lastMessageTimestamp: data.last_message_timestamp,
1413
- lastReadTimestamp: data.last_read_timestamp,
1414
- lastMessageType: data.last_message_type,
1415
- emoji: data.custom_like_icon,
1416
- color: data.custom_color,
1417
- adminIDs: data.admin_ids,
1418
- threadType: data.thread_type
1419
- };
1136
+ return {
1137
+ threadID: formatID(data.thread_fbid.toString()),
1138
+ participants: data.participants.map(formatID),
1139
+ participantIDs: data.participants.map(formatID),
1140
+ name: data.name,
1141
+ nicknames: data.custom_nickname,
1142
+ snippet: data.snippet,
1143
+ snippetAttachments: data.snippet_attachments,
1144
+ snippetSender: formatID((data.snippet_sender || "").toString()),
1145
+ unreadCount: data.unread_count,
1146
+ messageCount: data.message_count,
1147
+ imageSrc: data.image_src,
1148
+ timestamp: data.timestamp,
1149
+ muteUntil: data.mute_until,
1150
+ isCanonicalUser: data.is_canonical_user,
1151
+ isCanonical: data.is_canonical,
1152
+ isSubscribed: data.is_subscribed,
1153
+ folder: data.folder,
1154
+ isArchived: data.is_archived,
1155
+ recipientsLoadable: data.recipients_loadable,
1156
+ hasEmailParticipant: data.has_email_participant,
1157
+ readOnly: data.read_only,
1158
+ canReply: data.can_reply,
1159
+ cannotReplyReason: data.cannot_reply_reason,
1160
+ lastMessageTimestamp: data.last_message_timestamp,
1161
+ lastReadTimestamp: data.last_read_timestamp,
1162
+ lastMessageType: data.last_message_type,
1163
+ emoji: data.custom_like_icon,
1164
+ color: data.custom_color,
1165
+ adminIDs: data.admin_ids,
1166
+ threadType: data.thread_type
1167
+ };
1420
1168
  }
1421
1169
 
1422
1170
  function getType(obj) {
1423
- return Object.prototype.toString.call(obj).slice(8, -1);
1171
+ return Object.prototype.toString.call(obj).slice(8, -1);
1424
1172
  }
1425
1173
 
1426
1174
  function formatProxyPresence(presence, userID) {
1427
- if (presence.lat === undefined || presence.p === undefined) return null;
1428
- return {
1429
- type: "presence",
1430
- timestamp: presence.lat * 1000,
1431
- userID: userID,
1432
- statuses: presence.p
1433
- };
1175
+ if (presence.lat === undefined || presence.p === undefined) return null;
1176
+ return {
1177
+ type: "presence",
1178
+ timestamp: presence.lat * 1000,
1179
+ userID: userID || '',
1180
+ statuses: presence.p
1181
+ };
1434
1182
  }
1435
1183
 
1436
1184
  function formatPresence(presence, userID) {
1437
- return {
1438
- type: "presence",
1439
- timestamp: presence.la * 1000,
1440
- userID: userID,
1441
- statuses: presence.a
1442
- };
1185
+ return {
1186
+ type: "presence",
1187
+ timestamp: presence.la * 1000,
1188
+ userID: userID || '',
1189
+ statuses: presence.a
1190
+ };
1443
1191
  }
1444
1192
 
1445
1193
  function decodeClientPayload(payload) {
1446
- /*
1447
- Special function which Client using to "encode" clients JSON payload
1448
- */
1449
- return JSON.parse(String.fromCharCode.apply(null, payload));
1194
+ function Utf8ArrayToStr(array) {
1195
+ var out, i, len, c;
1196
+ var char2, char3;
1197
+ out = "";
1198
+ len = array.length;
1199
+ i = 0;
1200
+ while (i < len) {
1201
+ c = array[i++];
1202
+ switch (c >> 4) {
1203
+ case 0:
1204
+ case 1:
1205
+ case 2:
1206
+ case 3:
1207
+ case 4:
1208
+ case 5:
1209
+ case 6:
1210
+ case 7:
1211
+ out += String.fromCharCode(c);
1212
+ break;
1213
+ case 12:
1214
+ case 13:
1215
+ char2 = array[i++];
1216
+ out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
1217
+ break;
1218
+ case 14:
1219
+ char2 = array[i++];
1220
+ char3 = array[i++];
1221
+ out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
1222
+ break;
1223
+ }
1224
+ }
1225
+ return out;
1226
+ }
1227
+ return JSON.parse(Utf8ArrayToStr(payload));
1450
1228
  }
1451
1229
 
1452
1230
  function getAppState(jar) {
1453
- return jar
1454
- .getCookies("https://www.facebook.com")
1455
- .concat(jar.getCookies("https://facebook.com"))
1456
- .concat(jar.getCookies("https://www.messenger.com"));
1231
+ return jar.getCookies("https://www.facebook.com").concat(jar.getCookies("https://facebook.com")).concat(jar.getCookies("https://www.messenger.com"));
1232
+ }
1233
+
1234
+ function getData_Path(Obj, Arr, Stt) {
1235
+ if (Arr.length === 0 && Obj != undefined) {
1236
+ return Obj;
1237
+ }
1238
+ else if (Obj == undefined) {
1239
+ return Stt;
1240
+ }
1241
+ const head = Arr[0];
1242
+ if (head == undefined) {
1243
+ return Stt;
1244
+ }
1245
+ const tail = Arr.slice(1);
1246
+ return getData_Path(Obj[head], tail, Stt++);
1247
+ }
1248
+
1249
+ function setData_Path(obj, path, value) {
1250
+ if (!path.length) {
1251
+ return obj;
1252
+ }
1253
+ const currentKey = path[0];
1254
+ let currentObj = obj[currentKey];
1255
+
1256
+ if (!currentObj) {
1257
+ obj[currentKey] = value;
1258
+ currentObj = obj[currentKey];
1259
+ }
1260
+ path.shift();
1261
+ if (!path.length) {
1262
+ currentObj = value;
1263
+ } else {
1264
+ currentObj = setData_Path(currentObj, path, value);
1265
+ }
1266
+
1267
+ return obj;
1457
1268
  }
1458
- module.exports = {
1459
- CustomError,
1460
- isReadableStream,
1461
- get,
1462
- post,
1463
- postFormData,
1464
- generateThreadingID,
1465
- generateOfflineThreadingID,
1466
- getGUID,
1467
- getFrom,
1468
- makeParsable,
1469
- arrToForm,
1470
- getSignatureID,
1471
- getJar: request.jar,
1472
- generateTimestampRelative,
1473
- makeDefaults,
1474
- parseAndCheckLogin,
1475
- saveCookies,
1476
- getType,
1477
- _formatAttachment,
1478
- formatHistoryMessage,
1479
- formatID,
1480
- formatMessage,
1481
- formatDeltaEvent,
1482
- formatDeltaMessage,
1483
- formatProxyPresence,
1484
- formatPresence,
1485
- formatTyp,
1486
- formatDeltaReadReceipt,
1487
- formatCookie,
1488
- formatThread,
1489
- formatReadReceipt,
1490
- formatRead,
1491
- generatePresence,
1492
- generateAccessiblityCookie,
1493
- formatDate,
1494
- decodeClientPayload,
1495
- getAppState,
1496
- getAdminTextMessageType,
1497
- setProxy,
1498
- checkLiveCookie
1499
- };
1500
1269
 
1270
+ function getPaths(obj, parentPath = []) {
1271
+ let paths = [];
1272
+ for (let prop in obj) {
1273
+ if (typeof obj[prop] === "object") {
1274
+ paths = paths.concat(getPaths(obj[prop], [...parentPath, prop]));
1275
+ } else {
1276
+ paths.push([...parentPath, prop]);
1277
+ }
1278
+ }
1279
+ return paths;
1280
+ }
1281
+
1282
+ function cleanHTML(text) {
1283
+ text = text.replace(/(<br>)|(<\/?i>)|(<\/?em>)|(<\/?b>)|(!?~)|(&amp;)|(&#039;)|(&lt;)|(&gt;)|(&quot;)/g, (match) => {
1284
+ switch (match) {
1285
+ case "<br>":
1286
+ return "\n";
1287
+ case "<i>":
1288
+ case "<em>":
1289
+ case "</i>":
1290
+ case "</em>":
1291
+ return "*";
1292
+ case "<b>":
1293
+ case "</b>":
1294
+ return "**";
1295
+ case "~!":
1296
+ case "!~":
1297
+ return "||";
1298
+ case "&amp;":
1299
+ return "&";
1300
+ case "&#039;":
1301
+ return "'";
1302
+ case "&lt;":
1303
+ return "<";
1304
+ case "&gt;":
1305
+ return ">";
1306
+ case "&quot;":
1307
+ return '"';
1308
+ }
1309
+ });
1310
+ return text;
1311
+ }
1312
+
1313
+ function checkLiveCookie(ctx, defaultFuncs) {
1314
+ return defaultFuncs.get("https://m.facebook.com/me", ctx.jar).then(function (res) {
1315
+ if (res.body.indexOf(ctx.userID) === -1) {
1316
+ throw new CustomError({
1317
+ message: "Not logged in.",
1318
+ error: "Not logged in."
1319
+ });
1320
+ }
1321
+ return true;
1322
+ });
1323
+ }
1324
+
1325
+ function getAccessFromBusiness(jar, Options) {
1326
+ return function (res) {
1327
+ var html = res ? res.body : null;
1328
+ return get('https://business.facebook.com/content_management', jar, null, Options, null, { noRef: true })
1329
+ .then(function (res) {
1330
+ var token = /"accessToken":"([^.]+)","clientID":/g.exec(res.body)[1];
1331
+ return [html, token];
1332
+ })
1333
+ .catch(function () {
1334
+ return [html, null];
1335
+ });
1336
+ }
1337
+ }
1338
+
1339
+ module.exports = {
1340
+ CustomError,
1341
+ cleanHTML,
1342
+ isReadableStream: isReadableStream,
1343
+ get: get,
1344
+ get2: get2,
1345
+ post: post,
1346
+ postFormData: postFormData,
1347
+ generateThreadingID: generateThreadingID,
1348
+ generateOfflineThreadingID: generateOfflineThreadingID,
1349
+ getGUID: getGUID,
1350
+ getFrom: getFrom,
1351
+ makeParsable: makeParsable,
1352
+ arrToForm: arrToForm,
1353
+ getSignatureID: getSignatureID,
1354
+ getJar: request.jar,
1355
+ generateTimestampRelative: generateTimestampRelative,
1356
+ makeDefaults: makeDefaults,
1357
+ parseAndCheckLogin: parseAndCheckLogin,
1358
+ getData_Path,
1359
+ setData_Path,
1360
+ getPaths,
1361
+ saveCookies,
1362
+ getType,
1363
+ _formatAttachment,
1364
+ formatHistoryMessage,
1365
+ formatID,
1366
+ formatMessage,
1367
+ formatDeltaEvent,
1368
+ formatDeltaMessage,
1369
+ formatProxyPresence,
1370
+ formatPresence,
1371
+ formatTyp,
1372
+ formatDeltaReadReceipt,
1373
+ formatCookie,
1374
+ formatThread,
1375
+ formatReadReceipt,
1376
+ formatRead,
1377
+ generatePresence,
1378
+ generateAccessiblityCookie,
1379
+ formatDate,
1380
+ decodeClientPayload,
1381
+ getAppState,
1382
+ getAdminTextMessageType,
1383
+ setProxy,
1384
+ checkLiveCookie,
1385
+ getAccessFromBusiness,
1386
+ getFroms
1387
+ };