OpenSocial API Developer’s Guideを日本語に訳してみた。
昨日の「[Press 0024] Google OpenSocial API Documentationを日本語に訳してみた。」に引き続き、OpenSocial API Developer's Guideを訳してみました。
OpenSocial API Developer's Guide
まず目次。
- ソーシャルガジェットを記述する
- OpenSocial Libraryのインポート
- サンプル:友達のリストを表示する
- 永続的データ(Persistent Data)を利用する
- Activitiesを取得する
- 作成したガジェットをOrkutに追加する
- サンプルガジェット
ソーシャルガジェットを記述する
ソーシャルガジェットとは、OpenSocial JavaScript APIをサポートするコンテナ上で動作する、単純なガジェットである。例えばOrkutなどがそういったコンテナにあたる。
OpenSocial APIは「人」をターゲットとしたAPIであり、ユーザ同士で行動履歴を共有したり、友達の情報にアクセスしたりすることができる。
ソーシャルガジェットを記述するには、以下の2点が必要である。
- Orkut.comのようなOpenSocial APIをサポートするコンテナにアクセスする。
- Google Gadgetsの基本的な知識を学ぶ。詳しくは「Google Gadget API Developer Guide」を。
OpenSocial APIには以下の3つの部類の機能が存在する。
- ユーザ情報とユーザ間のリレーション情報
- 永続的データ
- 行動履歴
すべてのAPIは非同期にサーバにリクエストを投げて、情報の取得や更新を行う。そのため開発者は、サーバのレスポンスを受け取るためのコールバック関数を記述する必要が有る。
より詳細な情報は、「API Reference」を。
OpenSocial Libraryのインポート
OpenSocial APIを利用するには、以下の「Requires」セクションをガジェットの設定に追加すれば良い。
-
<ModulePrefs title="アプリケーションタイトル">
-
<Require feature="opensocial-0.5" />
-
</ModulePrefs>
サンプル:友達のリストを表示する
ここでは単純なサンプルを用いて、APIの基本的な使い方を説明する。データ取得リクエストを投げるには、まず「opensocial.newDataRequest()」を呼び出して、DataRequestインスタンスを生成する必要がある。その後取得したいデータ型に応じて「DataRequest.add(request)」を呼び出すと、データ取得リクエストが投げられる。
以下は友達リストを取得するためのサンプルコードである。
-
function onLoadFriends(dataResponse) {
-
// コールバック関数。
-
// ここで受け取ったレスポンスに対して処理を行う。
-
};
-
-
/**
-
* 友達リストを取得する。
-
*/
-
function getData() {
-
document.getElementById('message').innerHTML = 'Requesting friends...';
-
var req = opensocial.newDataRequest();
-
req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
-
req.add(req.newFetchPeopleRequest ('VIEWER_FRIENDS'), 'viewerFriends');
-
req.send(onLoadFriends);
-
};
「newFetch*Request」(newFetchPersonRequestおよびnewFetchPeopleRequestのこと)で記述されている2番目の方の引数(viewer・viewerFriends)はレスポンスからデータを取得する際にkeyとなる文字列である。
OpenSocial APIでは、以下の3つのroleが定義されている。
- Viewer:ブラウザ(でコンテナとなるサイト)にログインしているユーザ。あなたがOrkutにアクセスして、マイページや友達のプロフィールページ(上のGadgets)を見ている時は、あなた自身がViewerである。
- Owner:プロフィールやガジェットを所有する人。(あなたが貼付けたGadgetのOwnerはあなたってこと?だと思う。違ったらコメントもらえると助かりますm_ _m)
- Friends:OwnerやViewerの友達。
Gadget内では、まず最初のリクエストを生成するのが一般的である。これはJavaScript内で以下のonload handlerを呼び出せば良い。
-
_IG_RegisterOnloadHandler(getData);
最低限必要な知識
ここでは前セクションのサンプルを実行するための基礎知識を紹介する。以下はopensocial.DataResponse型のインプットに対して処理を実行するサンプルである。onLoadFriends()関数は引数として受け取るDataResponseのインスタンスをパースして、ViewerとそのViewerのFriendsの名前を表示している。
-
/**
-
* Parses the response to the friend information request and generates
-
* html to list the friends by their display name.
-
*
-
* @param {Object} dataResponse Friend information that was requested.
-
*/
-
function onLoadFriends(dataResponse) {
-
var viewer = dataResponse.get('viewer').getData();
-
var html = 'Friends of ' + viewer.getDisplayName();
-
html += ':<br><ul>';
-
var viewerFriends = dataResponse.get('viewerFriends').getData();
-
viewerFriends.each(function(person) {
-
html += '<li>' + person.getDisplayName();
-
});
-
html += '</ul>';
-
document.getElementById('message').innerHTML = html;
-
};
== 参考のため追記(ここから) ==
実行結果として、<div id="message"></div>内に、以下のようなHTMLが表示される。
-
Friends of VIEWER_NAME<br>
-
<ul>
-
<li>FRIEND_1_NAME</li>
-
<li>FRIEND_2_NAME</li>
-
:
-
:
-
<li>FRIEND_N_NAME</li>
-
</ul>
== 参考のため追記(ここまで) ==
onLoadFriends()関数のdataResponseという引数は、DataResponse型のインスタンスである。newFetch*Request()関数の呼び出し時にあらかじめ設定された文字列keyを引数にしてDataResponse.get(key)を呼びだすと、リクエストに含まれた該当するResponseItem型のインスタンスが返される。
リクエストが成功している場合は、dataResponse.get(key).getData()を呼ぶことで、実際のレスポンスデータを取得することができる。レスポンスデータの型は、共通のリクエスト呼び出しに紐づけられている。
- newFetchPersonRequest("VIEWER", key):ガジェット閲覧者の情報を取得し、opensocial.Person型のデータを返す。
- newFetchPeopleRequest("VIEWER_FRIENDS"', key):ガジェット閲覧者の友達情報を取得し、opensocial.Person型のcollection(配列)を返す。
- newFetchPersonRequest("OWNER", key):ガジェット所有者の情報を取得し、opensocial.Person型のデータを返す。(ガジェット所有者とは、おそらくガジェットを貼付けた人のことだと思います。違ったら教えてくださいm_ _m)
- newFetchPeopleRequest("OWNER_FRIENDS", key):ガジェット所有者の友達情報を取得し、opensocial.Person型のcollection(配列)を返す。
なお、リクエストが失敗した場合は、DataResponse.get(key).hadError()を呼び出すとtrueが返る。
友達リスト表示ガジェットのサンプルコード
以下のサンプルコードが、ここまで紹介してきた「友達リストを取得し表示するガジェット」の完全なサンプルコードである。
-
<?xml version="1.0" encoding="UTF-8" ?>
-
<Module>
-
<ModulePrefs title="List Friends Example">
-
<Require feature="opensocial-0.5"/>
-
</ModulePrefs>
-
<Content type="html">
-
-
<![CDATA[
-
-
<script type="text/javascript">
-
-
/**
-
* Request for friend information when the page loads.
-
*/
-
function getData() {
-
document.getElementById('message').innerHTML = 'Requesting friends...';
-
var req = opensocial.newDataRequest();
-
req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
-
req.add(req.newFetchPeopleRequest ('VIEWER_FRIENDS'), 'viewerFriends');
-
req.send(onLoadFriends);
-
};
-
-
/**
-
* Parses the response to the friend information request and generates
-
* html to list the friends along with their display name and picture.
-
*
-
* @param {Object} dataResponse Friend information that was requested.
-
*/
-
function onLoadFriends(dataResponse) {
-
var viewer = dataResponse.get('viewer').getData();
-
var html = 'Friends of ' + viewer.getDisplayName();
-
html += ':<br><ul>';
-
var viewerFriends = dataResponse.get('viewerFriends').getData();
-
viewerFriends.each(function(person) {
-
html += '<li>' + person.getDisplayName() + '</li>';
-
});
-
html += '</ul>';
-
document.getElementById('message').innerHTML = html;
-
};
-
_IG_RegisterOnloadHandler(getData);
-
-
</script>
-
<div id="message"> </div>
-
]]>
-
</Content>
-
</Module>
永続的データ(Persistent Data)を利用する
OpenSocial APIはユーザごと、ガジェットインスタンスごと、およびそのアプリケーションに関してグローバルなデータの保存/取得をサポートしている。
以下は、データ共有エリアにデータを保存するためのコード(の抜粋)である。
-
function populateMyAppData() {
-
var req = opensocial.newDataRequest();
-
var data1 = Math.random() * 5;
-
var data2 = Math.random() * 100;
-
var data3 = new Date().getTime();
-
-
req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField1", data1));
-
req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField2", data2));
-
req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField3", data3));
-
req.send(handlePopulateMyAppData);
-
};
注)保存されるデータはstring型のデータのみである。ほとんどの場合、このstringはJSONエンコーディングされることを推奨する。
保存したデータを取得するコードは以下の通りである。
-
var req = opensocial.newDataRequest();
-
-
//Request the following three app fields
-
var fields = [ "AppField1", "AppField2", "AppField3" ];
-
req.add(req.newFetchPersonAppDataRequest("VIEWER", fields), "viewer_data");
-
req.send(handleRequestMyData);
以下がこのサンプルの完全なコードである。ここではOpenSocial APIを用いて、異なる種類の共通リクエストを生成する方法も記述されている。
-
<?xml version="1.0" encoding="UTF-8" ?>
-
<Module>
-
<ModulePrefs title="Sample Requests">
-
<Require feature="opensocial-0.5"/>
-
</ModulePrefs>
-
<Content type="html">
-
-
<script type="text/javascript">
-
-
/**
-
* Sample calls for the OpenSocial API
-
*
-
* These functions show some basic uses of the social API.
-
*
-
*/
-
var htmlout = "";
-
var me = null;
-
_IG_RegisterOnloadHandler(requestMe);
-
-
/**
-
* How do I get my data?
-
*/
-
function requestMe() {
-
// Make a new DataRequest object. This is the base object you will
-
// create for all data requests
-
var req = opensocial.newDataRequest();
-
-
// Add a request to fetch the viewer to the current DataRequest
-
req.add(req.newFetchPersonRequest("VIEWER"), "viewer");
-
req.send(handleRequestMe);
-
};
-
-
/**
-
* How do I handle responses from fetch person requests?
-
*/
-
function handleRequestMe(data) {
-
// Note that we are getting the parameter we specified in the request
-
var viewer = data.get("viewer");
-
-
// Error handling
-
if (viewer.hadError()) {
-
//Handle error using viewer.getError()
-
console.log(viewer.getError());
-
return;
-
}
-
-
// If there was not an error, assign the global "me" variable
-
// Note the getData call to pull data out of the response object
-
me = viewer.getData();
-
-
// Normally you would batch the request to get friends and get the viewer
-
// in the same data request. These are separated in this example
-
// to show the request and response types separately.
-
requestFriends();
-
};
-
-
/**
-
* How do I get my friends??
-
*/
-
function requestFriends() {
-
var req = opensocial.newDataRequest();
-
-
// Add a request to fetch people to the current DataRequest.
-
// The parameter passed to newFetchPeopleRequest can be one of
-
// VIEWER_FRIENDS or OWNER_FRIENDS as needed
-
req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS"), "viewer_friends");
-
-
// Send the request, specifying the function that will receive data
-
req.send(handleRequestFriends);
-
};
-
-
/**
-
* How do I handle responses from fetch people requests?
-
*/
-
function handleRequestFriends(data) {
-
var myfriends = data.get("viewer_friends");
-
-
if (myfriends.hadError()) {
-
console.log(myfriends.getError());
-
return;
-
}
-
-
// Operate on each person that is returned. Note the getData() request
-
myfriends.getData().each(doSomethingWithPerson);
-
-
populateMyAppData();
-
};
-
-
/************************************************************************
-
* How do I operate on Person objects?
-
*/
-
function doSomethingWithPerson(person) {
-
htmlout += "This person's name: " + person.getDisplayName() + "<br />";
-
htmlout += "This person's picture: " + person.getField("picture") + "<br />";
-
};
-
-
/**
-
* How do we set user data?
-
*/
-
function populateMyAppData() {
-
var req = opensocial.newDataRequest();
-
-
var data1 = Math.random() * 5;
-
var data2 = Math.random() * 100;
-
var data3 = new Date().getTime();
-
-
htmlout += "Setting AppField1 to " + data1 + "<br />";
-
req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField1", data1)) + "<br />";
-
htmlout += "Setting AppField2 to " + data2 + "<br />";
-
req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField2", data2)) + "<br />";
-
htmlout += "Setting AppField3 to " + data3 + "<br />";
-
req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField3", data3)) + "<br />";
-
req.send(handlePopulateMyAppData);
-
};
-
-
/**
-
* How do I handle responses from update person app data requests?
-
*/
-
function handlePopulateMyAppData(data) {
-
if (data.hadError()) {
-
//Handle the error
-
console.log(data.getError());
-
}
-
requestMyData();
-
};
-
-
/**
-
* How do I fetch app data?
-
*/
-
function requestMyData() {
-
var req = opensocial.newDataRequest();
-
//Request the following three app fields
-
var fields = [ "AppField1", "AppField2", "AppField3" ];
-
req.add(req.newFetchPersonAppDataRequest("VIEWER", fields), "viewer_data");
-
req.send(handleRequestMyData);
-
};
-
-
/**
-
* How do I handle responses from app data requests?
-
*/
-
function handleRequestMyData(data) {
-
var mydata = data.get("viewer_data");
-
-
if (mydata.hadError()) {
-
console.log(mydata.getError());
-
return;
-
}
-
//Do something with the returned data - note the getData call
-
doSomethingWithMyData(mydata.getData());
-
};
-
-
/**
-
* How do we operate on user data?
-
*/
-
function doSomethingWithMyData(data) {
-
//Data is indexed by user id, and represents an object where keys
-
//correspond with the app data fields.
-
var mydata = data[me.getId()];
-
var div = document.getElementById('content_div');
-
htmlout += "My AppField1 data is: " + mydata["AppField1"] + "<br />";
-
htmlout += "My AppField2 data is: " + mydata["AppField2"] + "<br />";
-
htmlout += "My AppField3 data is: " + mydata["AppField3"] + "<br />";
-
div.innerHTML = htmlout;
-
};
-
</script>
-
<div id="content_div"></div>
-
]]>
-
</Content>
-
</Module>
== 参考のため追記(ここから) ==
このサンプルコードは、以下のような一連の処理を行う。
- ユーザAがガジェットにアクセス
- OpenSocial API経由でガジェットコンテナからユーザAの情報を取得
- meにユーザ情報を保存
- OpenSocial API経由でガジェットコンテナからユーザAの友達リストを取得
- 友達リストのHTMLを生成
- OpenSocial API経由でガジェットコンテナにユーザAに関する永続データを保存
- OpenSocial API経由でガジェットコンテナからユーザAに関する永続データを取得
- ユーザAの永続データリストのHTML生成
- <div id="content_div"></div>内に友達リストおよびユーザAの永続データリストを表示
-
<?xml version="1.0" encoding="UTF-8" ?>
-
<Module>
-
<ModulePrefs title="Activities" description="Sample code for reading and writing activity stream">
-
<Require feature="opensocial-0.5"/>
-
</ModulePrefs>
-
<Content type="html">
-
-
<script>
-
_IG_RegisterOnloadHandler(getActivities);
-
-
function getActivities() {
-
var req = opensocial.newDataRequest();
-
req.add(req.newFetchActivitiesRequest('VIEWER'), 'viewerActivities');
-
req.add(req.newFetchActivitiesRequest('VIEWER_FRIENDS'), 'friendActivities');
-
req.send(showActivities);
-
}
-
-
function showActivities(dataResponse) {
-
var viewerActivities = dataResponse.get('viewerActivities').getData()['activities'];
-
var friendActivities = dataResponse.get('friendActivities').getData()['activities'];
-
-
var htmlout = '';
-
htmlout += '<h2>Your activities:</h2><br>';
-
htmlout += getActivitiesHtml(viewerActivities);
-
htmlout += '<h2>Your friends\' activities:</h2><br>';
-
htmlout += getActivitiesHtml(friendActivities);
-
document.getElementById('read_activities').innerHTML = htmlout;
-
}
-
-
function getActivitiesHtml(stream) {
-
var htmlout = '';
-
stream.each(function(activity) {
-
var link = activity.getField('url');
-
if (link) {
-
htmlout += '<a href="' + link +'" target="_blank">'+ activity.getField('title') + '</a>';
-
} else {
-
htmlout += activity.getField('title');
-
}
-
htmlout += '<br>';
-
});
-
return htmlout;
-
}
-
-
function writeActivity() {
-
var streamTitle = 'Sample code for reading and writing activity stream';
-
var stream_params = {'url': 'http://samplestream.com' };
-
var stream = opensocial.newStream('', streamTitle, stream_params);
-
-
var title = _gel('title').value;
-
var link = _gel('link').value;
-
var activity_params = {'url' : link}
-
var activity = opensocial.newActivity(stream, title, activity_params)
-
opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, getActivities);
-
}
-
-
</script>
-
<div id="write_activities">
-
Title:<input id="title" /><br>
-
Link:<input id="link" /><br>
-
<input type="button" value="add activity" onclick="writeActivity();" />
-
</div>
-
<div id="read_activities">
-
</div>
-
-
]]>
-
</Content>
-
</Module>
- ユーザAがガジェットにアクセス
- OpenSocial API経由でガジェットコンテナからユーザAおよびユーザAの友達の行動情報を取得
- activity streamのFeedから各activityのtitileとlinkを抜き出し、ユーザA/ユーザAの友達の2つに分けてリスト表示
- <div id="write_activities"></div>内のフォームに入力があった場合は、優先度HIGHでtitleとlinkを新規activityとして登録し、最初に戻る
- http://sandbox.orkut.comにアクセスする。
- 左サイドナビゲーションにある「applications」をクリックする。
- 「Add an application by url」フィールドにあなたのガジェットのURLを追加する。
- canvasでガジェットを実行するため、左サイドナビゲーションの該当するリンクをクリックする。
== 参考のため追記(ここまで) ==
Activitiesを取得する
OpenSocial APIではユーザ同士で行動情報を共有することができる。これにはactivity streamが用いられる。activity streamは各エントリーがそのユーザの1アクションを表すFeedとして提供される。これにより、ガジェットの状態を更新することから、動画にレビューを書き込むことまで、様々な処理が可能とある。
activityには優先度という概念が存在する。優先度がHIGHな状況では、ユーザの代わりにgadgetがアクティビティのポストを行うこと対してユーザが認可済みでない場合は、アプリケーションからユーザに認可問い合わせが発行される。優先度がLOWの場合は、アプリケーションがポストする権限を所有していない場合は何も処理が実行されない。
以下のサンプルでは、activity stream APIは上記と同じrequest / response処理を行う。この例ではactivity streamをどのように取得(fetch)し、表示(display)し、新しいactivityを追加(add)するかも理解できる。
== 参考のため追記(ここから) ==
このサンプルコードは、以下のような一連の処理を行う。
== 参考のため追記(ここまで) ==
作成したガジェットをOrkutに追加する
Orkutはsocial gadgetをサポートする最初のコンテナです。最終的には多数のコンテナがsocial gadgetをサポートするようになります。また開発者自身がオリジナルのコンテナを構築することも可能です。
Orkutにガジェットを追加する方法は、以下の通りです。
サンプルガジェット
Orkut application directoryにアクセスすれば、ここにある以外のサンプルガジェットも見ることができる。












この記事がお役に立ちましたら、一言コメントもらえると嬉しいですm_ _m