Building OpenSocial Apps- P8

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
39
lượt xem
5
download

Building OpenSocial Apps- P8

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Building OpenSocial Apps- P8: Nhà phát triển của Thư viện Series từ Addison-Wesley cung cấp hành nghề lập trình với độc đáo, tài liệu tham khảo chất lượng cao hướng dẫn về các ngôn ngữ lập trình công nghệ mới nhất và họ sử dụng trong công việc hàng ngày của họ. Tất cả các sách trong thư viện của Nhà phát triển được viết bởi chuyên gia công nghệ các học viên những người có kỹ năng đặc biệt tại các tổ chức và trình bày thông tin một cách đó là hữu ích cho các lập trình viên khác....

Chủ đề:
Lưu

Nội dung Text: Building OpenSocial Apps- P8

  1. 324 Chapter 14 Marketing and Monetizing 12. Have you taken advantage of the OpenSocial platform and imported your apps to other social networks like Orkut or Hi5? I did at the start, but it became overwhelming to support multiple apps across mul- tiple sites that are not 100% compatible both in technology and policies, so now I just focus on MySpace and Facebook. 13. What advice, if any, would you offer a first-time app developer? Don’t expect your “big idea” will make you rich overnight. Dan Yue: Playdom (www.myspace.com/playdom) 1. Who are you? My name is Dan Yue and I’m the cofounder and CEO of Playdom, the largest game developer on MySpace. Prior to founding Playdom, I was employee num- ber 1 at Adify, an ad network platform acquired by Cox Enterprises in 2008; founded several wildly unsuccessful technology start-ups; and served as technical consultant to Wynn Design and Development … As a lifelong gamer, I’ve played thousands of hours of Final Fantasy 7 and Baldur’s Gate 2 and spent 34 long days as a semiprofessional Blackjack player. My commitment to the player experience runs so deep that I wake up several times a night to check the performance of Playdom’s games. 2. What OpenSocial apps have you created or helped to create? Playdom has developed and successfully launched 12 apps on MySpace, including seven RPGs. Playdom has also launched Poker Palace and Bumper Stickers on Hi5. 3. Is there anything you wish you had known before you started developing your first app? I wish we realized that games are much more successful on social platforms than other types of social apps.We first launched Kiss Me on MySpace, which was (and is) a success, but it may have been wiser to launch a game first, then follow with a social app. In the perfect scenario, you’d attract a high volume of installs with a highly engaging game; then you can use the first game’s popularity to cross-promote new apps. 4. How do you find the MySpace platform, in terms of both technology and growth opportunities? MySpace is a great platform that provides a lot of possibilities for developers. The average length of visit is longer on MySpace, compared to other social networks, and the emphasis is on self-expression and fun. Social games— and Playdom’s games in particular—work really well in MySpace’s environment. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. Interviews with Successful App Developers 325 5. And how do you find the MySpace platform in comparison to other platforms like Facebook? MySpace is very developer-focused, and we value our relationship with them. As one of many examples, their platform team recently conducted a survey to pinpoint developer pain points and solicit recommendations. (That said, we have a positive relationship with Facebook and find their team and policies by and large developer-friendly.) 6. What has been your most successful app in terms of number of installs? How many installs does it have? Mobsters is the number-1 app on MySpace with over 13.6 million installs. Playdom also has three of the top four apps on MySpace, including Own Your Friends, Kiss Me, and Bumper Stickers. 7. What did you try that did and didn’t work to promote your app and increase installs? We have generally enjoyed great success promoting our apps. Our two biggest strengths: cross-promotions (marketing a new game via a popular established game) and deeply integrating viral channels into our games (the best virals are a natural part of the game play). 8. Do you think your app(s) has been successful? Why or why not? A number of our apps have been successful. The most obvious indicator of suc- cess is in the number of installs: Mobsters is the obvious success, our largest MySpace app with over 13.6 installs; and Bumper Stickers is in second place with over 11 million installs to date. However, we really focus on the level of player engagement, and we’re very pleased with our DAU [Daily Active Users] and length-of-session metrics. 9. How did you scale your app once growth took off? Were you prepared, or was it a surprise? Playdom’s first app to hit it big was Own Your Friends, which rocketed to 5.7 million installs in the third month, only to grow to more than 7.5 [million] installs a month later.To be honest, we weren’t fully prepared:We didn’t have the server infrastructure to support the app’s massive growth. As a stopgap solution, the founding team got up several times a night to make sure the game was online. And we quickly focused on scaling the operation. Thanks to an angel investor, this was possible early in our history. 10. Have you tried to monetize your app? If so, how? Playdom has monetized various apps—and all our RPGs. Roughly 60% of our revenue comes from direct payments for virtual goods, including in-game advance- ment and limited edition items. Five percent of the people playing our games pur- chase virtual goods and the percentage goes up as players spend more time on our game.The other half of our revenue is generated via incentivized offers. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. 326 Chapter 14 Marketing and Monetizing 11. Have you ever spent money advertising your app? If so, where and was it worth it? We have purchased both sponsorships and cost-per-click banner ads on MySpace. Both have been worth the energy and money because of the return-per-user metrics they provide.With each user that clicks on the ad, that user brings in additional players through the app’s viral channels.These advertisements help seed virality—a critical driver of growth. 12. Have you taken advantage of the OpenSocial platform and imported your apps to other social networks like Orkut or Hi5? Poker Palace and Bumper Stickers have both been successfully launched on Hi5. 13. What advice, if any, would you offer a first-time app developer? New developers need to understand that in today’s market, it’s difficult to go massively viral by relying on old-school “spammy” methods.Viral channels need to be authentic to the game, and the game play needs to be fundamentally engaging. We’ve created a formula that speaks to a joint need to drive growth and reduce churn: G cD 0 or [Growth % of daily churn number of daily active users must be greater than 0] We’ve fueled growth by identifying the right in-game channels to deploy the virals.We’ve reduced churn by introducing in-game comments, compelling storylines, and mini-games. Summary In this chapter we looked at ways to spread your app, and then how to cash in once the installs start coming in. One thing to take away is that there are individuals and companies out there that are making money by making apps. We heard from a few of them in the interviews section and got some tips on how to achieve some success. When it comes to generating income, there is a wide variety of options; this is an expanding market and one that is interesting for advertisers. In terms of getting the biggest bang for your buck with ads, there are a lot of variables to consider. Using one of the bigger and more established companies, like Google, is a superior technical solution. You won’t see a lot of downtime with AdSense, for example. But AdSense isn’t built to target social networking apps. On the other hand, RockYou! Ads and Cubics are designed to specifically target the social networking user. But we encountered technical problems with both ad networks, so there’s a give-and-take you’ll need to consider. This is one of the most important decisions when it comes to developing and growing your app; ultimately you can’t make successful apps if you can’t pay for the Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. Summary 327 bandwidth. So it may take time for you to try different solutions, or a combination of solutions. Maybe your app is suited for micropayments and you needn’t bug your users with ads. Maybe your golfing app pulls up some great targeted ads via Google AdSense and you get lots of click-throughs. As we’ve seen, it’s easier than ever before to simply drop an ad into your app and start making money; the sooner you start thinking in terms of profit margins, the better. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. This page intentionally left blank Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. 15 Porting Your App to OpenSocial 0.9 Wnews is somethe OpenSocial spec is bad news. in constant flux while newsspec group e have good news and some Let’s go with the bad first.The bad that currently the seeks the Holy Grail of version 1.0.You may think that this isn’t so bad. After all, you log- ically go from version 0.8 to 0.9, then finally 1.0, right? Well, there is currently some talk of going from 0.8 to 0.9 to 0.10.That’s right: zero dot eight, zero dot nine, zero dot ten. We hope that won’t be the case and that the 0.9 spec will be stable enough that it can be called version 1.0 without too many changes. If that’s what happens, the spec should stop churning for a while, excluding a few bug fixes here and there. The other piece of bad news is that MySpace will probably continue to support the latest and greatest versions of the OpenSocial spec as they are released.That means version 0.9 will have the full support of MySpace. Sounds great, right? Well, if your app is currently written in version 0.7, that means you’ll now be two spec versions behind.The more versions that are released and supported by MySpace, the more likely it is that the older versions will receive less and less support.We’re already seeing this phenomenon to some extent. Bug fixes and feature releases for 0.7 are fewer and farther between compared to those for 0.8. Fortunately, the good news more than makes up for the bad. For the foreseeable future, MySpace will continue to support older versions of the OpenSocial spec. It’s a lot of effort to deprecate older versions of the spec, and too many apps are running on old versions. It will happen eventually, but it will probably be a long and drawn-out process. A little-known fact is that the 0.7 container actually also supports OpenSocial 0.6, an early and buggy release of the spec. By the time you read this page, dear readers, version 0.6 will be about two years old (or more)—an eternity in Internet time. If version 0.6 can last that long, and probably longer, then version 0.8 will be around for a long time as well. Even better news is the fact that when it comes down to it, not a whole lot is chang- ing from version 0.8 to version 0.9.The biggest change will be the inclusion of OSML to the spec. Since we covered OSML extensively in Chapters 10 and 11, we won’t Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. 330 Chapter 15 Porting Your App to OpenSocial 0.9 rehash that topic here.The other big change is what is called “OS Lite,” or the “Lightweight JS APIs.” OS Lite is, for the most part, a rewrite of the OpenSocial JavaScript APIs and has two main goals: to unify the JavaScript and REST APIs, and to use JSON for both inputs and outputs.These are both worthy goals, but the truth of the matter is that the original APIs will work just fine in version 0.9. Moving forward, OS Lite will probably become the standard, but it’s probably best to wait for version 1.0, when it becomes a bit more baked-in. Other than that, there are a few bug fixes, a feature or two, and a bit of a cleanup. Now, let’s take a look at the big changes. Media Item Support A slew of functions to support media items were added in 0.9; this includes fetches, updates, deletes, and (finally!) uploads. However, some of this functionality already existed on the MySpace platform as MySpace-specific extensions in 0.8. In the sections that follow, we’ll take a look at the new APIs and, if applicable, con- trast them with the 0.8 APIs.Then we’ll show some sample code so you can see how to use the new features. opensocial.Album The first thing we’ll look at is the new opensocial.Album object.The album object behaves exactly like the other OpenSocial objects, such as opensocial.Person; it has fields, and those fields are fetched with getField. Let’s take a look at the available fields that albums provide. OpenSocial 0.9* opensocial.Album.Field = { /** * String, unique identifier for the album. * May be used interchangeably with the string 'id'. * @member opensocial.Album.Field */ ID: 'id', /** * String, URL to a thumbnail cover of the album. * May be used interchangeably with the string 'thumbnailUrl'. * @member opensocial.Album.Field */ THUMBNAIL_URL: 'thumbnailUrl', *Code courtesy of OpenSocial.org: http://sites.google.com/site/opensocialdraft/Home/opensocial- javascript-api-reference/albums-js. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. Media Item Support 331 /** * String, the title of the album. * May be used interchangeably with the string 'title'. * @member opensocial.Album.Field */ TITLE: 'title', /** * opensocial.Address, location corresponding to the album. * May be used interchangeably with the string 'location'. * @member opensocial.Album.Field */ LOCATION: 'location', /** * String, ID of the owner of the album. * May be used interchangeably with the string 'ownerId'. * @member opensocial.Album.Field */ OWNER_ID: 'ownerId', /** * Array of MediaItem.TYPE, types of MediaItems in the album. * May be used interchangeably with the string 'mediaType'. * @member opensocial.Album.Field */ MEDIA_TYPE: 'mediaType', /** * Array of strings identifying the mime-types of media items in the album. * May be used interchangeably with the string 'mediaMimeType'. * @member opensocial.Album.Field */ MEDIA_MIME_TYPE:'mediaMimeType', /** * Integer, number of items in the album. * May be used interchangeably with the string 'mediaItemCount'. * @member opensocial.Album.Field */ MEDIA_ITEM_COUNT:'mediaItemCount' }; OpenSocial 0.8 on MySpace MyOpenSpace.Album.Field = { /** * A number representing an album's unique identifier. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. 332 Chapter 15 Porting Your App to OpenSocial 0.9 * @memberOf MyOpenSpace.Album.Field */ ALBUM_ID:"ALBUM_ID", /** * The RESTFUL URI with which to access the album on the API. * @memberOf MyOpenSpace.Album.Field */ ALBUM_URI:"ALBUM_URI", /** * The album's title. * @memberOf MyOpenSpace.Album.Field */ TITLE:"TITLE", /** * The geographic location where the album's pictures were taken. * @memberOf MyOpenSpace.Album.Field */ LOCATION:"LOCATION", /** * A URL for the album's default image. * @memberOf MyOpenSpace.Album.Field */ DEFAULT_IMAGE:"DEFAULT_IMAGE", /** * A string representing the album's privacy setting, * such as "Public" or "Private" * @memberOf MyOpenSpace.Album.Field */ PRIVACY:"PRIVACY", /** * An integer representing the total number of photos in the album * (not the number of photos actually contained * within the current object). * @memberOf MyOpenSpace.Album.Field */ PHOTO_COUNT:"PHOTO_COUNT", /** * A RESTFUL URI with which to access the photos contained in the album. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. Media Item Support 333 * @memberOf MyOpenSpace.Album.Field */ PHOTOS_URI:"PHOTOS_URI" }; The entities are basically the same—all the important stuff is there in both cases, such as IDs, album cover URL, and the number of media items in the album. Fetching Albums Here’s the functionality for fetching an album. First, let’s look at OpenSocial 0.9. OpenSocial 0.9† /** * The newFetchAlbumsRequest() creates an object for * DataRequest to request albums. * * @param {opensocial.IdSpec} An IdSpec used to specify which * people/groups to fetch albums from. * * @param {Map.<string, string>} opt_params * opt_params can specify the following: * opensocial.Album.Field.ID - an array of album IDs to fetch * (fetch all albums if empty, subject to pagination) * opensocial.Album.Field.MEDIA_TYPE - an array of MediaItem.TYPE * values to specify the kind of albums to fetch. * opensocial.DataRequest.AlbumRequestFields.FIRST - * The first item to fetch. * opensocial.DataRequest.AlbumRequestFields.MAX - * The maximum number of items to fetch. * @return {Object} A request object */ opensocial.DataRequest.prototype.newFetchAlbumsRequest = function(idSpec, opt_params) {}; And now, the MySpace 0.8 extension. OpenSocial 0.8 on MySpace /** * Creates an object to be used when sending to the server * @param {String} id The ID (VIEWER or OWNER) * of the person who owns the albums †Code courtesy of OpenSocial.org: http://sites.google.com/site/opensocialdraft/Home/opensocial- javascript-api-reference/datarequest. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  11. 334 Chapter 15 Porting Your App to OpenSocial 0.9 * @param {Map<opensocial.DataRequest.PeopleRequestFields.FIRST || * opensocial.DataRequest.PeopleRequestFields.MAX>} * opt_params Optional parameters specified when creating the albums. * @return {Object} A request object * @static * @memberOf MyOpenSpace.DataRequest */ MyOpenSpace.DataRequest.newFetchAlbumsRequest = function(id, opt_params) {}; There are no real functional differences between versions.The new version uses an IdSpec object instead of a plain old string ID. It can specify a particular album, whereas 0.8 had a separate endpoint for that, and the paging parameters are in a different namespace. Here’s an example function that takes in optional paging parameters, album ID, and callback function and makes a request for the Viewer’s photo albums: // Fetches the Viewer's photo albums function fetchViewerPhotoAlbums(first, max, album_id, callback){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; var idspec = opensocial.newIdSpec(params); // Create the DataRequest object var request = opensocial.newDataRequest(); params = {}; // Set the paging parameters if(first){ params[opensocial.DataRequest.AlbumRequestFields.FIRST] = first; } if(max){ params[opensocial.DataRequest.AlbumRequestFields.MAX] = max; } // Pick an album; album_id is an array of album IDs if(album_id){ params[opensocial.Album.Field.ID] = album_id; } // Force it to images params[opensocial.Album.Field.MEDIA_TYPE] = opensocial.MediaItem.Type.IMAGE; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. Media Item Support 335 // Add the request to the queue request.add(request.newFetchAlbumsRequest(idspec, params), "albums"); // Send it off request.send(callback); } In the function we specified opensocial.MediaItem.Type.IMAGE.The other possibility is opensocial.MediaItem.Type.VIDEO. Fetching Media Items Let’s look at the OpenSocial 0.9 method for fetching media items. OpenSocial 0.9‡ /** * The newFetchAlbumsRequest() creates an object for * DataRequest to request albums. * * @param {opensocial.IdSpec} An IdSpec used to specify which * people/groups to fetch media items from. * * @param {string} albumId * The ID of the album to fetch MediaItems from. * * @param {Map.<string, string>} opt_params * opt_params can specify the following: * opensocial.MediaItem.Field.ID - an array of media item IDs to * selectively fetch (fetch all items if empty, subject to pagination) * opensocial.MediaItem.Field.MEDIA_TYPE - an array of MediaItem.TYPE * values to specify the types of MediaItems to fetch * opensocial.DataRequest.MediaItemRequestFields.FIRST - * The first item to fetch. * opensocial.DataRequest.MediaItemRequestFields.MAX - * The maximum number of items to fetch. * * @return {Object} A request object */ opensocial.DataRequest.prototype.newFetchMediaItemsRequest = function(idSpec, albumId, opt_params){}; And now for version 0.8. ‡Code courtesy of OpenSocial.org: http://sites.google.com/site/opensocialdraft/Home/opensocial- javascript-api-reference/datarequest. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. 336 Chapter 15 Porting Your App to OpenSocial 0.9 OpenSocial 0.8 on MySpace /** * Creates an object to be used when sending to the server * @param {String} id The ID (VIEWER or OWNER) of * the person who owns the albums * @param {Map<opensocial.DataRequest.PeopleRequestFields.FIRST || * opensocial.DataRequest.PeopleRequestFields.MAX>} * opt_params Optional parameters specified when creating the videos. * @return {Object} A request object * @static * @memberOf MyOpenSpace.DataRequest */ MyOpenSpace.DataRequest.newFetchVideosRequest = function(id, opt_params) {}; /** * Creates an object to be used when sending to the server * @param {String} id The ID (VIEWER or OWNER) * of the person who owns the photos * @param {Map<opensocial.DataRequest.PeopleRequestFields.FIRST || * opensocial.DataRequest.PeopleRequestFields.MAX>} * opt_params Optional parameters specified when creating the photos. * @return {Object} A request object * @static * @memberOf MyOpenSpace.DataRequest */ MyOpenSpace.DataRequest.newFetchPhotosRequest = function(id, opt_params) {}; The big difference here is that the 0.9 API combines two MySpace 0.8 APIs into one, and it again uses an IdSpec object and modifies the paging parameter namespaces. In our Tic-Tac-Toe app, we had a function that fetched the Viewer’s photos; we’ll reproduce it here so that you can see the differences between versions. Version 0.8 Function for Fetching Viewer’s Photos // Fetch the Viewer's photos function fetchPhotosList(first, max, callback){ // Set the paging parameters var params = {}; params[opensocial.DataRequest.PeopleRequestFields.FIRST] = first; params[opensocial.DataRequest.PeopleRequestFields.MAX] = max; // Send the request var request = opensocial.newDataRequest(); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. Media Item Support 337 var id = opensocial.IdSpec.PersonId.VIEWER; var req = MyOpenSpace.DataRequest.newFetchPhotosRequest(id, params); request.add(req, TTT.RequestKeys.VIEWER_PHOTOS); request.send(callback); } Let’s now convert that code into 0.9. Version 0.9 Function for Fetching Viewer’s Photos // Fetches the Viewer's photos function fetchPhotosList(first, max, callback, media_id){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; var idspec = opensocial.newIdSpec(params); // Create the DataRequest object var request = opensocial.newDataRequest(); params = {}; // Set the paging parameters if(first){ params[opensocial.DataRequest.MediaItemRequestFields.FIRST] = first; } if(max){ params[opensocial.DataRequest.MediaItemRequestFields.MAX] = max; } // Pick a media item; media_id is an array of media IDs if(media_id){ params[opensocial.MediaItem.Field.ID] = media_id; } // Force it to images params[opensocial.MediaItem.Field.MEDIA_TYPE] = opensocial.MediaItem.Type.IMAGE; // Add the request to the queue request.add(request.newFetchAlbumsRequest(idspec, params), TTT.RequestKeys.VIEWER_PHOTOS); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. 338 Chapter 15 Porting Your App to OpenSocial 0.9 // Send it off request.send(callback); } Again we specified opensocial.MediaItem.Type.IMAGE, but opensocial. MediaItem.Type.VIDEO is supported as well. Updating Albums and Media Items These are APIs that allow you to update the metadata of albums and media items, not actually upload new ones.There are no 0.8 substitutes for these endpoints:§ /** * Updates the fields specified in the params. The following * fields cannot be set: MEDIA_ITEM_COUNT, * OWNER_ID, ID. Containers implement restrictions. * * @param {opensocial.IdSpec} An IdSpec used to specify which * people/groups to own the album. * * @param {string} albumId * The album to update. * * @param {Map<opensocial.Album.Field, object>} fields * The Album Fields to update.The following fields * cannot be set: MEDIA_ITEM_COUNT, * OWNER_ID, ID. Containers implement restrictions. * * @return {Object} A request object */ opensocial.DataRequest.prototype.newUpdateAlbumRequest = function(idSpec, albumId, fields){}; /** * Updates the fields specified in the params. The following * fields cannot be set: * ID, CREATED, ALBUM_ID, FILE_SIZE, NUM_COMMENTS. * Containers implement restrictions. * * @param {opensocial.IdSpec} An IdSpec used to specify which * people/groups own the album/media item. * * @param {string} albumId * The album containing the media item to update. * §Code courtesy of OpenSocial.org: http://sites.google.com/site/opensocialdraft/Home/opensocial- javascript-api-reference/datarequest. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16. Media Item Support 339 * @param {string} mediaItemId * The media item to update. * * @param {Map<opensocial.MediaItem.Field, object>} fields * The Album Fields to update. The following fields cannot be set: * ID, CREATED, ALBUM_ID, FILE_SIZE, NUM_COMMENTS. * Containers implement restrictions. * * @return {Object} A request object */ opensocial.DataRequest.prototype.newUpdateMediaItemRequest = function(idSpec, albumId, mediaItemId, fields){}; Let’s take a look at a quick example.The following function can be used to update the title, thumbnail URL, and description of a particular media item in a particular album. Since the functionality to update an album is very similar, we’ll leave it as an exercise for the reader to create a function to do so. // Updates a media item for the Viewer function updateMediaItem(album_id, media_id, newTitle, newPic, newDesc, callback){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; var idspec = opensocial.newIdSpec(params); // Create the DataRequest object var request = opensocial.newDataRequest(); var fields = {}; // Set the new fields fields[opensocial.MediaItem.Field.TITLE] = newTitle; fields[opensocial.MediaItem.Field.THUMBNAIL_URL] = newPic; fields[opensocial.MediaItem.Field.DESCRIPTION] = newDesc; // Add the request to the queue request.add(request.newUpdateMediaItemRequest(idspec, album_id, media_id, fields), "update_mi"); // Send it off request.send(callback); } Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. 340 Chapter 15 Porting Your App to OpenSocial 0.9 Uploading Media Items One of the big new features added to the spec is the ability to upload media. Sending the actual contents of an image isn’t very easy in JavaScript, so because of this the upload functionality works similarly to opensocial.requestSendMessage and opensocial. requestShareApp.You invoke opensocial.requestUploadMediaItem and a pop-up modal appears.The pop-up itself takes care of the actual uploading process. On MySpace either a Flash or a Java-based widget is used, depending on the end user’s system. Initially, only images are available for upload. Once an image has been uploaded and the user closes the pop-up window, a callback function is executed.The one parameter passed to this callback is an opensocial. ResponseItem object.This object contains information on any error that may have occurred, or an array of opensocial.MediaItem objects if there were any successful uploads. An example is in order: // Uploads an image to the specified album function uploadMediaItem(album_id){ opensocial.requestUploadMediaItem(album_id, uploadMediaItemCallback); } // Handles the response function uploadMediaItemCallback(response){ if(!response || response.hadError()){ // Error code var error_code = response.getErrorCode(); // Comma-delimited list of failed files var error_message = response.getErrorMessage(); // Array of failed files var failed_files = error_message.split(","); // Retry request? Update UI? } else{ // Array of MediaItem objects var mi_array = response.getData(); var div = document.getElementById("messages"); var url = opensocial.MediaItem.Field.THUMBNAIL_URL; for(var i = 0; i < mi_array.length; i++){ div.innerHTML += "
  18. Simplification of App Data 341 div.innerHTML += mi_array[i].getField(url); div.innerHTML += "' />"; } } } There are a couple of functions in the code.The first just wraps opensocial. requestUploadMediaItem.The second is specified as the callback function and handles the result of the attempted image upload.The response is checked for an error, and if one is found, we parse the error field for data.The error code is set as normal and should give you a good idea of what went wrong.The error message is a comma-delimited list of the files that had an error. If there was no error, either the user canceled the pop-up window or some files were uploaded. If the upload was successful, the data portion of the response contains an array of opensocial.MediaItem objects, one for each successfully uploaded image. If the array has a length of zero, you can assume the user canceled the action; otherwise you’re free to parse the array as you see fit. In our case, we simply iterate through the list of images and output them to the UI. Simplification of App Data The functionality of app data has remained constant between versions, but the APIs used to interact with it have been significantly simplified.The original API was deemed to be too complex for what was actually allowed. For example, it was possible to update the app data only for the Viewer, yet the function accepted an ID as a parameter even though its only valid value was VIEWER. To that end, the signatures for updating and deleting app data were modified.The following is what they used to look like. Version 0.8 (Updating and Deleting App Data) opensocial.DataRequest.prototype.newUpdatePersonAppDataRequest = function(id, key, value) {}; opensocial.DataRequest.prototype.newRemovePersonAppDataRequest = function(id, keys) {}; They have now been changed for 0.9. Version 0.9 (Updating and Deleting App Data) opensocial.DataRequest.prototype.newUpdatePersonAppDataRequest = function(key, value) {}; opensocial.DataRequest.prototype.newRemovePersonAppDataRequest = function(keys) {}; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. 342 Chapter 15 Porting Your App to OpenSocial 0.9 It’s a very simple change; you’ll literally just have to go through and remove the ID you were passing in. Updating and deleting app data weren’t the only APIs to be simplified; fetching app data also got a once-over.The entire opensocial.DataRequest. newFetchPersonAppDataRequest function was deprecated. Instead, app data was attached to the opensocial.Person object. Let’s take a look at an example: // Fetches the app data for Owner or Viewer function fetchPersonAppData(id, callback){ // Create an empty object to use for passing in the parameters var params = {}; var keys = ["key1", "key2", "key3"]; // Add the list of fields to the parameters params[opensocial.DataRequest.PeopleRequestFields.APP_DATA] = keys; // ID will be either: // opensocial.IdSpec.PersonId.VIEWER // or: // opensocial.IdSpec.PersonId.OWNER var appdata_req = req.newFetchPersonRequest(id, params); // Add the request to the queue and give it a key req.add(appdata_req, "app_data"); // Send it off req.send(callback); } This function fetches the app data for either the Viewer or the Owner. First an array of strings is created with all the app data keys we’d like to fetch—in this case we’d like to fetch three keys.Those keys are added to the parameter object via the opensocial. DataRequest.PeopleRequestFields.APP_DATA enum.The id variable can be either opensocial.IdSpec.PersonId.OWNER or opensocial.IdSpec.PersonId.VIEWER. The request is then sent as normal. Some small modifications are required to fetch the app data for the Owner’s or Viewer’s friends.The basic idea is to do everything as we did in the previous code sample but use opensocial.DataRequest.newFetchPeopleRequest instead. Note that when fetching friends, you need to provide an opensocial.IdSpec object instead of a string ID; see Chapter 3, Getting Additional MySpace Data, for details on that. To retrieve the app data in the callback, you must use a function that has been added to the opensocial.Person object:** **Code courtesy of OpenSocial.org: http://sites.google.com/site/opensocialdraft/Home/opensocial- javascript-api-reference/person. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. REST APIs 343 /** * Gets the app data for this person that is associated with the specified * key. * * @param {String} key The key to get app data for. * @return {String} The corresponding app data. */ opensocial.Person.prototype.getAppData = function(key) {}; You simply pass in the key of the app data you’re looking for, and the value is returned. Let’s look at an example: // Parse the app data function getAppData(response){ // First check for an error if(!response.hadError()){ // Person is now an opensocial.Person object var person = response.get("app_data").getData(); var val1 = person.getAppData("key1"); var val2 = person.getAppData("key2"); var val3 = person.getAppData("key3"); } else{ // Retry the request? } } The values of val1, val2, and val3 are the JSON objects that were stored in app data for key1, key2, and key3 respectively or undefined if nothing was found for that key. REST APIs For those of you using iframe apps and the REST APIs, there’s not too much change for you either.The SDKs will be updated to point to the new APIs, so the change should be invisible to you. Simply get the updated SDKs from the usual place: http://code.google. com/p/myspaceid-sdk/. Replace your existing source files with the new ones. If any of this sounds mysterious to you, check out Chapters 8 and 9 (where we cover OAuth and external iframe apps) for details.That should set you up with hitting the updated APIs. Unfortunately, it’s not quite that easy, since the responses of some of the APIs have been slightly modified.This difference in the response between versions exists because the MySpace 0.8 APIs weren’t quite to spec, but now in 0.9 they are. So it’s not that the spec changed; it’s just that MySpace is now compliant. Let’s take a look at the two most important APIs, person and friends, and take a look at how they’ve changed. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Đồng bộ tài khoản