Spaces:
Paused
Paused
Update index.js
Browse files8 unmodified lines91011121314151617181920212219202122232425262728293031323334353637383940414243444546474849505123242555262728293031326133343536373839404142434445467 unmodified lines545556575859606162848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264276364656611 unmodified lines787980818283844 unmodified lines899091929394951 unmodified line9798991001011024641031041051061071081091101111121131141151161171184704711191201211221231241251261274731281291301311321331341351361371381391401411 unmodified line1431441451461471481493 unmodified lines1531541551561571581591601611621631641651661672 unmodified lines1701711725075085095105115125135145155161731741751761771781791801811821831841851861871881 unmodified line1901911925241931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653662 unmodified lines3693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265475275288 unmodified linesimport nodeID3 from 'node-id3';import ytdl from 'ytdl-core';import FormData from 'form-data';import fetch from 'node-fetch';
const require = createRequire(import.meta.url);const fs = require('fs');const path = require('path');const { google } = require('googleapis');const puppeteer = require('puppeteer');
const PORT = process.env.PORT || 7860;const app = express();const readFileAsync = promisify(fs.readFile);import fetch from 'node-fetch';
const puppeteer = require('puppeteer');
// Function to ping a websiteasync function pingWebsite() { const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const page = await browser.newPage(); await page.setUserAgent("Mozilla/5.0 (Linux; Android 10; SM-G965U Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.141 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/420.0.0.32.61;]");
await page.goto('https://huggingface.co/spaces/ArashiCode/api'); console.log("ping") await browser.close();}
// Ping website every 5 hoursasync function pingEvery5Hours() { await pingWebsite(); setInterval(async () => { await pingWebsite(); }, 5 * 60 * 60 * 1000); // 5 hours in milliseconds}
// Start pingingpingEvery5Hours();
const tempDir = path.join(os.tmpdir(), "temp");const fss = fs.promises;
const __dirname = path.dirname(fileURLToPath(import.meta.url));// Membuat direktori sementara jika belum ada(async () => { if (!fs.existsSync(tempDir)) { await fss.mkdir(tempDir, { recursive: true }); }})();
const execPromise = promisify(exec);const youtube = google.youtube({ version: 'v3', auth: 'AIzaSyBPkpdJEGtAHebbaP3_CcA1_urfMFfeLLg' });
const tempDirBase = tempDir
app.use('/temp', express.static(tempDir));app.use(express.json());
app.get("/", (req, res) => { res.type("json"); const keluaran = {7 unmodified lines res.send(keluaran);});
// Fungsi untuk menghasilkan IP acakconst generateRandomIP = () => { const octet = () => Math.floor(Math.random() * 256); return `${octet()}.${octet()}.${octet()}.${octet()}`;};
async function igdl1(url) { const apiEndpoint = 'https://v3.igdownloader.app/api/ajaxSearch'; const requestOptions = { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]', 'Referer': 'https://igdownloader.app/en', 'X-Forwarded-For': generateRandomIP() }, }; const postData = `recaptchaToken=&q=${encodeURIComponent(url)}&t=media&lang=en`; try { const response = await axios.post(apiEndpoint, postData, requestOptions); const $ = cheerio.load(response.data.data); const downloadLinks = $('div.download-items__btn > a'); return await Promise.all(downloadLinks.map(async (index, element) => $(element).attr('href'))); } catch (error) { console.error('Instagram Downloader 1 - Error:', error.message); return null; }}
async function igdl2(url) { try { const response = await axios.post('https://fastdl.app/c/', { url: url, lang_code: 'en', token: '' }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36', 'Referer': 'https://fastdl.app/' }, responseType: 'arraybuffer' }); const html = response.data.toString('utf-8'); const $ = cheerio.load(html); $('img').remove(); const links = []; $('a').each((index, element) => links.push($(element).attr('href'))); return links; } catch (error) { console.error('Error downloading Instagram post:', error); return null; }}
async function igdl3(url) { const apiEndpoint = 'https://co.wuk.sh/api/json'; const requestData = { url, aFormat: 'mp3', filenamePattern: 'classic', dubLang: false, vQuality: '720' }; const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36', 'Referer': 'https://cobalt.tools/', }; try { const response = await axios.post(apiEndpoint, requestData, { headers }); const array_res = []; if (response.data.status === 'redirect') { array_res.push(response.data.url); } else if (response.data.status === 'picker') { response.data.picker.forEach(item => array_res.push(item.url)); } return array_res; } catch (error) { console.error('Instagram Downloader 3 - Error:', error.message); return null; }}
async function igdl4(url) { try { const apiEndpoint = 'https://v3.saveig.app/api/ajaxSearch'; const requestOptions = { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': '*/*', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]', 'Referer': 'https://saveig.app/en', }, }; const postData = `recaptchaToken=&q=${encodeURIComponent(url)}&t=media&lang=en`; const response = await axios.post(apiEndpoint, postData, requestOptions); const $ = cheerio.load(response.data.data); const downloadLinks = $('div.download-items__btn > a'); return await Promise.all(downloadLinks.map(async (index, element) => $(element).attr('href'))); } catch (error) { console.error('Instagram Downloader 4 - Error:', error.message); return null; }}
async function twdl1(url) { const apiUrl = 'https://savetwitter.net/api/ajaxSearch'; const headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]', 'Referer': 'https://x2twitter.com/id', 'X-Forwarded-For': generateRandomIP(), }; const data = `q=${encodeURIComponent(url)}&lang=id`;
try { const response = await axios.post(apiUrl, data, { headers }); if (!response.data.hasOwnProperty('data')) { throw new Error('Data tidak ditemukan di response'); } const $ = cheerio.load(response.data.data);
$('a[onclick="showAd()"][href="#"]').remove(); $('a[href="/"]').remove(); $('a[href="#"]').remove();
const hrefs = []; $('.dl-action').each((index, element) => { const firstAnchor = $(element).find('a').first(); hrefs.push(firstAnchor.attr('href')); });
return hrefs;
} catch (error) { throw new Error('Failed to fetch Twitter image: ' + error); }}
async function twdl2(url) { const apiUrl = 'https://x2twitter.com/api/ajaxSearch'; const headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]', 'Referer': 'https://x2twitter.com/id', 'X-Forwarded-For': generateRandomIP(), }; const data = `q=${encodeURIComponent(url)}&lang=id`;
try { const response = await axios.post(apiUrl, data, { headers }); if (!response.data.hasOwnProperty('data')) { throw new Error('Data tidak ditemukan di response'); } const $ = cheerio.load(response.data.data);
$('a[onclick="showAd()"][href="#"]').remove(); $('a[href="/"]').remove();
const hrefs = []; $('.dl-action').each((index, element) => { const firstAnchor = $(element).find('a').first(); hrefs.push(firstAnchor.attr('href')); });
return hrefs;
} catch (error) { throw new Error('Failed to fetch Twitter image: ' + error); }}
async function twdl3(url) { const apiUrl = 'https://twtube.app/en/download?url=';
const headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'User-Agent': 'Mozilla/5.0 (Linux; Android 12; SM-S908B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/99.0.4844.58 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/357.0.0.23.115;]', 'Referer': 'https://savetwitter.net/id/twitter-image-downloader', 'X-Forwarded-For': generateRandomIP(), }; try { const response = await axios.get(apiUrl + url, { headers }); const $ = cheerio.load(response.data); // Mendapatkan semua href dari elemen a dalam div dengan kelas 'square-box-btn' const allHrefs = []; // Menggunakan map untuk mengambil href dan mengembalikan array promise const promises = $('.square-box-btn a').map(async (index, element) => { let link = $(element).attr('href'); return link; }).get(); // Menunggu semua promise selesai dan mengumpulkan hasilnya return Promise.all(promises); } catch (error) { throw new Error('Failed to fetch Twitter image: ' + error); }}
async function DownloadFile(url) { try { const response = await axios.get(url, { responseType: 'arraybuffer' }); const mimeType = response.headers['content-type']; const buffer = response.data; const fileExtension = (await fileTypeFromBuffer(buffer)).ext; const filename = `downloaded_file_${Date.now()}.${fileExtension}`; const filePath = path.join(tempDir, filename); await fss.writeFile(filePath, buffer); console.log(`File berhasil diunduh dan disimpan sebagai: ${filePath}`); return { mimeType, filePath }; } catch (error) { console.error('Error saat mengunduh file:', error); return null; }}
const getInstagramDownloadLinks = async (url) => { let result = await igdl1(url); if (!result || result.length === 0) { result = await igdl2(url); } if (!result || result.length === 0) { result = await igdl3(url); } if (!result || result.length === 0) { result = await igdl4(url); } if (!result || result.length === 0) { result = { message: "all server error" }; } return result;};
const Twitter = async (url) => { let result = await twdl3(url); if (!result || result.length === 0) { result = await twdl2(url); } if (!result || result.length === 0) { result = await twdl1(url); } if (!result || result.length === 0) { result = { message: "all server error" }; } return result;};
app.get('/igdl', async (req, res) => { try { const { url } = req.query; if (!url) return res.status(400).json({ error: 'Parameter url is required' }); if (!/https?:\/\/(www\.)?instagram\.com\/(p|reel|tv)/.test(url)) return res.status(400).json({ error: "Example: https://www.instagram.com/p/Cz1fTwMJFpx/?igsh=MXRrY2g4eWNucGoyZg==" }); let result = await getInstagramDownloadLinks(url); let result_upload = { media: [] }
for (let item of result) { let unduh = await DownloadFile(item); result_upload.media.push({ type: unduh.mimeType, path: unduh.filePath, url_path: `https://arashicode-api.hf.space/temp/${path.basename(unduh.filePath)}` }); }
res.json(result_upload);
for (let item of result_upload.media) { try { await new Promise(resolve => setTimeout(resolve, 10 * 60 * 1000)); // 10 minutes await fss.unlink(item.path); console.log(`File ${item.path} deleted.`); } catch (error) { console.error(`Error deleting file ${item.path}:`, error); } } } catch (error) { console.error('Error processing request:', error); res.status(500).json({ error: 'Failed to process request\n' + error }); }});
app.get('/twdl', async (req, res) => { try { const { url } = req.query; if (!url) return res.status(400).json({ error: 'Parameter url is required' }); let result = await Twitter(url); let result_upload = { media: [] }
for (let item of result) { let unduh = await DownloadFile(item); result_upload.media.push({ type: unduh.mimeType, path: unduh.filePath, url_path: `https://arashicode-api.hf.space/temp/${path.basename(unduh.filePath)}`, url_path2: `http://${os.hostname()}:${PORT}/temp/${path.basename(unduh.filePath)}` }); }
res.json(result_upload);
for (let item of result_upload.media) { try { await new Promise(resolve => setTimeout(resolve, 10 * 60 * 1000)); // 10 minutes await fss.unlink(item.path); console.log(`File ${item.path} deleted.`); } catch (error) { console.error(`Error deleting file ${item.path}:`, error); } } } catch (error) { console.error('Error processing request:', error); res.status(500).json({ error: 'Failed to process request\n' + error }); }});
/****YTMP3YTMP3YTMP3YTMP3*****/// Fungsi untuk upload fileasync function uploader(buffer) { const { ext } = await fileTypeFromBuffer(buffer); const bodyForm = new FormData();11 unmodified lines };}
// Fungsi untuk mendapatkan URL thumbnail HDasync function getHDThumbnailUrl(videoId) { try { const response = await youtube.videos.list({ part: 'snippet', id: videoId });4 unmodified lines }}
// Fungsi untuk mendapatkan ID video dari URLasync function GetId(data) { const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtu(?:be\.com\/(?:watch\?(?:v=|vi=)|v\/|vi\/)|\.be\/|be\.com\/embed\/|be\.com\/shorts\/)|youtube\.com\/\?(?:v=|vi=))([\w-]{11})/; const res = regex.exec(data);1 unmodified line throw new Error("Please check the URL you have entered");}
// Fungsi untuk menambahkan tag ID3 ke file audioasync function addAudioTags(media, title, artist, year, imagecover) { try { let audioBuffer = (typeof media === 'string') ? Buffer.from((await axios.get(media, { responseType: 'arraybuffer', maxContentLength: -1 })).data) : (media instanceof Buffer) ? media : (() => { throw new Error('Media harus berupa URL string atau Buffer.'); })(); let audioBuffer; if (typeof media === 'string') { const response = await axios.get(media, { responseType: 'arraybuffer', maxContentLength: -1 }); audioBuffer = Buffer.from(response.data); } else if (media instanceof Buffer) { audioBuffer = media; } else { throw new Error('Media harus berupa URL string atau Buffer.'); }
const randomFilename = generateRandomName(10) + '.mp3'; const tmpFilePath = path.join(tempDir, randomFilename); fs.writeFileSync(tmpFilePath, audioBuffer);
const tags = { title, artist, year }; if (typeof imagecover === 'string') { const coverBuffer = Buffer.from((await axios.get(imagecover, { responseType: 'arraybuffer' })).data); tags.image = { mime: 'image/jpeg', type: { id: 3, name: 'Front Cover' }, description: 'Cover', imageBuffer: coverBuffer }; const response = await axios.get(imagecover, { responseType: 'arraybuffer' }); const coverBuffer = Buffer.from(response.data); tags.image = { mime: 'image/jpeg', type: { id: 3, name: 'Front Cover' }, description: 'Cover', imageBuffer: coverBuffer }; } else if (imagecover instanceof Buffer) { tags.image = { mime: 'image/jpeg', type: { id: 3, name: 'Front Cover' }, description: 'Cover', imageBuffer: imagecover }; tags.image = { mime: 'image/jpeg', type: { id: 3, name: 'Front Cover' }, description: 'Cover', imageBuffer: imagecover }; }
const success = nodeID3.write(tags, tmpFilePath); console[success ? 'log' : 'error'](success ? 'Tag ID3 berhasil diubah!' : 'Gagal mengubah tag ID3.');
return { msg: `Audio berhasil diubah.`, path: `${tmpFilePath}` }; } catch (error) { console.error('Terjadi kesalahan:', error);1 unmodified line }}
// Fungsi untuk menghasilkan nama acakfunction generateRandomName(length) { const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let randomName = '';3 unmodified lines return randomName;}
// Fungsi untuk mendapatkan URL audio MP3 dari video YouTubeasync function getAudioMP3Url(videoUrl) { try { const info = await ytdl.getInfo(videoUrl); const audioFormat = ytdl.chooseFormat(info.formats, { filter: 'audioonly', quality: 'highestaudio' }); const path_audio = path.join(tempDir, generateRandomName(10) + '.mp3'); let uploadResult; let convert;
await new Promise((resolve, reject) => { ffmpeg() .input(audioFormat.url)2 unmodified lines .outputOptions('-ab 128k') .outputOptions('-ar 44100') .on('end', async () => { const buffer = fs.readFileSync(path_audio); const id_video = await GetId(videoUrl); const hd_thumbnail = await getHDThumbnailUrl(id_video); const convert = await addAudioTags(buffer, info.videoDetails.title, info.videoDetails.ownerChannelName, 2024, hd_thumbnail); const buffer2 = fs.readFileSync(convert.path); uploadResult = await uploader(buffer2); console.log('Upload result:', uploadResult); fs.unlinkSync(path_audio); fs.unlinkSync(convert.path); resolve(uploadResult); try { const buffer = fs.readFileSync(path_audio); const id_video = await GetId(videoUrl); const hd_thumbnail = await getHDThumbnailUrl(id_video); convert = await addAudioTags(buffer, info.videoDetails.title, info.videoDetails.ownerChannelName, 2024, hd_thumbnail); const buffer2 = fs.readFileSync(convert.path);
fs.unlinkSync(path_audio);
resolve(); } catch (error) { reject(error); } }) .on('error', (err) => { console.error('FFmpeg conversion error:', err);1 unmodified line }) .save(path_audio); }); return uploadResult;
return { status: 200, title: info.videoDetails.title, result: { url_path: `https://${process.env.SPACE_HOST}/temp/${path.basename(convert.path)}`, curl_path: `https://${process.env.SPACE_HOST}/temp/${path.basename(convert.path)}?download=1&filename=${info.videoDetails.title}`, path: convert.path } }; } catch (error) { console.error('Error:', error); throw new Error('Failed to process audio URL'); }}
// Endpoint untuk mengunduh audio MP3 dari YouTubeapp.get('/ytmp3', async (req, res) => { try { const { url } = req.query; if (!url) return res.status(400).json({ error: 'Parameter url is required' });
let result = await getAudioMP3Url(url); res.json(result);
// Menghapus file setelah 10 menit try { await new Promise(resolve => setTimeout(resolve, 10 * 60 * 1000)); // 10 minutes await fss.unlink(result.result.path); console.log(`File ${result.result.path} deleted.`); } catch (error) { console.error(`Error deleting file ${result.result.path}:`, error); } } catch (error) { console.error('Error processing request:', error); res.status(500).json({ error: 'Failed to process request\n' + error }); }});
/*ββββββββββββββββββββββββββββββββββββββββββββββββ«β£βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ«β£βββββββββββββββββββββββββββββββββββββββββ*/
function generateRandomID(length = 8) { const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * characters.length)); } return result;}
async function komiku_download(url) { const instanceID = generateRandomID(); const tempDir = path.join(tempDirBase, instanceID); await fss.mkdir(tempDir);
// Extracting the title from the URL const title = url.split('/').filter(part => part).pop();
try { const response = await axios.get(url); const html = response.data; const $ = cheerio.load(html); const imgList = [];
$('#Baca_Komik img').each((index, element) => { const src = $(element).attr('src'); imgList.push({ path: src }); });
await processImages(imgList, tempDir, instanceID); const pdfPath = await createPDF(instanceID, tempDir);
console.log(`PDF berhasil dibuat: ${pdfPath}`); return { path: pdfPath, title: title, url: `https://${process.env.SPACE_HOST}/temp/${path.basename(pdfPathq)}` }; } catch (error) { console.log(error); throw error; } finally { await fss.rmdir(tempDir, { recursive: true }); }}
async function downloadImage(image, tempDir, instanceID) { const response = await axios.get(image.path, { responseType: 'arraybuffer' }); const imagePath = path.join(tempDir, `image_${instanceID}_${Date.now()}_${Math.floor(Math.random() * 1000)}.jpg`); await writeFileAsync(imagePath, response.data);
const imageHeight = await getImageHeight(imagePath); const command = `convert ${imagePath} -resize 720x -quality 75 -background white -gravity center -extent 720x${imageHeight} ${imagePath}`; await execPromise(command);
return imagePath;}
async function getImageHeight(imagePath) { const { stdout } = await execPromise(`identify -format "%h" ${imagePath}`); return parseInt(stdout.trim());}
async function processImages(imgList, tempDir, instanceID) { let partIndex = 0; let partImages = [];
for (let i = 0; i < imgList.length; i++) { const imagePath = await downloadImage(imgList[i], tempDir, instanceID); partImages.push(imagePath);
if (await getTotalHeight(partImages) > 64000) { await combineAndSave(partImages, partIndex, tempDir); partImages = []; partIndex++; } }
if (partImages.length > 0) { await combineAndSave(partImages, partIndex, tempDir); }}
async function getTotalHeight(imagePaths) { let totalHeight = 0; for (const imagePath of imagePaths) { totalHeight += await getImageHeight(imagePath); } return totalHeight;}
async function combineAndSave(imagePaths, partIndex, tempDir) { const combinedImagePath = path.join(tempDir, `combined_part_${partIndex}.jpg`); const command = `convert ${imagePaths.join(' ')} -append -quality 75 ${combinedImagePath}`; await execPromise(command);
imagePaths.forEach(fs.unlinkSync);
return combinedImagePath;}
async function createPDF(instanceID, tempDir) { const combinedParts = fs.readdirSync(tempDir).filter(file => file.startsWith('combined_part_')); const pdfPath = path.join(tempDir, `${instanceID}.pdf`); const createPDFCommand = `convert ${combinedParts.map(file => path.join(tempDir, file)).join(' ')} ${pdfPath}`; await execPromise(createPDFCommand); return pdfPath;}
app.get('/komiku/download', async (req, res) => { try { const { url } = req.query; if (!url) return res.status(400).json({ error: 'Parameter url is required' });
let result = await komiku_download(url); res.json(result);
// Menghapus file setelah 10 menit try { await new Promise(resolve => setTimeout(resolve, 10 * 60 * 1000)); // 10 minutes await fss.unlink(result.path); console.log(`File ${result.path} deleted.`); } catch (error) { console.error(`Error deleting file ${result.path}:`, error); } } catch (error) { console.error('Error processing request:', error); res.status(500).json({2 unmodified lines }});
/***********/
async function getLatestKomik(page) { const url = `https://api.komiku.id/manga/page/${page}/`; const headers = { 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36', 'Referer': 'https://komiku.id/pustaka/' };
try { const response = await axios.get(url, { headers }); const $ = cheerio.load(response.data); const mangaArray = [];
// Scraping data $('.bge').each((index, element) => { const title = $(element).find('.kan h3').text().trim(); const link_komik = $(element).find('.bgei a').attr('href'); const imgSrc = $(element).find('.bgei img').attr('src'); const type = $(element).find('.tpe1_inf b').text().trim(); const type2 = $(element).find('.tpe1_inf').text().trim(); const description = $(element).find('.kan p').text().trim(); const readersInfo = $(element).find('.judul2').text().trim(); const latestChapter = "https://komiku.id" + $(element).find('.new1:last-child a').attr('href');
mangaArray.push({ title, link_komik, imgSrc, type, type2, description, readersInfo, latestChapter }); });
return mangaArray; } catch (error) { console.error('Error fetching the URL', error); throw error; }}
async function GetKomik(url) { try { const response = await axios.get(url); const $ = cheerio.load(response.data);
const cover = $('#Informasi > div > img').attr('src'); const judul = $('#Informasi > table > tbody > tr:nth-child(1) > td:nth-child(2)').text().trim(); const jenis = $('#Informasi > table > tbody > tr:nth-child(3) > td:nth-child(2) > b').text().trim(); const konsepCerita = $('#Informasi > table > tbody > tr:nth-child(4) > td:nth-child(2)').text().trim(); const author = $('#Informasi > table > tbody > tr:nth-child(5) > td:nth-child(2)').text().trim(); const status = $('#Informasi > table > tbody > tr:nth-child(6) > td:nth-child(2)').text().trim(); const sinopsis = $('#Judul > p.desc').text().trim();
const genreElements = $('#Informasi > ul > li').map((i, el) => $(el).text().trim()).get();
const chapterElements = $('#daftarChapter > tr').map((i, el) => { if (i === 0) { return null; } return { judulSeries: $(el).find('td.judulseries > a').text().trim(), tanggalUpdate: $(el).find('td.tanggalseries').text().trim(), url: "https://komiku.id" + $(el).find('td.judulseries > a').attr('href') }; }).get().filter(chapter => chapter !== null);
const mangaInfo = { cover, judul, sinopsis, jenis, konsepCerita, author, status, genres: genreElements, chapters: chapterElements };
return mangaInfo; } catch (error) { console.error('Error fetching the URL', error); throw error; }}
app.get('/komiku/latest', async (req, res) => { try { const { page } = req.query; if (!page) return res.status(400).json({ error: 'Parameter page is required' });
let result = await getLatestKomik(page); res.json(result); } catch (error) { console.error('Error processing request:', error); res.status(500).json({ error: 'Failed to process request\n' + error }); }});
app.get('/komiku', async (req, res) => { try { const { url } = req.query; if (!url) return res.status(400).json({ error: 'Parameter url is required' });
let result = await GetKomik(url); res.json(result); } catch (error) { console.error('Error processing request:', error); res.status(500).json({ error: 'Failed to process request\n' + error }); }});
/*******************ββββββββββββββββββββββββββββββββββββββββββββββββ«β£βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ«β£βββββββββββββββββββββββββββββββββββββββββ*********************/
// Fungsi untuk ping websiteasync function pingWebsite() { const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const page = await browser.newPage(); await page.setUserAgent("Mozilla/5.0 (Linux; Android 10; SM-G965U Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.141 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/420.0.0.32.61;]"); await page.goto('https://huggingface.co/spaces/ArashiCode/api'); console.log("Ping"); await browser.close();}
// Ping website setiap 5 jamasync function pingEvery5Hours() { await pingWebsite(); setInterval(async () => { await pingWebsite(); }, 5 * 60 * 60 * 1000); // 5 hours in milliseconds}
// Mulai pingpingEvery5Hours();
app.listen(PORT, () => { console.log(`Server is running on port https://localhost:${PORT}`); console.log(`Server is running on port ${PORT}`);});index.js+375-395