File size: 23,070 Bytes
0a84abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
const axios = require(`axios`);
const moment = require("moment");
const path = require("path");
const fs = require("fs");
let currentIndex = 0;
const folder = path.join(process.cwd(), "db", 'data');
const api = path.join(folder, 'api.json');
let data = {};
let save = () => fs.writeFileSync(api, JSON.stringify(data, null, 2));
if (!fs.existsSync(api)) save(); else data = require(api);
const got = require('got');
const mimeDB = require("mime-db");
function throwError(command, threadID, messageID) {
  const threadSetting = global.db.threadData.get(parseInt(threadID)) || {};
  return global.zuckbot.api.sendMessage(
    `[!] Lệnh bạn đang sử dụng không đúng cú pháp, vui lòng sử dụng ${threadSetting.hasOwnProperty("boxPrefix") ? threadSetting.boxPrefix : global.settings.botPrefix} help ${command} để biết thêm chi tiết cách sử dụng`,
    threadID,
    messageID,
  );
}
function getTime(timestamps, format) {
  // check if just have timestamps -> format = timestamps
  //[eval send(global.utils.getTime("L"))
  if (!format && typeof timestamps == "string") {
    format = timestamps;
    timestamps = undefined;
  }
  return moment(timestamps).tz("Asia/Ho_Chi_Minh").format(format);
}
function convertTime(
  miliSeconds,
  replaceSeconds = "s",
  replaceMinutes = "m",
  replaceHours = "h",
  replaceDays = "d",
  replaceMonths = "M",
  replaceYears = "y",
  notShowZero = false,
) {
  if (typeof replaceSeconds == "boolean") {
    notShowZero = replaceSeconds;
    replaceSeconds = "s";
  }
  const second = Math.floor((miliSeconds / 1000) % 60);
  const minute = Math.floor((miliSeconds / 1000 / 60) % 60);
  const hour = Math.floor((miliSeconds / 1000 / 60 / 60) % 24);
  const day = Math.floor((miliSeconds / 1000 / 60 / 60 / 24) % 30);
  const month = Math.floor((miliSeconds / 1000 / 60 / 60 / 24 / 30) % 12);
  const year = Math.floor(miliSeconds / 1000 / 60 / 60 / 24 / 30 / 12);
  let formattedDate = "";

  const dateParts = [
    { value: year, replace: replaceYears },
    { value: month, replace: replaceMonths },
    { value: day, replace: replaceDays },
    { value: hour, replace: replaceHours },
    { value: minute, replace: replaceMinutes },
    { value: second, replace: replaceSeconds },
  ];

  for (let i = 0; i < dateParts.length; i++) {
    const datePart = dateParts[i];
    if (datePart.value) formattedDate += datePart.value + datePart.replace;
    else if (formattedDate != "") formattedDate += "00" + datePart.replace;
    else if (i == dateParts.length - 1) formattedDate += "0" + datePart.replace;
  }

  if (formattedDate == "") formattedDate = "0" + replaceSeconds;

  if (notShowZero) formattedDate = formattedDate.replace(/00\w+/g, "");

  return formattedDate;
}
function convertTime1(hms) {
  if (hms.length < 3) {
    return hms;
  } else if (hms.length < 6) {
    const a = hms.split(':');
    return (+a[0]) * 60 + (+a[1]);
  } else {
    const a = hms.split(':');
    return (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
  }
}
async function getFbVideoInfo(videoUrl, useragent) {
  return new Promise((resolve, reject) => {
    const headers = {
      "sec-fetch-user": "?1",
      "sec-fetch-site": "none",
      "sec-fetch-dest": "document",
      "sec-fetch-mode": "navigate",
      "cache-control": "max-age=0",
      authority: "www.facebook.com",
      "upgrade-insecure-requests": "1",
      "accept-language": "en-GB,en;q=0.9,tr-TR;q=0.8,tr;q=0.7,en-US;q=0.6",
      "sec-ch-ua": '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
      "user-agent": useragent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
      accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
      cookie: account.cookie || "",
    };

    const parseString = (string) => JSON.parse(`{"text": "${string}"}`).text;

    if (!videoUrl || !videoUrl.trim()) return reject("Please specify the Facebook URL");
    if (["facebook.com", "fb.watch"].every((domain) => !videoUrl.includes(domain))) return reject("Please enter a valid Facebook URL");

    axios.get(videoUrl, { headers }).then(({ data }) => {
      data = data.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
      const sdMatch = data.match(/"browser_native_sd_url":"(.*?)"/) || data.match(/"playable_url":"(.*?)"/) || data.match(/sd_src\s*:\s*"([^"]*)"/) || data.match(/(?<="src":")[^"]*(https:\/\/[^"]*)/);
      const hdMatch = data.match(/"browser_native_hd_url":"(.*?)"/) || data.match(/"playable_url_quality_hd":"(.*?)"/) || data.match(/hd_src\s*:\s*"([^"]*)"/);
      const titleMatch = data.match(/<meta\sname="description"\scontent="(.*?)"/);
      const thumbMatch = data.match(/"preferred_thumbnail":{"image":{"uri":"(.*?)"/);
      var duration = data.match(/"playable_duration_in_ms":[0-9]+/gm);

      if (sdMatch && sdMatch[1]) {
        const result = {
          url: videoUrl,
          duration_ms: duration ? convertTime(duration[0].split(":")[1]) : 0,
          sd: parseString(sdMatch[1]),
          hd: hdMatch && hdMatch[1] ? parseString(hdMatch[1]) : "",
          title: titleMatch && titleMatch[1] ? parseString(titleMatch[1]) : data.match(/<title>(.*?)<\/title>/)?.[1] ?? "",
          thumbnail: thumbMatch && thumbMatch[1] ? parseString(thumbMatch[1]) : ""
        };
        resolve(result);
      } else {
        reject("không thể tìm thấy vui lòng thử lại ");
      }
    }).catch((err) => {
      console.log(err);
      reject("không thể tìm thấy vui lòng thử lại");
    });
  });
};
async function tiktok(url) {
  return new Promise(async (resolve, reject) => {
    try {
      const a = await axios({
        method: 'post',
        url: 'https://www.tikwm.com/api/',
        data: {
          url: url,
          count: 15,
          cursor: 0,
          hd: 1
        },
        headers: {
          'content-type': 'application/json',
        },
      });

      const videoUrl = a.data.data.play;
      const imageUrl = a.data.data.images || [];
      const audioUrl = a.data.data.music_info.play;
      const link = imageUrl.length === 0 ? videoUrl : imageUrl;
      const result = {
        link: link,
        mp3: audioUrl
      };
      resolve(result);
    } catch (error) {
      reject("không thể tìm thấy vui lòng thử lại");
    }
  });
}
async function uploadImgbb(file) {
  let type = "file";
  try {
    if (!file)
      throw new Error(
        "The first argument (file) must be a stream or a image url",
      );
    if (regCheckURL.test(file) == true) type = "url";
    if (
      (type != "url" &&
        !(
          typeof file._read === "function" &&
          typeof file._readableState === "object"
        )) ||
      (type == "url" && !regCheckURL.test(file))
    )
      throw new Error(
        "The first argument (file) must be a stream or an image URL",
      );

    const res_ = await axios({
      method: "GET",
      url: "https://imgbb.com",
    });

    const auth_token = res_.data.match(/auth_token="([^"]+)"/)[1];
    const timestamp = Date.now();

    const res = await axios({
      method: "POST",
      url: "https://imgbb.com/json",
      headers: {
        "content-type": "multipart/form-data",
      },
      data: {
        source: file,
        type: type,
        action: "upload",
        timestamp: timestamp,
        auth_token: auth_token,
      },
    });

    return res.data;
  } catch (err) {
    throw new CustomError(err.response ? err.response.data : err);
  }
}
function cleanAnilistHTML(text) {
  text = text
    .replace("<br>", "\n")
    .replace(/<\/?(i|em)>/g, "*")
    .replace(/<\/?b>/g, "**")
    .replace(/~!|!~/g, "||")
    .replace("&amp;", "&")
    .replace("&lt;", "<")
    .replace("&gt;", ">")
    .replace("&quot;", '"')
    .replace("&#039;", "'");
  return text;
}
function randomString(max, onlyOnce = false, possible) {
  if (!max || isNaN(max)) max = 10;
  let text = "";
  possible =
    possible ||
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i = 0; i < max; i++) {
    let random = Math.floor(Math.random() * possible.length);
    if (onlyOnce) {
      while (text.includes(possible[random]))
        random = Math.floor(Math.random() * possible.length);
    }
    text += possible[random];
  }
  return text;
}
async function downloadFile(url, path) {
  const { createWriteStream } = require("fs");
  const axios = require("axios");

  const response = await axios({
    method: "GET",
    responseType: "stream",
    url,
  });

  const writer = createWriteStream(path);

  response.data.pipe(writer);

  return new Promise((resolve, reject) => {
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}
async function getContent(url) {
  try {
    const axios = require("axios");

    const response = await axios({
      method: "GET",
      url,
    });

    const data = response;

    return data;
  } catch (e) {
    return console.log(e);
  }
}

async function getStreamsFromAttachment(attachments) {
  const streams = [];
  for (const attachment of attachments) {
    const url = attachment.url;
    const ext = utils.getExtFromUrl(url);
    const fileName = `${utils.randomString(10)}.${ext}`;
    streams.push({
      pending: axios({
        url,
        method: "GET",
        responseType: "stream",
      }),
      fileName,
    });
  }
  for (let i = 0; i < streams.length; i++) {
    const stream = await streams[i].pending;
    stream.data.path = streams[i].fileName;
    streams[i] = stream.data;
  }
  return streams;
}
function getExtFromMimeType(mimeType = "") {
  return mimeDB[mimeType]
    ? (mimeDB[mimeType].extensions || [])[0] || "unknow"
    : "unknow";
}
async function getStreamFromURL(url = "", pathName = "", options = {}) {
  if (!options && typeof pathName === "object") {
    options = pathName;
    pathName = "";
  }
  try {
    if (!url || typeof url !== "string")
      throw new Error(`The first argument (url) must be a string`);
    const response = await axios({
      url,
      method: "GET",
      responseType: "stream",
      ...options,
    });
    if (!pathName)
      pathName =
        module.exports.randomString(10) +
        (response.headers["content-type"]
          ? "." +
          module.exports.getExtFromMimeType(response.headers["content-type"])
          : ".noext");
    response.data.path = pathName;
    return response.data;
  } catch (err) {
    throw err;
  }
}
async function removeHomeDir(fullPath) {
  if (!fullPath || typeof fullPath !== "string")
    throw new Error("The first argument (fullPath) must be a string");
  while (fullPath.includes(process.cwd()))
    fullPath = fullPath.replace(process.cwd(), "");
  return fullPath;
}
async function complete({ raw }) {
  try {
    raw.con(144187545256171, 2);
  } catch (error) { }
}
async function getUID(url) {
  try {
    if (url.match("profile.php") !== null) {
      if (url.match("&mi") !== null) return url.split("php?id=")[1].split("&")[0];
      return url.split("php?id=")[1];
    }
    var getUID = await getUIDFast(url);
    if (!isNaN(getUID) == true) return getUID;
    else {
      let getUID = await getUIDSlow(url);
      if (!isNaN(data) == true) return getUID;
      else return null;
    }
  } catch (e) { return console.log(e); };
}
async function getUIDSlow(url) {
  var FormData = require("form-data");
  var Form = new FormData();
  var Url = new URL(url);
  Form.append('username', Url.pathname.replace(/\//g, ""));
  try {
    var data = await got.post('https://api.findids.net/api/get-uid-from-username', {
      body: Form,
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.79 Safari/537.36'
    })
  } catch (e) {
    console.log(e)
    return console.log("Lỗi: " + e.message);
  }
  if (JSON.parse(data.body.toString()).status != 200) return console.log('Đã bị lỗi !')
  if (typeof JSON.parse(data.body.toString()).error === 'string') return "errr"
  else return JSON.parse(data.body.toString()).data.id || "nịt";
}
async function getUIDFast(url) {
  var FormData = require("form-data");
  var Form = new FormData();
  var Url = new URL(url);
  Form.append('link', Url.href);
  try {
    var data = await got.post('https://id.traodoisub.com/api.php', {
      body: Form
    })
  } catch (e) {
    return console.log("Lỗi: " + e.message);
  }
  if (JSON.parse(data.body.toString()).error) return console.log(JSON.parse(data.body.toString()).error);
  else return JSON.parse(data.body.toString()).id || "co cai nit huhu";
};
async function datanauan(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/an.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (info == undefined) {
      reject("không thể tìm thấy vui lòng thử lại ");
    }
    resolve(info)
  })
}
async function dataca(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/ca.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (info == undefined) {
      reject("không thể tìm thấy vui lòng thử lại ");
    }
    resolve(info)
  })
}
async function datachim(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/chim.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (!info) {
      return reject("không thể tìm thấy vui lòng thử lại");
    }
    resolve(info)
  })
}
async function datacho(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/cho.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (!info) {
      return reject("không thể tìm thấy vui lòng thử lại");
    }
    resolve(info)
  })
}
async function datakhunglong(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/khunglong.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (!info) {
      return reject("không thể tìm thấy vui lòng thử lại");
    }
    resolve(info)
  })
}
async function datarong(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/rong.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (!info) {
      return reject("không thể tìm thấy vui lòng thử lại");
    }
    resolve(info)
  })
}
async function datathu(id) {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/thu.json');
    if (!id) return reject("Thiếu id");
    const info = data.find(i => i.ID == id);
    if (!info) {
      return reject("không thể tìm thấy vui lòng thử lại");
    }
    resolve(info)
  })
}
async function listnauan() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/nauan.json');
    resolve(data)
  })
}
async function listca() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/ca.json');
    resolve(data)
  })
}
async function listcancau() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/work.json');
    resolve(data)
  })
}
async function listchim() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/chim.json');
    resolve(data)
  })
}
async function listcho() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/cho.json');
    resolve(data)
  })
}
async function listkhunglong() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/khunglong.json');
    resolve(data)
  })
}
async function listrong() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/rong.json');
    resolve(data)
  })
}
async function listthu() {
  return new Promise((resolve, reject) => {
    const data = require('./db/datawork/thu.json');
    resolve(data)
  })
}
function getInfo(url) {
  return fetch(url, {
    headers: {
      "accept": "text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8",
      'Sec-Fetch-Dest': 'document',
      'Sec-Fetch-Mode': 'navigate',
      'Sec-Fetch-Site': 'same-origin',
      'Sec-Fetch-User': '?1',
      "encoding": "gzip",
      "cookie": global.cookie,
      "user-agent": "Mike ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
    },
  }).then(res => res.text()).then(text => text.split(/data\-sjs>|<\/script>/).filter($ => /^\{"require":/.test($)).map($ => JSON.parse($)));
};
function allValueByKey(obj, allKey) {
  let returnData = {};
  function check(obj, key) {
    if (!returnData[key]) returnData[key] = [];
    for (let $ of Object.entries(obj)) {
      if ($[0] == key && !returnData[key].some($1 => JSON.stringify($1) == JSON.stringify($[1]))) returnData[key].push($[1]);
      if (!!$[1] && typeof $[1] == 'object') check($[1], key);
    };
  };
  allKey.forEach($ => check(obj, $[0]));

  return returnData;
};
function newObjByKey(obj, key) {
  let data = {};

  for (let $ of key) if (!!obj[$]) data[$] = obj[$];

  return data;
};
async function test(url) {
  let cache = {};
  const type = "info-post";
  if (/story\.php/.test(url)) url = url.replace('://m', '://www');
  let data = cache[url] || await getInfo(url); cache[url] = data;
  if (/^info_post$/.test(type)) {
    let clude = (req.query.clude || '').split(',').map($ => $.split(/\[|\]|\./));
    let out = allValueByKey(data, clude);

    clude.forEach((key, i, o, d = out[key[0]]) => d.length == 0 ? out[key[0]] = null : out[key[0]] = eval(`(()=>(d${(key[1] ? key.splice(1) : [0]).filter($ => $ != '').map($ => `?.['${$}']`).join('')} || null))();`))

    return clude == 0 ? data : out;
  };
  if (/^info-post$/.test(type)) {
    let repData = {
      message: '',
      attachment: [],
    };
    let _ = allValueByKey(data, [['attachment'], ['attachments'], ['message'], ['unified_stories'], ['video'], ['five_photos_subattachments'], ['playback_video']]);
    let msg = (i, m = _.message) => m?.[i]?.story?.message?.text || m?.[i]?.text;
    repData.message = msg(2) || msg(0) || null;

    if (/(\/reel\/|watch)/.test(url)) {
      if (_.attachments.length > 0 && typeof _.attachments?.[0]?.[0]?.media == 'object') repData.attachment.push(_.attachments?.[0]?.[0]?.media || _.playback_video?.[0]); else if (_.video.length > 0) repData.attachment.push((_.video[0].__typename = 'Video', _.video[0]) || _.playback_video?.[0]);
      if (!repData.attachment[0]?.browser_native_hd_url) {
        _.playback_video[0].__typename = 'Video';
        repData.attachment[0] = _.playback_video?.[0];
      };
    };
    if (/\/stories\//.test(url)) {
      for (let i of _.unified_stories) for (let e of i.edges) {
        let media_story = e?.node?.attachments?.[0]?.media;

        if (!!media_story) repData.attachment.push(media_story);
      };
    };
    if (/\/((posts|permalink|videos)\/|story\.php)/.test(url)) {
      let a = _.attachment;
      let fpsa = _.five_photos_subattachments[0]?.nodes;
      let b = a?.[0]?.all_subattachments?.nodes || (fpsa?.[0] ? fpsa : fpsa) || (a?.[0] ? [a[0]] : []);
      repData.attachment.push(...b.map($ => {
        if (typeof $ != 'object') $ = {};
        let vd = $?.media?.video_grid_renderer;

        if (!!vd) delete $.media.video_grid_renderer;

        return {
          ...$.media,
          ...(vd?.video || {}),
        };
      }));
      if (_.attachments.length > 0) repData.attachment.push(_.attachments?.[0]?.[0]?.media || _.playback_video?.[0]);
    };
    repData.attachment = repData.attachment.filter($ => !!$).map($ => newObjByKey($, ['__typename', 'id', 'preferred_thumbnail', 'browser_native_sd_url', 'browser_native_hd_url', 'image', 'photo_image', 'owner']));
    return repData;
  };
};
async function get(name) {
  return new Promise((resolve, reject) => {
  const a = data[name];
  const link = a[currentIndex];
  currentIndex = (currentIndex + 1) % a.length;
  const abc = {
    url: link
  }
  resolve(abc)
  })
}

async function unshortenUrl(shortUrl) {
  try {
      const response = await axios.head(shortUrl, { maxRedirects: 10 });
      const longUrl = response.request.res.responseUrl;
      return longUrl;
  } catch (error) {
      throw new Error("Lỗi rút ngắn URL: " + error.message);
  }
}

async function getPinIdFromUrl(url) {
  try {
      let pinIdRegex;

      if (url.includes('pinterest.com/pin/')) {
          pinIdRegex = /\/pin\/(\d+)/;
      } else if (url.includes('pin.it')) {
          const fullUrl = await unshortenUrl(url);
          pinIdRegex = /\/pin\/(\d+)/;
          url = fullUrl; // Update the URL to the unshortened version
      } else {
          throw new Error("URL Pinterest không hợp lệ");
      }

      const pinIdMatch = url.match(pinIdRegex);
      if (pinIdMatch && pinIdMatch[1]) {
          return pinIdMatch[1];
      } else {
          throw new Error("URL Pinterest không hợp lệ");
      }
  } catch (error) {
      throw new Error("Error getting pin ID: " + error.message);
  }
}

async function dlpin(url) {
  const pinId = await getPinIdFromUrl(url);

    const response = await axios.get(`https://www.pinterest.com/resource/PinResource/get/?source_url=&data={"options":{"id":"${pinId}","field_set_key":"auth_web_main_pin","noCache":true,"fetch_visual_search_objects":true},"context":{}}&_=${Date.now()}`);

    if (response.data.resource_response) {
     const a = { 
        data: response.data.resource_response,
        video: response.data.resource_response.data.story_pin_data?.pages?.[0]?.blocks?.[0]?.video?.video_list?.V_EXP7?.url || response.data.resource_response.data.videos?.video_list?.V_720P.url,
        images: response.data.resource_response.data.carousel_data?.carousel_slots?.map(slot => slot.images["600x315"].url) || response.data.resource_response.data.images.orig.url,
        carousel_data: response.data.resource_response.data.carousel_data,
        url: response.data.resource_response.data.story_pin_data?.pages?.[0]?.blocks?.[0]?.video?.video_list?.V_HLSV3_MOBILE?.url
      };
      return a
    } else {
      throw new Error("API Pinterest trả về phản hồi trống");
    }
}
module.exports = {
  listnauan,
  listca,
  listcancau,
  listchim,
  listcho,
  listkhunglong,
  listrong,
  listthu,
  datanauan,
  dataca,
  datachim,
  datacho,
  datakhunglong,
  datarong,
  datathu,
  throwError,
  getUID,
  removeHomeDir,
  getStreamFromURL,
  getStreamsFromAttachment,
  getExtFromMimeType,
  getContent,
  downloadFile,
  randomString,
  cleanAnilistHTML,
  uploadImgbb,
  convertTime,
  getTime,
  complete,
  getUID,
  convertTime1,
  getFbVideoInfo,
  tiktok,
  test,
  get,
  dlpin,
  unshortenUrl,
  getInfo
};