YouTube Data API では、クライアント アプリケーションで Google Data API フィード形式を使用して YouTube のコンテンツの取得と更新ができます。クライアント アプリケーションでは YouTube Data API フィードを使用して、動画、コメント、レスポンス、再生リスト、ユーザー プロフィール、ユーザー コンタクトに対してフェッチ、検索、更新をするほか、特定の条件に一致する動画の検索ができます。
このドキュメントでは、YouTube Data API の機能の背景を説明するだけでなく、PHP クライアント ライブラリを使用した API とのやり取りの例も示します。クライアント ライブラリはスタンドアロン リリース (Zend が提供) または Zend Framework の一部としてダウンロードできます。PHP クライアント ライブラリの設定について不明な点があれば、スタート ガイドをご覧ください。YouTube とやり取りするために PHP クライアント ライブラリが使用する、基礎となるプロトコルの詳細について興味がある場合は、デベロッパー ガイドのプロトコル ページをご覧ください。
このドキュメントは、PHP クライアント ライブラリを使用して YouTube とやり取りできるクライアント アプリケーションを作成するプログラマを対象としています。Data API との基本的なやり取りの一連の例を示します。
YouTube Data API リファレンス情報について詳しくは、リファレンス ガイドをご覧ください。
このドキュメントでは、Google Data API プロトコルの背後にある一般的概念と PHP について読者が理解していることを前提としています。
PHP のクラスとメソッドについて詳しくは、クライアント ライブラリの API ガイドをご覧ください。
このドキュメントには次のセクションがあります。
認証のセクションでは、特定のユーザー アカウントに API の操作を関連付けるために利用可能な 2 種類の認証方式について説明します。このセクションでは、YouTube Data API と他の Google Data API での認証の違いについても概説します。このドキュメントを通して、具体的な API 関数の説明では、関数にユーザーの認証が必要かどうかを明示しています。一般に動画やフィードのデータを変更する要求は、すべて認証を受ける必要があります。公開動画の読み取りのみの要求には、認証は必要ありません。
動画のフィードとエントリの説明のセクションでは、API の応答の例を示し、動画のリストまたは検索結果のセットから 1 本の動画の情報を抽出する方法について説明します。このセクションでは、特定の動画エントリのメタデータにアクセスする方法についても説明します。最後にこのセクションでは、個々の動画エントリを更新する方法について説明します。
動画の取得と検索のセクションでは、特定の動画のリストをフェッチする方法について説明します。これらのリストの中には、数種類の標準のフィード (「評価の高い動画」、「人気の動画」など) があります。その他の動画のリストには、特定のユーザーがアップロードした動画や、特定の動画に関連する動画のリストなどがあります。このセクションでは、API を使用して YouTube 動画ライブラリを特定の検索用語やカテゴリを指定してユーザーが検索できるようにする方法についても説明します。
動画のアップロードのセクションでは、アプリケーションから YouTube にユーザーが動画をアップロードできるようにする 2 種類の方法について簡単に説明します。さらにこのセクションでは、他の動画へのレスポンスとして動画をアップロードする方法についても説明します。
動画の更新と削除のセクションでは、API を使用して YouTube の動画に関する情報を更新する方法について説明します。API を使用して動画を削除する方法についても説明します。
コミュニティ機能の使用のセクションでは、YouTube の動画に対してユーザーが反応を示すことができる API の関数について説明します。これらの関数は、既存の動画についての評価、コメント、動画レスポンス、苦情を投稿する要求を伝えます。API を使用して、動画のコメントや動画レスポンスのリストを取得し、動画レスポンスを削除することもできます。
動画の保存と収集のセクションでは、お気に入りの動画、動画再生リスト、YouTube チャンネルへの登録に対して、API を使用してアクセス、作成、更新する方法について説明します。動画を追加または削除して、動画の再生リストやお気に入りを変更する方法についても示します。
ユーザー交流の利用のセクションでは、API を使用して、ユーザー プロフィールを取得し、更新する方法について説明します。このセクションでは、ユーザーのコンタクトを取得、追加、更新、削除する方法の他、メッセージを取得、送信、削除する方法についても説明します。
PHP クライアント ライブラリを使用するには、PHP 5.1.4 以上を実行している必要があります。さらに Zend_Gdata 1.5RC2 以上を使用する必要がありますが、これは Zend Framework の一部として配布されています。ご使用の環境の設定について詳しくは、スタート ガイドをご覧ください。
下記のサンプル コードは、コピーし、自分のコードに貼り付けて、必要に応じて変更できます。クライアント ライブラリと共に配布されるサンプル アプリケーションにも、多数の API 操作が含まれています。このアプリケーションは、 http://framework.zend.com/svn/framework/demos/Zend/Gdata/YouTubeVideoApp にあります。
YouTube Data API を使用して操作を行う前に、下記のように Zend_Gdata_YouTube オブジェクトを初期化する必要があります。公開コンテンツの取得以外のすべてのアクションには、認証が必要であることに注意してください。
<?php
require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
認証の必要な機能を使用する場合、ClientLogin と AuthSub のどちらを使用する予定かによって、次のヘルパー クラスのどちらかを含める必要もあります (詳しくは下記の認証のセクションをご覧ください)。
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
このガイドのメソッド例の多くは、Zend_Gdata_YouTube のインスタンスを操作します。
注意: Zend の library ディレクトリのコンテンツは、ご使用の PHP の include_path 内に含める必要があります。
PHP クライアント ライブラリを使用して、公開フィードと非公開フィードのどちらも処理できます。公開フィードは読み取り専用で、認証は必要ありません。非公開フィードでは、YouTube サーバーに対して正当性を証明する必要があります。さらに、YouTube デベロッパー キーを取得するために登録する必要があります。認証は、ユーザー名/パスワード認証を使用する ClientLogin か、AuthSub プロキシ認証により行うことができます。
AuthSub プロキシ認証は、YouTube/Google アカウントについてユーザーを認証する必要のあるウェブ アプリケーションが使用します。オペレータは YouTube ユーザーのユーザー名とパスワードにアクセスする必要はなく、特別な AuthSub トークンだけが必要です。
ユーザーが最初にクライアント アプリケーションにアクセスしたときには、まだ Google サービスによる認証は受けていません。この場合、認証を行う Google のページにユーザーを誘導するリンクを提示する必要があります。このページでは、アプリケーションによるユーザーの YouTube アカウントへのアクセス要求が認証されます。Zend Framework PHP Google Data クライアント ライブラリでは、そのための URL. を生成する関数を提供しています。下記のコードにより、AuthSubRequest ページへのリンクが設定されます。
// start a new session
session_start();
function getAuthSubRequestUrl($userName)
{
$next = 'http://mysite.com/welcome.php';
$scope = 'http://gdata.youtube.com';
$secure = false;
$session = true;
return Zend_Gdata_AuthSub::getAuthSubTokenUri($next, $scope, $secure, $session);
}
上記のコードでは、Google の YouTube サービスにトークンを要求する URL が生成されます。getAuthSubRequestUrl メソッドに送るパラメータは次のとおりです。
次のような URL が生成されます。
https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fgdata.youtube.com&session=1&secure=0&next=http%3A%2F%2Fwww.mysite.com%2Fwelcome.php
ユーザーは Google のサイトへのリンクをたどり、Google アカウントに対して正当性を証明します。ユーザーがアプリケーションの $next URL に戻ると、1 回限りのトークンが http://mysite.com/welcome.php?token=DQAADKEDE のようにリダイレクト先と共に送信されます。
セキュリティ上、このトークンは 1 回しか使用できないので、この 1 回限りのトークンをセッション トークンに交換する必要があります。次のコードでは、トークンをアップグレードする方法を示します。
$sessionToken = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
このコードでは、$_GET['token'] 変数に URL の token クエリ パラメータの値が含まれています。この token 値は、1 回限りの AuthSub トークンを表します。前述の getAuthSubRequestUrl 関数に $session = true を指定したので、このトークンは AuthSub セッション トークンに交換可能で、それを上記の getAuthSubSessionToken を呼び出すコードで行っています。
下記の関数では、以上の要求をすべて行います。最初にセッション トークンが既に設定されているかどうかを確認します。設定されていない場合は、前述の getAuthSubRequestUrl 関数を使用して認証用 URL を作成します。URL 文字列 ($_GET['token']) に 1 回限りのトークンが設定されていれば、それをセッション トークンにアップグレードします。最後に、デベロッパー キーを使用して、完全に認証された Zend_Gdata_Http_Client オブジェクトを作成して返します。
function getAuthSubHttpClient($developerKey)
{
if (!isset($_SESSION['sessionToken']) && !isset($_GET['token']) ){
echo '<a href="' . getAuthSubUrl() . '">Login!</a>';
return;
} else if (!isset($_SESSION['sessionToken']) && isset($_GET['token'])) {
$_SESSION['sessionToken'] = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
}
$httpClient = Zend_Gdata_AuthSub::getHttpClient($_SESSION['sessionToken']);
$httpClient->setHeaders('X-GData-Key', "key=${developerKey}");
return $httpClient;
}
次にアプリケーションの $httpClient を Zend_Gdata_YouTube サービス オブジェクトのコンストラクタに渡すことにより、完全に認証済みの YouTube サービス オブジェクトを作成できます。
$yt = new Zend_Gdata_YouTube($httpClient);
この完全に認証済みのサービス オブジェクトを使用して、その後のすべての YouTube API による要求を実行できます。AuthSub セッション トークンは、デベロッパーが明確に無効にする要求を発行するか、ユーザーが認可サイトのページにアクセスしてアクセスを無効にするまで有効です。
ClientLogin 認証は、ユーザー名とパスワードを保管またはユーザに問い合わせできる、インストールするアプリケーションで使用します。この認証形式を使用するには、アプリケーションが代理としてクエリを送信するユーザーのメール アドレスとパスワードを指定し、Zend_Gdata_ClientLogin クラスの静的 getHttpClient メソッドを呼び出します。認証には下記の URL も渡す必要があることに注意してください。たとえば次のように指定します。
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser@gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
資格情報が設定されると、その後のすべての Zend_Gdata_YouTube サービス オブジェクトへの要求を認証に、$httpClient オブジェクトを使用できます。$httpClient に必ずデベロッパー キーも渡します。
$myDeveloperKey = 'ABC123 ... ';
$httpClient->setHeaders('X-GData-Key', "key=${myDeveloperKey}");
$yt = new Zend_Gdata_YouTube($httpClient);
AuthSub と ClientLogin のどちらの方法についても詳しくは、Google Data API 認証のドキュメントを参照してください。
YouTube Data API では、動画のリストである動画フィードが数種類 (標準フィード、アップロード、登録、お気に入りなど) 提供されます。各フィードの URL はリファレンス ガイドに記載されています。
YouTube API のフィードの多くは、動画エントリで構成されています。これらのフィードは、Zend_Gdata_YouTube_VideoFeed オブジェクトとして最も簡単にモデル化できます。このオブジェクトにはそれぞれ複数の Zend_Gdata_YouTube_VideoEntry が含まれます。動画エントリはそれぞれ YouTube 上の 1 本の動画に対応し、その動画に関する情報が含まれます。
動画のリストを取得するコードの基本的な構造は、URL を作成して動画フィードを取得し、そのエントリを一度に 1 つずつ処理するもので、次のようになります。
function getAndPrintVideoFeed($location = Zend_Gdata_YouTube::VIDEO_URI)
{
$yt = new Zend_Gdata_YouTube();
$videoFeed = $yt->getVideoFeed($location);
foreach ($videoFeed as $videoEntry) {
printVideoEntry($videoEntry); // this function is documented fully here
}
}
動画の取得と検索のセクションでは、多数のよく使用されるフィード用 URL と、さまざまな動画フィードの取得方法について詳しく説明します。
特定の動画 ID がわかっている場合は、その動画エントリの情報だけを取得できます。エントリの URL は、その動画 ID がベースになります。
http://gdata.youtube.com/feeds/api/videos/videoID
次のコードでは、YouTube 上の動画に対応する VideoEntry を取得します。
$yt->getVideoEntry('the0KZLEacs');
VideoEntry オブジェクトから、サムネイル、プレーヤーの URL、動画の再生時間など、さまざまなメタデータが取得できます。下記のコードでは、この情報の一部を取得する方法を示します。PHP クライアント ライブラリは、XML 要素を PHP のクラスにマッピングすることで、この機能のほとんどを抽象化しています。VideoEntry エントリに関する重要な情報のほとんどは、media:group 要素 (VideoEntry の下位にあります) の子要素から入手できます。この XML 要素は MediaGroup オブジェクトにマッピングされ、$videoEntry->getMediaGroup() または $videoEntry->mediaGroup を呼び出すことで取得できます。mediaGroup の子要素へのアクセスを簡単にし、VideoEntry オブジェクトから直接呼び出せるように、クライアント ライブラリに多数のヘルパー メソッドが追加されています。こうしたメソッドの例の 1 つは、$videoEntry->getVideoTitle() です。
function printVideoEntry($videoEntry, $tabs = "")
{
// the videoEntry object contains many helper functions that access the underlying mediaGroup object
echo $tabs . 'Video: ' . $videoEntry->getVideoTitle() . "\n";
echo $tabs . "\tDescription: " . $videoEntry->getVideoDescription() . "\n";
echo $tabs . "\tCategory: " . $videoEntry->getVideoCategory() . "\n";
echo $tabs . "\tTags: " . implode(", ", $videoEntry->getVideoTags()) . "\n";
echo $tabs . "\tWatch page: " . $videoEntry->getVideoWatchPageUrl() . "\n";
echo $tabs . "\tFlash Player Url: " . $videoEntry->getFlashPlayerUrl() . "\n";
echo $tabs . "\tDuration: " . $videoEntry->getVideoDuration() . "\n";
echo $tabs . "\tView count: " . $videoEntry->getVideoViewCount() . "\n";
echo $tabs . "\tRating: " . $videoEntry->getVideoRatingInfo() . "\n";
echo $tabs . "\tGeo Location: " . $videoEntry->getVideoGeoLocation() . "\n";
// see the paragraph above this function for more information on the 'mediaGroup' object
// here we are using the mediaGroup object directly to its 'Mobile RSTP link' child
foreach ($videoEntry->mediaGroup->content as $content) {
if ($content->type === "video/3gpp") {
echo $tabs . "\tMobile RTSP link: " . $content->url . "\n";
}
}
echo $tabs . "\tThumbnails:\n";
$videoThumbnails = $videoEntry->getVideoThumbnails();
foreach($videoThumbnails as $videoThumbnail) {
echo $tabs . "\t\t" . $videoThumbnail->time . " - " . $videoThumbnail->url;
echo " height=" . $videoThumbnail->height;
echo " width=" . $videoThumbnail->width;
echo "\n";
}
}
自分のページに動画をプレーヤーと共に埋め込むために必要な情報の生成方法について詳しくは、プロトコル ガイドをご覧ください。
YouTube Data API では現在、さまざまな条件に対して動画の標準フィードを提供しています。これらのフィードは、サイト全体にわたるもので、ユーザー固有のフィードではありません。標準フィードの URL はすべて http://gdata.youtube.com/feeds/api/standardfeeds/ で始まり、その後にフィードの ID を続けます。取得できるフィードの一覧は、次のとおりです。
| フィード名 | フィード ID |
|---|---|
| 人気の動画 | most_viewed |
| 評価の高い動画 | top_rated |
| おすすめ | recently_featured |
| モバイル向け動画 | watch_on_mobile |
| 話題の動画 | most_discussed |
| お気に入り登録の多い動画 | top_favorites |
| リンク数の多い動画 | most_linked |
| コメントの多い動画 | most_responded |
| 新着動画 | most_recent |
地域固有の標準フィードも取得できます。それにはフォーマット http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID に localeID を指定します。たとえば日本での人気の動画のフィードは http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_viewed となります。予定されている localeID の全一覧は、リファレンス ガイドをご覧ください。
次の例では YouTube::getVideoFeed() メソッドを使用して、標準フィードをフェッチして出力する方法を示します。
これらのフィードの URL の一部は、定数として定義され、一部はヘルパー メソッドで取得可能ですが、リファレンス ガイドに規定されている値を使用して、URL を手作業で作成することもできます。標準フィードの取得には、Zend_Gdata_YouTube サービス オブジェクトの認証は必要ありません。
function getAndPrintStandardFeeds()
{
// constructing URL manually
$YOUTUBE_GDATA_SERVER = 'http://gdata.youtube.com';
$STANDARD_FEED_PREFIX = $YOUTUBE_GDATA_SERVER . '/feeds/api/standardfeeds/';
$TOP_RATED_FEED = $STANDARD_FEED_PREFIX . 'top_rated';
getAndPrintVideoFeed($TOP_RATED_FEED);
// URL as a constant in Zend_Gdata_YouTube
getAndPrintVideoFeed(Zend_Gdata_YouTube::STANDARD_TOP_RATED_URI);
// using helper method
$yt = new Zend_Gdata_YouTube();
printVideoFeed($yt->getTopRatedVideoFeed());
// choosing the time period for a standard feed
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery(Zend_Gdata_YouTube::STANDARD_TOP_RATED_URI);
$query->setTime('today');
// reusing the getAndPrintVideo feed function defined earlier
getAndPrintVideoFeed($query);
}
VideoFeed オブジェクトは VideoEntry オブジェクトのコレクションです。次のヘルパー関数で、フィード内に返された動画の詳細を出力します。
function printVideoFeed($videoFeed, $displayTitle = null)
{
$count = 1;
if ($displayTitle === null) {
$displayTitle = $videoFeed->title->text;
}
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
foreach ($videoFeed as $videoEntry) {
echo 'Entry # ' . $count . "\n";
printVideoEntry($videoEntry);
echo "\n";
$count++;
}
echo "</pre>\n";
}
各 YouTube ユーザーには動画フィードが 1 つ関連付けられており、このフィードはそのユーザーが http://gdata.youtube.com/feeds/api/users/username/uploads にアップロードした動画に対応します。次のコードでは、ユーザーのアップロード フィードをフェッチし、表示する方法を示します。
function getAndPrintUserUploads($userName)
{
$yt = new Zend_Gdata_YouTube();
printVideoFeed($yt->getuserUploads($userName));
}
$userName の代わりに文字列 'default' を使用して、現在認証されているユーザーの動画を取得することもできます。
関連する動画を取得するには、Video_Entry オブジェクトの動画 ID を Zend_Gdata_YouTube オブジェクトの getRelatedVideoFeed メソッドに渡します。これによって関連エントリを含む VideoFeed オブジェクトが取得されます。
$relatedVideosFeed = $yt->getRelatedVideoFeed($originalVideo->getVideoId());
YouTube Data API を使用すると、指定した条件に一致するエントリのセットを要求できます。たとえば特定の投稿者が公開した動画エントリ、特定の動画フォーマットのエントリ、特定のキーワードを含む動画エントリを要求できます。そのためには VideoQuery オブジェクトを特定の検索条件を含めて作成し、YouTube::getVideoFeed() メソッドに渡します。
たとえば キーワード検索をして、結果を再生回数順に並べ、制限付き動画 (API が「際どい」とみなすもの) を含める場合、VideoQuery オブジェクトの setVideoQuery、setOrderBy、setRacy のメソッドを使用します。次のコードでは、指定したキーワードに一致するすべての動画のタイトルと要約を、再生回数順に並べ、制限付き動画を含めて出力します。
function searchAndPrint($searchTerms)
{
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setOrderBy('viewCount');
$query->setRacy('include');
$query->setVideoQuery($searchTerms);
$videoFeed = $yt->getVideoFeed($query);
printVideoFeed($videoFeed, 'Search results for: ' . $searchTerms);
}
Query クラスと VideoQuery などのサブクラスは、フィード用 URL の作成を担当します。上記の VideoQuery は、次の URL と同等の URL を構成します。
http://gdata.youtube.com/feeds/api/videos?vq=searchTerms&racy=include&orderby=viewCount
検索パラメータを設定するためによく使用される VideoQuery メソッドには、次のものがあります。
setAuthorsetFormatsetRacysetMaxResultssetStartIndexsetOrderByRELEVANCE、VIEW_COUNT、UPDATED、RATING などによる順序を指定できます。setTimeTODAY、THIS_WEEK、THIS_MONTH、ALL_TIME の期間に限定するように設定します。setVideoQuery設定しようとするパラメータに対応するヘルパー メソッドが VideoQuery クラスにない場合、$query->setParam('name', 'value') メソッドを呼び出してカスタム パラメータを設定できます。クエリ パラメータについて詳しくは YouTube Data API リファレンス ガイドと Google Data API リファレンス ガイドをご覧ください。
指定したカテゴリとキーワードのセットに一致する動画だけを示すように、検索結果を制限できます。リファレンス ガイドでは、あらかじめ定義された YouTube カテゴリと、タグとも呼ばれるユーザー定義のキーワードの両方を指定する方法について説明しています。
下記のコードでは、検索キーワードを小文字に変換し、キーワード (タグ) を使用して検索する方法を示します。注意: YouTube のカテゴリとキーワードの両方になる言葉 ("comedy" など) もあるので、カテゴリとキーワードによる検索では、最初を大文字にした言葉 ("Comedy") は YouTube カテゴリを表し、小文字の言葉 ("comedy") はキーワードを表すという表記法を使用します。
function searchAndPrintVideosByKeywords($searchTermsArray)
{
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setOrderBy('viewCount');
$query->setRacy('include');
$keywordQuery = '';
foreach ($searchTermsArray as $searchTerm) {
$keywordQuery .= strtolower($searchTerm) . '/';
}
$query->setCategory($keywordQuery);
$videoFeed = $yt->getVideoFeed($query);
printVideoFeed($videoFeed, 'Search results for keyword search:');
}
デベロッパー タグとは、デベロッパーがアップロードしたコンテンツのキーワードとして使用する追加の隠しタグのことです。このキーワードは、一般には表示されず、動画の取得には使用できません。特定のデベロッパー タグによって動画を検索するには、通常の YouTube Data API の検索要求を送信しますが、必ずカテゴリ スキームと動画が一致するデベロッパー タグを指定します。デベロッパー タグを使用して動画にアクセスする場合は、クライアントの認は必要はありませんが、デベロッパー キーをヘッダーに設定する必要があります。下記の URL を使用して、デベロッパー タグ (下記では 'your_tag_here') に一致する動画のフィードを取得できます。
$devTagUrl = "http://gdata.youtube.com/feeds/videos/-/%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007%2Fdevelopertags.cat%7Dyour_tag_here"; // obtain a feed with videos matching the provided developer tag $yt->getVideoFeed($devTagUrl);
アップロード プロセスの大まかな流れについて、プロトコル ガイドの図を必ず確認してください。動画のアップロードには、動画を直接アップロードするか、動画のメタデータだけを送信し、HTML フォームにより動画をユーザーにアップロードさせる 2 つの方法があります。
詳しくは、次のページをご覧ください。
developers_guide_protocol.html#Process_Flows_for_Uploading_Videos
動画をアップロードするには、最初に新しい VideoEntry オブジェクトを作成し、必要なメンバーを指定します。下記の例では、YouTube に QuickTime の動画 "mytestmovie.mov" を次のプロパティを指定してアップロードします。
| プロパティ | 値 |
|---|---|
| タイトル | My Test Movie |
| カテゴリ | Autos |
| キーワード | cars, funny |
| 説明 | My description |
| ファイル名 | mytestmovie.mov |
| ファイルの MIME タイプ | video/quicktime |
| 非公開動画か? | false |
| 動画の位置 | 37, -122 (緯度, 経度) |
| デベロッパー タグ | mydevelopertag, anotherdevelopertag |
下記のコードでは、アップロードされる空の VideoEntry を作成します。次に Zend_Gdata_App_MediaFileSource オブジェクトを使用して、実際の動画ファイルを保存します。Zend_Gdata_YouTube_MediaGroup オブジェクトを使用して、動画のメタデータを保存します。$uploadUrl は、新しいエントリが投稿される位置です。この指定には、現在認証されているユーザーの $userName を指定するか、文字列 'default' (現在認証されているユーザーを指す) を指定できます。
$yt = new Zend_Gdata_YouTube($httpClient);
// create a new Zend_Gdata_YouTube_VideoEntry object
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
// create a new Zend_Gdata_App_MediaFileSource object
$filesource = $yt->newMediaFileSource('mytestmovie.mov');
$filesource->setContentType('video/quicktime');
// set slug header
$filesource->setSlug('mytestmovie.mov');
// add the filesource to the video entry
$myVideoEntry->setMediaSource($filesource);
// create a new Zend_Gdata_YouTube_MediaGroup object
$mediaGroup = $yt->newMediaGroup();
$mediaGroup->title = $yt->newMediaTitle()->setText('My Test Movie');
$mediaGroup->description = $yt->newMediaDescription()->setText('My description');
// the category must be a valid YouTube category
// optionally set some developer tags (see Searching by Developer Tags for more details)
$mediaGroup->category = array(
$yt->newMediaCategory()->setText('Autos')->setScheme('http://gdata.youtube.com/schemas/2007/categories.cat'),
$yt->newMediaCategory()->setText('mydevelopertag')->setScheme('http://gdata.youtube.com/schemas/2007/developertags.cat'),
$yt->newMediaCategory()->setText('anotherdevelopertag')->setScheme('http://gdata.youtube.com/schemas/2007/developertags.cat')
);
// set keywords
$mediaGroup->keywords = $service->newMediaKeywords()->setText('cars, funny');
$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);
$entry->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();
}
ブラウザ ベースのアップロードは、直接アップロードとほとんど同様に行われますが、作成する VideoEntry に MediaFileSource オブジェクトは付加しません。その代わりに、動画のすべてのメタデータだけを送信して、トークン 要素を受け取り、これを使用して HTML のアップロード フォームを作成できます。
$yt = new Zend_Gdata_YouTube($httpClient);
// create a Zend_Gdata_YouTube_VideoEntry
$myVideoEntry= new Zend_Gdata_YouTube_VideoEntry();
// set up media group as in the example above
$mediaGroup = $yt->newMediaGroup();
$mediaGroup->title = $yt->newMediaTitle()->setText('My Test Movie');
$mediaGroup->description = $yt->newMediaDescription()->setText('My description');
// 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('Autos')->setScheme($categoryScheme),
$yt->newMediaCategory()->setText('mydevelopertag')->setScheme($developerTagScheme),
$yt->newMediaCategory()->setText('anotherdevelopertag')->setScheme($developerTagScheme)
);
$mediaGroup->keywords = $yt->newMediaKeywords()->setText('cars, funny');
$myVideoEntry->mediaGroup = $mediaGroup;
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
$tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];
上記のコードでは、HTML フォームを作成するのに使用するリンクとトークンを、ユーザーのブラウザに表示するために出力しています。簡単なフォームの例を下記に示します。これには上記で $myVideoEntry から取得した要素のように、返されたトークン 要素のコンテンツを表す $tokenValue を指定しています。フォームの送信後にユーザーをアプリケーションのウェブサイトにリダイレクトするため、必ず $nextUrl パラメータを上記の $postUrl に付加します。これは AuthSub リンクの $next パラメータと同じように機能します。1 つ異なる点は、ここでは 1 回限りのトークンの代わりに status と id 変数が URL の中に返される点です。
// place to redirect user after upload
$nextUrl = 'http://mysite.com/youtube_uploads';
// build the form
$form = '<form action="'. $postUrl .'?nexturl='. $nextUrl .
'" method="post" enctype="multipart/form-data">'.
'<input name="file" type="file"/>'.
'<input name="token" type="hidden" value="'. $tokenValue .'"/>'.
'<input value="Upload Video File" type="submit" />'.
'</form>';
// assuming that $nextUrl was http://mysite.com/youtube_uploads http://mysite.com/youtube_uploads?status=200&id=JPF-DXF7hzc
status パラメータには、アップロード トランザクションの HTTP トランザクション ステータスが返されます。id パラメータには、アップロードした動画に割り当てられた YouTube 動画 ID が返されます。
動画のアップロード後、その動画は認証されたユーザーのアップロード フィードにすぐに表示されます。ただし処理が終わるまでは、サイト上に公開されません。拒否された動画や、アップロードに失敗した動画も、認証されたユーザーのアップロード フィードにのみ残ります。次のコードでは、VideoEntry のステータスを確認して、動画が有効になったか、拒否されたかを調べます。
// check if video is in draft status
try {
$control = $videoEntry->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 = $videoEntry->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";
}
}
}
動画のメタデータを更新するには、VideoEntry オブジェクトを更新してから、Zend_Gdata_YouTube サービスの updateEntry メソッドを使用します。updateEntry は HTTP PUT 要求を発行するので、動画エントリの「編集」リンクをその場所として使用する必要があります。次のコードでは、動画のタイトルを更新する方法と、更新を送信するための動画の「編集」リンクを取得する方法を示します。
$videoEntry->mediaGroup->title->text = 'A new title'; $putUrl = $videoEntry->getEditLink()->getHref(); $yt->updateEntry($videoEntry, $putUrl);
動画を削除するには、認証されたユーザーのアップロード フィードを取得し、Zend_Gdata_YouTube サービス オブジェクトの delete() メソッドを呼び出して、削除する VideoEntry を渡します。
$yt->delete($videoEntryToDelete);
動画を評価するには、VideoEntry に Rating オブジェクトを追加し、その VideoEntry の評価リンクに投稿 (POST) します。
// create a new Zend_Gdata_App_Entry
$ratingEntry = $service->newEntry();
// create a new Zend_Gdata_App_Extension_Rating element
$rating = $service->newRating();
$rating->setMax(5);
$rating->setMin(1);
// create a custom attribute for gd:rating value="5",
// setting the new rating to be submitted to '5 stars'
$rating->setExtensionAttributes(array(array('namespaceUri' => 'http://schemas.google.com/g/2005', 'name' => 'value', 'value' => '5')));
// add the extension element to the rating entry
$ratingEntry->extensionElements = array($rating);
// obtain the ratings url for the video that you wish to rate
$ratingUrl = $videoEntry->getLink('http://gdata.youtube.com/schemas/2007#video.ratings')->getHref();
// post the $ratingEntry to the $ratingUrl using the insertEntry method of the Zend_Gdata_YouTube service object
try {
$response = $service->insertEntry( $ratingEntry, $ratingUrl );
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
特定の VideoEntry オブジェクトに対して、次のコードに示すように、その動画のコメントを含むフィードを取得して、出力できます。
getAndPrintCommentFeed($videoEntry->videoId);
function getAndPrintCommentFeed($videoId)
{
$yt = new Zend_Gdata_YouTube();
$commentFeed = $yt->getVideoCommentFeed($videoId);
printCommentFeed($commentFeed);
}
function printCommentFeed($commentFeed, $displayTitle = null)
{
$count = 1;
if ($displayTitle === null) {
$displayTitle = $commentFeed->title->text;
}
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
foreach ($commentFeed as $commentEntry) {
echo 'Entry # ' . $count . "\n";
printCommentEntry($commentEntry);
echo "\n";
$count++;
}
echo "</pre>\n";
}
function printCommentEntry($commentEntry)
{
echo 'Comment: ' . $commentEntry->title->text . "\n";
echo "\tFull text: " . $commentEntry->content->text . "\n";
echo "\tAuthor: " . $commentEntry->author->name->text . "\n";
}
新しいコメントを追加するには、Zend_Gdata_YouTube サービス オブジェクトを使用します。
$newComment = $yt->newCommentEntry();
$newComment->content = $service->newContent()->setText('new comment');
// post the comment to the comment post URL
$comment_post_url = 'http://gdata.youtube.com/feeds/videos/'. $video_id .'/comments';
$updatedVideoEntry = $yt->insertEntry( $comment2, $comment_post_url );
コメントを削除するには、まず Zend_Gdata_YouTube_CommentFeed オブジェクトを通してそのコメントを取得する必要があります。次に Zend_Gdata_YouTube サービス オブジェクトを使用して、特定の CommentEntry を削除します。
$yt->delete($commentEntryToBeDeleted);
動画フィードの中の各動画エントリには、関連する動画レスポンス フィードが含まれている場合があり、それ自体も動画フィードです。次のコードでは、特定の VideoEntry の動画レスポンスに関する情報を取得して出力する方法を示します。
function getAndPrintVideoResponses($videoEntry)
{
$responsesFeedUrl = $videoEntry->getVideoResponsesLink()->getHref();
getAndPrintVideoFeed($responsesFeedUrl);
}
この例では、getAndPrintVideoFeed() 関数を再使用しています。この場合、フィードの URL は手作業で作成しないで、VideoEntry::getVideoResponsesLink()->getHref() を呼び出すことで動的に取得します。フィードの URL を知る必要なく、フィードを取得する方法について詳しくは、リファレンス ガイドのフィード間の移動をご覧ください。
前のセクションで示したように、動画レスポンスのリンクを取得後、別の動画に対応する VideoEntry を投稿 (POST) して、最初の動画の動画レスポンスにすることができます。
$yt->insertEntry($videoResponseEntry, $responsesFeedUrl);
動画レスポンスを投稿するには、YouTube に投稿することをその動画のオーナーが承認する必要があります。
動画レスポンス リンクを使用して取得した VideoFeed オブジェクトのリストに含まれる動画のどれかを所有している場合、その動画を動画レスポンスから削除できます。それには、Zend_Gdata_YouTube サービス オブジェクトの delete() を呼び出して、削除するエントリを渡します。
$yt->delete($videoEntryToBeDeleted);
動画に関する苦情を追加するには、Atom エントリを VideoEntry オブジェクトの苦情リンクに投稿 (POST) します。下記のコードでは、動画を報告する方法を示します。
$complaintUrl = $badVideoEntry->getVideoComplaintsLink()->getHref();
$complaintEntry = $yt->newEntry();
$newComplaint->content = $yt->newContent()->setText('This video is inapproriate.');
// then use the $yt service to insert the entry
try {
$yt->insertEntry($complaintEntry, $complaintUrl);
} catch (Zend_App_Exception $e) {
print $e->getMessage();
}
YouTube のユーザーは動画にお気に入りのマークを付けることができます。ユーザーのお気に入りのフィードの場所は、通常次の URL になります。
http://gdata.youtube.com/feeds/api/users/username/favorites
ユーザーのお気に入りの動画を取得するには、Zend_Gdata_YouTube サービス オブジェクトのフィードを要求します。返されるフィードは、VideoEntry オブジェクトが含まれる通常の動画フィードです。
$favoritesFeed = $yt->getUserFavorites($userName);
注意: または文字列 default を渡して、現在認証されているユーザーのお気に入りを取得することもできます。
お気に入りの動画を追加するには、Zend_Gdata_YouTube サービス オブジェクトの insertEntry メソッドを使用して、新しいお気に入り (通常の Zend_Gdata_YouTube_VideoEntry) をユーザーのお気に入りのフィードに登録します。
$yt->insertEntry($newFavoriteVideoEntry, $favoritesFeed);
お気に入りを削除するには、Zend_Gdata_YouTube_VideoEntry オブジェクトに対して delete() メソッドを使用します。必ずユーザーの実際のお気に入りのフィードから、削除するお気に入りを取得してください。そうしないと、実際の動画エントリが削除されます。
$favoriteVideoToBeDeleted->delete();
YouTube の各ユーザーには各再生リスト内の動画を含むフィードへのリンクのリストである再生リストフィードが関連付けられています。
手作業でユーザーのすべての再生リストのリストをフェッチするには、次の URL を使用します。
http://gdata.youtube.com/feeds/api/users/username/playlists
注意: または文字列 default を渡して、現在認証されているユーザーのお気に入りを取得することもできます。
function getAndPrintPlaylistListFeed($userName, $showPlaylistContents)
{
$yt = new Zend_Gdata_YouTube();
$playlistListFeed = $yt->getPlaylistListFeed($userName);
printPlaylistListFeed($playlistListFeed, $showPlaylistContents);
}
function printPlaylistListFeed($playlistListFeed, $showPlaylistContents)
{
$count = 1;
if ($displayTitle === null) {
$displayTitle = $playlistListFeed->title->text;
}
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
foreach ($playlistListFeed as $playlistListEntry) {
echo 'Entry # ' . $count . "\n";
printPlaylistListEntry($playlistListEntry, $showPlaylistContents);
echo "\n";
$count++;
}
echo "</pre>\n";
}
前述の例で取得したように、PlaylistListEntry が得られると、次のコードを使用して、実際の再生リストをフェッチして出力できます。
function printPlaylistListEntry($playlistListEntry, $showPlaylistContents = false)
{
echo 'Playlist: ' . $playlistListEntry->title->text . "\n";
echo "\tDescription: " . $playlistListEntry->description->text . "\n";
if ($showPlaylistContents === true) {
getAndPrintPlaylistVideoFeed($playlistListEntry, "\t\t");
}
}
function getAndPrintPlaylistVideoFeed($playlistListEntry, $tabs = "")
{
$yt = new Zend_Gdata_YouTube();
$playlistVideoFeed = $yt->getPlaylistVideoFeed($playlistListEntry->getPlaylistVideoFeedUrl());
foreach ($playlistVideoFeed as $playlistVideoEntry) {
printVideoEntry($playlistVideoEntry, $tabs . "\t");
}
}
この関数 printPlaylistListEntry() にはオプションのブール型パラメータ showPlaylistContents があり、このパラメータが true の場合、各再生リスト内の動画のリストも出力します。この場合、次のセクションで定義する関数を使用します。
新しい再生リストを追加するには、Zend_Gdata_YouTube サービス オブジェクトを使用して再生リストを作成し、それをユーザーの再生リストの URL に登録します。
$newPlaylist = $yt->newPlaylistListEntry();
$newPlaylist->description = $yt->newDescription()->setText('description of my new playlist');
$newPlaylist->title = $yt->newTitle()->setText('title of my new playlist');
// post the new playlist
$postLocation = 'http://gdata.youtube.com/feeds/users/default/playlists';
try {
$yt->insertEntry($newPlaylist, $postLocation);
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
再生リストを更新するには、取得した Zend_Gdata_YouTube_PlaylistListEntry オブジェクトを変更し、save() メソッドを使用してその変更を保存します。
$playlistToBeUpdated->description->setText('new description for my playlist');
$playlistToBeUpdated->save();
再生リストに動画を追加するには、VideoEntry オブジェクトを使用します。下記のコードでは、既にわかっているエントリ ID を使用して VideoEntry を取得し、それを PlaylistLinkEntry に対応する再生リストに追加します。位置を指定していないので、新しい動画は再生リストの最後に追加されます。
$postUrl = $playlistToAddTo->getPlaylistVideoFeedUrl();
// video entry to be added
$videoEntryToAdd = $service->getVideoEntry('4XpnKHJAok8');
// create a new Zend_Gdata_PlaylistListEntry, passing in the underling DOMElement of the VideoEntry
$newPlaylistListEntry = $service->newPlaylistListEntry($videoEntryToAdd->getDOM());
$newPlaylistListEntry->description = $service->newDescription()->setText('Custom description');
$newPlaylistListEntry->title = $service->newTitle()->setText('Custom title');
// post
try {
$yt->insertEntry($newPlaylistListEntry, $postUrl);
} catch (Zend_App_Exception $e) {
print $e->getMessage();
}
上記のコードでは、動画にカスタム タイトルとカスタム説明を指定しています。これは必須ではありません。指定しない場合、動画の実際のタイトルと説明が使用されます。
再生リスト内の各動画のカスタム タイトルとカスタム説明を変更するには、その動画の PlaylistVideoEntry オブジェクトを更新して update メソッドを呼び出します。
// get a Zend_Gdata_PlaylistVideoEntry from the feed generated by $yt->getPlaylistVideoFeedUrl
$playlistVideoEntryToBeModified->setPosition($yt->newPosition(2));
$playlistVideoEntryToBeModified->setTitle($yt->newTitle('Updated title for my video'));
// update by putting the new entry to the entry's edit link
try {
$yt->updateEntry($playlistVideoEntryToBeModified, $playlistVideoEntryToBeModified->getEditLink()->getHref());
}
注意: 再生リスト上の動画のタイトルと説明を、動画のオリジナルのタイトルと説明に戻したい場合は、上記のコードでタイトルと説明の両方に NULL を渡します。
再生リストから動画を削除するには、PlaylistListEntry の delete() メソッドを使用します。
$playlistEntryToBeDeleted->delete();
再生リストを削除するには、Zend_Gdata_YouTube_PlaylistListEntry オブジェクトに対して delete() メソッドを使用します。
$playlistListEntryToBeDeleted->delete();
特定のユーザーが登録しているチャンネル、検索、お気に入りのリストをフェッチするには、次の URL を使用します。
http://gdata.youtube.com/feeds/api/users/username/subscriptions
注意: または文字列 default を渡して、現在認証されているユーザーのお気に入りを取得することもできます。
次のコードでは、特定のユーザーの SubscriptionEntry オブジェクトのリストを取得して出力する方法を示します。
function getAndPrintSubscriptionFeed($userName)
{
$yt = new Zend_Gdata_YouTube();
// obtain a user's subscription feed. Alternatively you can use the string 'default'
// to retrieve subscriptions for the currently authenticated user
$subscriptionFeed = $yt->getSubscriptionFeed($userName);
printSubscriptionFeed($subscriptionFeed);
}
function printSubscriptionFeed($subscriptionFeed)
{
$count = 1;
if ($displayTitle === null) {
$displayTitle = $subscriptionFeed->title->text;
}
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
foreach ($subscriptionFeed as $subscriptionEntry) {
echo 'Entry # ' . $count . "\n";
printSubscriptionEntry($subscriptionEntry);
echo "\n";
$count++;
}
echo "</pre>\n";
}
function printSubscriptionEntry($subscriptionEntry)
{
$type = 'unknown';
$subscriptionFeedLinkMap = array(
'query' => 'http://gdata.youtube.com/schemas/2007#video.query',
'favorites' => 'http://gdata.youtube.com/schemas/2007#user.favorites',
'channel' => 'http://gdata.youtube.com/schemas/2007#user.uploads'
);
echo 'Subscription: ' . $subscriptionEntry->title->text . "\n";
// look at the category property to to determine the type of subscription,
// which is currently one of: query, favorites, channel
foreach ($subscriptionEntry->category as $category) {
if ($category->scheme == 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat') {
$type = $category->term;
}
}
echo "\tType: " . $type . "\n";
echo "\tURL: ";
// use the map defined above to fine the appropriate feedLink, depending on
// what type of subscription entry was passed
$feedLink = $subscriptionEntry->getFeedLink($subscriptionFeedLinkMap[$type]);
if ($feedLink !== null) {
echo $feedLink->href;
}
echo "\n";
}
新しい登録を作成するには、認証されたユーザーの登録フィードの中に、新しい SubscriptionEntry を挿入します。次のコードでは、"GoogleDevelopers" チャネルに認証されたユーザーを登録します。
$newSubscription = $yt->newSubscriptionEntry();
$newSubscription->extensionElements = array($yt->newUsername('GoogleDevelopers'));
$subscriptionTypesSchema = 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat';
$newSubscription->category = array($yt->newCategory('channel', $subscriptionTypesSchema));
$subscriptionsFeedUrl = 'http://gdata.youtube.com/feeds/users/'. $userName .'/subscriptions';
// and then post using $yt->insertEntry
try {
$yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
echo $e->getMessage();
}
"GoogleDevelopers"ユーザーのお気に入りを登録することもできます。
$newSubscription = $yt->newSubscriptionEntry();
$newSubscription->extensionElements = array($yt->newUsername('GoogleDevelopers'));
$subscriptionTypesSchema = 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat';
$newSubscription->category = array($yt->newCategory('favorites', $subscriptionTypesSchema));
$subscriptionsFeedUrl = 'http://gdata.youtube.com/feeds/users/default/subscriptions';
// and then post using $yt->insertEntry
try {
$yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
echo $e->getMessage();
}
最後に、特定の検索キーワードを登録することもできます。ここでは "puppies" に関する動画の検索を登録しています。
$newSubscription = $yt->newSubscriptionEntry();
// create a yt:querystring extension element to indicate a search for 'puppies'
$ytQuerystringValue = 'puppies';
$ytQuerystringSchema = 'http://gdata.youtube.com/schemas/2007';
$subscriptionTypesSchema = 'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat';
$newSubscription->extensionElements = array(
new Zend_Gdata_App_Extension_Element('queryString', 'yt', $ytQuerystringSchema, $ytQuerystringValue)
);
$newSubscription->category = array(
$yt->newCategory('query', $subscriptionTypesSchema)
);
// and then post using $yt->insertEntry
$subscriptionsFeedUrl = 'http://gdata.youtube.com/feeds/users/default/subscriptions';
try {
$yt->insertEntry($newSubscription, $subscriptionsFeedUrl);
} catch (Zend_App_Exception $e) {
echo $e->getMessage();
}
この機能は PHP クライアント ライブラリの将来のバージョンに含まれることに注意してください。yt:querystring 拡張要素を自動的に生成して設定するヘルパー メソッドを提供する予定です。
ユーザーの登録を削除するには、SubscriptionEntry オブジェクトに対して delete() を呼び出します。
$subscriptionEntryToBeDeleted->delete();
手作業で YouTube のユーザー プロフィールをフェッチするには、次の URL を使用します。
http://gdata.youtube.com/feeds/api/users/username
ユーザー プロフィールを取得して出力するコードは、次のとおりです。
function getAndPrintUserProfile($userName)
{
$yt = new Zend_Gdata_YouTube();
$userProfileEntry = $yt->getUserProfile($userName);
$displayTitle = $userProfileEntry->title->text;
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
echo 'Username: ' . $userProfileEntry->getUsername() . "\n";
echo "\tAge: " . $userProfileEntry->getAge() . "\n";
echo "\tGender: " . $userProfileEntry->getGender() . "\n";
echo "\tRelationship: " . $userProfileEntry->getRelationship() . "\n";
echo "\tBooks: " . $userProfileEntry->getBooks() . "\n";
echo "\tCompany: " . $userProfileEntry->getCompany() . "\n";
echo "\tHobbies: " . $userProfileEntry->getHobbies() . "\n";
echo "\tHometown: " . $userProfileEntry->getHometown() . "\n";
echo "\tLocation: " . $userProfileEntry->getLocation() . "\n";
echo "\tMovies: " . $userProfileEntry->getMovies() . "\n";
echo "\tMusic: " . $userProfileEntry->getMusic() . "\n";
echo "\tOccupation: " . $userProfileEntry->getOccupation() . "\n";
echo "\tSchool: " . $userProfileEntry->getSchool() . "\n";
echo "</pre>\n";
}
ユーザー名の代わりに、「現在認証されているユーザー」を意味する文字列 default を使用できることに注意してください。クライアント ライブラリでは PHP 5.2 でのみ利用可能なオーバーロードされるマジック メソッドを利用しています。PHP 5.1 を使用している場合は、上記の呼び出しを変更する必要があります。その場合、$userProfileEntry->getAge() などの呼び出しは $userProfileEntry->getAge()->getTitle() に変更する必要があります。
特定のユーザーのコンタクトのリストは、次の URL で取得できます。
http://gdata.youtube.com/feeds/api/users/username/contacts
次のコードでは、特定のユーザーのコンタクト リストを取得して出力する方法を示します。
function getAndPrintContactsFeed($userName)
{
$yt = new Zend_Gdata_YouTube();
$contactsFeed = $yt->getContactsFeed($userName);
printContactsFeed($contactsFeed);
}
function printContactsFeed($contactsFeed)
{
$count = 1;
if ($displayTitle === null) {
$displayTitle = $contactsFeed->title->text;
}
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
foreach ($contactsFeed as $contactsEntry) {
echo 'Entry # ' . $count . "\n";
printContactsEntry($contactsEntry);
echo "\n";
$count++;
}
echo "</pre>\n";
}
function printContactsEntry($contactsEntry)
{
echo 'Contact: ' . $contactsEntry->title->text . "\n";
foreach ($contactsEntry->category as $category) {
if ($category->scheme == 'http://schemas.google.com/g/2005#kind') {
$type = $category->term;
}
}
echo "\tType: " . $type . "\n";
}
新しいコンタクトを Friend として追加するには、Zend_Gdata_YouTube サービス オブジェクトの insertEntry メソッドを使用します。
$newContact = $yt->newContactEntry();
$newContact->username = $yt->newUsername('newContactsUsername');
$newContact->category = array($yt->newCategory('http://gdata.youtube.com/schemas/2007#friend',
'http://schemas.google.com/g/2005#kind'));
コンタクトを承認または拒否するには、対応する ContactEntry のステータスを更新します。
要求を承認するには、次のようにします。
$contactEntry->setStatus($yt->newStatus('accepted'));
$contactEntry->save();
要求を拒否するには、ContactEntry のステータスに値 'rejected' を渡します。
コンタクトを削除するには、ContactEntry オブジェクトに対して delete() メソッドを呼び出します。
$contactToBeDeleted->delete();
コンタクトを互いに承認した YouTube ユーザー間では、メッセージを送信できます。API を通して送信するすべてのメッセージには VideoEntry を含める必要があります。
ユーザーの受信ボックスのコンテンツを取得するには、ユーザーの受信ボックスの URL に認証済みの要求を送ります。
http://gdata.youtube.com/feeds/api/users/username/inbox
下記の例では、認証されているユーザーの受信ボックスのコンテンツを出力します。
$inboxFeedUrl = 'http://gdata.youtube.com/feeds/api/users/username/inbox';
$inboxFeed = $yt->getFeed($inboxFeedUrl);
function printVideoMessageFeed($inboxFeed, $displayTitle = null)
{
$count = 1;
if ($displayTitle === null) {
$displayTitle = $videoFeed->title->text;
}
echo '<h2>' . $displayTitle . "</h2>\n";
echo "<pre>\n";
foreach ($inboxFeed as $videoMessageEntry) {
echo 'Entry # ' . $count . "\n";
printVideoMessage($videoMessageEntry);
echo "\n";
$count++;
}
echo "</pre>\n";
}
function printVideoMessage($videoMessageEntry, $tabs = "")
{
echo $tabs . 'Subject: ' . $videoMessageEntry->getVideoTitle() . "\n";
echo $tabs . "\tAuthor: " . $videoEntry->getAuthor() . "\n";
echo $tabs . "\tMessage: " . $videoEntry->getVideoDescription() . "\n";
}
ユーザーにメッセージを送信するには、VideoEntry オブジェクトを作成して、ユーザーの受信ボックスのフィードに挿入します。次のコードでは、変数 $receivingUser で識別されるユーザーに、動画を含むメッセージを送信します。メッセージに動画を挿入するには、video_id を含めます。
$inboxUrl = 'http://gdata.youtube.com/feeds/api/users/' . $receivingUser . '/inbox';
$videoMessageEntry = $yt->newEntry();
// pass in the ID of the video to be included in your message (required)
$newMessage = $yt->newMediaEntry();
$newMessage->id = $yt->newId('video_id');
$newMessage->title = $yt->newTitle('message title');
$newMessage->extensionElements = array($yt->newDescription('message body'));
// insert the message
try {
$yt->insertEntry($newMessage, $inboxUrl);
} catch (Zend_App_Excetion $e) {
print $e->getMessage();
}
メッセージの受信者は、メッセージの送信者側でコンタクトを承認されている必要があります。
メッセージを削除するには、そのエントリに対して delete() を呼び出します。
$videoMessageEntryToBeDeleted->delete();