毎日漫然な愚者

少ない時間で挑むGNO2とモンハン日記ばかり?

PHP YouTube 動画をアップする

2009-03-31 23:19:29 | Weblog

タイトルのようなことができないかという話。
で、調べた結果、以下の記事を発見

デベロッパー ガイド: PHP - YouTube の API とツール - Google Code
メモ:YouTubeAPI + PHP(Zend) - ftshの日記
ZooTube.jp で YouTube API を使ってみています | ぢぢらぶろぐ

これで、検索とブラウザからのアップロードはできました。(激しく感謝)
ただ、ローカルファイルを直接アップする方法が、
最初のリンクぐらいしか見当たらなかったので、
ガイドを元に作ってみました。

gdata.php
――――――――――――――――――――――――――――――― 
<?php
$PathLIB = '/path/to/Zend';
set_include_path(get_include_path() . PATH_SEPARATOR . $PathLIB);
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

function doUpload($fileVars)
{
 // YouTubeサービス利用のログイン情報
 //  * YouTubeAPIの開発コード - 取得して代入
 $sDeveloperKey = 'デベロッパーキー'; 
 //  * YouTubeアカウント名
 $sAccount = 'hoge';
 //  * YouTubeログインパスワード
 $sPassword = 'fuga';

 // 動画アップロードについての情報
 //  [ アップロードする動画のタイトル ]
 $sMovieTitle     = 'Local Test Movie';
 //  [ 動画の説明文 ]
 $sDescription    = 'none ...';
 //  [ デベロッパータグ ] -
 $sDevTag         = 'hogehoge';
 //  [ タグ ] -
 $sTags           = 'Film,Tech,';
 //  [ カテゴリー ] - 定義のあるカテゴリーを使うこと - http://gdata.youtube.com/schemas/2007/categories.cat
 $sCats           = 'Film';     
 //  [ キーワード ]
 $sKeywords       = 'hoge.fuga';
 //  [ アップロード後に遷移する画面 ]
 $sNextUrl        = 'http://'.$_SERVER['SERVER_NAME'].'/gdata/gdata_uploaded.php';
 //  [ YouTubeクライアントログイン用のURL ]
 $authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';

 // クライアントログインオブジェクト作成
 $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
              $username     = $sAccount,
              $password     = $sPassword,
              $service      = 'youtube',
              $client       = null,
              $source       = 'gdataTest', // a short string identifying your application
              $loginToken   = null,
              $loginCaptcha = null,
              $authenticationURL
              );
 $httpClient->setHeaders('X-GData-Key', "key={$sDeveloperKey}"); //出来たオブジェクトにデベロッパーキーも持たせる。

 /***********
  * アップロードのコア
  */

 $yt = new Zend_Gdata_YouTube($httpClient);
 // create a Zend_Gdata_YouTube_VideoEntry
 $myVideoEntry= new Zend_Gdata_YouTube_VideoEntry();

 // create a new Zend_Gdata_App_MediaFileSource object
 $filesource = $yt->newMediaFileSource($saveFile);
 $filesource->setContentType('video/quicktime');
 // set slug header
 $filesource->setSlug($saveFile);

 // add the filesource to the video entry
 $myVideoEntry->setMediaSource($filesource);

 // set up media group as in the example above
 $mediaGroup              = $yt->newMediaGroup();
 $mediaGroup->title       = $yt->newMediaTitle()->setText( $sMovieTitle );
 $mediaGroup->description = $yt->newMediaDescription()->setText( $sDescription );
 $mediaGroup->keywords    = $yt->newMediaKeywords()->setText( $sKeywords );


 // note the different schemes for categories and developer tags
 //  [使えるカテゴリの一覧]
 $categoryScheme     = 'http://gdata.youtube.com/schemas/2007/categories.cat';
 //  [デベロッパータグの定義]
 $developerTagScheme = 'http://gdata.youtube.com/schemas/2007/developertags.cat';

 $mediaGroup->category = array( 
        $yt->newMediaCategory()->setText($sCats)->setScheme($categoryScheme),
        $yt->newMediaCategory()->setText($sDevTag)->setScheme($developerTagScheme),
        $yt->newMediaCategory()->setText('anotherdevelopertag')->setScheme($developerTagScheme)
        );

 $myVideoEntry->mediaGroup = $mediaGroup;

 // set video location
 $yt->registerPackage('Zend_Gdata_Geo');
 $yt->registerPackage('Zend_Gdata_Geo_Extension');
 $where = $yt->newGeoRssWhere();
 $position = $yt->newGmlPos('37.0 -122.0');
 $where->point = $yt->newGmlPoint($position);
 $myVideoEntry->setWhere($where);

 // upload URL for the currently authenticated user
 $uploadUrl = 'http://uploads.gdata.youtube.com/feeds/users/default/uploads';

 try {
  $newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
 } catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
 }

 //↓ステータスチェックサンプル
 // check if video is in draft status
 try {
  $control = $newEntry->getControl();
 } catch (Zend_Gdata_App_Exception $e) {
  echo $e->getMessage();
 }
 if ($control instanceof Zend_Gdata_App_Extension_Control) {
  if ($control->getDraft() != null && $control->getDraft()->getText() == 'yes') {
   $state = $newEntry->getVideoState();
   if ($state instanceof Zend_Gdata_YouTube_Extension_State) {
    print 'Upload status: '. $state->getName() .' '.  $state->getText();
   } else {
    print "Not able to retrieve the video status information yet. Please try again shortly.\n";
   }
  }
 }
}

if (is_uploaded_file($_FILES['savefile']['tmp_name'])) {
 $result = doUpload($_FILES);
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE></TITLE>
</HEAD>
<BODY>
<TABLE border="1">
 <thead>
  <form action="./gdata.php" method="post" enctype="multipart/form-data">
  <tr>
   <td colspan="3">アップロード(ファイル保存後に実行)</td>
   <td colspan="5"><input type="file" name="savefile" ></td>
  </tr>
  <tr>
   <td colspan="8"><input type="submit" name="submit" value="送信"></td>
  </tr>
  </form>
 </thead>
 </TBODY>
</TABLE>

</BODY>
</HTML>

―――――――――――――――――――――――――――――――
今回は動作確認が目的なので、
ブラウザでアップした動画を一度サーバで保存し、
その保存したファイルをYouTubeにアップするという、
めんどくさい動きをしています。

YouTubeアップ後はステータスを表示するという、
サンプルそのままな感じです^^;

ちなみに、ブラウザアップロードと違い、
アップした動画のIDは以下のような感じでとれたりします。

$newEntry->getVideoId()

なんで、アップ後にユーザにアップ先を通知する場合は、
このIDを使えばいいというわけになります。

まぁ、突っ込みどころは満載なんですが、
サンプルってことでひとつよろしくお願いします^^;


最新の画像もっと見る