| const express = require('express') | |
| const axios = require('axios') | |
| const Spotify = require('./lib/spotify.js') | |
| const app = express() | |
| app.set('json spaces', 2) | |
| const PORT = 7860 | |
| let totalRequest = 0 | |
| app.use((req, res, next) => { | |
| totalRequest++ | |
| next() | |
| }) | |
| app.all('/', (req, res) => { | |
| res.json({ uptime: new Date(process.uptime() * 1000).toUTCString().split(' ')[4], totalRequest }) | |
| }) | |
| app.all('/search', async (req, res) => { | |
| try { | |
| const { q, type = "track", limit = 10 } = req.query | |
| if (!q) return res.json({ status: false, error: '"q" parameter is undefined!' }) | |
| const search = await Spotify.search(q, type, limit) | |
| res.json(search) | |
| } catch (e) { | |
| res.json({ status: false, error: e?.message || e }) | |
| } | |
| }) | |
| app.all('/play', async (req, res) => { | |
| try { | |
| const { q } = req.query | |
| if (!q) return res.json({ status: false, error: '"q" parameter is undefined!' }) | |
| const search = await Spotify.search(q, "track", 1) | |
| const track = Array.isArray(search) ? search[0] : search | |
| const id = track?.id | |
| if (!id) return res.json({ status: false, error: 'No valid track found.' }) | |
| res.json({ status: true, result: track, download: `https://${req.hostname}/track/${id}` }) | |
| } catch (e) { | |
| res.json({ status: false, error: e?.message || e }) | |
| } | |
| }) | |
| app.all('/track/:id', async (req, res) => { | |
| try { | |
| const { id } = req.params | |
| if (!id) return res.json({ status: false, error: 'Track ID is not valid.' }) | |
| const dl = await Spotify.download(`https://open.spotify.com/track/${id}`) | |
| const url = dl?.download | |
| if (!url) return res.json({ status: false, error: 'cant find download url!' }) | |
| const response = await axios({ | |
| url, | |
| method: 'GET', | |
| responseType: 'stream' | |
| }) | |
| res.setHeader('Content-Disposition', `attachment; filename="${id}.mp3"`) | |
| res.setHeader('Content-Type', 'audio/mpeg') | |
| response.data.pipe(res) | |
| } catch (e) { | |
| res.json({ status: false, error: e?.message || e }) | |
| } | |
| }) | |
| app.listen(PORT) |