Skip to content

Instantly share code, notes, and snippets.

@nitobuendia
Last active April 13, 2022 13:52
Show Gist options
  • Save nitobuendia/322af002230231cc1c00ceeeca577385 to your computer and use it in GitHub Desktop.
Save nitobuendia/322af002230231cc1c00ceeeca577385 to your computer and use it in GitHub Desktop.
Shuffle YouTube Playlist (via Apps Script)
/**
* @fileoverview Shuffles a YouTube playlist on every run.
*
* Note: currently this only supports up to 50 videos, but you can extend it to
* support more by combining the pages into one.
*
* This code is meant to be run on Google Apps Script. To get started with
* YouTube API on Apps Script and add the YouTube service, read this article:
* https://developers.google.com/apps-script/guides/services/advanced
*/
/** @const {string} Playlist id. Copy from the URL of the playlist (&list=). */
const PLAYLIST_ID = '';
/**
* Shuffles a YouTube playlist videos.
*
* Call this function to start the process.
* Retrieves all videos (up to 50) on the given playlist id into an array.
* Shuffles the array in a random order.
* Updates the YouTube playlist with the new shuffled video positions.
*/
function main() {
const playlistItems = YouTube.PlaylistItems.list(
['id', 'snippet'],
{
'playlistId': PLAYLIST_ID,
'maxResults': 50,
});
// TODO(reader): the code only handles first 50 videos, as this is the max
// result from YouTube API without pagination. If your playlist is longer,
// you may need to request all the other pages to have a complete list of
// videos when calling getItems();
let videos = playlistItems.getItems();
videos = shuffleArray(videos);
videos.forEach((video, arrayIndex) => {
const previousPosition = video.snippet.position;
video.snippet.position = arrayIndex;
YouTube.PlaylistItems.update(
{
'id': video.id,
'snippet': {
'playlistId': PLAYLIST_ID,
'position': video.snippet.position,
'resourceId': {
'kind': video.snippet.resourceId.kind,
'videoId': video.snippet.resourceId.videoId,
},
},
},
['snippet'],
);
console.log(
`video id: ${video.snippet.resourceId.videoId}, ` +
`before position: ${previousPosition}, ` +
`after position: ${video.snippet.position}`
);
});
}
/**
* Randomly shuffles a given array.
* @param {!Array<T>} array Array to shuffle.
* @return {!Array<T>} Same array but with elements shuffled in order.
*/
function shuffleArray(array) {
let currentIndex = array.length;
let randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
const currentElement = array[currentIndex];
const randomElement = array[randomIndex];
array[currentIndex] = randomElement;
array[randomIndex] = currentElement;
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment