const yts = require('yt-search'); const morgan = require('morgan'); const express = require('express'); const ytdl = require('ytdl-core'); const ffmpeg = require("fluent-ffmpeg") const { Writable, pipeline, Readable, PassThrough } = require('stream'); const util = require('util'); const axios = require('axios'); const FormData = require('form-data') const cp = require('child_process') const os = require('os') const cheerio = require('cheerio') const cloudscraper = require('cloudscraper') const acrcloud = require("acrcloud"); const { File } = require('megajs') const { BingChat } = require("bing-chat-cjs-rnz"); const path = require("path") const fs = require("fs") const mimes = require("mime-types") let fetch; (async () => { fetch = (await import('node-fetch')).default; })(); // Regex untuk mengidentifikasi URL YouTube dan Mega const ytIdRegex = /(?:https?:\/\/)?(?:www\.|music\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=|shorts\/|user\/\S+\/\S+\/)|youtu\.be\/)([\w-]{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; }; // isURL function isUrl(url) { let regex = new RegExp(/(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%.+~#=]{1,256}\.[a-zA-Z0-9()]{1,9}\b([-a-zA-Z0-9()@:%+.~#?&//=]*)/, 'gi'); if (!regex.test(url)) return false; return url?.match(regex); } //RANDOM function generateRandomUserAgent() { const androidVersions = ['4.0.3', '4.1.1', '4.2.2', '4.3', '4.4', '5.0.2', '5.1', '6.0', '7.0', '8.0', '9.0', '10.0', '11.0', '12.0', '13.0']; const deviceModels = ['M2004J19C', 'S2020X3', 'Xiaomi4S', 'RedmiNote9', 'SamsungS21', 'GooglePixel5', 'iPhone13,4', 'SM-A526B', 'SM-G991B', 'SM-G998B', 'iPhone13,2', 'iPhone13,3', 'iPhone13,1', 'SM-G996B', 'SM-G970F']; const buildVersions = ['RP1A.200720.011', 'RP1A.210505.003', 'RP1A.210812.016', 'QKQ1.200114.002', 'RQ2A.210505.003', 'RQ3A.211001.001', 'SD1A.210817.036', 'T825YDXU3CTK1', 'QKQ1.191014.012', 'QKQ1.190918.001', 'QKQ1.190626.002', 'QKQ1.190716.003', 'QKQ1.190626.002', 'QKQ1.190626.002', 'QKQ1.190626.002']; const browsers = ['Chrome', 'Firefox', 'Safari', 'Edge', 'Opera']; const getRandomElement = (arr) => arr[Math.floor(Math.random() * arr.length)]; const getRandomNumber = (max) => Math.floor(Math.random() * max) + 1; const selectedModel = getRandomElement(deviceModels); const selectedBuild = getRandomElement(buildVersions); const selectedBrowser = getRandomElement(browsers); const browserVersion = `${selectedBrowser}/${getRandomNumber(96)}.${getRandomNumber(999)}.${getRandomNumber(9999)}.${getRandomNumber(99)}`; const userAgent = `Mozilla/5.0 (Linux; Android ${getRandomElement(androidVersions)}; ${selectedModel} Build/${selectedBuild}) AppleWebKit/537.36 (KHTML, like Gecko) ${browserVersion} Mobile Safari/537.36`; return userAgent; } function generateRandomIP() { return Array(4) .fill(0) .map(() => Math.floor(Math.random() * 256)) .join('.'); } //BIMG // async function bimg(query) { // const { BingApi } = await import("bing-nodejs"); // const bing = new BingApi({ // cookie: process.env.BING_IMAGE_COOKIE // }); // let data = await bing.createImage(query).then((res) => { // return res.urls; // string[] // }); // // Filter out links that end with '.svg' // let filteredData = data.filter(i => !i.includes('.svg')); // return filteredData // } async function bingChat(text) { const api = new BingChat({ cookie: process.env.BING_IMAGE_COOKIE }) const res = await api.sendMessage(text, { variant: 'Precise' }) return res?.text } async function acrCloud(buffer) { let { mime } = await (await import('file-type')).fileTypeFromBuffer(buffer); if (/audio|video/.test(mime)) { const wow = new acrcloud({ host: "identify-ap-southeast-1.acrcloud.com", access_key: "b1cc283b4fb72483ebb6ea9c53512331", access_secret: "xyqJGTZRTrUotaraHEjji00WBClx7RpWozywdANq" }); let { status, metadata } = await wow.identify(buffer); if (status.code !== 0) throw new Error(status.msg); //console.log(metadata.music[0]) return metadata.music[0]; } else { throw new Error('Error: only audio/video files are supported'); } } // MEDIAFIRE DL async function mediafire(url) { return new Promise(async (resolve, reject) => { var a, b; if (!/https?:\/\/(www\.)?mediafire.com/.test(url)) return resolve(); try { const data = await axios.get(url, { headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP(), } }); 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 = /(.+?)\s*(?:\(|$)/.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 upload_date = $li.eq(1).find('span').text().trim(); const filesize = $li.eq(0).find('span').text().trim(); const filesizeB = formatSize(filesize); const result = { url: Url || url2, url2, filename, filetype, ext, upload_date, filesize, filesizeB }; resolve(result); } } catch (error) { reject(error); } }); } //SAVEIG async function igdl(_0x159ab8) { return new Promise(async (_0xe63f96) => { try { if ( !_0x159ab8.match( /(?:https?:\/\/(web\.|www\.|m\.)?(facebook|fb)\.(com|watch)\S+)?$/ ) && !_0x159ab8.match( /(https|http):\/\/www.instagram.com\/(p|reel|tv|stories)/gi ) ) { return _0xe63f96({ status: false, msg: 'Link Url not valid', }) } function _0x4f89d0(_0x3ec4f9) { let [_0x5d994e, _0x1c6a7f, _0x5522f1, _0x35fc84, _0x2719e7, _0xe3576] = _0x3ec4f9 function _0x1db5bb(_0x447b96, _0x3426c2, _0xf423a5) { const _0x34129a = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/'.split( '' ) let _0x2ca1b1 = _0x34129a.slice(0, _0x3426c2), _0x6bc246 = _0x34129a.slice(0, _0xf423a5), _0x44307a = _0x447b96 .split('') .reverse() .reduce(function (_0xdc78cf, _0x964717, _0x5306fd) { if (_0x2ca1b1.indexOf(_0x964717) !== -1) { return (_0xdc78cf += _0x2ca1b1.indexOf(_0x964717) * Math.pow(_0x3426c2, _0x5306fd)) } }, 0), _0x2590e4 = '' while (_0x44307a > 0) { _0x2590e4 = _0x6bc246[_0x44307a % _0xf423a5] + _0x2590e4 _0x44307a = (_0x44307a - (_0x44307a % _0xf423a5)) / _0xf423a5 } return _0x2590e4 || '0' } _0xe3576 = '' for ( let _0xc0cce1 = 0, _0x2517ec = _0x5d994e.length; _0xc0cce1 < _0x2517ec; _0xc0cce1++ ) { let _0x51d70e = '' while (_0x5d994e[_0xc0cce1] !== _0x5522f1[_0x2719e7]) { _0x51d70e += _0x5d994e[_0xc0cce1] _0xc0cce1++ } for (let _0x465f12 = 0; _0x465f12 < _0x5522f1.length; _0x465f12++) { _0x51d70e = _0x51d70e.replace( new RegExp(_0x5522f1[_0x465f12], 'g'), _0x465f12.toString() ) } _0xe3576 += String.fromCharCode( _0x1db5bb(_0x51d70e, _0x2719e7, 10) - _0x35fc84 ) } return decodeURIComponent(encodeURIComponent(_0xe3576)) } function _0x5f2063(_0xd04512) { return _0xd04512 .split('decodeURIComponent(escape(r))}(')[1] .split('))')[0] .split(',') .map((_0x31dcab) => _0x31dcab.replace(/"/g, '').trim()) } function _0x439f4e(_0x401f4e) { return _0x401f4e .split('getElementById("download-section").innerHTML = "')[1] .split('"; document.getElementById("inputData").remove(); ')[0] .replace(/\\(\\)?/g, '') } function _0x425f2f(_0x29e814) { return _0x439f4e(_0x4f89d0(_0x5f2063(_0x29e814))) } const _0x1168e5 = (await import("got")) .post('https://snapsave.app/action.php?lang=id', { headers: { 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', 'content-type': 'application/x-www-form-urlencoded', origin: 'https://snapsave.app', referer: 'https://snapsave.app/id', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36', }, form: { url: _0x159ab8 }, }) .text(), _0x42d136 = _0x425f2f(_0x1168e5), _0x1ccb10 = cheerio.load(_0x42d136), _0x48456b = [] if ( _0x1ccb10('table.table').length || _0x1ccb10('article.media > figure').length ) { const _0x8e687b = _0x1ccb10('article.media > figure') .find('img') .attr('src') _0x1ccb10('tbody > tr').each((_0x352b2e, _0x6ebec2) => { const _0x2f2888 = _0x1ccb10(_0x6ebec2), _0x1206d7 = _0x2f2888.find('td'), _0x1a2aee = _0x1206d7.eq(0).text() let _0x4733a0 = _0x1206d7.eq(2).find('a').attr('href') || _0x1206d7.eq(2).find('button').attr('onclick') const _0x2a6a17 = /get_progressApi/gi.test(_0x4733a0 || '') _0x2a6a17 && (_0x4733a0 = /get_progressApi\('(.*?)'\)/.exec(_0x4733a0 || '')?.[1] || _0x4733a0) _0x48456b.push({ resolution: _0x1a2aee, thumbnail: _0x8e687b, url: _0x4733a0, shouldRender: _0x2a6a17, }) }) } else { _0x1ccb10('div.download-items__thumb').each((_0x31a9cb, _0x155e08) => { const _0x3051a0 = _0x1ccb10(_0x155e08).find('img').attr('src') _0x1ccb10('div.download-items__btn').each((_0x24db73, _0x55d14a) => { let _0x5e29b6 = _0x1ccb10(_0x55d14a).find('a').attr('href') !/https?:\/\//.test(_0x5e29b6 || '') && (_0x5e29b6 = 'https://snapsave.app' + _0x5e29b6) _0x48456b.push({ thumbnail: _0x3051a0, url: _0x5e29b6, }) }) }) } if (!_0x48456b.length) { return _0xe63f96('Result Not Found! Check Your Url Now!') } return _0xe63f96(_0x48456b) } catch (_0x576c75) { return _0xe63f96('Request Failed With Code 401') } }) } async function igdl2(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: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP(), ...form.getHeaders() } }); data = await data.json(); return data; } catch (e) { return e; } } async function convertMp4ToAudio(inputBuffer) { return new Promise((resolve, reject) => { const inputStream = new Readable(); inputStream.push(inputBuffer); inputStream.push(null); const outputBuffer = []; const outputStream = new Writable({ write(chunk, encoding, callback) { outputBuffer.push(chunk); callback(); } }); ffmpeg(inputStream) .toFormat('mp3') .on('end', () => { console.log('Conversion finished!'); resolve(Buffer.concat(outputBuffer)); }) .on('error', (err) => { console.error('Error during conversion:', err); reject(err); }) .pipe(outputStream); }); } 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 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); } async function fileDitch(media, ext){ let {fileTypeFromBuffer} = await (await import('file-type')) let mime = await fileTypeFromBuffer(media) let form = new FormData() form.append("files[]", media, `${Date.now()}.${ext ? ext : mime?.ext || "bin"}`) let {data } = await axios.post("https://up1.fileditch.com/temp/upload.php", form, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36", "accept": "*/*", "accept-language": "id;q=0.9", "sec-ch-ua": "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Brave\";v=\"128\"", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "\"Windows\"", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-site", "sec-gpc": "1", "Referer": "https://fileditch.com/", "Referrer-Policy": "strict-origin-when-cross-origin", ...form.getHeaders() } }) // console.log(data) if (data?.files[0]?.url) { return data?.files[0]?.url } else { return data } //https://up1.fileditch.com/upload.php } async function ytAPI(url) { try { const cookie = [ { "domain": ".youtube.com", "expirationDate": 1738764557.53631, "hostOnly": false, "httpOnly": false, "name": "__Secure-1PAPISID", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "ZxxtRaUn-ihsYDT5/ArDjL8QbSdQ6L1Hbg", "id": 1 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536472, "hostOnly": false, "httpOnly": true, "name": "__Secure-1PSID", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "g.a000mwhEV6cw_ZG7uGYHi0E-2I6FiR-0Ip4YBuoWWVq0sDGEIYZUfbp9BpERMomIr3WQJ7DNBgACgYKAbESARQSFQHGX2MiugDxYOon-cKOzB4Bh_KDqBoVAUF8yKpwbqv3lrEHGD7YZpPaXKej0076", "id": 2 }, { "domain": ".youtube.com", "expirationDate": 1740061227.741547, "hostOnly": false, "httpOnly": true, "name": "__Secure-1PSIDCC", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "AKEyXzXla4j7VyRZR6aPSEk9FcZTgJ87C5N9gBpsZNuSG6E39ApftOWuq1DrmlNlK_rI091Q1t4x", "id": 3 }, { "domain": ".youtube.com", "expirationDate": 1740060716.083712, "hostOnly": false, "httpOnly": true, "name": "__Secure-1PSIDTS", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "sidts-CjEBUFGohxesOafrCCqc5We5_RDl7eiejTLKKlWqATgxUSc2ZU6Q4Grzi5aWUzneo3JcEAA", "id": 4 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536355, "hostOnly": false, "httpOnly": false, "name": "__Secure-3PAPISID", "path": "/", "sameSite": "no_restriction", "secure": true, "session": false, "storeId": "0", "value": "ZxxtRaUn-ihsYDT5/ArDjL8QbSdQ6L1Hbg", "id": 5 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536519, "hostOnly": false, "httpOnly": true, "name": "__Secure-3PSID", "path": "/", "sameSite": "no_restriction", "secure": true, "session": false, "storeId": "0", "value": "g.a000mwhEV6cw_ZG7uGYHi0E-2I6FiR-0Ip4YBuoWWVq0sDGEIYZU5a5upCtMjTBwwc-YUR0FHwACgYKAV4SARQSFQHGX2MiNdi-ERZGM6peeWKVbt_cNRoVAUF8yKoY9DV-VvOsSTi1B4kxLA2R0076", "id": 6 }, { "domain": ".youtube.com", "expirationDate": 1740061227.741586, "hostOnly": false, "httpOnly": true, "name": "__Secure-3PSIDCC", "path": "/", "sameSite": "no_restriction", "secure": true, "session": false, "storeId": "0", "value": "AKEyXzVvQWuv6fqsrejb1Fq8TolQRpXNN8HM1XBpTZAxIFJCN4BoaNebkeAE15ZdP5iKnN6RbIhV", "id": 7 }, { "domain": ".youtube.com", "expirationDate": 1740060716.0838, "hostOnly": false, "httpOnly": true, "name": "__Secure-3PSIDTS", "path": "/", "sameSite": "no_restriction", "secure": true, "session": false, "storeId": "0", "value": "sidts-CjEBUFGohxesOafrCCqc5We5_RDl7eiejTLKKlWqATgxUSc2ZU6Q4Grzi5aWUzneo3JcEAA", "id": 8 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536219, "hostOnly": false, "httpOnly": false, "name": "APISID", "path": "/", "sameSite": "unspecified", "secure": false, "session": false, "storeId": "0", "value": "UK-7xFyNoG1CZvBj/A7mVt-WOSxyZOg_2N", "id": 9 }, { "domain": ".youtube.com", "expirationDate": 1738764557.53613, "hostOnly": false, "httpOnly": true, "name": "HSID", "path": "/", "sameSite": "unspecified", "secure": false, "session": false, "storeId": "0", "value": "A_wGA3WRMbnXRC-aa", "id": 10 }, { "domain": ".youtube.com", "expirationDate": 1738764558.473367, "hostOnly": false, "httpOnly": true, "name": "LOGIN_INFO", "path": "/", "sameSite": "no_restriction", "secure": true, "session": false, "storeId": "0", "value": "AFmmF2swRQIgSePokHmqstWCqfHPVcAKm8mhFbRFFvRoKSMVmz2IQgwCIQCbsPnOsRkIxwilmFF91yfDfVH_M8_LZvYNw8I9x1Ymfw:QUQ3MjNmeUo5ZnI0RGlMdWZMNWppdlVYTUxrdldjNDhPTVg2eHR4dHhjdkhwOTJydUlqRmZ4ZEpmQmtwUllUVUViV1ptWnRHWW9pcDNqRVVjSkJJSV9rRjVza0tRWkt4U1FRc3AyeDFKRzJkcjRTTFkyQTQ4RWNVV0tMUExrWlluaUhZMy1CUHhmeXlBS1hVaEN3bE9rcmYybnlrVVBTUXdn", "id": 11 }, { "domain": ".youtube.com", "expirationDate": 1725114026.728297, "hostOnly": false, "httpOnly": false, "name": "PREF", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "f4=4000000&f6=40000000&tz=Asia.Jakarta&repeat=NONE&autoplay=true&f5=20000&f7=150", "id": 12 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536265, "hostOnly": false, "httpOnly": false, "name": "SAPISID", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "ZxxtRaUn-ihsYDT5/ArDjL8QbSdQ6L1Hbg", "id": 13 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536424, "hostOnly": false, "httpOnly": false, "name": "SID", "path": "/", "sameSite": "unspecified", "secure": false, "session": false, "storeId": "0", "value": "g.a000mwhEV6cw_ZG7uGYHi0E-2I6FiR-0Ip4YBuoWWVq0sDGEIYZUZerrBxC46plRv_EcS3JTwAACgYKAZsSARQSFQHGX2MiZo8XZpd2djM_gFImKp30exoVAUF8yKrxlcio8blNMJOeKPD8B3Es0076", "id": 14 }, { "domain": ".youtube.com", "expirationDate": 1740061227.741445, "hostOnly": false, "httpOnly": false, "name": "SIDCC", "path": "/", "sameSite": "unspecified", "secure": false, "session": false, "storeId": "0", "value": "AKEyXzUCURmJmXgv1oW7r8t4elAXijNr-l53BYCLrfyVl5QdcjdX9fcINywVisRZosm-8UJH-SOj", "id": 15 }, { "domain": ".youtube.com", "hostOnly": false, "httpOnly": false, "name": "SOCS", "path": "/", "sameSite": "unspecified", "secure": true, "session": true, "storeId": "0", "value": "CAISNQgDEitib3FfaWRlbnRpdHlmcm9udGVuZHVpc2VydmVyXzIwMjMwODI5LjA3X3AxGgJlbiADGgYIgJnPpwY", "id": 16 }, { "domain": ".youtube.com", "expirationDate": 1738764557.536175, "hostOnly": false, "httpOnly": true, "name": "SSID", "path": "/", "sameSite": "unspecified", "secure": true, "session": false, "storeId": "0", "value": "AcoGVKtj08k_B75KA", "id": 17 }, { "domain": ".youtube.com", "expirationDate": 1724509232, "hostOnly": false, "httpOnly": false, "name": "ST-tladcw", "path": "/", "sameSite": "unspecified", "secure": false, "session": false, "storeId": "0", "value": "session_logininfo=AFmmF2swRQIgSePokHmqstWCqfHPVcAKm8mhFbRFFvRoKSMVmz2IQgwCIQCbsPnOsRkIxwilmFF91yfDfVH_M8_LZvYNw8I9x1Ymfw%3AQUQ3MjNmeUo5ZnI0RGlMdWZMNWppdlVYTUxrdldjNDhPTVg2eHR4dHhjdkhwOTJydUlqRmZ4ZEpmQmtwUllUVUViV1ptWnRHWW9pcDNqRVVjSkJJSV9rRjVza0tRWkt4U1FRc3AyeDFKRzJkcjRTTFkyQTQ4RWNVV0tMUExrWlluaUhZMy1CUHhmeXlBS1hVaEN3bE9rcmYybnlrVVBTUXdn", "id": 18 } ] const agentOptions = { pipelining: 5, maxRedirections: 0, }; const agent = ytdl.createAgent(cookie, agentOptions); const ID = ytdl.getVideoID(url) //let videoStream = await ytdl(ID, { filter: 'audioandvideo', quality: 'highestvideo' }); let data = await ytdl.getInfo('https://www.youtube.com/watch?v=' + ID, {agent}) let format = ytdl.chooseFormat(data.formats, { filter: 'videoandaudio', quality: 'highestvideo', agent }); let audioStream = await ytdl(ID, {filter: "audioandvideo", quality:"lowestvideo", agent}) //let buffermp4 = await streamToBuffer(videoStream) let buffermp3 = await streamToBuffer(audioStream) buffermp3 = await convertMp4ToAudio(buffermp3) //buffermp4 = await fileDitch(buffermp4) buffermp3 = await fileDitch(buffermp3) return { mp4_url: format.url, mp3_url: buffermp3, } } catch (err) { console.error('Error occurred:', err); 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', {headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP(), }})).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 }; }; //TWITTER API async function twitterDL(url) { try { let form = new FormData(); form.append('q', url); form.append('lang', 'en'); let response = await fetch('https://x2twitter.com/api/ajaxSearch', { method: 'POST', body: form, headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP(), ...form.getHeaders() } }); let data = await response.json(); const $ = cheerio.load(data?.data); let downloads = []; $('.dl-action a').each((index, element) => { const format = $(element).text().trim(); const url = $(element).attr('href'); if (url !== '#') { downloads.push({ format, url }); } }); // Jika tidak ada unduhan dari load pertama, coba load kedua if (downloads.length === 0) { $('a').each((index, element) => { const href = $(element).attr('href'); if (href && href !== '/' && href !== '#') { downloads.push(href); } }); } return { downloads }; } catch (error) { return error; } } const app = express() .set('json spaces', 4) .use(morgan('dev')) .use(express.json()) .all('/', async (req, res) => { const v8 = require('v8'); const status = {}; status['diskUsage'] = cp.execSync('du -sh').toString().split('M')[0] + ' MB'; const used = process.memoryUsage(); for (let x in used) status[x] = formatSize(used[x]); const totalmem = os.totalmem(); const freemem = os.freemem(); status['memoryUsage'] = `${formatSize(totalmem - freemem)} / ${formatSize(totalmem)}`; const heapStats = v8.getHeapStatistics(); for (let x in heapStats) status[x] = formatSize(heapStats[x]); // Menambahkan informasi CPU const cpus = os.cpus(); status['cpuUsage'] = cpus.map((cpu, index) => ({ core: index + 1, model: cpu.model, speed: `${cpu.speed} MHz`, times: cpu.times })); const host = 'https://' + req.get('host'); res.json({ creator: `@${process.env['SPACE_AUTHOR_NAME'] || 'ALOK FF'}`, message: 'Hello World!', uptime: new Date(process.uptime() * 1000).toUTCString().split(' ')[4], status, list: [ { title: "BING AI", method: "GET", example: `${host}/bing?q=` }, { title: "Facebook Downloader", method: "GET", example: `${host}/fb?url=` }, { title: "Google Search", method: "GET", example: `${host}/googleSearch?q=` }, { title: "Google Search Image", method: "GET", example: `${host}/gimage?q=` }, { title: "Instagram Downloader", method: "GET", example: `${host}/ig?url=` }, { title: "Mediafire Downloader", method: "GET", example: `${host}/mediafire?url=` }, { title: "Mega Downloader", method: "GET", example: `${host}/mega?url=`+ "${encodeURIComponent('url')}" }, { title: "Pinterest Downloader", method: "GET", example: `${host}/pindl?url=` }, { title: "Remove Background", method: "GET", example: `${host}/removebg?url=` }, { title: "Tiktok Downloader", method: "GET", example: `${host}/tt?url=` }, { title: "Twitter/X Downloader", method: "GET", example: `${host}/twitter?url=` }, { title: "Whatmusic Search", method: "GET", example: `${host}/whatmusic?url=` }, { title: "Youtube Downloader", method: "GET", example: `${host}/ytdl?url=` }, { title: "Youtube Search", method: "GET", example: `${host}/ytsearch?q=` }, ] })}) .get('/yt', async (req, res) => { try { let { url } = req.query; //if (!ytIdRegex.test(url)) return res.json({ message: 'Invalid URL' }); if (!ytdl.validateURL(url)) return res.json({ message: 'Invalid URL' }); let videoID = ytdl.getVideoID(url); //let dataInfo = await ytdl.getBasicInfo(videoID) || {}; let otherAPI = await (await axios.get("https://line.1010diy.com/web/free-mp3-finder/detail?url="+url))?.data?.data ? await (await axios.get("https://line.1010diy.com/web/free-mp3-finder/detail?url="+url))?.data?.data : null let response = { metadata: otherAPI, //other: otherAPI || null }; return res.json({message: "Success", code: 200, data:response}) } catch (e) { console.log(e); return res.status(500).json({ message: "Internal Server Error", code: 500 }); } }) .get('/ig', async (req,res) => { try { let {url} = req.query let regex = /https?:\/\/(www\.)?instagram\.com\/(p|reel|tv)\/[a-zA-Z0-9_-]+\/?/; if (!regex.test(url)) return res.json({ message: 'Invalid URL' }); let data = await igdl(url) return res.json({message: "Success", code: 200, data:data}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/removebg', async (req, res) => { try { let {transparentBackground } = await import("transparent-background") let {url} = req.query if (!url) return res.json({ message: 'Invalid URL' }); const inputUrl = (await axios.get(url, { responseType: 'arraybuffer' // Set response type ke 'arraybuffer' untuk mendapatkan buffer })).data const output = await transparentBackground(inputUrl, await (await(await import('file-type')).fileTypeFromBuffer(inputUrl))?.ext || "png", { // uses a 1024x1024 model by default // enabling fast uses a 384x384 model instead fast: false, }); // res.set('Content-Type', 'application/octet-stream'); // Set content type untuk buffer return res.json({message:"Success", code : 200, data: await fileDitch(output, await (await(await import('file-type')).fileTypeFromBuffer(inputUrl))?.ext || "png")}); } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }) } }) .get('/tt', async (req, res) => { try { const { url } = req.query; // Validasi URL TikTok const tiktokUrlRegex = /^https?:\/\/(www\.|v(t|m|vt)\.|t\.)?tiktok\.com/i; if (!tiktokUrlRegex.test(url)) { return res.json({ message: 'Invalid URL', code: 400 }); } const results = []; // Coba ambil data dari API tikwm.com try { const response = await fetch(`https://tikwm.com/api/?url=${encodeURIComponent(url)}`, { headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP(), } }); if (response.ok) { const data = await response.json(); if (data.code === -1) { return res.json({ message: "Internal Server Error", code: 500, data: data, }); } // Jika berhasil dan data.code bukan -1, simpan data dan kembalikan hasilnya results.push({ source: 'tikwm.com', data }); return res.json({ message: "Success", code: 200, data: results, }); } else { // Jika response tidak OK, log error dan kembalikan respons error console.log({ message: 'Failed to fetch data from tikwm.com', status: response.status }); return res.json({ message: "Internal Server Error", code: 500, error: 'Failed to fetch data from tikwm.com', }); } } catch (e) { // Penanganan error jika terjadi kesalahan selama fetching dari tikwm.com console.log({ message: 'Unexpected Error', error: e }); return res.json({ message: "Internal Server Error", code: 500, error: e.message || 'Unexpected error occurred', }); } } catch (e) { // Penanganan error jika terjadi kesalahan yang tidak terduga console.log({ message: 'Unexpected Error', error: e }); return res.json({ message: "Internal Server Error", code: 500, error: e.message || 'Unexpected error occurred', }); } }) .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}`, { headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP(), } }); data = await data.json(); if (!data) return res.json({ message: 'API TO API KOID' }); return res.json({message: "Success", code: 200, data:data}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .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({message: "Success", code: 200, data:data}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) // .get('/bimg', async (req, res) => { // try { // let q = req.query.q || req.query.query; // if (!q) return res.json({ message: 'Input parameter q' }); // let data = await bimg(q) // return res.json({query: q, data: data}) // } catch (e) { // console.log(e); // return res.json({ message: e.message }); // } // }) .get('/bing', async (req, res) => { try { let q = req.query.q || req.query.query; if (!q) return res.json({ message: 'Input parameter q' }); let data = await bingChat(q) if (data.length === 0) { async function gpt4o(prompt) { let session_hash = Math.random().toString(36).substring(2); try { let resPrompt = await axios.post('https://kingnish-opengpt-4o.hf.space/run/predict', { "data": [{ "text": prompt, "files": [] }], "event_data": null, "fn_index": 1, "trigger_id": 14, "session_hash": session_hash }, { headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP() } }); let res = await axios.post('https://kingnish-opengpt-4o.hf.space/queue/join?__theme=light', { "data": [ null, null, false ], "event_data": null, "fn_index": 3, "trigger_id": 14, "session_hash": session_hash }, { headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP() } }); let event_ID = res.data.event_id; let anu = await axios.get('https://kingnish-opengpt-4o.hf.space/queue/data?session_hash=' + session_hash, { headers: { 'User-Agent': generateRandomUserAgent(), 'X-Forwarded-For': generateRandomIP() } }); const lines = anu.data.split('\n'); const processStartsLine = lines.find(line => line.includes('process_completed')); if (processStartsLine) { const processStartsData = JSON.parse(processStartsLine.replace('data: ', '')); let ress = processStartsData.output.data; let result = ress[0][0][1]; return result; } else { return 'error kang!'; } } catch (error) { console.error(error); return 'error kang!'; } } data = await gpt4o(q) //return res.json({message: 'Terkena Chaptcha BOT!!!'}) } return res.json({message: "Success", code: 200, data:data}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/whatmusic', async (req, res) => { try { let { url } = req.query async function downloadBuffer(url) { try { const response = await axios({ method: 'get', url: url, responseType: 'arraybuffer' }); return Buffer.from(response.data, 'binary'); } catch (error) { throw new Error(`Failed to download the file: ${error.message}`); } } if (!url) return res.json({ message: 'Input parameter url' }); if (!isUrl(url)) return res.json({ message: 'Invalit Input Link' }) let data = await acrCloud(await downloadBuffer(isUrl(url)[0])) if (!data) return res.json({ error: 'Error'}); return res.json({message: "Success", code: 200, data:data}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/eval', async (req, res) => { let evalCmd = ''; try { let q = req.query.q || req.query.query; if (!q) return res.json({ message: 'Input parameter q' }); evalCmd = /await/i.test(q) ? eval('(async() => { ' + q + ' })()') : eval(q); } catch (e) { evalCmd = e; } new Promise((resolve, reject) => { try { resolve(evalCmd); } catch (err) { reject(err); } }) ?.then(alok =>{ let result = util.format(alok) return res.json({message: "Success", code: 200, data: result}); }) ?.catch(err => { return res.json({ message: "Internal Server Error", code: 500, message: util.format(err) }); }); }) .get('/ytsearch', async (req, res) => { try { let q = req.query.q || req.query.query; if (!q) return res.json({ message: 'Input parameter q' }); let aloka = await yts(q); if (!aloka?.all[0]) return res.json({ message: 'Not found' }); return res.json({message: "Success", code: 200, data: aloka?.all}); } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .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({message: "Success", code: 200, data:data}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/ytdl', async (req, res) => { try { let { url } = req.query; //if (!ytIdRegex.test(url)) return res.json({ message: 'Invalid URL' }); if (!ytdl.validateURL(url)) return res.json({ message: 'Invalid URL' }); let data = await ytAPI(url) || {}; let videoID = ytdl.getVideoID(url); let dataInfo = await yts({ videoId: videoID }) || {}; //let otherAPI = await (await axios.get("https://line.1010diy.com/web/free-mp3-finder/detail?url="+url))?.data?.data ? await (await axios.get("https://line.1010diy.com/web/free-mp3-finder/detail?url="+url))?.data?.data : null let response = { ...dataInfo, mp4: data.mp4_url, mp3: data.mp3_url, //other: otherAPI || null }; return res.json({message: "Success", code: 200, data:response}); } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/twitter', async (req, res) => { try { let { url } = req.query; url = url.replace('x.com', 'twitter.com'); // Mengganti x.com dengan twitter.com dalam URL if (!/(https?:\/\/(www\.)?(twitter|x)\.com\/.*\/status\/.*)/.test(url)) { return res.json({ message: 'Invalid URL' }); } let data = await twitterDL(url); return res.json({message: "Success", code: 200, data: data}); } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/googleSearch', async (req, res) => { try { let q = req.query.q || req.query.query; if (!q) return res.json({ message: 'Input parameter q' }); let get = await (require("google-it"))({"query": q}) return res.json({message: "Success", code: 200, data: get}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/gimage', async (req, res) => { try { let q = req.query.q || req.query.query; if (!q) return res.json({ message: 'Input parameter q' }); let get = await (require("async-g-i-s"))(q) return res.json({message: "Success", code: 200, data: get}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/mega', async (req, res) => { try { let { url } = req.query; if (!/https:\/\/mega\.nz\/file\/[a-zA-Z0-9]{8}#[a-zA-Z0-9-_]{43}/.test(url)) { return res.json({ message: 'Invalid URL' }); } const file = File.fromURL(url); await file.loadAttributes(); let data = await file.downloadBuffer(); mimes.types['py'] = 'text/x-python'; // Python mimes.types['java'] = 'text/x-java-source'; // Java mimes.types['c'] = 'text/x-c'; // C mimes.types['cpp'] = 'text/x-c++src'; // C++ mimes.types['cc'] = 'text/x-c++src'; // C++ mimes.types['cxx'] = 'text/x-c++src'; // C++ mimes.types['cs'] = 'text/x-csharp'; // C# mimes.types['php'] = 'application/x-httpd-php'; // PHP mimes.types['rb'] = 'text/x-ruby'; // Ruby mimes.types['pl'] = 'text/x-perl'; // Perl mimes.types['sh'] = 'application/x-sh'; // Shell Script mimes.types['go'] = 'text/x-go'; // Go mimes.types['swift'] = 'text/x-swift'; // Swift mimes.types['kt'] = 'text/x-kotlin'; // Kotlin mimes.types['rs'] = 'text/x-rustsrc'; // Rust mimes.types['scala'] = 'text/x-scala'; // Scala mimes.types['r'] = 'text/x-r-source'; // R mimes.types['R'] = 'text/x-r-source'; // R (alternatif untuk huruf besar) mimes.types['lua'] = 'text/x-lua'; // Lua mimes.types['md'] = 'text/markdown'; // Markdown mimes.types['json'] = 'application/json'; // JSON mimes.types['js'] = 'application/javascript'; // JavaScript mimes.types['ts'] = 'application/x-typescript'; // TypeScript mimes.types['xml'] = 'application/xml'; // XML mimes.types['yaml'] = 'application/x-yaml'; // YAML mimes.types['yml'] = 'application/x-yaml'; // YAML (alternatif) mimes.types['html'] = 'text/html'; // HTML mimes.types['htm'] = 'text/html'; // HTML (alternatif) mimes.types['css'] = 'text/css'; // CSS mimes.types['scss'] = 'text/x-scss'; // SCSS (Sass) mimes.types['sass'] = 'text/x-sass'; // Sass mimes.types['less'] = 'text/x-less'; // Less mimes.types['coffee'] = 'text/coffeescript'; // CoffeeScript mimes.types['dart'] = 'application/dart'; // Dart mimes.types['sql'] = 'application/sql'; // SQL mimes.types['vb'] = 'text/x-vbscript'; // VBScript mimes.types['vbs'] = 'text/x-vbscript'; // VBScript (alternatif) mimes.types['bat'] = 'application/x-msdos-program'; // Batch script mimes.types['cmd'] = 'application/cmd'; // Command script mimes.types['ps1'] = 'application/x-powershell'; // PowerShell script mimes.types['ini'] = 'text/plain'; // INI file mimes.types['toml'] = 'application/toml'; // TOML mimes.types['cfg'] = 'text/plain'; // Configuration file mimes.types['conf'] = 'text/plain'; // Configuration file mimes.types['properties'] = 'text/plain'; // Properties file mimes.types['log'] = 'text/plain'; // Log file mimes.types['yml'] = 'application/x-yaml'; // YAML file mimes.types['rst'] = 'text/x-rst'; // reStructuredText mimes.types['latex'] = 'application/x-latex'; // LaTeX mimes.types['tex'] = 'application/x-tex'; // TeX mimes.types['bib'] = 'text/x-bibtex'; // BibTeX mimes.types['mat'] = 'application/x-matlab-data'; // MATLAB mimes.types['m'] = 'text/x-matlab'; // MATLAB or Objective-C mimes.types['octave'] = 'text/x-octave'; // GNU Octave mimes.types['rmd'] = 'text/x-r-markdown'; // R Markdown mimes.types['jl'] = 'text/x-julia'; // Julia mimes.types['clj'] = 'text/x-clojure'; // Clojure mimes.types['cljs'] = 'text/x-clojurescript'; // ClojureScript mimes.types['cljc'] = 'text/x-clojure'; // Clojure (Common) mimes.types['erl'] = 'text/x-erlang'; // Erlang mimes.types['hs'] = 'text/x-haskell'; // Haskell mimes.types['lhs'] = 'text/x-literate-haskell'; // Literate Haskell mimes.types['ml'] = 'text/x-ocaml'; // OCaml mimes.types['mli'] = 'text/x-ocaml'; // OCaml Interface mimes.types['fs'] = 'text/x-fsharp'; // F# mimes.types['fsi'] = 'text/x-fsharp'; // F# Interactive mimes.types['fsx'] = 'text/x-fsharp'; // F# Script mimes.types['fsscript'] = 'text/x-fsharp'; // F# Script (alternative) mimes.types['elm'] = 'text/x-elm'; // Elm mimes.types['elm'] = 'application/elm'; // Elm (alternative) mimes.types['ex'] = 'text/x-elixir'; // Elixir mimes.types['exs'] = 'text/x-elixir'; // Elixir Script mimes.types['eex'] = 'text/x-eex'; // Elixir Embedded Templates mimes.types['html.eex'] = 'text/x-html-elixir'; // Elixir HTML Embedded Templates mimes.types['hx'] = 'text/x-haxe'; // Haxe mimes.types['hxml'] = 'application/hxml'; // Haxe XML mimes.types['sml'] = 'text/x-sml'; // Standard ML mimes.types['thy'] = 'text/x-isabelle-theory'; // Isabelle Theory mimes.types['lean'] = 'text/x-lean'; // Lean mimes.types['v'] = 'text/x-verilog'; // Verilog mimes.types['sv'] = 'text/x-systemverilog'; // SystemVerilog mimes.types['vhd'] = 'text/x-vhdl'; // VHDL mimes.types['vhdl'] = 'text/x-vhdl'; // VHDL (alternative) mimes.types['scm'] = 'text/x-scheme'; // Scheme mimes.types['ss'] = 'text/x-scheme'; // Scheme (alternative) mimes.types['rkt'] = 'text/x-racket'; // Racket mimes.types['lisp'] = 'text/x-common-lisp'; // Common Lisp mimes.types['asd'] = 'text/x-common-lisp'; // Common Lisp ASDF mimes.types['cl'] = 'text/x-common-lisp'; // Common Lisp (alternative) mimes.types['el'] = 'text/x-emacs-lisp'; // Emacs Lisp mimes.types['sc'] = 'text/x-supercollider'; // SuperCollider mimes.types['f'] = 'text/x-fortran'; // Fortran mimes.types['f90'] = 'text/x-fortran'; // Fortran (alternative) mimes.types['f95'] = 'text/x-fortran'; // Fortran (alternative) mimes.types['v'] = 'text/x-vim'; // Vim Script mimes.types['pro'] = 'text/x-prolog'; // Prolog mimes.types['pl'] = 'text/x-prolog'; // Prolog (alternative to Perl) mimes.types['p'] = 'text/x-pascal'; // Pascal mimes.types['pas'] = 'text/x-pascal'; // Pascal (alternative) mimes.types['d'] = 'text/x-d'; // D mimes.types['ada'] = 'text/x-ada'; // Ada mimes.types['adb'] = 'text/x-ada'; // Ada Body mimes.types['ads'] = 'text/x-ada'; // Ada Specification mimes.types['nim'] = 'text/x-nim'; // Nim mimes.types['nimble'] = 'text/x-nim'; // Nimble mimes.types['cr'] = 'text/x-crystal'; // Crystal mimes.types['cl'] = 'text/x-clarion'; // Clarion mimes.types['prg'] = 'text/x-clarion'; // Clarion Program mimes.types['l'] = 'text/x-lex'; // Lex/Flex mimes.types['yy'] = 'text/x-bison'; // Bison/Yacc mimes.types['bison'] = 'text/x-bison'; // Bison/Yacc (alternative) mimes.types['mly'] = 'text/x-menhir'; // Menhir let {fileTypeFromBuffer} = await (await import('file-type')) return res.json({ message:"Success", code: 200, result : {name: file?.name, fileSize: file?.size || 0, size: formatSize(file?.size) || "0 B", mimetype: mimes.lookup(file?.name) || (await fileTypeFromBuffer(data))?.mime || "application/octet-stream", ext: mimes.extension(mimes.lookup(file?.name)) || (await fileTypeFromBuffer(data))?.ext || file?.name?.split(".")[1] || "bin", data: await fileDitch(Buffer.from(data), mimes.extension(mimes.lookup(file?.name)) || (await fileTypeFromBuffer(data))?.ext || file?.name?.split(".")[1] || "bin"), } }) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .get('/spotifySearch', async (req, res) => { try { async function spotifySearch(query) { let acc = JSON.parse(process.env.ALL_ACC_SPOTIFY) acc = acc[Math.floor(Math.random() * acc.length)]; async function getToken() { try { const response = await axios.post( "https://accounts.spotify.com/api/token", new URLSearchParams({ grant_type: "client_credentials", client_id: acc?.id, client_secret: acc?.secret, }), { headers: { "Content-Type": "application/x-www-form-urlencoded", }, } ); return response.data.access_token; } catch (error) { return null; } } const token = await getToken(); if (!token) { return []; } async function searchSpotifyTrack(query, token) { const url = "https://api.spotify.com/v1/search"; const config = { headers: { Authorization: `Bearer ${token}`, }, params: { q: query, type: "track", market: "ID", include_external: "audio", }, }; try { const response = await axios.get(url, config); const tracks = response.data.tracks.items; const trackInfo = tracks.map((track) => ({ name: track.name, artist: track.artists.map((artist) => artist.name).join(", "), album: track.album.name, id: track.album.id, release_date: track.album.release_date, url: track.external_urls.spotify, popularity: track.popularity, preview_url: track.preview_url, duration_ms: track.duration_ms, explicit: track.explicit, thumbnail: track.album.images[0] ? track.album.images[0].url : null, track_number: track.track_number, total_tracks: track.album.total_tracks, is_local: track.is_local, })); return trackInfo; } catch (error) { console.error( "Error searching Spotify track:", error.response ? error.response.data : error.message ); return []; } } async function getSpotifyInfoFromURL(url, token) { try { const spotifyId = url.split("/").pop().split("?")[0]; if (!spotifyId) return []; const response = await axios.get( `https://api.spotify.com/v1/tracks/${spotifyId}`, { headers: { Authorization: `Bearer ${token}`, }, } ); const track = response.data; return [ { name: track.name, artist: track.artists.map((artist) => artist.name).join(", "), album: track.album.name, id: track.album.id, release_date: track.album.release_date, url: track.external_urls.spotify, popularity: track.popularity, preview_url: track.preview_url, duration_ms: track.duration_ms, explicit: track.explicit, thumbnail: track.album.images[0] ? track.album.images[0].url : null, track_number: track.track_number, total_tracks: track.album.total_tracks, is_local: track.is_local, }, ]; } catch (error) { console.error( "Error fetching Spotify info from URL:", error.response ? error.response.data : error.message ); return []; } } let results = []; if (query.startsWith("https://open.spotify.com/track/")) { results = await getSpotifyInfoFromURL(query, token); } else { results = await searchSpotifyTrack(query, token); } return results; } let q = req.query.q || req.query.query; if (!q) return res.json({ message: 'Input parameter q' }); let get = await spotifySearch(q) return res.json({message: "Success", code: 200, data: get}) } catch (e) { console.log(e); return res.json({ message: "Internal Server Error", code: 500 }); } }) .use((req, res, next) => { res.redirect('/'); }) .listen(7860, () => console.log('App running on port 7860'));