Categories
Code

Create YouTube Playlist with Google Script and Sheets

This Google Scripts reads the list of YouTube Video IDs from a Google Spreadsheet and adds them all to an existing playlist in YouTube.

Please enable the YouTube API under Advanced Google Services and inside the corresponding Google Cloud Platform project. You can also create YouTube playlist by appending the video IDs to a special URL.

function addVideoToYouTubePlaylist() {
  // Read the source videos from Google Sheet
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  
  // Add your own playlist Id here
  var playlistId = "PLAYLIST_ID_HERE";
  
  // iterate through all rows in the sheet
  for (var d=1,l=data.length; d

		
Categories
Code

Search YouTube with Google Script and YouTube API

This Google Script shows how to query the YouTube API to search videos by keywords. The source data is in a column in Google Spreadsheet and we connect to the YouTube Data API via Google Apps Script. The YouTube service should be in enabled in the Google Cloud Platform project.

function findYouTubeVideoByKeywords() {
  // get the search query from Google Sheets
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  
  // iterate through all rows in the sheet
  for (var d=1,l=data.length; d

		
Categories
Code

Create RSS Feed for YouTube Search Results

Based upon the Twitter RSS Feed, a Maryland based Rails developers has created a Google Script that creates a RSS feed of YouTube videos matching your search terms. You pass the search phrase as a parameter to the Google Script web app and it uses the ContentService to serve the results as an RSS feed.

Before authorizing the code, go to the Google Developers console and enable the YouTube Data API for your Apps Script project. You may also be required to create credentials before using the YouTube API in Apps Script. Publish the script as web app and set access to anyone, even anonymous.


/*
  YouTube RSS Feeds
  Written by @user1535152 http://stackoverflow.com/q/30486682/512127
  Based on http://www.labnol.org/internet/twitter-rss-feed/28149/  
*/

function doGet(e) {
    
  var title  = ("Youtube RSS Feed for " + e.parameter.search),
      timez  = Session.getScriptTimeZone(),
      search = encodeURIComponent(e.parameter.search),
      link   = ("https://www.youtube.com/results?search_query=" + search),
      self   = ScriptApp.getService().getUrl() + "?" + search;
        
  var rss='';
  rss+='';
  rss+=''+title+'';
  rss+=''+link+'';
  rss+='';
  rss+='' + title + ' updated on ' + new Date() + '.';
  
  var results = YouTube.Search.list('id, snippet', {
    q: search,
    maxResults: 50,
    order: 'date'
  });
  
  for (var i = 0; i < results.items.length; i++){
    var item = results.items[i];
    rss += "";
    rss += "" + item.snippet.title + "";
    rss += "http://www.youtube.com/watch?v=" + item.id.videoId + "";
    rss += "" + item.snippet.description + "";
    rss += "" + Utilities.formatDate(new Date(item.snippet.publishedAt), timez, "EEE, dd MMM yyyy HH:mm:ss Z") + "";
    rss += "http://www.youtube.com/watch?v=" + item.id.videoId + "";
    rss += "";
  }
  
  rss+="";
  
  return ContentService.createTextOutput(rss).setMimeType(ContentService.MimeType.RSS);
}

Categories
Code

Make your YouTube Playlists Private with Google Scripts

The Google Script will check the privacy status of each of your YouTube playlists and set the visibility status of the ones that are either public or unlisted to private. Good option if you would not like the Internet to know about the various playlists you have saved in your YouTube channel.

You’ll have to enable the YouTube Data API available under Advanced Google Services inside the Google Apps Script Editor.


/* Source: http://qiita.com/ttyokoyama/items/05c7c62cd30e3f2227db */

function makeYouTubePrivate() {
  
  var nextToken = "";
  
  while (nextToken != null) {
  
    var res = YouTube.Playlists.list('snippet,status', {
                        maxResults: 50,
                        mine: true,
                        pageToken: nextToken });
    
    for(var i = 0; i < res.items.length; i++) {
    
      var item = res.items[i];
      
      if(item.status.privacyStatus != "private") {
        Logger.log("Updating " + item.snippet.title + ", " + item.status.privacyStatus );
        item.status.privacyStatus = "private";
        var updateRes = YouTube.Playlists.update(item, "snippet, status");
        Logger.log(updateRes.status.privacyStatus);
      }
      
    }
    
    nextToken = res.nextPageToken;
  }
}
Categories
Code

RegEx to Extract Video ID from YouTube URLs

The regular expression will extract the video ID from any YouTube URL and it works with shortened URLs (youtu.be) and embed URLs (youtube.com/embed/) as well.


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{
        alert("Could not extract video ID.");
    }
}

Another alternative that will extract the video ID as well as the playlist ID from YouTube URLS:

    var id = url.match("v=([a-zA-Z0-9\_\-]+)&?")[1];
    var list = url.match("list=([a-zA-Z0-9\-\_]+)&?");
    list = list ? list[1] : "";
Categories
Code

Find Videos with the YouTube Search API

The instant search feature at Zero Dollar Movies uses the YouTube data API to find free movies on the YouTube website.

When the user enters a search query, the script makes a request to the gdata.youtube.com (YouTube data API) for search results. The resultset is returned in JSON format. The code uses YouTube API v2 and, while optional, it may be a good idea to include a developer key in the API requests.





Generate a YouTube Developer Key

You can go to the Google API console to create a developer key for your project. Go to cloud.google.com/console and start a new project. Give your project a unique name and then choose APIs to turn on the YouTube Data API. Next create a new key under Public API access, set the type as Browser key and the website referrer as your website address (to prevent abuse).

YouTube Data API Quota Limits

YouTube Data API v3’s quota is 50,000,000 units per day. The quota cost of making a single search request to YouTube is just 2 units and thus a normal web application is unlikely to exceed the quota anytime soon.

You can also enable billing the Google Cloud console to further increase your quota.

Categories
Code

YouTube Data API and Google Apps Script

The YouTube Playlists tool is written using the Google Data API but you can also use Google Apps Script for the task.

The App Script connects to YouTube through oAuth and then you can use YouTube Data feeds (gdata.youtube.com) to fetch information about any YouTube playlist given its ID. The ID can be easily extracted from a YouTube playlist URL using a regular expression (PL[A-Za-z0-9_-]+) and the video lists is available in JSON format that can be parsed using the Utilities.jsonParse library of Apps Script.


function youtubePlaylist(playlistID){
  
  var oAuthConfig, options, videos = [], result, json, i, start=1, title="";
  
  oAuthConfig = UrlFetchApp.addOAuthService("youtube");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=http%3A%2F%2Fgdata.youtube.com%2F");
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setConsumerKey("anonymous");
  oAuthConfig.setConsumerSecret("anonymous");
  
  options = {
    "oAuthServiceName" : "youtube",
    "oAuthUseToken" : "always"
  };

  do {

    // Run in a loop since YouTube Data API only returns 50 videos in a batch
    result = UrlFetchApp.fetch("http://gdata.youtube.com/feeds/api/playlists/" + playlistID
                               + "?v=2&max-results=50&alt=json&start-index="+start, options);
    
    json = Utilities.jsonParse(result.getContentText());
        
    if (!json.feed.entry) 
      break;
    
    if (start==1) {
      videos.push(json.feed.title.$t);
    }
    
    for (i=0; i

		
Categories
Code

Managing YouTube with Google Data API

The Copy YouTube Playlists tool uses Google Data API (PHP) and YouTube API (v3) to clone any public YouTube playlist into the YouTube account of the authorized user.

You need to create your own OAuth2 secret keys from the Google Developer’s Console and also the redirect URL should point to the page where the PHP script is hosted.

setClientId($OAUTH2_CLIENT_ID);
    $client->setClientSecret($OAUTH2_CLIENT_SECRET);
    $client->setRedirectUri($redirect);

    $youtube = new Google_YoutubeService($client);

    if (isset($_GET['code'])) {

        if (strval($_SESSION['state']) !== strval($_GET['state'])) {
            die('The session state did not match.');
        }

        $client->authenticate();
        $_SESSION['token'] = $client->getAccessToken();
        header('Location: ' . $redirect);

    }

    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    if ($client->getAccessToken()) {

            try {

                if ( preg_match('/(PL[A-Za-z0-9_-]+)/', $_POST["url"], $match) ) {

                    $plID = $match[0];
                    $pl_options = array ("id" => $plID, "maxResults" => 1);
                    $playlistDetails = $youtube->playlists->listPlaylists("snippet", $pl_options);

                    if ( $playlistDetails["pageInfo"]["totalResults"] == 1 ) {

                        $options = array ("playlistId" => $plID, "maxResults" => 50);
                        $videos = "";

                        do {

                            $playlist = $youtube->playlistItems->listPlaylistItems("snippet", $options);
                            $nextPageToken = $playlist["nextPageToken"];
                            $options["pageToken"] = $nextPageToken;

                            foreach ($playlist["items"] as $playlistItem) {
                                $videos .=  $playlistItem["snippet"]["resourceId"]["videoId"] . "#";
                            }

                        } while ($nextPageToken);

                        $playlistSnippet = new Google_PlaylistSnippet();
                        $playlistSnippet->setTitle($playlistDetails["items"][0]["snippet"]["title"]);

                        $playlistStatus = new Google_PlaylistStatus();
                        $playlistStatus->setPrivacyStatus('private');

                        $youTubePlaylist = new Google_Playlist();
                        $youTubePlaylist->setSnippet($playlistSnippet);
                        $youTubePlaylist->setStatus($playlistStatus);

                        $playlistResponse = $youtube->playlists->insert('snippet,status', $youTubePlaylist, array());

                        $ids = explode ( "#", $videos ) ;

                        for ($i=0; $isetVideoId($ids[$i]);
                            $resourceId->setKind('youtube#video');

                            $playlistItemSnippet = new Google_PlaylistItemSnippet();
                            $playlistItemSnippet->setPlaylistId($playlistResponse['id']);
                            $playlistItemSnippet->setResourceId($resourceId);

                            $playlistItem = new Google_PlaylistItem();
                            $playlistItem->setSnippet($playlistItemSnippet);

                            $playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());

                        }

                    }

                }

            } catch (Google_ServiceException $e) {
                $htmlBody .= sprintf('

A service error occurred: %s

', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('

An client error occurred: %s

', htmlspecialchars($e->getMessage())); } } else { $htmlBody = << END; } $_SESSION['token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody = <<Step 1: Sign-in with YouTube

END; } ?>
Categories
Code

YouTube Player API for Partial Embeds

You can embed a part of YouTube video using the YouTube Player API. The API offers loadVideoById and cueVideoById function both of which allow you to specify a start and end time for the embedded video.

 



 
Categories
Code

Embed YouTube Videos with JavaScript

This explains how you can embed YouTube videos using the Google+ approach – only the video thumbnail is loaded along with the page and the actual player loads when the user hits the play button.

 


<script> // Find all the YouTube video embedded on a page var videos = document.getElementsByClassName("youtube"); for (var i=0; i  
Categories
Code

YouTube Storyboard Bookmarklet – JavaScript

YouTube Image Frames is bookmarklet that extracts all the storyboard images of any YouTube video.

/*
    YouTube Storyboard Frames
    -------------------------
    Written by Amit Agarwal (amit @labnol.org)
    See video demo at http://youtu.be/Y6yfGGxXyHw
*/

// Extract the Storyboard URL from the HTML Source
 a = yt.playerConfig.args.storyboard_spec;

// If the Storyboard parameter is missing, no thumbnails would be generated
 if (!a) {
    alert("Sorry we had trouble creating a storyboard for this YouTube video.");
    exit();
 }

// Parse the Storyboard URL to get the base and unique ID of thumbnail images
 b = a.split("|");
 base = b[0].split("$")[0] + "2/M";
 c = b[3].split("#");
 sigh = c[c.length - 1];

// Get the length of the YouTube video 
// If the video is longer than 20 minutes, the storyboard has more image frames
 t = yt.playerConfig.args.length_seconds;
 n = (t < 60 * 20) ? 5 : t / (60 * 4);

// Queue all the thumbnail images
 var imgs = "";
 for (i = 0; i < n; i++) {
   imgs += "
"; } // Extract the YouTube video title var title = yt.playerConfig.args.title; msg = "" + "

TITLE

IMAGES
"; msg = msg.replace("TITLE", title); msg = msg.replace("IMAGES", imgs); // Put everything in an HTML page and open it in a new window var labnol = window.open(); labnol.document.open(); labnol.document.write(msg); labnol.document.close(); // When you click the bookmarklet, all the // available storyboard frames will open in a new window