1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Building OpenSocial Apps- P2 pdf

50 310 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Getting Basic MySpace Data
Trường học University of Social Sciences and Humanities, Vietnam National University Ho Chi Minh City
Chuyên ngành Information Technology
Thể loại Tài liệu
Thành phố Ho Chi Minh City
Định dạng
Số trang 50
Dung lượng 441,16 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

In this chapter we’ll do just that by covering how to access and use your users’ data tomake your app more dynamic and appealing.We’ll show how to retrieve your users’ friends; use pagin

Trang 1

ptgError Handling

JavaScript errors from apps seem to be an all-too-common occurrence, but they don’thave to be Most developers don’t expect errors to occur, and so they don’t test or pre-pare for them as a result, but errors do happen.Your best defense against them is to admitthat yes, they do occur, and yes, you need to be ready for them

OpenSocial offers a few functions you can use to deal with errors In the followingexample we check for errors before we parse the response for data If an error is found,the response data isn’t parsed

/**

* Check if the response had an error; if it did, log it and if

* it was an INTERNAL_ERROR attempt to retry the request

* @param {opensocial.DataResponse} data

If the list of supported views contains the specified view, requestNavigateTo is invoked and the View object is passed in To make use of the rNT function, you might

do something like this in the onclick handler of a button:

rNT(gadgets.views.ViewType.CANVAS);

That will cause the browser to navigate to the app’s Canvas page.

Trang 2

25

if(ri && ri.hadError()){

// Output the error message log(ri.getErrorMessage());

// Check the error code; an INTERNAL_ERROR can simply mean // network congestion or MySpace server instability if(opensocial.ResponseItem.Error.INTERNAL_ERROR === ri.getErrorCode()){

// Retry the request a certain number of times; make // sure you don't create an infinite loop here!

if(retries > 0){

retries ;

window.setTimeout(getInitialData, 1000);

} } } return true;

} return false;

}

First, we check if the response is null or undefined, and then check if the global errorflag was set in the DataResponseobject by calling the object’s hadError()function

This flag is set if any of the requests had an error Each ResponseItemhas an error flag

as well, so we’ll need to check each ResponseItemin order to find out which requesthad the error, if the global flag was set We do this by calling the ResponseItem’s

hadError()function In this case we had only one request, so there is only one

ResponseItem, but in the event of multiple ResponseItemobjects we would checkeach one in turn to determine its error state

Similar to an opensocial.Enumobject that has two types of data, one for display andone for logical comparisons, each opensocial.ResponseItemthat encounters an erroralso has two types of data.The error message, accessed by getErrorMessage(), is anarbitrary string that should describe the error and help you debug what happened.Theerror code, accessed by getErrorCode(), matches up to one of the codes found in the

opensocial.ResponseItem.Errorenum Common causes for each type of error codemay be found in Table 2.4

You’ll notice that we also attempted to retry the request in the event of an

INTERNAL_ERROR.This is because an INTERNAL_ERRORcan sometimes occur because ofnetwork congestion or other temporary problems.Your request might succeed if youwait a second or so and try again

Error Handling 25

Trang 3

Handling errors offers two benefits:

n There are no embarrassing JavaScript errors when you try to retrieve objects thatdon’t exist

n There’s a possibility that you can recover from your error by retrying the request

Table 2.4 Common Error Code Causes

opensocial.ResponseItem.Error The most common cause of this error is that BAD_REQUEST some part of your request didn’t make

sense to the container For example, you passed in a negative value that should be positive, you didn’t supply a required field,

or you passed in an invalid ID for a lar request.

particu-opensocial.ResponseItem.Error This error is returned only when the server

not commonly seen.

opensocial.ResponseItem.Error This is a catchall error that typically occurs INTERNAL_ERROR when something unknown happens on the

MySpace side of the request As such, it should be intermittent It can also occur in opensocial.requestPermission (a topic we’ll cover in the section on requesting per- missions in Chapter 3) if a permission was requested but no new permission was granted, or if the server returned an unknown status code.

opensocial.ResponseItem.Error This error is returned if you’ve requested NOT_IMPLEMENTED some OpenSocial functionality that MySpace

doesn’t support If you receive this error, either the entire function you’re calling isn’t available, or some parameter in a request isn’t supported An example of the latter would be that you requested an opensocial.Person field that isn’t supported.

opensocial.ResponseItem.Error This error most commonly happens when UNAUTHORIZED you’ve requested data to which you don’t

have access It may be possible to use opensocial.requestPermission to ask the user to grant your app access to the data Again, see Chapter 3 for details.

Trang 4

This request/response pattern is the foundation of any OpenSocial app.You will use itevery time you request data from the server, so we hope you were paying attention.

Note

Code listings and/or code examples for this chapter and every other chapter can be found

on our Google Code page under http://opensocialtictactoe.googlecode.com

27

Trang 5

ptg

Trang 6

3

Getting Additional

MySpace Data

In the preceding chapter we covered how to fetch and make use of the Personobject

on the MySpace platform But there’s a lot more data out there—such as the user’sfriend list and the photos the user has uploaded It’s the use of all this data that willpropel your app from a lifeless Web game to a dynamic and social application with viralpotential

Most application developers use the friend list in order to spread and share theirapplications (see Chapter 5, Communication and Viral Features, to learn how) and otherendpoints like albums and videos to make their apps more personal and engaging for theuser

In this chapter we’ll do just that by covering how to access and use your users’ data tomake your app more dynamic and appealing.We’ll show how to retrieve your users’

friends; use paging to sort, sift, and display the data; as well as explore viewing albums,photos, and videos.We’ll also discuss some extras, such as how to check whether a useralready has an app installed and how to check for and request permissions from a user As

we start to request more and more sensitive data, such as a user’s photos, permissions willstart to come into play more and more

From now on, our Tic-Tac-Toe game is no longer a boring JavaScript applet It’s afeature-packed app that actually uses the power of the MySpace social network

How to Fetch a Friend List and Make Use

of the Data

This section will show you how to fetch a list of friends and then page through that list

You’ll also learn the various ways you can sort and filter a friend list, such as restricting it

to only friends who have the app installed

Trang 7

In our example Tic-Tac-Toe app, we’ll use the list of friends in two ways:

n Provide a list of all the Viewer’s friends so the Viewer can send invitations to thosefriends to add the app

n Provide a list of friends who already have the app installed so the Viewer canchallenge those friends to a game of Tic-Tac-Toe

The actual invitation sending and game play challenges will be covered in Chapter 5,Communication and Viral Features.This section will lay the foundation for thosefunctions by showing you how to pull out the friend list and filter it accordingly

A Quick JavaScript Lesson

Up until now, we’ve kept the code simple by sticking to OpenSocial-specific JavaScript.

We did this by separating the Tic-Tac-Toe game logic from the OpenSocial code and ing everything globally namespaced (meaning the code can be called from anywhere; this

keep-is its “scope” in programming terms).

Moving forward, our app will become more and more complex This added complexity requires us to start introducing more advanced JavaScript techniques such as object notation and object-oriented programming.

This is not a book on JavaScript programming but on how to build dynamic OpenSocial apps on MySpace You’ll find, however, that you’ll learn a lot about JavaScript along the way!

To this end you’ll start to notice the use of the TTT namespace This is where we’ll keep all the code for game-specific functionality For example, in Chapter 2, Getting Basic MySpace Data, we provided a key of "v" when we requested the Viewer data In this chapter we move all of those keys into an enum: TTT.RequestKeys So instead of using key "v", we use key TTT.RequestKeys.VIEWER.

We concentrate on the OpenSocial code in this book, but feel free to dig into the full code listings found at our Google Code site: http://opensocialtictactoe.googlecode.com.

Getting the Friend List

This is the same request/response idea from Chapter 2, Getting Basic MySpace Data,that helps define OpenSocial In fact, the friend list is just an opensocial.Collection

ofopensocial.Personobjects, but instead of dealing with just one Personas inChapter 2, we’re dealing with a list of them

There are two major differences between fetching a single Personand fetching afriend list:

n CallnewFetchPeopleRequestinstead of newFetchPersonRequest

n Instead of passing in an ID (such as Viewer or Owner), pass in an

opensocial.IdSpecobject

AnIdSpecobject is a different way to specify a group of IDs It requires you todefine two parameters: the user ID and the network distance.The user ID specifies the

Trang 8

context for the IdSpec—basically letting MySpace know if you’re asking for a groupinvolving the Owner or the Viewer MySpace supports the contexts of only Viewer andOwner In other words, you can’t get a friend list for a random user; it has to be foreither the Viewer or the Owner

The network distance defines how far out the connections go For example, ing a network distance of 0 would denote just the Owner or the Viewer, and a networkdistance of 1 would denote the friends of the Owner or the Viewer At this timeMySpace supports a network distance only to a maximum of 1, so you can’t fetch thefriends of your friends

specify-Let’s create a fetchFriendList()function to get a basic friend list.This functionwraps the newFetchPeopleRequest Our example is heavily simplified, though, so itisn’t our final version of the function We’ll expand on it as we see what else you can dowith a friend list We’ll be inserting this function into the code of our Tic-Tac-Toe appfound in Chapter 2 For those of you following along at home, place this functionanywhere in the script tag in that code:

function fetchFriendList(callback){

// Create the IdSpec object var params = {};

params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;

params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1;

var idspec = opensocial.newIdSpec(params);

// Create the DataRequest object var request = opensocial.newDataRequest();

// Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS);

// Send it off request.send(callback);

}

First, the IdSpecobject is created using a user ID of VIEWERand a network distance of

1 to specify that we want the friends of the Viewer Next, an opensocial.DataRequest

object is instantiated and the request is added to the queue with a custom key of

TTT.RequestKeys.VIEWER_FRIENDS Finally, the request is sent off (and the response willfind its way back to the specified callback)

Filters and Sorts

The first example we showed you just fetches an arbitrary subset of friends of the Viewer

This list is typically returned in the order in which the friendships were made and is not

How to Fetch a Friend List and Make Use of the Data 31

Trang 9

terribly complex OpenSocial, however, defines a number of ways to sort and filterfetched lists, making them a lot more useful Before getting to the code, let’s look at theavailable options.The MySpace-supported filter types and sorts are shown in Table 3.1

Let’s revisit the fetchFriendList()function, but this time with support for sortsand filters Again, we’re not quite at the final version of our function, but this codebrings us a step closer:

function fetchFriendList(callback, filter, sort){

// Create the IdSpec object var params = {};

params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;

params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = sort;

} // Create the DataRequest object var request = opensocial.newDataRequest();

// Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS);

// Send it off request.send(callback);

}

You can see that the filters and sorts are specified by adding opensocial.

DataRequest.PeopleRequestFields.FILTERandopensocial.DataRequest.

PeopleRequestFields.SORT_ORDERto the parameters

Paging

According to the OpenSocial spec, the default number of items returned for a request is 20

That means our fetchFriendList()function returns the first 20 friends in the list Butwhat if a user has more than 20 friends? Enter paging

Trang 10

Paging is a way to get a large collection of data one chunk at a time.That means thatonce we have fetched friends 1 to 20, we can then fetch friends 21 to 40, then 41 to 60,and so on OpenSocial also provides a way to specify which chunk of friends you wantfor a given request

To demonstrate paging, let’s expand one final time on our fetchFriendList()

function:

function fetchFriendList(first, max, callback, filter, sort){

// Create the IdSpec object var params = {};

params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;

Table 3.1 Supported Friend List Filters and Sorts on MySpace

opensocial.DataRequest.FilterType The default filter, essentially no filter ALL

opensocial.DataRequest.FilterType Fetches only those friends who have

opensocial.DataRequest.FilterType MySpace allows users to define top or

friends who appear at the top of the user’s Friend Space, and this filter fetches only those friends.

MyOpenSpace.DataRequest.FilterType Fetches only friends who

MyOpenSpace.DataRequest.SortOrder.ID Not a filter; allows you to sort a friend

list by ID (ascending) Note that this sort is applied after the page is fetched, so it doesn’t take the user’s entire friend list, sort it, and return a particular page What happens is that a page of friends is taken and that list is sorted This is not particularly useful.

opensocial.DataRequest.SortOrder.NAME Another sort; sorts the returned list by

nickname (ascending) Like the ceding sort, this one isn’t the most useful as the entire friend list isn’t sorted up front, only the returned page.

pre-How to Fetch a Friend List and Make Use of the Data 33

Trang 11

params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = sort;

} // Create the DataRequest object var request = opensocial.newDataRequest();

// Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS);

// Send it off request.send(callback);

}

You’ll notice that opensocial.DataRequest.PeopleRequestFields.FIRSTand

opensocial.DataRequest.PeopleRequestFields.MAXhave been added to theparameters.MAXdefines the maximum number of friends to fetch at a time, so if youspecified a MAXof 100 (the maximum allowed by MySpace), you’d get the friend list inchunks of 100.FIRSTspecifies which friend to start fetching from, so if you specifiedthatFIRSTis 201 and MAXis 100, you’d get friends 201 to 300

That means you’ll want to keep MAXat a constant value and increment FIRSTby thatvalue for each request Assume we define MAXto be 50; we’d start out with a value of

FIRSTas 1 If the user requested the next page, we’d change FIRSTto 51, and then 101,and so forth.The API provides you with the total number of friends in the list (in addi-tion to the number fetched with the current request) to aid you in paging

In our Tic-Tac-Toe app we fetch 20 friends at a time You can see a successful friendlist request in Figure 3.1

Trang 12

Let’s take a look at the paging object we used:

TTT.Lists.Pager = { pager_wrap:"<div class='pager'>{0}</div>", pager_prev:"<span onclick='TTT.Lists.Pager.prev();'><< prev</span>&nbsp;", pager_next:"&nbsp;<span onclick=’TTT.Lists.Pager.next();’>next >></span>", page_size:20,

} var markup = "";

if(current_list.first > this.page_size){

// If the first index is greater than the size of // a page then there will be a previous page markup += this.pager_prev;

} if(current_list.total >

Trang 13

} if(markup.length > 0){

markup = this.pager_wrap.replace("{0}", markup);

} return markup;

}, prev:function(){

var current_list = TTT.Lists.getCurrentList();

current_list.first -= this.page_size;

fetchFriends(current_list.list_type);

}, next:function(){

var current_list = TTT.Lists.getCurrentList();

current_list.first += this.page_size;

fetchFriends(current_list.list_type);

} };

ThePagerobject in our Tic-Tac-Toe app does three things:

1 Provides HTML markup for Next and Prev buttons that we can use to allow theuser to actually navigate between pages

2 Stores the value of FIRSTthat is the current value

3 Handles what happens when the Next and Prev buttons are clicked

Meanwhile, the getMarkUp()function handles the actual paging algorithm Withthis function there are three possible outcomes:

1 The number of records fetched is less than the number requested (MAX) Thismeans there is only one page of data, so no paging is required

2 The value of FIRSTis greater than the size of a page.Therefore, there is at leastone previous page, so we need the Prev link

3 The total number of friends is greater than all the friends fetched so far Therefore,there are more friends who can be fetched, so a Next link must be added

Trang 14

Tip: Advanced Technique

You’ll see as we progress through this chapter that our Tic-Tac-Toe app presents the user with three lists One is the entire friend list, one is the list of friends who have the app installed, and the third is the list of photos the user has uploaded to his or her MySpace Profile The lists all appear fairly similar—each item is in a box that can be clicked, each has a picture, and each has some text underneath If all these lists are so similar, why not abstract the code so you can use the same functions to generate all three lists?

This is exactly what we did We created a TTT.List object to represent a list, a TTT.Lists object that keeps track of all the current lists that are on the page

(note the s at the end), and a TTT.ListTypes enum to differentiate the types of lists.

The TTT.List object contains the status of a particular list, including which type it is It also has references to the actual Document Object Model (DOM) elements that get displayed, the OpenSocial objects that were fetched, paging parameters, what to do when it’s clicked, and the keys used to access the stored OpenSocial data It’s essentially an interface for what a list should look like.

The TTT.Lists object stores the collection of lists and which list is currently selected.

We also do something similar for the set of tabs along the top of the app Check out the TTT.Tab and TTT.Tabs objects for more abstraction fun!

Using the Data

We’ve now defined a function that wraps the OpenSocial function

newFetchPeopleRequest() In our Tic-Tac-Toe app we call that function like so:

}

First we get a reference to the currently selected list If it’s the list of friends who havethe app installed, we add that filter (TTT.ListTypes.HASAPP_FRIENDS) and send it intothe wrapper

How to Fetch a Friend List and Make Use of the Data 37

Trang 15

TTT.Lists.callback = function(response){

var current_list = TTT.Lists.getCurrentList();

var retryRequest = function(){

var data = null;

// Loop through the available keys to // find the actual data in the response for(var key in TTT.RequestKeys){

if(response.get(TTT.RequestKeys[key])){

data = response.get(TTT.RequestKeys[key]).getData();

break;

} } // Something bad happened to it if(null === data){

retryRequest();

return;

} else{

// Save the actual data to the TTT.List object current_list.list = data.asArray();

// Save the total number of items in the list current_list.total = data.getTotalSize();

// Draw the list TTT.Lists.draw();

} } else{

// If there was a permission issue if(data.getErrorCode() ===

opensocial.ResponseItem.Error.UNAUTHORIZED){

var reason = "To set a custom background for the game board!";

opensocial.requestPermission(

Trang 16

[MyOpenSpace.Permission.VIEWER_ACCESS_TO_PUBLIC_VIDEOS_PHOTOS], reason,

TTT.Lists.permCallback);

} // If there was an error and there are retries left, go for it else if(current_list.retries > 0){

retryRequest();

return;

} // Out of retries

else{

log("Oops, there was an error! Try refreshing the page.");

} } };

The callback checks for errors in the request and handles any retry attempts Each listmaintains its own retry count, and a failed request is retried the specified number of times

If there was no error, the response is looped through in an attempt to find out whatdata it contains.This allows the callback to handle any kind of response It can currentlyhandle the friend list responses, and as you’ll see later on, it can also handle the responsefor the photo list

If everything works (and it should), the data is saved to the TTT.Listobject, alongwith the total size of the collection for paging purposes, and the filtered list is drawn

Since each friend is represented by an opensocial.Personobject, actually parsing outthe data for each friend is similar to how it was done in Chapter 2 For details, refer to thatchapter, or for a complete code reference for the function TTT.Lists.draw(), check theChapter 3 sample code found here: http://code.google.com/p/opensocialtictactoe/source/

Photos

You can fetch all of the photos your user has uploaded to his or her MySpace Profile,provided the user grants your app proper permissions Users can limit permissions, butwe’ll explore how to deal with that later in the permissions section of this chapter Bydefault, though, you should have access to all of a user’s public photos Photos are

Fetching Media 39

Trang 17

defined by the MyOpenSpace.Photoobject, which contains the fields shown in Table 3.2.These fields are accessed in the same way as for a Person, for example,

photo.getField(MyOpenSpace.Photo.Field.CAPTION).Let’s take a look at the function signature that’s used to fetch photos.You’ll noticethat it’s slightly different from how we fetch people:

MyOpenSpace.DataRequest.newFetchPhotosRequest = function(id, opt_params)

idis a string used to identify who owns the photos.The value can be either

opensocial.IdSpec.PersonId.VIEWERoropensocial.IdSpec.PersonId.OWNER

opt_paramsis an object that specifies optional parameters In this case only thepaging parameters opensocial.DataRequest.PeopleRequestFields.FIRSTand

opensocial.DataRequest.PeopleRequestFields.MAXare allowed

The reason the function signature is in a different format from the other requestfunctions is that it is a MySpace-specific extension.The OpenSocial spec defines waysfor containers to extend the core functionality of the OpenSocial spec In this caseMySpace has added several new endpoints Because it’s an extension, the function exists

in the MyOpenSpacenamespace and not the opensocialnamespace

In our Tic-Tac-Toe app we fetch the list of photos for the user and allow the user to selectone That photo then becomes the background for the Tic-Tac-Toe game board Let’s take alook at a function that wraps MyOpenSpace.DataRequest.newFetchPhotosRequest:

function fetchPhotosList(first, max, callback){

// Add some paging parameters var params = {};

// Send it off request.send(callback);

Trang 18

ptg Figure 3.2 Screen shot of a successful photo request.

We set some paging parameters, create the opensocial.DataRequestobject, andsend off the request.You’ll notice the other big difference here, besides the namespacechange, of executing one of the MySpace extensions.Typically the fetch request, such as

newFetchPeopleRequest, is called via an instance of an opensocial.DataRequest

object However, when using this MySpace extension, we call it statically from the

MyOpenSpace.DataRequestnamespace.You can compare and contrast this functionwith the fetchFriendsListfunction to see the slight differences.This code can beseen in action in Figure 3.2

Albums and Videos

The pattern for fetching albums and videos is actually the same as it is for fetchingphotos So, if you know how to request photos, you know how to fetch albums andvideos

Obviously, the fields and objects differ depending on what you’re fetching, but thebasic structure remains the same.That said, we’ve included the fields and functionsignatures here as a reference for you

AlbumsAlbums are defined by the MyOpenSpace.Albumobject, which contains the fieldsoutlined in Table 3.3

Fetching Media 41

Trang 19

The function signature is as follows:

MyOpenSpace.DataRequest.newFetchAlbumsRequest = function(id, opt_params)

idis a string used to identify who owns the albums.The value can be either

out-The function signature is as follows:

MyOpenSpace.DataRequest.newFetchVideosRequest = function(id, opt_params)

idis a string used to identify who owns the videos The value can be either

LOCATION The geographic location where the album’s photographs were taken DEFAULT_IMAGE A URL that points to the album’s default image

PRIVACY A string indicating the album’s privacy settings; set to either

“Private” or “Public”

PHOTO_COUNT An integer indicating the number of photos in an album PHOTOS_URI The value (RESTful URI) for accessing the photos within the

album

Trang 20

Using opensocial.requestPermission and opensocial.hasPermission to Check a User’s Permission Settings

Permission settings are applied to both data and actions A user can specify permissions on

a per-app basis, but there are a couple of global permission settings that you’ll need toeither work with or work around (see Chapter 2, Getting Basic MySpace Data, for details)

In our Tic-Tac-Toe app we display a list of the user’s photos to the user But publicand private photos each have their own permission setting, so we should first check tosee if we have permission before we send out the request In our app we check whether

we at least have access to the user’s public photos:

DATE_CREATED The date when the video was created LAST_UPDATE The date when the video was last updated MEDIA_TYPE An integer indicating the media type of the video DESCRIPTION A description of the video

THUMB_URL A URL pointing to the thumbnail image associated with the video MEDIA_STATUS The current status of the video

RUN_TIME The run time, or length, of the video TOTAL_VIEWS The total number of views a video has received TOTAL_COMMENTS An integer indicating the number of comments the video has

received TOTAL_RATING An integer representing the video’s overall rating TOTAL_VOTES An integer representing the total number of votes the video has

received COUNTRY A string indicating the video’s country of origin; typically used to

identify culture, not geographic location LANGUAGE A string indicating the video’s language

Using opensocial.requestPermission and opensocial.hasPermission 43

Trang 21

// If no new permissions were granted, the // response will have an error

hasPermission()to see if we can make this call If we can, we fetch the photos If wecan’t, we request permission.To do this, we first must provide a reason.The reason is just

a string that is displayed to the user.Then we call opensocial.requestPermission(),passing in a callback function Note that MySpace supports only one permission at atime here, but you’ll need to put the Permissionobject into an array anyway

Finally, once the user closes the permission window, the callback function is executed

The main piece of information the response provides is whether or not a permission wasgranted If no new permissions were granted,hadError()will be true If a new

permission was granted,hadError()will be false If there was no error, we know thepermission was granted and we can continue on to fetch the photo list.Table 3.5 presentsall of the supported Personfields along with their return types

Table 3.5 Permissions You Can Request on MySpace MySpace-Supported Permission Description MyOpenSpace.Permission Posts the app on the user’s MySpace Profile DISPLAY_ON_PROFILE

MyOpenSpace.Permission Posts the app on the user’s Home surface DISPLAY_ON_HOME

MyOpenSpace.Permission Sends activities updates to the user’s friends;

SEND_UPDATES_TO_FRIENDS for example, “Susan just won a game of

Tic-Tac-Toe”

MyOpenSpace.Permission Shows friends’ activities updates about the SHOW_UPDATES_FROM_FRIENDS app; for example, “Your friend Bob just won

a game of Tic-Tac-Toe”

Trang 22

Table 3.5 Continued

MyOpenSpace.Permission Grants access to the app for any photos or ACCESS_TO_PRIVATE_VIDEOS_ videos that are marked as “Private”;

MyOpenSpace.Permission Grants access to the app for all public photos ACCESS_TO_PUBLIC_ and videos; enabled by default

VIDEOS_PHOTOS MyOpenSpace.Permission Grants access to the user’s identity information ACCESS_TO_IDENTITY_

INFORMATION MyOpenSpace.Permission Allows the app to upload photos directly to ADD_PHOTOS_TO_ALBUMS a user’s photo albums

MyOpenSpace.Permission Allows the app to update a user’s status and

MyOpenSpace.Permission Allows the app to view and use the user’s full CONTACT_INFO contact info (full name, age, sex, location,

and birthday) MyOpenSpace.Permission Allows the app to view the user’s full Profile FULL_PROFILE_INFO information, such as favorite books,

television shows, etc.

MyOpenSpace.Permission Allows the app to make updates to the user’s UPDATE_PROFILE Profile data; no endpoint currently makes

use of this, however MyOpenSpace.Permission Allows the app to send notifications to other SEND_NOTIFICATIONS users while the user is interacting with

the app; see Chapter 5 for details on notifications

MyOpenSpace.Permission If set, the user receives notifications from RECEIVE_NOTIFICATIONS the app; see Chapter 5 for details on

notifications

Summary

One of the nice things about OpenSocial is that the basic techniques for most tasks arefairly similar For example, requesting a friend list follows a similar request/responsepattern to requesting a photo Once you have that basic technique down, you canextrapolate and use it again and again

Just be careful and watch out for permissions—they’re one of the biggest causes ofunexpected behavior in apps, and they will trip you up if your code doesn’t work toaccommodate them If you’re running into problems with any requests, always checkyour permissions

Note

Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com

Trang 23

ptg

Trang 24

4

Persisting Information

As your ambitions for what you want to do with OpenSocial grow, so will your needs

One of the first needs you’ll have is persisting information between sessions.Without thehelp of an external server, you have two options for storing persistent data: the app datastore and cookies In this chapter we’ll compare different methods of persistent storageand show you how to use them

We’ll grow our sample application and show you how to use persistent storage toallow users to set a custom name for themselves in the game and keep track of theirhigh scores from session to session

App Data Store

The app data store is your premier option for serverless storage.This is the only storagemechanism that is officially supported in OpenSocial.The app data store works as asimple key/value storage mechanism If you’re not familiar with a key/value store, itlooks something like what is shown in Table 4.1

The app data store allows you to get away with not building or setting up an structure for your app, provided your needs are simple.You may store only text and arelimited to 20K of total data and 1024 bytes (characters) per key (at the time of thiswriting) App data is fairly flexible.Your app is allowed only read/write access to theViewer’s data, but it may read app data from any of the following people/groups:

infra-n Viewer

n Owner

n Viewer friends

n Owner friends

Trang 25

According to the spec, anything placed in the app data store is supposed to be able toevaluate to a valid JSON object Depending on the version of OpenSocial being used,the data stored will behave slightly differently If your app is under version 0.7, it canstore just about any string value—JSON or not With the 0.8 and later versions of the OpenSocial spec implementation, the data has to be properly parsable JSON data

There is currently discussion among those who participate in the development of theOpenSocial spec about whether the app data store should be only JSON objects, orJSON-parsable data—like simple strings.Your safest bet is to store data as JSON objects

If you do choose to store JSON data, you need to make use of the gadget JSON parser

to evaluate it.The call is simple enough:gadgets.json.parse(your_json_string) Inpractice, however, the gadget JSON parser is a little temperamental, so you need to getused to formatting your JSON “just so.” Firebug is an invaluable tool in sorting this out(Firebug, along with how to get it, is mentioned in the Introduction)

Now, let’s write some code

Saving and Retrieving Data

Saving data involves creating an opensocial.newUpdatePersonAppDataRequest

request object and sending it to the server in a data request Each edit or add of any key

in the Viewer’s app data store requires a new request, so the following code is a handyutility method for doing this (the callback parameter is optional, but it’s good practice toinclude it for error processing):

function setAppDataKey(key, value, callback) { var req = opensocial.newDataRequest();

For our Tic-Tac-Toe app we’re going to add a little customization by making use ofthe app data store.We’re going to allow the user to specify a game name that is differentfrom his or her standard MySpace display name.We’re also going to add a placeholderkey to the app data store for tracking the user’s high score

Table 4.1 Basic Key/Value Stores

FavoriteColor Green

Ngày đăng: 24/12/2013, 06:17

TỪ KHÓA LIÊN QUAN

w