File size: 16,515 Bytes
8c38b3e
 
 
06c148c
0f4da65
06c148c
 
450f783
6e83753
e388521
2ce3791
5604b18
6e83753
5604b18
 
 
9198234
8c38b3e
 
9198234
8c38b3e
 
 
 
 
 
 
 
 
 
64a5388
 
 
 
 
 
4a63200
64a5388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c34e60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18cd92f
450f783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c317478
06c148c
345b44b
a36c555
345b44b
06c148c
345b44b
06c148c
345b44b
 
0c7b8fd
345b44b
0c7b8fd
345b44b
06c148c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c317478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06c148c
392c65e
06c148c
345b44b
4d495e1
c317478
 
 
 
 
 
 
 
 
 
 
 
 
41f16f2
06c148c
c317478
 
 
 
 
 
 
 
 
 
 
06c148c
 
 
0f4da65
06c148c
c317478
 
 
 
 
 
 
 
 
 
 
 
06c148c
 
c317478
 
 
 
 
 
 
 
 
 
8c38b3e
9198234
8c38b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9198234
8c38b3e
9198234
8c38b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9198234
 
8c38b3e
 
 
6f58f04
148f7c0
 
c086c13
e99a7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea48482
c086c13
 
 
 
 
64a5388
 
 
 
 
e99a7b1
 
148f7c0
8c38b3e
6b9d192
 
 
 
 
 
 
 
 
9758b02
6b9d192
 
 
 
 
 
8c38b3e
6b9d192
 
 
 
 
 
 
 
 
18cd92f
dd6e00f
18cd92f
51331b5
18cd92f
 
 
 
 
 
 
 
 
dd6e00f
18cd92f
 
51331b5
 
 
 
 
 
cb87e78
 
18cd92f
51331b5
 
dd6e00f
51331b5
 
 
 
 
 
 
 
cb87e78
 
18cd92f
51331b5
 
dd6e00f
51331b5
 
450f783
 
 
 
 
 
18cd92f
450f783
18cd92f
dd6e00f
18cd92f
450f783
e99a7b1
8c38b3e
 
 
 
 
18cd92f
8c38b3e
 
dd6e00f
8c38b3e
e802f17
64a5388
 
 
3c87efa
64a5388
 
 
 
 
 
 
 
 
 
a0eadcd
c317478
 
 
 
 
 
 
 
 
 
 
dd6e00f
c317478
 
2ce3791
 
 
 
 
 
 
 
 
 
 
 
69b3985
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
const yts = require('yt-search');
const morgan = require('morgan');
const express = require('express');
const ytdl = require('ytdl-core');
const { Writable, pipeline } = require('stream');
const util = require('util');
const axios = require('axios');
const FormData = require('form-data')
const cheerio = require('cheerio')
const cloudscraper = require('cloudscraper')
const {file} = require('megajs')
let fetch;

(async () => {
    fetch = (await import('node-fetch')).default;
})();

// Regex untuk mengidentifikasi URL YouTube dan Mega
const ytIdRegex = /(?:http(?:s|):\/\/|)(?:(?:www\.|)?youtube(?:\-nocookie|)\.com\/(?:shorts\/)?(?:watch\?.*(?:|\&)v=|embed\/|v\/)?|youtu\.be\/)([-_0-9A-Za-z]{11})/;

// Fungsi untuk melakukan HTTP POST request
const post = async (url, form, headers = {}) => {
    const response = await fetch(url, {
        method: 'post',
        body: new URLSearchParams(form),
        headers
    });
    return response;
};


// MEDIAFIRE DL
async function mediafire(url) {
  return new Promise(async(resolve, reject) => {
  var a, b;
  if (!/https?:\/\/(www\.)?mediafire\.com/.test(url)) return resolve()
   const data = await axios.get(url).catch(function (error) {})
   if (!data) {
  resolve()
   } else {
  const $ = cheerio.load(data.data);
  const Url = ($('#downloadButton').attr('href') || '').trim();
  const url2 = ($('#download_link > a.retry').attr('href') || '').trim();
  const $intro = $('div.dl-info > div.intro');
  const filename = $intro.find('div.filename').text().trim();
  const filetype = $intro.find('div.filetype > span').eq(0).text().trim();
  const ext = ((b = (a = /\(\.(.*?)\)/.exec($intro.find('div.filetype > span').eq(1).text())) === null || a === void 0 ? void 0 : a[1]) === null || b === void 0 ? void 0 : b.trim()) || 'bin';
  const $li = $('div.dl-info > ul.details > li');
  const aploud = $li.eq(1).find('span').text().trim();
  const filesize = $li.eq(0).find('span').text().trim();
  const filesizeB = (0, formatSize)(filesize);
  const result = {
    url: Url || url2,
    url2,
    filename,
    filetype,
    ext,
    upload_date: aploud,
    filesize,
    filesizeB
  };
  resolve(result)
   }
  })
}


//SAVEIG
async function igdl(query) {
url_dl = [];
let headers = {
      'Accept': '*/*',
      'Accept-Language': 'en-US,en;q=0.9',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      'Referer': 'https://saveig.app/',
      'Referrer-Policy': 'strict-origin-when-cross-origin',
      'X-Requested-With': 'XMLHttpRequest'
   }
let options = {
method: 'POST',
uri: 'https://saveig.app/api/ajaxSearch',
headers: headers,
formData: {
q: query
}
}
ch = cheerio.load(JSON.parse(await cloudscraper(options)).data);
ch('.download-items__btn').each(function(a,b) { url_dl.push(ch(b).find('a').attr('href'))})
return url_dl;
}

//FBDL
async function fby2mate(url) {
  try {
    let form = new FormData()
    form.append('q', url)
    form.append('vt', 'facebook')
    let data = await fetch(`https://y2mate.mx/api/ajaxSearch/facebook`, {
      method: 'POST',
      body: form,
      headers: {
        ...form.getHeaders()
      }
    })
    data = await data.json()
    return data
  } catch (e) {
    return e
  }
}

//YTDL-CORE
async function uploadBuffer(buffer) {
    return new Promise(async (resolve, reject) => {
      let res = await axios.post('https://ilhamdev-up.hf.space/upload', {
        file: buffer.toString('base64'),
        headers: {
          'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
        }
      }).catch(e => reject(e))
      if (res.status !== 200) {
        resolve(res?.statusText)
      } else {
        resolve(res?.data?.url)
      }
    })
}
async function streamToBuffer(stream) {
    const chunks = [];
    const captureChunks = new Writable({
        write(chunk, encoding, callback) {
            chunks.push(chunk);
            callback();
        }
    });
      
    await util.promisify(pipeline)(stream, captureChunks);

    return Buffer.concat(chunks);
} 
function formatViews(viewCount) {
  if (viewCount >= 1000000000) {
    return (viewCount / 1000000000).toFixed(1) + 'B';
  } else if (viewCount >= 1000000) {
    return (viewCount / 1000000).toFixed(1) + 'M';
  } else {
    return viewCount >= 1000
      ? (viewCount / 1000).toFixed(1) + 'K'
      : viewCount.toString();
  }
}

function formatDuration(durationInSeconds) {
  const hours = Math.floor(durationInSeconds / 3600);
  const minutes = Math.floor((durationInSeconds % 3600) / 60);
  const seconds = durationInSeconds % 60;

  return hours > 0
    ? hours +
        ':' +
        minutes.toString().padStart(2, '0') +
        ':' +
        seconds.toString().padStart(2, '0')
    : minutes + ':' + seconds.toString().padStart(2, '0');
}

function formatSize(bytes, si = false, dp = 2) {
   const thresh = si ? 1000 : 1024;

   if (Math.abs(bytes) < thresh) {
      return `${bytes} B`;
   }

   const units = si
      ? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
      : ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
   let u = -1;
   const r = 10 ** dp;

   do {
      bytes /= thresh;
      ++u;
   } while (
      Math.round(Math.abs(bytes) * r) / r >= thresh &&
      u < units.length - 1
   );

   return `${bytes.toFixed(dp)} ${units[u]}`;
}

async function ytmp4(url, quality = 'highestvideo') {
  try {
    const ID = ytdl.getVideoID(url),
          data = await ytdl.getInfo('https://www.youtube.com/watch?v=' + ID)
      const videoStream = await ytdl(ID, { filter: 'videoandaudio', quality: 'highestvideo' });
      let buffer = await streamToBuffer(videoStream)
      let upload = await uploadBuffer(buffer)
      let format = ytdl.chooseFormat(data.formats, { filter: 'videoandaudio', quality: quality });

    if (format) {
      return {
        title: data.videoDetails.title,
        description: data.videoDetails.description,
        channel: data.videoDetails.ownerChannelName,
        views: formatViews(data.videoDetails.viewCount),
        publish: data.videoDetails.publishDate,
        duration: formatDuration(data.videoDetails.lengthSeconds),
        size: format.contentLength ? formatSize(format.contentLength) : 0,
        quality: format.qualityLabel,
        thumb: data.videoDetails.thumbnails[0].url,
        dl_url: format.url,
       url_v2: upload,
          }
    } else {
      throw new Error('No suitable format found');
    }
  } catch (error) {
    console.error('Error occurred:', error);
    return null;
  }
}
async function ytmp3(url, bitrate = 'lowestaudio') {
  try {
    const ID = ytdl.getVideoID(url),
          data = await ytdl.getInfo('https://www.youtube.com/watch?v=' + ID)
      let audioStream = await ytdl(ID, { filter: 'audioonly', quality: 'lowestaudio', });
      let buffer = await streamToBuffer(audioStream)
      let upload = await uploadBuffer(buffer)
      let format = ytdl.chooseFormat(data.formats, { filter: 'audioonly', quality: bitrate });

    if (format) {
      return {
        title: data.videoDetails.title,
        description: data.videoDetails.description,
        channel: data.videoDetails.ownerChannelName,
        views: formatViews(data.videoDetails.viewCount),
        publish: data.videoDetails.publishDate,
        duration: formatDuration(data.videoDetails.lengthSeconds),
        size: format.contentLength ? formatSize(format.contentLength) : 0,
        quality: format.audioQuality,
        thumb: data.videoDetails.thumbnails[0].url,
          dl_url: format.url,
        url_v2: upload
      }
    } else {
      throw new Error('No suitable format found');
    }
  } catch (error) {
    console.error('Error occurred:', error);
    return null;
  }
}

// Fungsi untuk mengkonversi video dari YouTube
const convert = async (url, v_id, ftype, fquality, fname, token, timeExpire) => {
    let params = {
        v_id,
        ftype,
        fquality,
        fname,
        token,
        timeExpire,
        client: 'yt5s.com'
    };

    // Mengirim permintaan konversi
    let resServer = await (await post(url, params, { 'x-requested-key': 'de0cfuirtgf67a' })).json();
    let server = resServer.c_server;

    // Jika tidak ada server dan tipe file adalah mp3, kembalikan null
    if (!server && ftype === 'mp3') return server || resServer.d_url || '';

    // Mengambil data hasil konversi
    let data = await (await post(`${server}/api/json/convert`, params)).json();
    let result;

    // Memeriksa status kode hasil konversi
    if (data.statusCode === 200) result = data.result;
    while (!result) {
        let json = await (await post(`${server}/api/json/convert`, params)).json();
        if (json.statusCode === 200) {
            result = json.result;
            break;
        }
        await new Promise(resolve => setTimeout(resolve, 2000));
    }
    return result;
};

// Fungsi untuk mendownload video dari YouTube
const youtubedl = async (url) => {
    let html = await (await fetch('https://yt5s.com/en32')).text();
    let urlAjax = (html.match(/k_url_search="(.*?)"/) || [])[1];
    let urlConvert = (html.match(/k_url_convert="(.*?)"/) || [])[1];
    let json = await (await post(urlAjax, { q: url, vt: 'home' })).json();
    let video = {}, audio = {};
    if (!json?.links) throw json.mess;
    Object.values(json.links.mp4).map(({ k, size }) => video[k] = {
        quality: k,
        fileSizeH: size,
        fileSize: parseFloat(size) * (/MB$/.test(size) ? 1000 : 1),
        download: convert.bind(null, urlConvert, json.vid, 'mp4', k, json.fn, json.token, parseInt(json.timeExpires))
    });

    Object.values(json.links.mp3).map(({ key, size }) => audio[key] = {
        quality: key,
        fileSizeH: size,
        fileSize: parseFloat(size) * (/MB$/.test(size) ? 1000 : 1),
        download: convert.bind(null, urlConvert, json.vid, 'mp3', key.replace(/kbps/i, ''), json.fn, json.token, parseInt(json.timeExpires))
    });

    return {
        id: json.vid,
        title: json.title,
        thumbnail: `https://i.ytimg.com/vi/${json.vid}/0.jpg`,
        video,
        audio
    };
};

const app = express()
    .set('json spaces', 4)
    .use(morgan('dev'))
    .use(express.json())
    .all('/', (req, res) =>  { 
      const host = 'https://' + req.get('host');
      res.json({
  "List": [
    {
      "title": "Tiktok Downloader",
      "method": "GET",
      "example": `${host}/tt?url=`,
    },
    {
      "title": "Facebook Downloader",
      "method": "GET",
      "example": `${host}/fb?url=`,
    },
    {
      "title": "Instagram Downloader",
      "method": "GET",
      "example": `${host}/ig?url=`,
    },
    {
      "title": "Youtube Downloader",
      "method": "GET",
      "example": `${host}/ytdl?url=`,
    },
    {
      "title": "Youtube Search",
      "method": "GET",
      "example": `${host}/ytsearch?q=`,
    },
    {
      "title": "Pinterest Downloader",
      "method": "GET",
      "example": `${host}/pindl?url=`,
    },
    {
      "title": "Mediafire Downloader",
      "method": "GET",
      "example": `${host}/mediafire?url=`,
    }
  ]
})})
    .get('/yt', async (req, res) => {
    const host = 'https://' + req.get('host');
    try {
        let { url, type, quality, json } = req.query;
        if (!ytIdRegex.test(url)) return res.json({ message: 'Invalid URL' });
        if (!!json) {
            let ytId = ytIdRegex.exec(url)?.[1];
            if (!ytId) return res.json({ message: 'No video id found' });
            let data = await yts({ videoId: ytId });
            const downloadUrls = {
                audio: `${host}/yt?url=${url}&type=audio&quality=128kbps`,
                video: `${host}/yt?url=${url}&type=video&quality=`,
            };
            return res.json({
                ...data,
                download: downloadUrls
            });
        }
        if (!type || !/audio|video/i.test(type)) type = 'video';
        let data = await youtubedl(url).catch(e => console.log(e));
        if (!data) return res.json({ message: 'Error: link download not found' });
        type = type.toLowerCase();
        let result = quality ? Object.values(data[type]).find(x => x.quality == quality) : Object.values(data[type])[0];
        if (quality && !result) return res.json({ message: `Invalid quality: ${quality}, available quality (${Object.keys(data[type]).join('/')})` });
        if (!result) return res.json({ message: 'Error: can\'t download' });
        res.redirect(await result.download());
    } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
  .get('/ig', async (req,res) => {
    try {
      let {url} = req.query
      let regex = /https?:\/\/(www\.)?instagram\.com\/(p|reel|tv)/;
      if (!regex.test(url)) return res.json({ message: 'Invalid URL' });
      let data = await igdl(url)
      return res.json(data)
    } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
  })
    .get('/tt', async (req, res) => {
        try {
            let { url } = req.query
            let regex = /https?:\/\/(www\.|v(t|m|vt)\.|t\.)?tiktok\.com/;
            if (!regex.test(url)) return res.json({ message: 'Invalid URL' });
            let data = await fetch(`https://tikwm.com/api/?url=` + url)
            data = await data.json()
            if (!data) return res.json({ message: 'API TO API KOID:v' });
            return res.json(data)
        } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
    .get('/pindl', async (req, res) => {
        try {
            let { url } = req.query
            let regex = /https:\/\/pin\.it\/\w+|https:\/\/[a-z]{2}\.pinterest\.com\/pin\/\d+/;
            if (!regex.test(url)) return res.json({ message: 'Invalid URL' });
            let data = await fetch(`https://pinterestdownloader.io/id/frontendService/DownloaderService?url=` + url)
            data = await data.json()
            if (!data) return res.json({ message: 'API TO API KOID:v' });
            return res.json(data)
        } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
    .get('/fb', async (req, res) => {
      try {
        let {url} = req.query
        let regex = /https?:\/\/(fb\.watch|(www\.|web\.|m\.)?facebook\.com)/;
        if (!regex.test(url)) return res.json({ message: 'Invalid URL' });
        let data = await fby2mate(url)
        return res.json(data)
      } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
    .get('/ytsearch', async (req, res) => {
        try {
            let q = req.query.q || req.query.query;
            if (!q) return res.json({ message: 'Input parameter q' });
            let data = await yts(q);
            if (!data.all[0]) return res.json({ message: 'Not found' });
            return res.json(data.all);
        } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
    .get('/mediafire', async (req, res) => {
        try {
            let { url } = req.query
          //console.log(url)
            if (!/https?:\/\/(www\.)?mediafire\.com\/(file|download)/i.test(url)) {
        return res.json({ message: 'Invalid URL' });
            }
            let data = await mediafire(url)
            return res.json(data)
        } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
    .get('/ytdl', async (req, res) => {
        try {
            let { url } = req.query
            if (!ytIdRegex.test(url)) return res.json({ message: 'Invalid URL' });
            let video = await ytmp4(url)
            let audio = await ytmp3(url)
            return res.json({
                video: video,
                audio: audio
            })
        } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
    })
  .get('/mega', async (req,res) => {
    try {
      let {url} = req.query
      let regex = if (!/https:\/\/mega\.nz\/file\/[a-zA-Z0-9]{8}#[a-zA-Z0-9-_]{43}/.test(url)) {
 return res.json({ message: 'Invalid URL' });
  }
      console.log(url)
    } catch (e) {
            console.log(e);
            return res.json({ message: e.message });
        }
  })
    .listen(7860, () => console.log('App running on port 7860'));