File size: 2,003 Bytes
30c8700
 
 
f5299ac
 
 
 
 
 
 
30c8700
 
 
f5299ac
30c8700
f5299ac
 
 
30c8700
f5299ac
30c8700
 
f5299ac
30c8700
 
 
f5299ac
 
 
30c8700
f5299ac
30c8700
 
f5299ac
30c8700
 
 
 
 
 
f5299ac
 
 
30c8700
f5299ac
30c8700
 
078cb71
 
 
 
30c8700
 
 
 
 
 
 
034df1b
30c8700
 
 
 
f5299ac
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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)