Youtubeの簡易クライアントのテスト

YoutubeAPIで自分がアップロードした動画を非公開ビデオも含めて取得する方法が見つからないのでHTTP_Clientで無理やりもってくるためのスクリプトを書く。

とりあえずGDataと統合されたっぽいしこの辺にも上がってるのでもうちょっと待てば認証APIとか出そうな気がするけどまぁいいや。

試験的にしかやってないので、

  • エラー処理とかやってない。
  • 取得できるのはmy_videosとmy_playlistsだけ。
  • しかも1ページ分しか取ってこない。

という使えない感満載。必要に応じて拡張していく。

youtube_client.php

<?php
require_once "HTTP/Client.php"; 

define ('YOUTUBE_BASE_URL', 'http://jp.youtube.com/');
define ('YOUTUBE_INDEX_URL', YOUTUBE_BASE_URL.'index');
define ('YOUTUBE_LOGIN_URL', YOUTUBE_BASE_URL.'login');
define ('YOUTUBE_VIDEOS_URL', YOUTUBE_BASE_URL.'my_videos');
define ('YOUTUBE_PLAYLISTS_URL', YOUTUBE_BASE_URL.'my_playlists');
define ('YOUTUBE_WATCH_URL', YOUTUBE_BASE_URL.'watch');

class Youtube_Client
{
  var
    $http_client = null ,
    $username    = '' ,
    $password    = '' ,
    $loggedin    = false ,
    $videos      = array() ,
    $playlists   = array();
  
  function Youtube_Client($username, $password)
  {
    $this->username = $username;
    $this->password = $password;
    $this->http_client = new HTTP_Client;
    register_shutdown_function(array($this, 'shutdown'));
  }
  
  function shutdown()
  {
    $this->logout();
    $this->http_client->reset();
  }
  
  function login()
  {
    if(!$this->loggedin)
    {
      $code = $this->http_client->head(YOUTUBE_VIDEOS_URL);
      if($code==200)
      {
        $response = $this->http_client->currentResponse();
        if(strpos($response['body'], '<input id="loginUsername"'))
        {
          $code = $this->http_client->post(
            YOUTUBE_LOGIN_URL,
            array(
              'username' => $this->username,
              'password' => $this->password,
              'current_form' => 'loginForm' ,
              'action_login' => 'ログイン' ,
            )
          );
          if($code == 200)
          {
            $response = $this->http_client->currentResponse();
            if(strpos($response['body'], '<input id="loginUsername"')===false)
            {
              $this->loggedin = true;
            }
          }
        }
        else
        {
          $this->loggedin = true;
        }
      }
    }
    return $this->loggedin;
  }
  
  function logout()
  {
    $code = $this->http_client->post(YOUTUBE_INDEX_URL, array('action_logout' => 1));
    if($code == 200)
    {
      $this->loggedin = false;
    }
    return !$this->loggedin;
  }
  
  function getVideos()
  {
    if(empty($this->videos))
    {
      if(!$this->loggedin && !$this->login())
      {
        return null;
      }
      $code = $this->http_client->get(YOUTUBE_VIDEOS_URL);
      if($code == 200)
      {
        $response = $this->http_client->currentResponse();
        preg_match_all('/<a\shref="\/watch\?v=([a-z0-9_-]+)">(.+?)<\/a>/i', $response['body'], $matches, PREG_SET_ORDER);
        foreach($matches as $match)
        {
          if(!isset($this->videos[$match[1]]))
          {
            $this->videos[$match[1]] = array();
          }
          $this->videos[$match[1]]['id'] = $match[1];
          if(preg_match('/<img\ssrc="(.+?)"\s\/>/', $match[2], $thumbnail))
          {
            $this->videos[$match[1]]['thumbnail'] = $thumbnail[1];
          }
          else
          {
            $this->videos[$match[1]]['name'] = $match[2];
          }
          $this->videos[$match[1]]['url'] = YOUTUBE_WATCH_URL.'?v='.$match[1];
        }
      }
    }
    return $this->videos;
  }
  function getPlayLists()
  {
    if(empty($this->playlists))
    {
      if(!$this->loggedin && !$this->login())
      {
        return null;
      }
      $code = $this->http_client->get(YOUTUBE_PLAYLISTS_URL);
      if($code == 200)
      {
        $response = $this->http_client->currentResponse();
        preg_match_all('/<a\shref="my_playlists\?p=([a-z0-9]+)">(.+?)<\/a>/i', $response['body'], $matches, PREG_SET_ORDER);
        foreach($matches as $match)
        {
          $this->playlists[$match[1]] = array('id' => $match[1], 'name' => $match[2], 'url' => YOUTUBE_PLAYLISTS_URL.'?p='.$match[1]);
        }
      }
    }
    return $this->playlists;
  }
}
?>

使用例

<?php
require_once('youtube_client.php');

$youtube = new Youtube_Client('[USERNAME]', '[PASSWORD]');

print_r($youtube->getPlayLists());
print_r($youtube->getVideos());

とかするとこんな感じで配列を返す。

Array (
  [プレイリストのID] => Array (
    [id] => プレイリストのID
    [name] => プレイリストの名前
    [url] => http://jp.youtube.com/my_playlists?p=プレイリストのID
  )
)

Array (
  [動画のID] => Array (
    [id] => 動画のID
    [thumbnail] => サムネイル画像のURL
    [url] => http://jp.youtube.com/watch?v=動画のID
    [name] => 動画のタイトル
  )
)