1

How can I create Videos IDs with javascript? I want to make a website that gives user random videos, but at the same time for me, I want to learn what is the YouTube Video ID algorithm

  • Does this answer your question? [How do I get a random YouTube video with the YouTube API?](https://stackoverflow.com/questions/11315416/how-do-i-get-a-random-youtube-video-with-the-youtube-api) – Jax-p Aug 08 '22 at 11:12
  • I don't wantAPI, I want to learn the algorithm of videos IDs – Daniel Dinca Aug 08 '22 at 14:04
  • In the context of the video https://youtu.be/gocwRvLhDf8 2:23 I tried all YT videos ids incrementally and found the "rarest" video id: 0000088ZZQg Because YT videos ids are made of 11 characters there are 64^11 possibilities. I tried 8,733,472,426 possibilities with the YT Data API v3 and found the "rarest" video id beginning with 5 zeros. I did that because it proves that YT video ids aren't long enough because this video could be unlisted and then this would be a critical security and privacy issue. By the way we can then badly approximate the number of YouTube videos to 8,448,755,855. – Benjamin Loison Aug 08 '22 at 14:59

1 Answers1

0

The process is is straight forward when laid out this way:

  1. Generate random unsigned 64-bit ID number
  2. Check if ID already exists; if so, repeat (1)
  3. Generate Base64 string of ID, by splitting into 8-bit chunks
  4. Replace / with -. Replace + with _. Delete = if present

Here's a simple JS implementation, though it doesn't do any checks (that's usually done server side):

function yt_rand_id() {
let chars2replace = {'/': '-', '+': '_', '=': ''};
let random_bytes = new Uint8Array(8).map(() => Math.floor(Math.random() * 256))
let base64_hash = btoa(String.fromCharCode.apply(0, random_bytes));
base64_hash = base64_hash.replace(/[/+=]/g, match => chars2replace[match]);
return base64_hash;
}

console.log(yt_rand_id(), yt_rand_id(), yt_rand_id(), yt_rand_id());

Hope this helped someone.

bryc
  • 12,710
  • 6
  • 41
  • 61