spotifyd / app.js
Rianofc's picture
Update app.js
823a0a9 verified
const express = require('express');
const axios = require('axios');
const NodeCache = require('node-cache');
const crypto = require('crypto');
const path = require('path');
const app = express();
const cache = new NodeCache();
let idCounter = 1;
// Serve static files (HTML, CSS, JS)
app.use(express.static(path.join(__dirname)));
// Main UI
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Spotify Downloader UI
// Generate unique short key
function generateKey() {
const id = idCounter++;
const rand = crypto.randomBytes(3).toString('hex');
return `${id}-${rand}`;
}
// Scrape via RapidAPI using provided API key
async function aio(url) {
if (!url || !url.startsWith('https://')) throw new Error('Invalid URL');
const apiKey = '1dda0d29d3mshc5f2aacec619c44p16f219jsn99a62a516f98';
const { data } = await axios.post(
'https://auto-download-all-in-one.p.rapidapi.com/v1/social/autolink',
{ url },
{
headers: {
'content-type': 'application/json; charset=utf-8',
'accept-encoding': 'gzip',
'cache-control': 'no-cache',
'referer': 'https://auto-download-all-in-one.p.rapidapi.com/',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'x-rapidapi-host': 'auto-download-all-in-one.p.rapidapi.com',
'x-rapidapi-key': apiKey
}
}
);
return data;
}
/**
* Endpoint to scrape & shorten media URLs
* GET /proxy-url?url=<source_url>&ttlSeconds=<seconds>
*/
app.get('/proxy-url', async (req, res) => {
const { url, ttlSeconds } = req.query;
if (!url) return res.status(400).json({ error: 'Missing url parameter' });
try {
const result = await aio(url);
if (result.data && Array.isArray(result.data.medias)) {
result.data.medias = result.data.medias.map(media => {
const key = generateKey();
cache.set(key, media.url, ttlSeconds ? Number(ttlSeconds) : 0);
return { ...media, url: `${req.protocol}://${req.get('host')}/proxy-url/d/${key}` };
});
}
res.json(result);
} catch (err) {
console.error('Error in proxy-url:', err.message);
res.status(500).json({ error: err.message });
}
});
/**
* Download proxy endpoint
* GET /proxy-url/d/:key
*/
app.get('/proxy-url/d/:key', async (req, res) => {
const key = req.params.key;
const target = cache.get(key);
if (!target) return res.status(404).send('Link expired or invalid');
try {
const response = await axios.get(target, { responseType: 'stream' });
Object.entries(response.headers).forEach(([name, value]) => res.setHeader(name, value));
response.data.pipe(res);
} catch (err) {
console.error('Download error:', err.message);
res.status(502).send('Download failed');
}
});
// Health check
app.get('/health', (req, res) => res.send('OK'));
const PORT = process.env.PORT || 7860;
app.listen(PORT, () => console.log(`AIO Downloader running on port ${PORT}`));