File size: 2,234 Bytes
d7ade7a
 
2345742
70ea3ad
1ab3fc9
7edd258
f44bab2
d7ade7a
 
 
 
 
 
 
 
 
 
1ab3fc9
 
 
 
 
d7ade7a
 
 
 
f44bab2
d7ade7a
1ab3fc9
d7ade7a
 
f44bab2
1ab3fc9
f44bab2
1ab3fc9
d7ade7a
 
 
 
f44bab2
d7ade7a
 
 
 
 
1ab3fc9
f44bab2
1ab3fc9
f44bab2
d7ade7a
 
 
 
 
 
1ab3fc9
f44bab2
 
1ab3fc9
 
7edd258
d7ade7a
 
f44bab2
d7ade7a
7edd258
 
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
import got from "got";
import * as cheerio from "cheerio";
import { FacebookDlArgsSchema, FacebookDlSchema } from "../types/facebook-v1.js";
import { DEFAULT_HEADERS } from "../constant.js";

async function facebookdl(url) {
    FacebookDlArgsSchema.parse(arguments);

    const html = await got("https://fdownloader.net/en", { headers: { ...DEFAULT_HEADERS } }).text();
    
    const k_url_search = /k_url_search="(.*?)"/.exec(html)?.[1] || null;
    const k_exp = /k_exp="(.*?)"/.exec(html)?.[1] || null;
    const k_token = /k_token="(.*?)"/.exec(html)?.[1] || null;

    if (!k_url_search || !k_exp || !k_token) {
        throw new Error("Failed to extract necessary tokens.");
    }

    const form = {
        k_exp,
        k_token,
        q: url,
        lang: "en",
        web: "fdownloader.net",
        v: "v2",
        w: "",
    };

    const data = await got.post(k_url_search, {
        headers: { ...DEFAULT_HEADERS, referer: "https://fdownloader.net/" },
        form,
    }).json();

    const $ = cheerio.load(data.data);

    const thumbnail = $(".thumbnail > .image-fb > img").attr("src") || null;
    const duration = $(".content > .clearfix > p").text() || null;
    
    const video = $("table.table").eq(0).find("tbody > tr").map((_, el) => {
        const $el = $(el);
        const quality = $el.find("td").eq(0).text().trim();
        const downloadUrl = $el.find("td").eq(2).find("a").attr("href");
        
        if (downloadUrl) {
            return { quality, download: () => Promise.resolve(downloadUrl) };
        }
    }).toArray().filter(Boolean);

    const audio = [];
    const audioUrl = $("#audioUrl").attr("value") || null;
    if (audioUrl) {
        audio.push({ quality: "128kbps", download: () => Promise.resolve(audioUrl) });
    }

    const result = { thumbnail, duration, video, audio };

    console.log(result);
    return FacebookDlSchema.parse(result);
}

async function convert(url, v_id, ftype, videoUrl, videoType, videoCodec, audioUrl, audioType, fquality, fname, exp, token) {
    return got.post(url, {
        form: { ftype, v_id, videoUrl, videoType, videoCodec, audioUrl, audioType, fquality, fname, exp, token, cv: "v2" },
    });
}

export { facebookdl, convert };