Skip to content

Instantly share code, notes, and snippets.

@fuongz
Created July 4, 2022 14:51
Show Gist options
  • Save fuongz/f90ed6edceb86a470f51c6e0eb762845 to your computer and use it in GitHub Desktop.
Save fuongz/f90ed6edceb86a470f51c6e0eb762845 to your computer and use it in GitHub Desktop.
import type { NextApiRequest, NextApiResponse } from 'next'
const getYoutubePlaylistId = (url: string): string => {
const regExp = /list=([^&]+)/
const match = regExp.exec(url)
if (match) {
return match[1]
}
return ''
}
const buildYoutubeUrl = (id: string): string => {
return `https://www.youtube.com/playlist?list=${id}`
}
const isUrl = (url: string): boolean => {
const regExp = /^(http|https):\/\//
return regExp.test(url)
}
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
if (req.method === 'POST') {
const { url } = req.body
let youtubeId = url
if (isUrl(url)) {
youtubeId = getYoutubePlaylistId(url)
}
const response = await fetch(buildYoutubeUrl(youtubeId))
const data: any = await response.text()
const extract = data
.substring(data.indexOf('var ytInitialData =') + 20, data.lastIndexOf('}}};</script><script nonce') + 3)
.replace(/\n/g, '')
.replace(/\\/g, '')
.replace(/""/g, '"')
.replace(/"query":"}}/g, '"query":""}}')
.replace(/"description":","/g, '"description":"","')
const responseData = JSON.parse(extract)
if (responseData.contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[0].itemSectionRenderer.contents[0].playlistVideoListRenderer.contents) {
const videos = responseData.contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[0].itemSectionRenderer.contents[0].playlistVideoListRenderer.contents
const videoList = videos
.map((video: any) => {
const title: string = video.playlistVideoRenderer?.title.runs[0].text
const episode = title?.includes('Tập ') ? title?.substring(title.indexOf('Tập '), title.indexOf('Tập ') + 7) : null
return {
episode,
title,
url: video.playlistVideoRenderer?.videoId,
thumbnail: video.playlistVideoRenderer?.thumbnail.thumbnails[0].url,
}
})
.filter((video: any) => video.episode !== null && video.title.indexOf('Thám Tử Lừng Danh Conan') !== -1)
return res.status(200).json(videoList)
}
return res.status(200).json({
data: [],
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment