-
Notifications
You must be signed in to change notification settings - Fork 2
/
ytdlr.js
44 lines (43 loc) · 1.52 KB
/
ytdlr.js
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
35
36
37
38
39
40
41
42
43
44
(() => {
let fetch
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: '3', 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 || []]
}
}
})()