aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/radio/stream.js
blob: 42e8521d80999e8b7c6dd29e9f0203ee5e78243b (plain) (blame)
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
import withSession from 'hocs/withSession'

export default withSession(async (req, res) => {
  switch (req.method) {
    case 'POST':
      try {
        const user = req.session.get('user')
        const { station } = JSON.parse(req.body)

        if (!user || !user?.isVerified || !station) {
          throw new Error('Something went wrong')
        }

        const response = await fetch(station.replace('radios', 'radios/play'))
        const data = await response.text()

        const script = /(?<=ST\.radio = {)[\s\S]*?(?=script)/.exec(data)?.[0]
        const url = /(?<=url: ").*(?=")/.exec(script)?.[0]
        const mimeType = /(?<=content_type: ").*(?=")/.exec(script)?.[0]

        const songImage = /(?<="song-image")[\s\S]*?(?=div)/.exec(data)?.[0]
        const thumbnail = /(?<=src\=").*(?=")/.exec(songImage)?.[0]

        res.status(200).json({url, mimeType, thumbnail})
      } catch (error) {
        console.log(error)
        res.status(400).send('')
      }
      break
    default:
      res.status(400).send('')
      break
  }
})