UNPKG

ytdlr

Version:

Simple YouTube Download Module

45 lines (43 loc) 1.6 kB
(() => { let fetch = 0 let host = 'https://www.youtube.com' let path = '/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8' if (typeof window === 'undefined') { fetch = (url, opts) => { url = new URL(url) opts = { ...opts, host, path } return new Promise((resolve, reject) => { let req = require(url.protocol.slice(0, -1)).request(opts, (res, data = '') => { res.on('data', chunk => { data += chunk }) res.on('end', () => resolve(JSON.parse(data))) }) if (opts.body) req.write(opts.body) req.on('error', e => reject(e)) req.end() }) } module.exports = ytdlr } else { fetch = (url, opts) => window.fetch(url, opts).then(j => j.json()) window.ytdlr = (id, lang) => ytdlr(id || new URLSearchParams(window.location.search).get('v'), lang) } async function ytdlr (id, lang = 'en-US') { lang = lang.split('-') let body = await fetch(host + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ context: { client: { hl: lang[0], gl: lang[1], clientName: 'ANDROID', clientVersion: '16.50', clientScreen: 'EMBED' }, thirdParty: { embedUrl: host } }, videoId: id }) }) if (body.playabilityStatus.status !== 'OK') throw Error(body.playabilityStatus.reason) return { details: body.videoDetails, formats: [...body.streamingData.formats, ...body.streamingData.adaptiveFormats] } } })()