Rianofc commited on
Commit
88690bd
·
verified ·
1 Parent(s): c291799

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +35 -53
app.js CHANGED
@@ -8,107 +8,89 @@ const app = express();
8
  const cache = new NodeCache();
9
  let idCounter = 1;
10
 
11
- app.use(express.json());
 
12
 
13
- // Serve the HTML UI
14
  app.get('/', (req, res) => {
15
  res.sendFile(path.join(__dirname, 'index.html'));
16
  });
17
 
18
- /**
19
- * Generate a unique short key composed of an incremental ID and random text.
20
- * Example: "23-ab12cd"
21
- */
22
  function generateKey() {
23
  const id = idCounter++;
24
  const rand = crypto.randomBytes(3).toString('hex');
25
  return `${id}-${rand}`;
26
  }
27
 
28
- /**
29
- * Scrape helper: uses RapidAPI auto-download service to resolve media URLs
30
- * @param {string} url - Original social media link
31
- * @returns {object} - Parsed response with download URLs
32
- */
33
  async function aio(url) {
34
- if (!url || !url.includes('https://')) {
35
- throw new Error('Url is required and must include https://');
36
- }
37
-
38
- const response = await axios.post(
39
  'https://auto-download-all-in-one.p.rapidapi.com/v1/social/autolink',
40
- { url: url },
41
  {
42
  headers: {
 
43
  'accept-encoding': 'gzip',
44
  'cache-control': 'no-cache',
45
- 'content-type': 'application/json; charset=utf-8',
46
- referer: 'https://auto-download-all-in-one.p.rapidapi.com/',
47
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
48
  'x-rapidapi-host': 'auto-download-all-in-one.p.rapidapi.com',
49
- // TODO: replace with your actual RapidAPI key
50
- 'x-rapidapi-key': '1dda0d29d3mshc5f2aacec619c44p16f219jsn99a62a516f98'
51
  }
52
  }
53
  );
54
- return response.data;
55
  }
56
 
57
  /**
58
- * Create a short proxy URL for downloading remote content. Optionally scrapes social links.
59
- * GET /proxy-url?url=<url>&ttlSeconds=<seconds>
60
  */
61
  app.get('/proxy-url', async (req, res) => {
62
  const { url, ttlSeconds } = req.query;
63
- if (!url || !url.startsWith('http')) {
64
- return res.status(400).json({ error: 'Missing or invalid "url" query parameter' });
65
- }
66
 
67
- let targetUrl = url;
68
  try {
69
- const data = await aio(url);
70
- if (data.url) {
71
- targetUrl = data.url;
72
- } else if (Array.isArray(data.data) && data.data[0] && data.data[0].url) {
73
- targetUrl = data.data[0].url;
 
 
74
  }
 
75
  } catch (err) {
76
- console.warn('Scrape failed, using original URL:', err.message);
 
77
  }
78
-
79
- const key = generateKey();
80
- const ttl = ttlSeconds ? Number(ttlSeconds) : 0;
81
- cache.set(key, targetUrl, ttl);
82
-
83
- const shortUrl = `${req.protocol}://${req.get('host')}/proxy-url/d/${key}`;
84
- res.json({ shortUrl });
85
  });
86
 
87
  /**
88
- * Proxy endpoint to stream content by key
89
  * GET /proxy-url/d/:key
90
  */
91
  app.get('/proxy-url/d/:key', async (req, res) => {
92
- const { key } = req.params;
93
- const url = cache.get(key);
94
- if (!url) {
95
- return res.status(404).send('Invalid or expired link');
96
- }
97
 
98
  try {
99
- const response = await axios.get(url, { responseType: 'stream' });
100
- Object.entries(response.headers).forEach(([name, value]) => {
101
- res.setHeader(name, value);
102
- });
103
  response.data.pipe(res);
104
  } catch (err) {
105
  console.error('Download error:', err.message);
106
- res.status(502).send('Failed to download the requested resource');
107
  }
108
  });
109
 
110
  // Health check
111
  app.get('/health', (req, res) => res.send('OK'));
112
 
113
- const PORT = process.env.PORT || 7860;
114
  app.listen(PORT, () => console.log(`AIO Downloader running on port ${PORT}`));
 
8
  const cache = new NodeCache();
9
  let idCounter = 1;
10
 
11
+ // Serve static files (HTML, CSS, JS)
12
+ app.use(express.static(path.join(__dirname)));
13
 
14
+ // Main UI
15
  app.get('/', (req, res) => {
16
  res.sendFile(path.join(__dirname, 'index.html'));
17
  });
18
 
19
+ // Spotify Downloader UI
20
+ // Generate unique short key
 
 
21
  function generateKey() {
22
  const id = idCounter++;
23
  const rand = crypto.randomBytes(3).toString('hex');
24
  return `${id}-${rand}`;
25
  }
26
 
27
+ // Scrape via RapidAPI using provided API key
 
 
 
 
28
  async function aio(url) {
29
+ if (!url || !url.startsWith('https://')) throw new Error('Invalid URL');
30
+ const apiKey = '1dda0d29d3mshc5f2aacec619c44p16f219jsn99a62a516f98';
31
+ const { data } = await axios.post(
 
 
32
  'https://auto-download-all-in-one.p.rapidapi.com/v1/social/autolink',
33
+ { url },
34
  {
35
  headers: {
36
+ 'content-type': 'application/json; charset=utf-8',
37
  'accept-encoding': 'gzip',
38
  'cache-control': 'no-cache',
39
+ 'referer': 'https://auto-download-all-in-one.p.rapidapi.com/',
 
40
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
41
  'x-rapidapi-host': 'auto-download-all-in-one.p.rapidapi.com',
42
+ 'x-rapidapi-key': apiKey
 
43
  }
44
  }
45
  );
46
+ return data;
47
  }
48
 
49
  /**
50
+ * Endpoint to scrape & shorten media URLs
51
+ * GET /proxy-url?url=<source_url>&ttlSeconds=<seconds>
52
  */
53
  app.get('/proxy-url', async (req, res) => {
54
  const { url, ttlSeconds } = req.query;
55
+ if (!url) return res.status(400).json({ error: 'Missing url parameter' });
 
 
56
 
 
57
  try {
58
+ const result = await aio(url);
59
+ if (result.data && Array.isArray(result.data.medias)) {
60
+ result.data.medias = result.data.medias.map(media => {
61
+ const key = generateKey();
62
+ cache.set(key, media.url, ttlSeconds ? Number(ttlSeconds) : 0);
63
+ return { ...media, url: `${req.protocol}://${req.get('host')}/proxy-url/d/${key}` };
64
+ });
65
  }
66
+ res.json(result);
67
  } catch (err) {
68
+ console.error('Error in proxy-url:', err.message);
69
+ res.status(500).json({ error: err.message });
70
  }
 
 
 
 
 
 
 
71
  });
72
 
73
  /**
74
+ * Download proxy endpoint
75
  * GET /proxy-url/d/:key
76
  */
77
  app.get('/proxy-url/d/:key', async (req, res) => {
78
+ const key = req.params.key;
79
+ const target = cache.get(key);
80
+ if (!target) return res.status(404).send('Link expired or invalid');
 
 
81
 
82
  try {
83
+ const response = await axios.get(target, { responseType: 'stream' });
84
+ Object.entries(response.headers).forEach(([name, value]) => res.setHeader(name, value));
 
 
85
  response.data.pipe(res);
86
  } catch (err) {
87
  console.error('Download error:', err.message);
88
+ res.status(502).send('Download failed');
89
  }
90
  });
91
 
92
  // Health check
93
  app.get('/health', (req, res) => res.send('OK'));
94
 
95
+ const PORT = process.env.PORT || 3000;
96
  app.listen(PORT, () => console.log(`AIO Downloader running on port ${PORT}`));