I have the following code below that takes a new row added to my Google Spreadsheet (has a header row) and extracts the video ID. If the ID does not exist in the playlist, it adds the video to the playlist. If it doesn't, it skips it. Not really comfortable with Google Apps Script, so I would like some constructive feedback.
function addVideoToYouTubePlaylist() {
// retrieve video ID list from the playlist.
var playlistId = "PL6bCFcS8yqQxSPjwZ9IXFMfVm6kaNGLfi";
var list = [];
var pageToken = "";
do {
var res = YouTube.PlaylistItems.list(["snippet"], {playlistId: playlistId, maxResults: 50, pageToken: pageToken});
if (res.items.length > 0) list = list.concat(res.items);
pageToken = res.nextPageToken || "";
} while (pageToken);
var obj = list.reduce((o, e) => Object.assign(o, {[e.snippet.resourceId.videoId]: e.snippet.resourceId.videoId}), {});
// read the source videos from Google Sheet
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
// iterate through all rows in the sheet
for (var d=1,l=data.length; d<l; d++) {
var videoId = extractVideoID(data[d][0]);
if (!obj[videoId]) {
YouTube.PlaylistItems.insert({
snippet: {
playlistId: playlistId,
resourceId: {
kind: "youtube#video",
videoId: extractVideoID(videoId)
}
}
}, "snippet");
}
else{
console.log("Already in playlist");
}
sheet.deleteRow(d+1); // delete row after video is checked
}
}
function extractVideoID(url){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
if ( match && match[7].length == 11 ){
return match[7];
}
else if (!( match && match[7].length == 11 )){
console.log("Could not extract video ID.");
var trimmedVideoID = url.replace("https://youtu.be/", "");
trimmedVideoID = trimmedVideoID.replace('https://www.youtube.com/watch?v=', "");
trimmedVideoID = trimmedVideoID.replace('https://youtube.com/watch?v=', "");
trimmedVideoID = trimmedVideoID.replace("&feature=youtu.be", "");
trimmedVideoID = trimmedVideoID.replace("&feature=share", "");
console.log(trimmedVideoID);
return trimmedVideoID;
}
}