import { decode , ParsedUrlQuery , } from 'querystring' ; import { VercelRequest , VercelResponse , } from '@vercel/node' ; import { renderToString } from 'react-dom/server' ; import { nowPlaying , lastPlayed , trackAudioFeatures , } from '../src/services/spotify' ; import { Player } from '../src/components/spotify/NowPlaying' ; param { VercelRequest } req param { VercelResponse } res export default async function ( req , res ) { try { let { Authorization , item , is_playing : isPlaying = false , progress_ms : progress = 0 , } = await nowPlaying ( ) ; if ( ! item ) { const response = await lastPlayed ( Authorization ) ; item = response . item ; } const params = decode ( req . url . split ( '?' ) [ 1 ] ) ; if ( params && typeof params . open !== 'undefined' ) { if ( item && item . external_urls ) { res . writeHead ( 302 , { Location : item . external_urls . spotify , } ) ; return res . end ( ) ; } return res . status ( 200 ) . end ( ) ; } let audioFeatures = null ; if ( Object . keys ( item ) . length ) { audioFeatures = await trackAudioFeatures ( item . id , Authorization ) ; } res . setHeader ( 'Content-Type' , 'image/svg+xml' ) ; res . setHeader ( 'Cache-Control' , 's-maxage=1, stale-while-revalidate' ) ; const { duration_ms : duration , name : track , } = item ; const { images = [ ] } = item . album || { } ; const cover = images [ images . length - 1 ] ?. url ; let coverImg = null ; if ( cover ) { const buff = await ( await fetch ( cover ) ) . arrayBuffer ( ) ; coverImg = `data:image/jpeg;base64,${ Buffer . from ( buff ) . toString ( 'base64' ) }` ; } const artist = ( item . artists || [ ] ) . map ( ( { name } ) => name ) . join ( ', ' ) ; const text = renderToString ( Player ( { artist , audioFeatures , cover : coverImg , duration , isPlaying , progress , track , } ) ) ; return res . send ( text ) ; } catch ( error ) { console . log ( error ) ; return res . send ( 'Authentication Errors!' ) ; } }