[予習その2] YouTube API Tech Talk・コードラボ

その1:http://muzigram.muzigen.net/2013/02/youtube-api-tech-talk.html

続き

■ Lesson 3: Requesting the YouTube User Id and List of Uploads

https://docs.google.com/document/d/1QLF1Nrg8xBCOfZrC8yVICKi53OWwY4FPky7iZdk9NdI/pub#h.odszgbq0my2j

valid な OAuth 2 access tokenを手に入れたのでYoutubeから2つ程、情報を取得してみよう。というお話。

認証を通過すると以下の関数が実行される。
  function loadAPIClientInterfaces() {
    gapi.client.load('youtube', 'v3', function() {
      gapi.client.load('youtubeAnalytics', 'v1', function() {
        // Once both the client interfaces are loaded, use the Data API to request information
        // about the authenticated user's channel.
        getUserChannel();
      });
    });
  }

  • youtubeとyoutubeAnalytics両方のAPIをロード
  • gapi.client.loadのcallbackでgapi.client.loadしてる。
  • getUserChannelを実行

  function getUserChannel() {
    // https://developers.google.com/youtube/v3/docs/channels/list
    var request = gapi.client.youtube.channels.list({
      // mine: true indicates that we want to retrieve the channel for the authenticated user.
      mine: true,
      part: 'id,contentDetails'
    });

    request.execute(function(response) {
      if ('error' in response) {
        displayMessage(response.error.message);
      } else {
        // We will need the user id associated with this channel later on when making calls to the
        // Analaytics API. It looks like UCdLFeWKpkLhkguiMZUp8lWA.
        channelId = response.items[0].id;
        // This is a string of the form UUdLFeWKpkLhkguiMZUp8lWA, and represents a unique
        // identifier for the uploads in the authenticated user's channel.
        var uploadsListId = response.items[0].contentDetails.relatedPlaylists.uploads;
        // Now that we have the uploads list id, retrieve the items in the uploads list.
        getUploadsList(uploadsListId);
      }
    });
  }

requestを作成、実行。request.executeの中身は実行された際のcallback。

  • request.execute実行される
  • 結果がfunction(response)に渡される。
  • うまくいっていたらuploadsListIdを取得してgetUploadsListを実行

function getUploadsList(listId) {内
 var videoIds = $.map(response.items, function(item) {
            return item.snippet.resourceId.videoId;
          });

補足

$.map()はjQuery.map(array, callback)のことで 配列にcallback文の処理をして返す。

function getMetadataForVideos(videoIds) {内
callback : function(response) のthisは通常のthisではなく、callback内のthisであることに留意

■ Lesson 4: Requesting YouTube Analytics Data for a Given Video

https://docs.google.com/document/d/1QLF1Nrg8xBCOfZrC8yVICKi53OWwY4FPky7iZdk9NdI/pub#h.q9dzy1uklmei
与えられた動画のAnalytics Dataの取得

function displayVideoAnalytics内で、今までと同様にリクエスト投げて値を取得してます。
formatDateStringpadToTwoCharactersで細かいstringの調整などもしてるのでみてみるといいと思います。

このデモではログインしているアカウントを使ってますが、ログアウトせずに他のアカウントを使う場合はChromeのシークレットモードがおすすめ!っとのこと

■ 補足

どのAPIを叩いてるかは以下のURLと比較するとわかりやすくなります。
https://developers.google.com/youtube/v3/docs/

0 件のコメント :