aboutsummaryrefslogtreecommitdiffstats
path: root/pages/api/youtube/player.js
blob: a6d3a7e69927f152f9d5660f267e8c346347351d (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
import withSession from 'hocs/withSession'
import ytdl from 'ytdl-core'

const getId = url => {
  const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/
  const match = url.match(regExp)
  return (match && match[7].length === 11) ? match[7] : false
}

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

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

        const info = await ytdl.getInfo(getId(url))

        res.status(200).json(info)
      } catch (error) {
        res.status(400).json([])
      }
      break
    default:
      res.status(400).send()
      break
  }
})