OpenSocial/Orkut Developer's Guide (OpenSocial API v0.6) http://www.ark-web.jp/sandbox/wiki/376.html

以下、AIRS 加藤さんに訳していただきました。

[edit]

Orkut Developer's Guide (OpenSocial API v0.6)

元記事:Orkut Developer’s Guide

[edit]

Orkutアプリケーションの用語

用語説明
ApplicationGadgetとOpenSocial APIを利用して、Orkut上の経験を拡張するサードパーティのコード。
Application definitionアプリケーションを定義するXMLファイル。文法はgadget仕様として知られる”gadget spec”に基づく
Application directoryOrkutに登録済アプリケーションのリスト
Application settings pageユーザーがインストールしたアプリケーションのリスト。ユーザーは自由にアプリケーションを追加したり削除したりすることが出来る。
Application canvas pageアプリケーションのフルサイズのページ。
Surfaceアプリケーションが表示される場所。Orkutでは、アプリケーションはcanvasと**profileの両方のSurfaceに表示することが出来る。
Left navbarOrkutの各ページの左側にあるリンクのリスト。
Left nav link左サイドバー内の各リンク。これらのリンクはOrkutの各セクションによって変化する。
Activity stream1人のpersonをベースにしたアクティビティのリストを含むデータフィード。
[edit]

Orkutアプリケーションを作る

Orkutアプリケーションの作成には Google Gadget Editor を利用することが出来る。Google Gadget Editorを利用して作成したコードを保存すると、右上にアプリケーションのXMLコードへのリンクが表示される。
http://code.google.com/apis/orkut/docs/images/img01.png

リンク先ではアプリケーション定義を確認することが出来る。

http://code.google.com/apis/orkut/docs/images/img02.png

[edit]

Orkutアプリケーションのインストール

sandbox.orkut.comで、 My Applications にアクセスする。
http://code.google.com/apis/orkut/docs/images/img03.png

そして、入力フィールドにアプリケーション定義のURLを貼り付け、”add application” を押す。

アプリケーションの承認ページが表示され、インストールされるアプリケーションが許可を求める権限のリストが表示される。
http://code.google.com/apis/orkut/docs/images/img07.png
“add this app to my profile”ボタンを押すと、My Applicationsと左サイドバーに追加したアプリケーションが表示される。

http://code.google.com/apis/orkut/docs/images/img04.png

複数のアプリケーションを追加した場合、アプリケーションの並び替えをおこなうことができ、前から3つめまでのアプリケーションへのリンクが左サイドバー内に表示される。

http://code.google.com/apis/orkut/docs/images/img08.png

[edit]

サンプルアプリケーション

http://code.google.com/apis/orkut/docs/images/img05.png

[edit]

Orkutのapplication XMLキャッシュをバイパスする

Orkut sandboxでは現在キャッシュは無効化されている。アプリケーションはページを取得するたびリフレッシュされる。

[edit]

OpenSocialアプリケーション

OpenSocialアプリケーションは、gadgetsテクノロジーに基づいた新しいタイプのアプリケーションである。gadgetsテクノロジーを拡張したOpenSocial APIをサポートすることで、ウェブサイトからソーシャルデータを取得できるようになる。OrkutはOpenSocialコンテナの一例で、以下のセクションでは、Orkutの環境で動くOpenSocialアプリケーションに的を絞って説明する。

[edit]

Orkut querystring parameters

Orkut provides some querystring parameters that give you additional data about the context your application is running in. These parameters can be parsed manually using window.location.href, or you can use the Google Gadget convenience function gadgets.util.getUrlParameters().

NameHow to retrieveExample value
Parent URLgadgets.util.getUrlParameters()[“parent”]http://sandbox.orkut.com
Client Languagegadgets.util.getUrlParameters()[“lang”]en-US
Client Countrygadgets.util.getUrlParameters()[“country”]US
[edit]

Determining the current application surface

In Orkut, your application may occupy the canvas and profile surfaces. The easiest way to get the current surface is to call the following code:

var mode = opensocial.getEnvironment().getSurface();

Which assigns an opensocial.Surface object to the mode variable. See Available surfaces in Orkut for a listing of surfaces that may be returned by this call.

The following example demonstrates getting the current surface and conditionally executing code against the returned value:

var modes = { canvas : 1, profile : 2 };
function getMode() {
  return modes[opensocial.getEnvironment().getSurface().getName()];
}
if (getMode()  modes.canvas) {
  /* Do some canvas specific stuff here */
}

if (getMode()  modes.profile) {
  / Do some profile specific stuff here /
}
[edit]

Available surfaces in Orkut

Obtain an array of available Surface objects by calling the opensocial.getEnvironment().getSupportedSurfaces() function.

var surfaces = opensocial.getEnvironment().getSupportedSurfaces();
/* surfaces now contains an array of opensocial.Surface objects */

Orkut returns the following array (shown here in JSON notation):

  [
    { name : "profile", isPrimaryContentValue : false },
    { name : "canvas", isPrimaryContentValue : true },
    { name : "html-composer", isPrimaryContentValue : false }
  ]

Each surface corresponds with a different Orkut page:

[edit]

Navigating to another surface

If you wish to provide links to other surfaces, you need to pass an opensocial.Surface object to the opensocial.requestNavigateTo() method. You can choose to use one of the objects returned by the getSupportedSurfaces() call described in the Available surfaces in Orkut section, but this may not be convenient for all applications.

The following code sample shows creating a new opensocial.Surface object and passing it to the requestNavigateTo() method:

  /**
   * When called, this method asks the container to switch to the canvas
   * surface 
   */
  function gotoCanvas() {
    var canvas_surface = new opensocial.Surface("canvas");
    opensocial.requestNavigateTo(canvas_surface);
  };

  /**
   * When called, this method asks the container to switch to the profile
   * surface
   */
  function gotoProfile() {
    var profile_surface = new opensocial.Surface("profile");
    opensocial.requestNavigateTo(profile_surface);
  };
[edit]

Getting the fully qualified Orkut Profile URL

The profile URL returned by Orkut returns a partial path that you need to resolve to the sandbox domain. A querystring parameter named parent is passed to your gadget’s IFrame and can be combined with the profile path to generate a fully qualified URL:

  function request() {
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest("VIEWER"), "viewer");
    req.send(response);
  };

  function response(data) {
    var viewer = data.get("viewer").getData();
    var profile = gadgets.util.getUrlParameters()["parent"] + 
                  viewer.getField(opensocial.Person.Field.PROFILE_URL);
    /* profile now contains the viewer's profile URL */
  };

  request();

The profile variable will contain a fully qualified URL that points to the user’s profile page on Orkut.

[edit]

Obtaining the application’s ID

In the 0.6 version of the API, there is no call to return your application’s ID number, and the workaround for version 0.5 will not work. Store this value manually if you wish to use it in your application.

[edit]

Passing data to your application through the querystring

There are cases where you may need to pass data to your application’s canvas view from the querystring. Orkut allows for a special parameter named “appParams” that you can use to pass parameter data to your application. For example, going to the URL

http://sandbox.orkut.com/Application.aspx?appId=xxxxxxxxxxxx&appParams=hello%3Dhi

(where xxxxxxxxxxxx is your application’s ID number) will forward a parameter named hello with a value of hi to your application. Retrieve this parameter in the following manner:

  var prefs = opensocial.getEnvironment().getParams();
  var hello = prefs["hello"];
  /* hello now contains the value "hi" */

To pass multiple variables in the appParams parameter, just put them in querystring format and urlencode the result. For example, to pass variables foo with value 12345 and bar with value “Bar value”, first generate a querystring:

foo=12345&bar=Bar value

then urlencode this result:

foo%3D12345%26bar%3DBar%20value

and assign it to the appParams parameter:

http://sandbox.orkut.com/Application.aspx?appId=xxxxxxxxxxxx&appParams=foo%3D12345%26bar%3DBar%20value
[edit]

Passing data to your application through requestNavigateTo()

If you are using the opensocial.requestNavigateTo() calls, you may supply an optional parameter containing data to be passed to the new page.

The following code passes two variables: foo and bar to the canvas surface of the current application:

  function gotoCanvas(params) {
    var canvas_surface = new opensocial.Surface("canvas");
    opensocial.requestNavigateTo(canvas_surface, params);
  };

  var my_params = {
    foo : 12345,
    bar : "Bar value" 
  };

  gotoCanvas(my_params);

In the canvas view, check for these values with the following code:

  var prefs = opensocial.getEnvironment().getParams();
  var foo = prefs["foo"];
  /* foo contains 12345 */

  var bar = prefs["bar"];
  /* bar contains "Bar value" */

You should see that after the navigation has taken place, your URL will look similar to:

http://sandbox.orkut.com/Application.aspx?appId=xxxxxx&uid=xxxxxx&appParams=foo%3D12345%26bar%3DBar%20value

This follows the same format as discussed in Passing data to your application through the querystring

[edit]

Getting a user’s Orkut UID

There are times when you need to obtain a Person’s Orkut UID, which is different from their OpenSocial ID number. For example, the Orkut UID be used to generate a link to a canvas page in another user’s context. Get the Orkut UID by parsing the user’s profile URL and extracting the UID parameter:

Important! This method is Orkut-specific and not portable to other OpenSocial containers. You should not use this method unless your application needs this data for Orkut-only functionality.

  function request() {
    var req=opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest("VIEWER"), "viewer");
    req.send(response);
  };

  function response(data) {
    var viewer = data.get("viewer").getData();
    var profile_url = viewer.getField(opensocial.Person.Field.PROFILE_URL);
    var regex = /uid=([^&#]+)/;
    var result = profile_url.match(regex);
    if (result.length == 2) {
      var uid = result[1];
      /* uid now contains the viewer's Orkut UID */
    } else {
      /* there was a problem getting the UID */
    }
  };

  request();

The “uid” variable will contain a value that can be used to construct links to an application canvas. See Linking to pages inside your application for more information.

[edit]

Linking to pages inside your application

You can combine some of these techniques to create URLs that can link to different pages in your application. Imagine that you wish to provide a link to an “about” page in your gadget. First, you need to dynamically generate a link similar to:

http://sandbox.orkut.com/Application.aspx?appId=XXXXXXXX&uid=YYYYYYYY&appParams=page%3Dabout

Where XXXXXXXX is the application ID (see Obtaining the application’s ID) and YYYYYYYY is the Orkut UID of the person you wish to link to (see Getting a user’s Orkut UID). URLs in this format can be constructed in the following manner:

  function makeLink(page, app_id, uid) {
    return [ gadgets.util.getUrlParameters()["parent"], 
             "/Application.aspx?appId=", 
             app_id, 
             "&uid=",
             uid,
             "&appParams=page%3D", 
             page ].join("");
  };

  /* stored_app_id should be initialized to the application ID - Check the 
   * "Obtaining the application's ID" section for details on
   * obtaining this.
   * stored_uid should be initialized to the user's Orkut UID - Note that 
   * is _not_ the same as the opensocial ID number!  Check the 
   * "Getting a user's Orkut UID" section for details on 
   * obtaining this. */

  var about_url = makeLink("about", stored_app_id, stored_uid);

You can print these links in a user’s activity stream, or even on an external website.

If you don’t want to generate a URL, but just want to redirect a user to the “about” page as they use your application, call opensocial.requestNavigateTo() with extra parameter data:

  function gotoPage(to_page) {
    var canvas_surface = new opensocial.Surface("canvas");
    var params = {};
    paramspage = to_page;
    opensocial.requestNavigateTo(canvas_surface, params);
  };
  gotoPage("about");

In your application, switch on the value of the page parameter to choose which page to render:

  var page = opensocial.getEnvironment().getParams()["page"]; 

  if (page == "about") {
    renderAboutPage();
  } else {
    renderNormalPage();
 }

This code will work no matter which method you choose to pass the page parameter to your application.

[edit]

Scrap-extension applications

A scrap-extension application is a gadget that allows users to write HTML scraps without having to write or copy/paste HTML into the scrapbook text box. These applications can generate sophisticated HTML content that is entered into into the scrap textbox. Then the user just has to click “post scrap” to post the scrap.

Creating scrap-extention applications is simple. First, be sure to specify that your gadget is a scrap-extension application by including in your gadget’s . Orkut applications with this feature will not appear in the leftnav. Instead, they will show up in the ‘Add…’ dropdown menu on the scrapbook page. They will still be listed on the ‘my applications’ page.

The ‘html-composer’ feature provides access to the _IG_ReturnRawHtmlString method which takes a string as a parameter. This string is passed to Orkut and used to populate the scrapbook page.

Note: For info on what HTML you can use in scraps, see these scrap formatting tips.

Here’s an example of a simple scrap-extension application. The user is prompted to enter their name and their favorite color. This information is used to generate the HTML for a scrap where the text is displayed in whatever color the user enters.

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Test Scrappy" height="100" width="450">
    <Require feature="html-composer"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[

      <script type="text/javascript">
        function sendMsg() {
          var name = from_name.value;
          var dropdown = document.getElementById('scrapcolor');
          var color = dropdown.options[dropdown.selectedIndex].value;

          _IG_ReturnRawHtmlString("<span style='color:" + color + "'>" + name + " likes to send " + color + " colored scraps" + "!</span>");
        }
      </script>

      <div id="content_div" style="font-size:12pt; padding:5px; text-align: center; background-color: #dcdcdc">
        Please enter your name:  <input type="textbox" name="name" id="from_name" value=""/><br>
        Please select the color of your scrap:
        <SELECT NAME="scrapcolor" id="scrapcolor" value="">
          <OPTION VALUE="blue">blue
          <OPTION VALUE="green">green
          <OPTION VALUE="red">red
          <OPTION VALUE="yellow">yellow
          <OPTION VALUE="orange">orange
        </SELECT>
        <br> 
        <input type="button" name="submit" id="submit" value="submit" onClick="sendMsg()" />
      </div>
    ]]>
  </Content>
</Module>

You can even use OpenSocial features in your scrap-extension application. Here’s a modified version of the previous example that inserts the viewer’s name into the textbox automatically. The changes are highlighted in bold.

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Test Scrappy" height="100" width="450">
    <Require feature="html-composer"/>
    <Require feature="opensocial-0.6"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[ 

      <script type="text/javascript">
        function request() {
          var req = opensocial.newDataRequest();
            req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), "viewer");
          req.send(response);
        }

        function response(data) {
          var viewer = data.get("viewer").getData();
          var name = viewer.getDisplayName();
          document.getElementById('from_name').value=name;
        }

        function sendMsg() {
          var name = from_name.value;
          var dropdown = document.getElementById('scrapcolor');
          var color = dropdown.options[dropdown.selectedIndex].value;

          _IG_ReturnRawHtmlString("<span style='color:" + color + "'>" + name + " likes to send " + color + " colored scraps" + "!</span>");
        }

        gadgets.util.registerOnLoadHandler(request);
      </script>

      <div id="content_div" style="font-size:12pt; padding:5px; text-align: center; background-color: #dcdcdc">
        Please enter your name:  <input type="textbox" name="name" id="from_name" value=""/><br>
        Please select the color of your scrap:
        <SELECT NAME="scrapcolor" id="scrapcolor" value="">
          <OPTION VALUE="blue">blue
          <OPTION VALUE="green">green
          <OPTION VALUE="red">red
          <OPTION VALUE="yellow">yellow
          <OPTION VALUE="orange">orange
        </SELECT>
        <br>
        <input type="button" name="submit" id="submit" value="submit" onClick="sendMsg()" />
      </div>
    ]]>
  </Content>
</Module>

You can also use type=url gadgets for scrap-extension applications. The content returned from the URL you specify will be rendered on Orkut. Here’s an example of a type=url application:

<Module>
  <ModulePrefs title="Scrapplication" scrolling="false" height="280" width="470">
    <Require feature="html-composer"/>
  </ModulePrefs>
  <Content type="url" href="http://www.example.com/orkut/scrapplication.php"/>
</Module>
[edit]

To learn more

So concludes this review of OpenSocial programming specifics within an Orkut environment. To continue learning about the OpenSocial API in general, you’ll also want to check out the additional documentation and materials hosted at the OpenSocial API home page.

投稿者加藤? | パーマリンク

| append.gif

tag: OpenSocial


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2008-05-15 (木) 12:11:15 (4201d)

アークウェブのサービスやソリューションはこちら