Created
January 3, 2019 17:27
-
-
Save imjosh/13181a5698904b8c6eb20b1ba2184366 to your computer and use it in GitHub Desktop.
Get a direct MP4 link for a YouTube video
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Notes | |
Usage: Open YouTube in browser and run from console | |
References: | |
https://tyrrrz.me/Blog/Reverse-engineering-YouTube | |
https://gist.github.com/el3zahaby/9e60f1ae3168c38cc0f0054c15cd6a83 | |
http://rg3.github.io/youtube-dl/ https://github.com/rg3/youtube-dl/ | |
const videoInfoRegex = /(?:quality=(\w*?),)(?:type=video\/mp4.*?)&url=(.*?),/g; // find all mp4 links | |
*/ | |
async function extractYoutubeMp4Link(vidId) { | |
const regex = /type=video\/mp4.*?&url=(.*?),/; // find first mp4 link | |
const findStr = 'url_encoded_fmt_stream_map='; | |
const findStrLen = 27 | |
const vidInfo = await getVideoInfo(vidId); | |
const decodedInfo = decodeURIComponent(decodeURIComponent(vidInfo)); | |
const streamMap = decodedInfo.substr(decodedInfo.indexOf(findStr) + findStrLen); | |
return regex.exec(streamMap)[1]; | |
} | |
function getVideoInfo(vidId) { | |
const url = `https://www.youtube.com/get_video_info?video_id=${vidId}`; | |
return fetch(url, { | |
mode: "no-cors", | |
}) | |
.then(res => res.text()) | |
.then(body => body); | |
} | |
function getYoutubeMp4Link(vidId) { | |
extractYoutubeMp4Link(vidId) | |
.then(url => console.log(url)) | |
.catch(err => console.error(err)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment