RAILS PRESS RUBY on RAILS, it’s DRY and COOL …

RSS Feed

RAILS PRESS RSS

Tag Cloud

はてなブックマーク - railspress.matake.jp の注目エントリー
象形文字くさび形文字ミイラそろばんの玉そろばんコーラン占いの板?象牙大英博物館
« 前のエントリ
Google OpenSocial API Documentationを日本語に訳してみた。
次のエントリー »
Hosting OpenSocial Appsを日本語に訳してみた。

Posted on
2007/11/21

Tags
Google, OpenSocial, ドキュメント翻訳, 連載

Keywords


この記事をはてなブックマークに登録 この記事のはてなブックマーク数 この記事を livedoor クリップに登録この記事の livedoor クリップ数 このエントリを del.icio.us に追加
ブックマークに追加する

OpenSocial API Developer’s Guideを日本語に訳してみた。

昨日の「[Press 0024] Google OpenSocial API Documentationを日本語に訳してみた。」に引き続き、OpenSocial API Developer's Guideを訳してみました。

OpenSocial API Developer's Guide

まず目次。

ソーシャルガジェットを記述する

ソーシャルガジェットとは、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」セクションをガジェットの設定に追加すれば良い。

LANG : shell etc.
  1. <ModulePrefs title="アプリケーションタイトル">
  2.   <Require feature="opensocial-0.5" />
  3. </ModulePrefs>

サンプル:友達のリストを表示する

ここでは単純なサンプルを用いて、APIの基本的な使い方を説明する。データ取得リクエストを投げるには、まず「opensocial.newDataRequest()」を呼び出して、DataRequestインスタンスを生成する必要がある。その後取得したいデータ型に応じて「DataRequest.add(request)」を呼び出すと、データ取得リクエストが投げられる。

以下は友達リストを取得するためのサンプルコードである。

LANG : shell etc.
  1. function onLoadFriends(dataResponse) {
  2.   // コールバック関数。
  3.   // ここで受け取ったレスポンスに対して処理を行う。
  4. };
  5.  
  6. /**
  7. * 友達リストを取得する。
  8. */
  9. function getData() {
  10.   document.getElementById('message').innerHTML = 'Requesting friends...';
  11.   var req = opensocial.newDataRequest();
  12.   req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
  13.   req.add(req.newFetchPeopleRequest ('VIEWER_FRIENDS'), 'viewerFriends');
  14.   req.send(onLoadFriends);
  15. };

「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を呼び出せば良い。

LANG : shell etc.
  1. _IG_RegisterOnloadHandler(getData);

最低限必要な知識

ここでは前セクションのサンプルを実行するための基礎知識を紹介する。以下はopensocial.DataResponse型のインプットに対して処理を実行するサンプルである。onLoadFriends()関数は引数として受け取るDataResponseのインスタンスをパースして、ViewerとそのViewerのFriendsの名前を表示している。

LANG : shell etc.
  1. /**
  2. * Parses the response to the friend information request and generates
  3. * html to list the friends by their display name.
  4. *
  5. * @param {Object} dataResponse Friend information that was requested.
  6. */
  7. function onLoadFriends(dataResponse) {
  8.   var viewer = dataResponse.get('viewer').getData();
  9.   var html = 'Friends of ' + viewer.getDisplayName();
  10.   html += ':<br><ul>';
  11.   var viewerFriends = dataResponse.get('viewerFriends').getData();
  12.   viewerFriends.each(function(person) {
  13.     html += '<li>' + person.getDisplayName();
  14.   });
  15.   html += '</ul>';
  16.   document.getElementById('message').innerHTML = html;
  17. };

== 参考のため追記(ここから) ==
実行結果として、<div id="message"></div>内に、以下のようなHTMLが表示される。

LANG : shell etc.
  1. Friends of VIEWER_NAME<br>
  2. <ul>
  3.   <li>FRIEND_1_NAME</li>
  4.   <li>FRIEND_2_NAME</li>
  5.     :
  6.     :
  7.   <li>FRIEND_N_NAME</li>
  8. </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が返る。

友達リスト表示ガジェットのサンプルコード

以下のサンプルコードが、ここまで紹介してきた「友達リストを取得し表示するガジェット」の完全なサンプルコードである。

LANG : shell etc.
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <Module>
  3.   <ModulePrefs title="List Friends Example">
  4.     <Require feature="opensocial-0.5"/>
  5.   </ModulePrefs>
  6.   <Content type="html">
  7.  
  8.   <![CDATA[
  9.  
  10.   <script type="text/javascript">
  11.  
  12.   /**
  13.    * Request for friend information when the page loads.
  14.    */
  15.   function getData() {
  16.     document.getElementById('message').innerHTML = 'Requesting friends...';
  17.     var req = opensocial.newDataRequest();
  18.     req.add(req.newFetchPersonRequest('VIEWER'), 'viewer');
  19.     req.add(req.newFetchPeopleRequest ('VIEWER_FRIENDS'), 'viewerFriends');
  20.     req.send(onLoadFriends);
  21.   };
  22.  
  23.   /**
  24.    * Parses the response to the friend information request and generates
  25.    * html to list the friends along with their display name and picture.
  26.    *
  27.    * @param {Object} dataResponse Friend information that was requested.
  28.    */
  29.   function onLoadFriends(dataResponse) {
  30.     var viewer = dataResponse.get('viewer').getData();
  31.     var html = 'Friends of ' + viewer.getDisplayName();
  32.     html += ':<br><ul>';
  33.     var viewerFriends = dataResponse.get('viewerFriends').getData();
  34.     viewerFriends.each(function(person) {
  35.       html += '<li>' + person.getDisplayName() + '</li>';
  36.     });
  37.     html += '</ul>';
  38.     document.getElementById('message').innerHTML = html;
  39.   };
  40.   _IG_RegisterOnloadHandler(getData);
  41.  
  42.   </script>
  43.   <div id="message"> </div>
  44.   ]]>
  45.   </Content>
  46. </Module>

永続的データ(Persistent Data)を利用する

OpenSocial APIはユーザごと、ガジェットインスタンスごと、およびそのアプリケーションに関してグローバルなデータの保存/取得をサポートしている。

以下は、データ共有エリアにデータを保存するためのコード(の抜粋)である。

LANG : shell etc.
  1. function populateMyAppData() {
  2.   var req = opensocial.newDataRequest();
  3.   var data1 = Math.random() * 5;
  4.   var data2 = Math.random() * 100;
  5.   var data3 = new Date().getTime();
  6.  
  7.   req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField1", data1));
  8.   req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField2", data2));
  9.   req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField3", data3));
  10.   req.send(handlePopulateMyAppData);
  11. };

注)保存されるデータはstring型のデータのみである。ほとんどの場合、このstringはJSONエンコーディングされることを推奨する。

保存したデータを取得するコードは以下の通りである。

LANG : shell etc.
  1. var req = opensocial.newDataRequest();
  2.  
  3. //Request the following three app fields
  4. var fields = [ "AppField1", "AppField2", "AppField3" ];
  5. req.add(req.newFetchPersonAppDataRequest("VIEWER", fields), "viewer_data");
  6. req.send(handleRequestMyData);

以下がこのサンプルの完全なコードである。ここではOpenSocial APIを用いて、異なる種類の共通リクエストを生成する方法も記述されている。

LANG : shell etc.
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <Module>
  3.  <ModulePrefs title="Sample Requests">
  4.   <Require feature="opensocial-0.5"/>
  5.  </ModulePrefs>
  6.  <Content type="html">
  7.  
  8.   <script type="text/javascript">
  9.  
  10.    /**
  11.     * Sample calls for the OpenSocial API
  12.     *
  13.     * These functions show some basic uses of the social API. 
  14.     *
  15.     */
  16.    var htmlout = "";
  17.    var me = null;      
  18.    _IG_RegisterOnloadHandler(requestMe);
  19.  
  20.    /**
  21.     * How do I get my data?
  22.     */
  23.    function requestMe() {
  24.      // Make a new DataRequest object.  This is the base object you will
  25.      // create for all data requests
  26.      var req = opensocial.newDataRequest();
  27.  
  28.      // Add a request to fetch the viewer to the current DataRequest
  29.      req.add(req.newFetchPersonRequest("VIEWER"), "viewer");
  30.      req.send(handleRequestMe);
  31.    };
  32.            
  33.    /**
  34.     * How do I handle responses from fetch person requests?
  35.     */
  36.    function handleRequestMe(data) {
  37.      // Note that we are getting the parameter we specified in the request
  38.      var viewer = data.get("viewer");
  39.  
  40.      // Error handling
  41.      if (viewer.hadError()) {
  42.        //Handle error using viewer.getError()
  43.        console.log(viewer.getError());
  44.        return;
  45.      }
  46.  
  47.      // If there was not an error, assign the global "me" variable
  48.      // Note the getData call to pull data out of the response object
  49.      me = viewer.getData();
  50.  
  51.      // Normally you would batch the request to get friends and get the viewer
  52.      // in the same data request. These are separated in this example
  53.      // to show the request and response types separately.
  54.      requestFriends();
  55.    };
  56.                
  57.    /**
  58.     * How do I get my friends??
  59.     */
  60.    function requestFriends() {
  61.      var req = opensocial.newDataRequest();
  62.  
  63.      // Add a request to fetch people to the current DataRequest.
  64.      // The parameter passed to newFetchPeopleRequest can be one of
  65.      // VIEWER_FRIENDS or OWNER_FRIENDS as needed
  66.      req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS"), "viewer_friends");
  67.  
  68.      // Send the request, specifying the function that will receive data
  69.      req.send(handleRequestFriends);
  70.    };
  71.  
  72.   /**
  73.     * How do I handle responses from fetch people requests?
  74.     */
  75.    function handleRequestFriends(data) {
  76.      var myfriends = data.get("viewer_friends");
  77.  
  78.      if (myfriends.hadError()) {
  79.        console.log(myfriends.getError());
  80.        return;
  81.      }
  82.                
  83.      // Operate on each person that is returned.  Note the getData() request
  84.      myfriends.getData().each(doSomethingWithPerson);
  85.  
  86.      populateMyAppData();
  87.    };
  88.  
  89.    /************************************************************************
  90.     * How do I operate on Person objects?
  91.     */
  92.    function doSomethingWithPerson(person) {
  93.      htmlout += "This person's name: " + person.getDisplayName() + "<br />";
  94.      htmlout += "This person's picture: " + person.getField("picture") + "<br />";
  95.    };
  96.  
  97.    /**
  98.     * How do we set user data?
  99.     */
  100.    function populateMyAppData() {
  101.      var req = opensocial.newDataRequest();
  102.      
  103.      var data1 = Math.random() * 5;
  104.      var data2 = Math.random() * 100;
  105.      var data3 = new Date().getTime();
  106.      
  107.      htmlout += "Setting AppField1 to " + data1 + "<br />";
  108.      req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField1", data1)) + "<br />";
  109.      htmlout += "Setting AppField2 to " + data2 + "<br />";
  110.      req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField2", data2)) + "<br />";
  111.      htmlout += "Setting AppField3 to " + data3 + "<br />";
  112.      req.add(req.newUpdatePersonAppDataRequest("VIEWER", "AppField3", data3)) + "<br />";
  113.      req.send(handlePopulateMyAppData);
  114.    };
  115.  
  116.    /**
  117.     * How do I handle responses from update person app data requests?
  118.     */
  119.    function handlePopulateMyAppData(data) {
  120.      if (data.hadError()) {
  121.        //Handle the error
  122.        console.log(data.getError());
  123.      }
  124.      requestMyData();
  125.    };
  126.    
  127.    /**
  128.     * How do I fetch app data?
  129.     */
  130.    function requestMyData() {
  131.      var req = opensocial.newDataRequest();
  132.      //Request the following three app fields
  133.      var fields = [ "AppField1", "AppField2", "AppField3" ];
  134.      req.add(req.newFetchPersonAppDataRequest("VIEWER", fields), "viewer_data");
  135.      req.send(handleRequestMyData);
  136.    };
  137.  
  138.    /**
  139.     * How do I handle responses from app data requests?
  140.     */
  141.    function handleRequestMyData(data) {
  142.      var mydata = data.get("viewer_data");
  143.  
  144.      if (mydata.hadError()) {
  145.        console.log(mydata.getError());
  146.        return;
  147.      }
  148.      //Do something with the returned data - note the getData call
  149.      doSomethingWithMyData(mydata.getData());
  150.    };
  151.  
  152.    /**
  153.     * How do we operate on user data?
  154.     */
  155.    function doSomethingWithMyData(data) {
  156.      //Data is indexed by user id, and represents an object where keys
  157.      //correspond with the app data fields.
  158.      var mydata = data[me.getId()];
  159.      var div = document.getElementById('content_div');
  160.      htmlout += "My AppField1 data is: " + mydata["AppField1"] + "<br />";
  161.      htmlout += "My AppField2 data is: " + mydata["AppField2"] + "<br />";
  162.      htmlout += "My AppField3 data is: " + mydata["AppField3"] + "<br />";
  163.      div.innerHTML = htmlout;
  164.    };
  165.  </script>
  166.  <div id="content_div"></div>
  167.   ]]>
  168.  </Content>
  169. </Module>

== 参考のため追記(ここから) ==

このサンプルコードは、以下のような一連の処理を行う。

  1. ユーザAがガジェットにアクセス
  2. OpenSocial API経由でガジェットコンテナからユーザAの情報を取得
  3. meにユーザ情報を保存
  4. OpenSocial API経由でガジェットコンテナからユーザAの友達リストを取得
  5. 友達リストのHTMLを生成
  6. OpenSocial API経由でガジェットコンテナにユーザAに関する永続データを保存
  7. OpenSocial API経由でガジェットコンテナからユーザAに関する永続データを取得
  8. ユーザAの永続データリストのHTML生成
  9. <div id="content_div"></div>内に友達リストおよびユーザAの永続データリストを表示
  10. == 参考のため追記(ここまで) ==

    Activitiesを取得する

    OpenSocial APIではユーザ同士で行動情報を共有することができる。これにはactivity streamが用いられる。activity streamは各エントリーがそのユーザの1アクションを表すFeedとして提供される。これにより、ガジェットの状態を更新することから、動画にレビューを書き込むことまで、様々な処理が可能とある。

    activityには優先度という概念が存在する。優先度がHIGHな状況では、ユーザの代わりにgadgetがアクティビティのポストを行うこと対してユーザが認可済みでない場合は、アプリケーションからユーザに認可問い合わせが発行される。優先度がLOWの場合は、アプリケーションがポストする権限を所有していない場合は何も処理が実行されない。

    以下のサンプルでは、activity stream APIは上記と同じrequest / response処理を行う。この例ではactivity streamをどのように取得(fetch)し、表示(display)し、新しいactivityを追加(add)するかも理解できる。

    LANG : shell etc.
    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <Module>
    3.  <ModulePrefs title="Activities" description="Sample code for reading and writing activity stream">
    4.   <Require feature="opensocial-0.5"/>
    5.  </ModulePrefs>
    6.  <Content type="html">
    7.  
    8. <script>
    9. _IG_RegisterOnloadHandler(getActivities);
    10.  
    11. function getActivities() {
    12.   var req = opensocial.newDataRequest();
    13.   req.add(req.newFetchActivitiesRequest('VIEWER'), 'viewerActivities');
    14.   req.add(req.newFetchActivitiesRequest('VIEWER_FRIENDS'), 'friendActivities');
    15.   req.send(showActivities);
    16. }
    17.  
    18. function showActivities(dataResponse) {
    19.   var viewerActivities = dataResponse.get('viewerActivities').getData()['activities'];
    20.   var friendActivities = dataResponse.get('friendActivities').getData()['activities'];
    21.  
    22.   var htmlout = '';
    23.   htmlout += '<h2>Your activities:</h2><br>';
    24.   htmlout += getActivitiesHtml(viewerActivities);
    25.   htmlout += '<h2>Your friends\' activities:</h2><br>';
    26.   htmlout += getActivitiesHtml(friendActivities);
    27.   document.getElementById('read_activities').innerHTML = htmlout;
    28. }
    29.  
    30. function getActivitiesHtml(stream) {
    31.   var htmlout = '';
    32.   stream.each(function(activity) {
    33.     var link = activity.getField('url');
    34.     if (link) {
    35.       htmlout += '<a href="' + link +'" target="_blank">'+ activity.getField('title') + '</a>';
    36.     } else {
    37.       htmlout += activity.getField('title');
    38.     }
    39.     htmlout += '<br>';
    40.   });
    41.   return htmlout;
    42. }
    43.  
    44. function writeActivity() {
    45.   var streamTitle = 'Sample code for reading and writing activity stream';
    46.   var stream_params = {'url': 'http://samplestream.com' };
    47.   var stream = opensocial.newStream('', streamTitle, stream_params);
    48.  
    49.   var title = _gel('title').value;
    50.   var link = _gel('link').value;
    51.   var activity_params = {'url' : link}
    52.   var activity = opensocial.newActivity(stream, title, activity_params)
    53.   opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, getActivities);
    54. }
    55.  
    56. </script>
    57. <div id="write_activities">
    58.   Title:<input id="title" /><br>
    59.   Link:<input id="link" /><br>
    60.   <input type="button" value="add activity" onclick="writeActivity();" />
    61. </div>
    62. <div id="read_activities">
    63. </div>
    64.  
    65.   ]]>
    66.   </Content>
    67. </Module>

    == 参考のため追記(ここから) ==

    このサンプルコードは、以下のような一連の処理を行う。

    1. ユーザAがガジェットにアクセス
    2. OpenSocial API経由でガジェットコンテナからユーザAおよびユーザAの友達の行動情報を取得
    3. activity streamのFeedから各activityのtitileとlinkを抜き出し、ユーザA/ユーザAの友達の2つに分けてリスト表示
    4. <div id="write_activities"></div>内のフォームに入力があった場合は、優先度HIGHでtitleとlinkを新規activityとして登録し、最初に戻る

    == 参考のため追記(ここまで) ==

    作成したガジェットをOrkutに追加する

    Orkutはsocial gadgetをサポートする最初のコンテナです。最終的には多数のコンテナがsocial gadgetをサポートするようになります。また開発者自身がオリジナルのコンテナを構築することも可能です。

    Orkutにガジェットを追加する方法は、以下の通りです。

    1. http://sandbox.orkut.comにアクセスする。
    2. 左サイドナビゲーションにある「applications」をクリックする。
    3. 「Add an application by url」フィールドにあなたのガジェットのURLを追加する。
    4. canvasでガジェットを実行するため、左サイドナビゲーションの該当するリンクをクリックする。

    サンプルガジェット

    Orkut application directoryにアクセスすれば、ここにある以外のサンプルガジェットも見ることができる。


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

[...] OpenSocial API Developer’s Guideの翻訳については「[Press 0025] OpenSocial API Developer’s Guideを日本語に訳してみた。」をご覧下さい。 [...]


[...] 「[Press 0024] Google OpenSocial API Documentationを日本語に訳してみた。」、「[Press 0025] OpenSocial API Developer’s Guideを日本語に訳してみた。」の続き。 [...]


コメントはこちらから




使用可能タグ: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


« 前のエントリ
Google OpenSocial API Documentationを日本語に訳してみた。
次のエントリー »
Hosting OpenSocial Appsを日本語に訳してみた。