Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disco0/ffecf8fd8914e8387cd3e5ae286526d6 to your computer and use it in GitHub Desktop.
Save disco0/ffecf8fd8914e8387cd3e5ae286526d6 to your computer and use it in GitHub Desktop.
// this function handles the form submit
function addVideoToPlaylist(e){
// 'Youtube url' is the question title from our form. If you change your question change this value
// youtube_parser() takes the url and strips the video_id
var id = youtube_parser(e.namedValues['Youtube url'][0]);
var desc = e.namedValues['Comment'][0]; // if you would like to add a note with playlist item add form field
addToPlaylist(id, desc);
}
// This function is taken from the YouTube API doc (Javascript example)
// https://developers.google.com/youtube/v3/docs/playlists/insert
//
// Add a video to a playlist. The "startPos" and "endPos" values let you
// start and stop the video at specific times when the video is played as
// part of the playlist. However, these values are not set in this example.
function addToPlaylist(id, desc, startPos, endPos) {
// this is my playlist id and you need to replace with your own
// To get this in your YouTube channel create or go to you playlist
// and the list id will be in your browser address bar. Basically everything
// after https://www.youtube.com/playlist?list=
var playlistId ="PLlMXkWgzMBtOZGp6beg10WqKb66wIk9eu";
// the API requires a resource object. This next bit builds it
var details = {
videoId: id,
kind: 'youtube#video'
}
if (startPos != undefined) {
details['startAt'] = startPos;
}
if (endPos != undefined) {
details['endAt'] = endPos;
}
if (desc == undefined) { // HT @mambelli
var desc = "";
}
var part= 'snippet,contentDetails';
var resource = {
snippet: {
playlistId: playlistId,
resourceId: details
},
contentDetails:{
note: desc
}
};
// cheating slightly and doing no error handling. When you setup the form submit you can choose to recieve
// notification of errors. The form response will be submitted to the spreadsheet regardless.
var request = YouTube.PlaylistItems.insert(resource, part);
}
// Little helper..
// http://stackoverflow.com/a/8260383/1027723
function youtube_parser(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{
throw("Url incorrecta");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment