Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Building OpenSocial AppsA Field Guide to Working with the MySpace Platform
When you write OpenSocial applications for MySpace, you can reach millions of users overnight. Building OpenSocial Apps shows you how, one step at a time. Whether you’re building casual widgets orfeature-rich, professional applications, this book will teach you everything you need to know.
The authors are the leading experts on OpenSocial and MySpace and have personally helped constructthe MySpace platform and OpenSocial standards. In this indispensable book, they walk you through the entire process of building apps, from signing up through building complex apps that can scale tothousands of users and interoperate on more than fifty social networks, such as Hi5, Orkut, andLinkedIn. They demonstrate today’s best practices for building OpenSocial applications and presentdozens of tips for leveraging both MySpace and OpenSocial to their fullest. Coverage includes
“The authors did a great job covering the various ins and outs of OpenSocial, and especially the specific MySpace quirks. If you are a new social networking application developer or even someone
who just wants to write better OpenSocial Apps, then this book has what you are looking for.”—Cassandra Doll, Software Engineer, Google
ColeRussellWhyte
BuildingOpenSocial Apps
Chris ColeChad RussellJessica Whyte
Foreword by Dan Peterson, President, OpenSocial Foundation
Building O
penSocial Apps
Developer’s Library
The Insider’s Guide to WritingOpenSocial Applications forMySpace—and Beyond!
A Field Guide to Working with theMySpace Platform
Web Development Cover image © Glowimages/Getty Images
ISBN-13:ISBN-10:
978-0-321-61906-80-321-61906-4
9 7 8 0 3 2 1 6 1 9 0 6 8
5 4 4 9 9
$44.99 US / $53.99 CANADA
A companion web site (opensocialtictactoe.googlecode.com) includes an extensive library of downloadablesource code and other support materials.
Text printed on recycled paper
informit.com/devlibrary
Developer’s Library
■ Installing and working with the MySpaceDeveloper Platform
■ Retrieving, parsing, and displaying user data,friend lists, and photos
■ Sending App invitations and notifications ■ Building mashups that communicate with
third-party web services
■ Marketing your App and building your user base■ Designing for performance, scalability, and fault
tolerance■ Securing MySpace and OpenSocial apps,
and protecting users’ privacy■ Building apps that display ads and accept
micropayments
Chris Cole, a software architect at MySpace, is a major contributor to building the MySpace OpenPlatform. A core contributor to the OpenSocial 0.9 specification, he is primary architect and implementerof the OpenSocial Markup Language for MySpace. Chad Russell, lead developer on the MySpaceOpenSocial team, knows both OpenSocial and the MySpace platform inside and out. Jessica Whytehas worked for several years as a journalist, most recently with Journalists for Human Rights.
0321619064_cole_opensocial.qxd 9/18/09 10:05 AM Page 1
Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initialcapital letters or in all capitals.
The screenshots and other depictions of myspace.com contained in this book may notaccurately represent myspace.com as it exists today or in the future, including withoutlimitation with respect to any policies, technical specs or product design.
The authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connectionwith or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom coversand content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact:
U.S. Corporate and Government Sales(800) [email protected]
For sales outside the United States, please contact:
International [email protected]
Visit us on the Web: informit.com/aw
Library of Congress Cataloging-in-Publication Data
Cole, Chris, 1974-Building OpenSocial apps : a field guide to working with the
MySpace platform/Chris Cole, Chad Russell, Jessica Whyte.p. cm.
Includes bibliographical references and index.ISBN-13: 978-0-321-61906-8 (pbk. : alk. paper)ISBN-10: 0-321-61906-4 (pbk. : alk. paper)
1. Entertainment computing. 2. Internet programming. 3. MySpace.com. 4. OpenSocial. 5. Web site development. 6. Social networks—Computer network resources.7. Application program interfaces (Computer software) I. Russell, Chad. II. Whyte, Jessica. III. Title.
QA76.9.E57C65 2010006.7'54—dc22
2009032342
Copyright © 2010 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means,electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, IncRights and Contracts Department501 Boylston Street, Suite 900Boston, MA 02116Fax: (617) 671-3447
ISBN-13: 978-0-321-61906-8ISBN-10: 0-321-61906-4
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing, October 2009
Editor-in-ChiefMark L. Taub
Acquisitions EditorTrina MacDonald
DevelopmentEditorSonglin Qiu
Managing EditorJohn Fuller
Full-ServiceProductionManagerJulie B. Nahil
ProjectManagementdiacriTech LLC
Copy EditorBarbara Wood
IndexerJack Lewis
ProofreaderGeorge Seki
TechnicalReviewersCassie DollBess HoBenjamin Schupak
Book DesignerGary Adair
CompositordiacriTech LLC
Cole_FM.qxp 9/23/09 2:11 AM Page iv
ForewordThe Internet is constantly evolving, with vast arrays of information on every topicgrowing at a remarkable pace. Google’s 1998 search index had only 26 million Webpages; a decade later it recognizes more than 1 trillion URLs.With so muchinformation, we need a new set of tools to make sense of the Internet.The transition isfrom a strict focus on informational content, to being able to take advantage of our con-text, our relationships, and our activities.
Enter the social Web, a relatively new twist to the Internet, which is being built up bysocial networks, portals, and even more traditional businesses.The “Open Stack” is a setof specifications being developed by grass-roots communities all over the world, enablingdevelopers to create new products and services enhanced by user-specific data.TheOpen Stack includes specifications such as OAuth, which provides secure access to data;OpenID, a global identity standard; and OpenSocial, a common API for building applica-tions.These specifications are becoming the underlying infrastructure for the social Web,weaving a social fabric throughout the Web.
OpenSocial enables developers to learn a single core programming model that canbe applied to all “OpenSocial containers,” those sites that support the OpenSocialspecification.With standards-based tools, including a JavaScript-based gadget API,a REST-based data access API, lightweight storage capabilities, and access to commonviral channels, developers can build inside those containers as well as create applicationsfor mobile phones or other sites. In late 2009, less than two years after its introduction,more than 50 sites have implemented support for the OpenSocial specification. Inaggregate, these sites provide developers with access to more than 750 million users allover the world.
By taking advantage of the OpenSocial API and the information available in thisbook, you will have a great opportunity to reach a lot of users. For example, you’llfind the OpenSocial API supported by many major sites that span the globe:Yahoo!,iGoogle, Xiaonei and 51.com (China), Mixi (Japan), orkut (Brazil), Netlog (Europe),and, of course, MySpace. Beyond that, OpenSocial is also supported by moreproductivity-oriented sites like LinkedIn and by Fortune 100 companies as diverse asIBM and Lockheed Martin.
With this book, you can quickly get up and running with OpenSocial on MySpace,and you’ll be poised to leverage that experience to reach users on other sites as well.Thein-depth programming examples provide a good introduction to the design optionsavailable when building with the OpenSocial API, and the code is open source for easeof use and future reference.Additionally, the MySpace Platform tips sprinkledthroughout will help you avoid common mistakes and understand the intricacies of theirplatform policies. Getting a feel for how social platforms operate will be valuable as youcontinue to explore the wide world of OpenSocial.
OpenSocial is constantly evolving, just like the rest of the Internet.The OpenSocialspecification is managed through an open process where anyone can contribute their ideasto influence the next version of the specification and help move the social Web forward.
Cole_FM.qxp 9/23/09 2:11 AM Page xvi
Since its creation, there have been several significant revisions to the specification,introducing some new programming methodologies and improvements that make it easierfor new developers to start using OpenSocial.As you’re getting into the OpenSocial API,be sure to contribute back to the OpenSocial.org community your ideas on how toimprove the specification.
It’s open. It’s social. It’s up to you.
—Dan Peterson, president, OpenSocial FoundationSan Francisco, California
August 2009
Cole_FM.qxp 9/23/09 2:11 AM Page xvii
IntroductionWelcome to the wonderful world of social apps.You are about to enter—or have alreadyentered—a fast-paced and treacherous landscape that can be exciting, frustrating,intellectually challenging—and yes, it can even be pretty profitable.
We hope to be your guide through both the hidden pitfalls and the soaring peaks.There is much to gain from this exciting new market; social apps have been aroundfor only a few years, after all. Many successful apps have yet to be created and thendiscovered by the millions upon millions of passionate MySpace users.
In this book we’ll start from scratch and walk you through the entire process ofbuilding apps, from signing up as a developer all the way to building highly complexsocial apps that can scale out to thousands of users.We have extensive experience on theMySpace Development Platform (MDP), from building apps to helping build theplatform itself.We’ll point out the many idiosyncrasies and quirks of the platform, as wellas the many ways to squeeze out a little better performance by making a few tweaks toyour existing apps.
Throughout this book we’ll demonstrate best practices and show lots of samplecode as we take a step-by-step approach to app development. Starting with a simple“Hello World”–style app, we’ll add functionality until we have a fully built,feature-rich app.We’ll fetch data on the current user, get the user’s friend list andphotos, and parse all the data that comes back to display it on the screen.We’ll sendapp invitations and notifications to help spark viral growth and send requests back toWeb services running on a third-party server in order to process and store data.Finally, and possibly most important, we’ll show you how to make money developingapps using ads and micropayments.
When it comes to developing social apps on the MySpace platform, the sky is thelimit.As of this writing, the most popular app on MySpace has more than 13 millioninstalls. Maybe your app will be the next big thing.All it takes is a good idea and a littlebit of knowledge. If you provide the former, we can provide the latter.
Our hope is that this book is accessible both to experienced social app developers andto those developers who have only heard about it on the news.To that end, if you’restanding in the technology section of your local bookstore reading this, and you have abit of computer programming knowledge mixed in with some free time and curiosity,this book is for you.
We’ll start from scratch in this introduction to ramp you up on MySpace andOpenSocial. For those who already have apps up and running out in the wild, this bookis also for you, as we’ll dig pretty deeply into the platform a little later on.You may befamiliar with the ideas and terms we introduce here, so feel free to skip ahead a bit.(Check out the section on tools, though!)
Cole_Intro.qxp 9/23/09 7:20 PM Page xxi
How to Read This BookThere are a couple of ways to read this book. If you’re an experienced app developer,you can use this as a reference book.The index will direct you to specific topics, whereyou can consult the various tables, sample code, and tips. Or, if you need to learn a newaspect of the platform, you can skip directly to that chapter and dive right in.
If you’re not an experienced app developer, we suggest you start from the beginning.We’ll start off with a “Hello World”–style app in Chapter 1 and add to it in eachsubsequent chapter. By the time the app is completed, you’ll have a broad knowledgebase of the entire platform.We then branch out into some advanced topics to take youa step further.
Assumptions Made by the AuthorsThis is not a book about how to code in JavaScript or Python or any other language.Wewill try to follow good practice in our sample code throughout the book, and we’llpoint out a few interesting tidbits along the way, but that’s all.This is a book on how towrite OpenSocial apps on MySpace.
To that end, we assume the following:
n You have basic knowledge of computer programming in general. Maybe you workat a software company and write PHP every day, or you’ve taken a few program-ming classes, or you’ve taught yourself by constructing your own Web page.
n You have basic knowledge of JavaScript or are willing to pick up the basics.We’renot talking advanced stuff here, just the basics like calling functions, giving valuesto variables, and that kind of thing.
With all that said, let’s get started!
What Is MySpace?Ah, MySpace. Land of lost friends now found, hours wasted, and every band on theplanet, large and small. Oh, and spam. Lots of spam. You can find the site here:www.myspace.com.
MySpace is a social network.You sign up for free and you’re given a “profile”; theProfile page is a Web page that others can view and you can edit. On your Profile youcan add information about yourself, pick a display name, and upload a picture. Otherswho view your Profile can leave comments for all to see.The cascading style sheets(CSS) of Profile pages can also be edited, so individuals can alter the styles of the page to“bling” out their Profiles in ways both beautiful and stunningly, shockingly bad.
In addition to a Profile page, you are given a Home page (shown in Figure I.1),which only you can see. It contains your notifications,“You have new mail!” and thelike, along with various links to other parts of the site and updates from your friends.
It is the friend aspect that truly makes a social network.The idea is simple; you signup and are assigned a single solitary friend:Tom, one of the cofounders of MySpace.
xxii Introduction
Cole_Intro.qxp 9/23/09 7:20 PM Page xxii
Through various means, such as searching, browsing, or having a robot guess “People YouMay Know,” you can find new friends and add them to your list. Having other users asfriends grants you certain privileges to their information.You may have access to theirProfiles even if they’re set to “Private”; you see their updates on your feed; and, mostimportant to us, friends can interact inside apps.
That’s MySpace in a nutshell.You sign up, bling out your Profile, add some friends,upload some pictures, install some apps, and send some messages.
What Is OpenSocial?OpenSocial is a specification that defines how Web sites allow third-party apps to run ontheir sites.That means many things. For example, OpenSocial defines what information aWeb site can and must expose for each of its users. It defines a client-side JavaScript run-time environment with a set of APIs that describe how to fetch and update that userdata.This environment is commonly called an “OpenSocial container.” Likewise, itdefines a set of server-side APIs that manipulate the same data but can be called from aserver running your language of choice, such as PHP. It also defines a markup languagecalled OSML that can be used to draw your app and fetch data.
This specification was started by the folks at Google, along with the help of MySpace,Hi5, and other initial early adopters. Maintenance of the spec has since been passed tothe OpenSocial Foundation and the community.That means any implementers, such asMySpace, Orkut, and LinkedIn, app developers, or really anyone at all can suggestmodifications to the spec and participate in setting the direction.Those modifications arethen voted on in a public forum and either brought into the spec (found at http://opensocial.org) or rejected.
Introduction xxiii
Figure I.1 A MySpace Home page.
Cole_Intro.qxp 9/23/09 7:20 PM Page xxiii
Any site on the Web is free to implement the OpenSocial spec.The idea is that whena site becomes OpenSocial-compliant, it is able to run almost any of the thousands ofapps already created using OpenSocial. If a site has correctly implemented all the variousAPIs, an app running on MySpace should run just as well anywhere else.That’s thetheory, anyway. In practice there are differences, some small, some large, between thevarious OpenSocial implementers, which can make it tricky to maintain an app onmultiple sites.
What Is the MySpace Open Platform?The MySpace Open Platform (sometimes called MySpace Developer Platform or MDP)is simply MySpace’s implementation of the OpenSocial spec. MDP is a blanket term thatcovers how to sign up as a developer, how to update your app, and how to actually runyour app.
MySpace tries its best (we really do) to fully implement the OpenSocial spec, butthere are bound to be some inconsistencies. Most of these inconsistencies are small, butwe’ll cover them as they come up throughout this book. MySpace has also implementedsome features that aren’t in the spec; we’ll cover these as well.
More than on any other OpenSocial-enabled site, developing apps on the MySpaceplatform gives you access to a huge number of users and potential customers.As of thiswriting, MySpace has more than 130 million monthly active users and is growing everyday. Forty-five million of those users have installed apps.To give you an idea of thedemographics, 53% of app users are female, with an average age of 18 to 24.That is avery marketable demographic to have at your fingertips.
What Tools Will You Need?Here’s where we finally start to get a little technical.After many long nights spentdebugging why that callback wasn’t being fired or where that stupid 401 unauthorizederror was coming from, we’ve found some really useful tools that will make your lifeeasier. Let’s repeat that for effect:These tools will make your life easier.
BrowsersFirst, a quick note on browsers. Install Firefox right now. Go to www.firefox.com. In ouropinion it’s best to develop on Firefox, get your app running the way you like it, thenworry about running it in Internet Explorer (IE) as well. Developing on the Web is stillan “IE and everyone else” process.You get an app working in Firefox, and that means itwill probably work just fine in Safari, Chrome, and Opera.Then you can bang your headfor a few hours (days?) fighting floating divs and onclick handlers in IE.
FirebugFirebug is the main reason Firefox is the Web developer’s browser of choice. Firebug isan incredible tool for all Web developers, and every single one of us should install this
xxiv Introduction
Cole_Intro.qxp 9/23/09 7:20 PM Page xxiv
Firefox extension. It’s even more useful because all JavaScript “alert” and “confirm”functions are blocked by the OpenSocial container, so it really is the best way to debug.Get it at http://getfirebug.com.
Firebug has many useful functions.We won’t go into every last one here, but there area few that we use every single day. To follow along at home, install the Firebug exten-sion, restart Firefox, navigate to your Web page of choice, then click Tools → Firebug →Open Firebug.The Firebug window will open at the bottom of the browser.
InspectThe Inspect feature allows you to view and edit CSS and inline style on any HTML element currently on the page. Click Inspect at the top left of the Firebug window andhover your cursor over a Web page.You’ll see that the various HTML elements becomehighlighted. Clicking on one will show you the HTML markup of that element in the leftpane and its current style in the right pane.You can then add a style or modify the existingstyle on the fly.
This is very useful for building up user interface (UI) elements quickly. Instead ofmaking a change, saving a file, uploading it, and reloading the page in a browser, you canjust edit the style very quickly and try different values.When you find what works inFirebug, you can make one edit to your page and it should be good to go.
ConsoleThe Console tab shows you a couple of useful things.The first useful bit of informationis that any and all JavaScript errors are displayed here, with a description of the erroralong with its file name and line number.The second is that any outgoing Web servicerequests are shown here.You’ll be able to view the exact outgoing URL, any parametersand headers sent along, and the response from the server.As most MySpace requests aresent as outgoing Web service requests, this is an invaluable debugging tool.You’ll be ableto see if the correct parameters were appended to the request, and you won’t have tooutput the response onto a div on the UI to see if you got the correct response or somesort of error.
ScriptThe Script tab is your debugger.You can load any HTML or JavaScript file into the leftpane by selecting the file in the drop-down above that pane.You can then set break-points at any line with a green line number. In the right pane you can set watches onvariables, view the current stack, and manipulate the breakpoints you’ve set.
With the Watch window you can interrogate any object by simply typing the variablename into the New Watch Expression bar. Doing so displays the object’s current stateand value. But you can also directly manipulate objects. Say you wanted to see whatwould happen if a Boolean variable were true instead of false; you can set thatdirectly by entering something like varName = true into the Watch Expression bar.
Need to figure out what’s causing that JavaScript error? Set a breakpoint on that lineand inspect the objects and variables that are causing the issue. Need to figure outexactly what the response looks like from a request to the MySpace servers? Set a
Introduction xxv
Cole_Intro.qxp 9/23/09 7:20 PM Page xxv
breakpoint in your callback function and add the response object to your Watch list(see this in action in Figure I.2).
There are countless other things you can do with the Script tab, and Firebug ingeneral, but we can’t discuss them all here.We hope we’ve sold you on its usefulness andthat you’ll discover the many great features it has to offer.
FiddlerFiddler is a free tool that watches all the traffic coming into and out of your computer.With respect to building apps, it is useful mainly if you decide to use the server APIs asopposed to the JavaScript APIs.We’ll discuss what that means later on in the book, butkeep this tool in mind when you get there.To give you a little bit of a preview, you’ll besending requests for data to MySpace, and those requests need to be sent using anauthentication scheme. Using the authentication scheme is tricky, but Fiddler will helpyou see exactly what you’re sending to MySpace and exactly what MySpace is sendingback to you. Get it here: www.fiddler2.com.
One other thing to note is that Fiddler works natively in Internet Explorer but notFirefox. If you do a little bit of Googling, you can get it up and running in bothbrowsers.
xxvi Introduction
Figure I.2 Interrogating the response from MySpace’s serversusing Firebug.
Cole_Intro.qxp 9/23/09 7:20 PM Page xxvi
2Getting Basic MySpace Data
In this chapter we’ll start with a very basic version of the Tic-Tac-Toe application andthen expand on it to include examples of how you might fetch a user’s name, address,and gender.We’ll then show you how to use that information in your application. Onthe way, we’ll cover how MySpace and OpenSocial define an opensocial.Personobject and how to use that information to enrich your application.
We’ll also get to really play with our Tic-Tac-Toe game.This will be our exampleapp, and over the course of the book we’ll take you from a basic game to a fully func-tional and feature-rich application.
At each step along the way we’ll teach you new methods and programming tricks foraccessing and using the OpenSocial API. Code examples will be shown in full and thenbroken down into segments for further explanation, allowing you to zero in on a specificfeature or trouble spot.
The Two Concepts That Every Developer Should KnowBefore we begin, there are two basic concepts that every MySpace and OpenSocial appdeveloper should know about:
n In the world of MySpace apps, everyone is either an Owner or a Viewer.n The MySpace permission model is a complex and confusing beast that will likely
leave you frustrated and angry.
On that note, let’s get started!
Basic Concepts: Owner and ViewerThe concept of Owner and Viewer is central to OpenSocial, and it boils down to
Owner � the MySpace user on whose surface the application is running
Viewer � the MySpace user who is currently interacting with the application
Cole_ch02.qxp 9/22/09 6:17 PM Page 9
Once you start accessing MySpace data, all the requests you make are made in thecontext of the Owner and the Viewer.
For example, let’s say John has the app installed and Jane is viewing John’s MySpaceProfile. John is the Owner and Jane is the Viewer.Alternatively, if John is looking at theapp on his own MySpace Profile, he is both the Owner and the Viewer.
When you request data, you’ll be asking for information about either the Owner orthe Viewer.
Basic Concepts: Permissions for Accessing MySpace DataNot all user data is accessible to apps, and the data that is accessible is subject to asometimes convoluted permission model.The key idea behind the MySpacepermission model (dubbed Open Canvas) is that under certain circumstances an appcan access a user’s data even if that user hasn’t installed the app. However, this accesscan happen only on the app’s Canvas surface and not on the Home or Profile surfaces.
Under this model there are essentially three core questions used to determinewhether an app can access a piece of data:
1. Does the Viewer have the app installed?
2. Is the Viewer logged in?
3. Has the Viewer blocked the app? Blocking an app prevents any and all accessto the Viewer’s data.
Figure 2.1 is a quick reference chart for Open Canvas; remember, though, that thesepermissions can change. So stay on your toes and watch out for permission traps whenaccessing user data.
Starting Our Tic-Tac-Toe AppThe first thing we need to do is to get the basic Tic-Tac-Toe app started. Since this appis just scaffolding on which to hang OpenSocial concepts, we’re going to gloss over a lotof the details.At this initial level our app could just as easily be a JavaScript gameembedded in a Web page. It is the OpenSocial code that we will add later that will makethe game come alive.
NoteBefore we start, you should have the basic version of Tic-Tac-Toe installed as an app on yourMySpace developer account. You will find the code on our Google Code page athttp://code.google.com/p/opensocialtictactoe/source/browse/trunk/chapter2/chapter2ttt.html. For instructions on how to create, publish, and edit an app, please refer to Chapter 1,Your First MySpace App.
The game is a simple table grid of nine squares. Each square has a click handlerto record player moves. Underneath the surface is a state-of-the-art computer AI (i.e., random-move engine) to play against.
10 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 10
The remainder of this chapter will introduce some basic concepts that are centralto OpenSocial and apply them to our Tic-Tac-Toe app. At the end of this chapter,our app will display the current player’s name, gender, current location, and Profileimage.
Accessing MySpace User DataMySpace Profile data is represented in OpenSocial by the opensocial.Person object.Essentially,
opensocial.Person � a MySpace Profile
The opensocial.Person object contains the methods shown in Table 2.1.In addition, the opensocial.Person object supports a wide range of data fields,
such as a user’s ID, Profile picture, or favorite movies.Table 2.2 presents all of the sup-ported person fields along with their return types.
Yes
Viewer hasadded the app
Basic Ownerdata* (Home)
Basic Ownerdata* (Profile)
Basic Ownerdata* (Canvas)
Basic Viewerdata* (Home)
Basic Viewerdata* (Profile)
Basic Viewerdata* (Canvas)
Owner’sfriend list
Yes
Yes
Yes
Yes
No
Yes
No
Yes
Viewer’sfriend list
Owner’s publicmedia**
Viewer’spublicmedia**
Viewer hasn’tadded the app
Viewer islogged out
Viewer hasblocked theapp
Yes
Yes
Yes
Yes
Yes
YesYesYes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
No
No
No No No
NoNo
NoNo
NoNo
*Basic person data is defined as the user’s display name, URL, Profile picture, and user ID.** “Media” includes photos, albums, and videos.
Figure 2.1 MySpace Open Canvas permission model for accessing user data.
Accessing MySpace User Data 11
Cole_ch02.qxp 9/22/09 6:17 PM Page 11
Table 2.1 opensocial.Person Methods*
Method Purpose
getDisplayName() Gets a text display name for this person; guaranteed to return a useful string
getField(key, opt_params) Gets data for this person that is associated with the specified key
getId() Gets an ID that can be permanently associated with this person
isOwner() Returns true if this person object represents the owner of the current page
isViewer() Returns true if this person object represents the currently logged-in user
*Portions of this chart are modifications based on work created and shared by Google (http://code.google.com/apis/opensocial/docs/0.8/reference/#opensocial.Person) and used according to terms described in theCreative Commons 2.5 Attribution License (http://creativecommons.org/licenses/by/2.5/).
Table 2.2 MySpace opensocial.Person Fields*
MySpace-Supported Person Field Description Return Type
opensocial.Person. A general statement about the StringField.ABOUT_ME person
opensocial.Person. Person’s age NumberField.AGE
opensocial.Person.Field. An object containing the opensocial.
BODY_TYPE person’s body type; MySpace BodyType
returns only opensocial.BodyType.Field.BUILD
and opensocial.BodyType.Field.HEIGHT
opensocial.Person.Field. Person’s favorite books Array of stringsBOOKS**
opensocial.Person.Field. Description of the person’s StringCHILDREN children
opensocial.Person.Field. Person’s current location; opensocial.
CURRENT_LOCATION MySpace returns only Address
opensocial.Address.
Field.REGION, opensocial.
Address.Field.COUNTRY,and opensocial.Address.Field.POSTAL_CODE
opensocial.Person.Field. Person’s date of birth DateDATE_OF_BIRTH
opensocial.Person.Field. Person’s drinking status (with opensocial.
DRINKER the enum’s key referencing Enum
opensocial.Enum.Drinker)
12 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 12
Table 2.2 Continued
MySpace-Supported Person Field Description Return Type
opensocial.Person.Field. Person’s ethnicity StringETHNICITY
opensocial.Person.Field. Person’s gender (with the enum’s opensocial.
GENDER key referencing opensocial. Enum
Enum.Gender)
opensocial.Person.Field. Whether or not the person has BooleanHAS_APP added the app
opensocial.Person.Field. Person’s favorite heroes Array of stringsHEROES**
opensocial.Person.Field.ID MySpace user ID String
opensocial.Person.Field. Person’s interests, hobbies, or Array of stringsINTERESTS** passions
opensocial.Person.Field. Jobs the person has held; Array of JOBS MySpace returns only opensocial.
opensocial.Organization. Organization
Field.NAME and opensocial.Organization.Field.TITLE
opensocial.Person.Field. Person’s statement about whom opensocial.
LOOKING_FOR or what he or she is looking Enum
for or what he or she isinterested in meetingpeople for
opensocial.Person.Field. Person’s favorite movies Array of stringsMOVIES**
opensocial.Person.Field. Person’s favorite music Array of stringsMUSIC**
opensocial.Person.Field. An object containing the person’s opensocial.
NAME name; MySpace returns only Name
opensocial.Name.Field.
UNSTRUCTURED
opensocial.Person.Field. Person’s current network status opensocial.
NETWORK_PRESENCE (with the enum’s key Enum
referencing opensocial.Enum.Presence)
opensocial.Person.Field. Person’s nickname StringNICKNAME
opensocial.Person.Field. Person’s Profile song opensocial.
PROFILE_SONG Url
opensocial.Person.Field. Person’s Profile URL String (must bePROFILE_URL fully qualified)
opensocial.Person.Field. Person’s relationship status StringRELATIONSHIP_STATUS
Accessing MySpace User Data 13
Cole_ch02.qxp 9/22/09 6:17 PM Page 13
Table 2.2 Continued
MySpace-Supported Person Field Description Return Type
opensocial.Person.Field. Person’s religion or religious StringRELIGION views
opensocial.Person.Field. Person’s sexual orientation StringSEXUAL_ORIENTATION
opensocial.Person.Field. Person’s smoking status (with opensocial.
SMOKER the enum’s key referencing Enum
opensocial.Enum.Smoker)
opensocial.Person.Field. Person’s status StringSTATUS
opensocial.Person.Field. Person’s photo thumbnail URL String (must beTHUMBNAIL_URL fully qualified)
opensocial.Person.Field. Person’s favorite TV shows Array of stringsTV_SHOWS
opensocial.Person.Field. URLs related to the person or Array of URLS the person’s Web pages or opensocial.
feeds; returns only the Profile Url
URL, so it’s better to use opensocial.Person.Field.
PROFILE_URL instead
MyOpenSpace.Person.Field. Medium-sized version of the opensocial.
MEDIUM_IMAGE image returned by Url
THUMBNAIL_URL; MySpace returns opensocial.Url.Field.ADDRESS and opensocial.Url.Field.
TYPE. This field is not part of the OpenSocial spec and is a MySpace-specific extension.
MyOpenSpace.Person.Field. Large version of the image opensocial.
LARGE_IMAGE returned by THUMBNAIL_URL; Url
MySpace returns opensocial. Url.Field.ADDRESS and opensocial.Url.Field.
TYPE. This field is not part of the OpenSocial spec and is a MySpace-specific extension.
*Portions of this chart are modifications based on work created and shared by Google (http://code.google.com/apis/opensocial/docs/0.8/reference/#opensocial.Person.Field) and used according to terms described in theCreative Commons 2.5 Attribution License (http://creativecommons.org/licenses/by/2.5/).**The data response for these fields is unstructured and is always an array of one element. For example,a user’s heroes aren’t separated out into array elements; instead, the response is a text blob. This isbecause these fields on a MySpace Profile are free text.
14 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 14
Accessing Profile Information Using the opensocial.PersonObjectThe first thing we’re going to add to our basic Tic-Tac-Toe app is the ability to getthe default fields for our Viewer by fetching the corresponding opensocial.Personobject using an opensocial.DataRequest. MySpace defines these default opensocial.Person.Field values for the Person object:
n Profile URL, or opensocial.Person.Field.PROFILE_URLn Image URL, or opensocial.Person.Field.THUMBNAIL_URLn Display name, or opensocial.Person.Field.NAMEn User ID, or opensocial.Person.Field.ID
These are the bare-minimum default fields that, as long as you have access to thePerson object, will always be returned.
One thing to note is that all requests to the MySpace API are asynchronous, meaningyou launch them as “fire and forget” requests.Typically you make a request and specify acallback function; when the server is done processing your request, it passes the results asa parameter into your callback function. One result of this is that you’re probably goingto want to put your data requests at the start of the code.That way the MySpace APIcan start processing your request as soon as possible, and your app won’t be stuck waitingfor data to come back.
How Asynchronous JavaScript Requests WorkJavaScript is capable of making synchronous or asynchronous data requests back toservers on the current page’s originating domain. Under the hood this is accomplishedvia the XMLHttpRequest object. This may be alternately referred to as XHR or Ajax.
OpenSocial wraps this functionality up in the opensocial.DataRequest object, soyou don’t need to know all the gory details. Because this is always done asynchronouslywith OpenSocial, your code needs to specify a callback function to handle the serverresponse.
JavaScript in the browser is inherently single-threaded, which basically means that itcan do only one thing at a time. Asynchronous processing allows your app to not“freeze” while it’s waiting for API requests to the MySpace servers to respond. A call-back function allows your app to resume processing when it gets the data response.
Let’s take a look at a function that does the following:
1. Instantiates an opensocial.DataRequest object
2. Calls newFetchPersonRequest to create a generic request object, passing in theVIEWER as a parameter
3. Adds the request to the queue by calling add(), passing in a key to name therequest
Accessing MySpace User Data 1515
Cole_ch02.qxp 9/22/09 6:17 PM Page 15
16 Chapter 2 Getting Basic MySpace Data
The following code shows this function:
/**
* Makes the initial call for the Viewer's opensocial.Person
* object and requests all fields supported by MySpace
*/
function getInitialData(){
// Returns an opensocial.DataRequest object
var req = opensocial.newDataRequest();
// Create a request object, passing in the Viewer; this will
// specify we want the opensocial.Person for the Viewer
var viewer_req = req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER);
// Add the request to the queue and give it a key
req.add(viewer_req, "v");
// Start processing the requests and specify the callback function
req.send(getDataCallback);
}
The first line of the function simply returns an opensocial.DataRequest object.The DataRequest object is designed to take care of all your requesting needs.Whiledeveloping our app, we’ll make heavy use of it.
opensocial.IdSpec.PersonId.VIEWER is one of many enums you’ll encounter inOpenSocial. In JavaScript this actually resolves into a string, and on MySpace specificallyit is equal to the string VIEWER.You can use the string and enum interchangeably, but werecommend using the enum for two reasons:
n If you mistype the enum, your mistake triggers a JavaScript error, but if youmistype the string, it isn’t immediately obvious that something went wrong, so it isharder to debug.
n The values to which the enums resolve aren’t yet clearly outlined in theOpenSocial spec, so different containers might resolve enums to different strings.
We use opensocial.IdSpec.PersonId.VIEWER here to state that we want to fetchthe Viewer’s data. Had we wanted to fetch the Owner’s data, we would have usedopensocial.IdSpec.PersonId.OWNER.
newFetchPersonRequest takes the ID of the user you want to request as a parame-ter (in this case the Viewer) and returns an object.That object is actually unnamed byOpenSocial, and the documentation simply refers to it as a “request.”This object is neverused directly beyond how it’s used here—passed into DataRequest’s add() function.
Essentially, the DataRequest object creates “request” objects that are passed into itsown add function. It may seem a little confusing, but remember—you’ll never have touse that mysterious, unnamed “request” object directly, and all OpenSocial API callsfollow this general pattern.
16 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 16
17
The add function takes that request and adds it to a queue that is stored in theDataRequest object. We also give the request a key and, in this case, the string "v".This key is used to identify the response of a specific request; we’ll use this key laterwhen we talk about how to parse responses.
The last line tells the container to start processing the request queue by callingsend().We pass the name of our callback function into send() as a parameter; whenthe server is done processing our request, it calls this function while passing in theresponse. You can see the flow of the OpenSocial data request and response pattern inFigure 2.2.
CODE EXAMPLE:function callback_func(data){ data.get("your_owner_key").getData();}
4. Receive and parse the response from the server
The server will return an opensocial.DataResponseobject which will, in turn, contain a number ofopensocial.ResponseItem objects. Each of thesewill correspond to a request made in step 2.
CODE EXAMPLE:req.send(callback_func);
3. Send the request to the server and request a callback
All requests to the MySpace servers are asynchronous.That means requests are sent in a “fire and forget” manner.The request is sent to the server and the server createsthe response. Once the response is ready, the callbackfunction is executed and the response is passed in.
2. Add the request to the DataRequest object
CODE EXAMPLE:req.add(req.newFetchPersonRequest("OWNER"),"your_owner_key");req.add(req.newFetchPersonRequest("VIEWER");
Here you can also pass in an optional key for eachrequest (the first request) or no key at all (the secondrequest). When you parse the response you’ll use thekey to identify each request. If you don’t pass in a key,the MySpace container will add a default key.
Instantiate an opensocial.DataRequest object.The DataRequest object can hold several requestsat once which can be sent as a batch to the server.
CODE EXAMPLE:var req5opensocial.newDataRequest();
1. Create an opensocial.DataRequest object
Figure 2.2 Basic request and response pattern for OpenSocial.
Accessing MySpace User Data 17
Cole_ch02.qxp 9/22/09 6:17 PM Page 17
18 Chapter 2 Getting Basic MySpace Data
Getting More than Just the Default Profile DataFields beyond the default person fields typically follow a slightly different request patternand may also require higher permission levels for access.
As an example of this, we’ll be requesting our Viewer’s status message (like a headlineor shout-out), address, and gender.We’ve modified the function shown previously tonow specify that we want this additional data:
/**
* Makes the initial call for the Viewer's opensocial.Person
* object and requests all fields supported by MySpace
*/
function getInitialData(){
// Returns an opensocial.DataRequest object
var req = opensocial.newDataRequest();
// Used to specify what data is returned in the response
var fields = [opensocial.Person.Field.CURRENT_LOCATION,
opensocial.Person.Field.GENDER,
opensocial.Person.Field.STATUS];
// Create an empty object to use for passing in the parameters;
// the parameters here are additional person fields from above
var opt_params = {};
// Add the list of fields to the parameters
opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = fields;
// Create a request object, passing in the Viewer; this will
// specify we want the opensocial.Person for the Viewer
var viewer_req =
req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER,opt_params);
// Add the request to the queue and give it a key
req.add(viewer_req, "v");
// Start processing the request and specify the callback function
req.send(getDataCallback);
}
Let’s take a look at what’s changed.The first line is the same; we instantiate anopensocial.DataRequest object. In the next line we create an array ofopensocial.Person.Field enums; this list corresponds to the specific Person fieldswe want from the API.
Next, an empty object is created called opt_params.This is another OpenSocial pat-tern that you’ll see repeated in many places. Requests typically have some default action,and if you want to modify the default action, you need to supply some parameters to
18 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 18
define what you want to do.You do this by adding certain properties to an object andpassing that object into the request.
When the MySpace container is processing a request for Viewer or Owner data, itchecks the parameters sent in for a property named profileDetail. If it finds such aproperty, it knows that additional fields were requested. So let’s take a look at that lineagain:
// Add the list of fields to the parameters
opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = fields;
On MySpace, opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILSresolves to the string profileDetail. We’re creating that property and setting it equal tothe array of opensocial.Person.Field values we created earlier.The container nowknows that additional fields were requested.
The rest of the function is the same as before—we create the request, add it to thequeue, and send it off.
opensocial.DataResponse and opensocial.ResponseItem (aka, Using MySpace User Data)The various person fields are returned in different ways, but there are essentially threetypes of responses:
n A literal, such as a string or a number. For example,opensocial.Person.Field.STATUS returns a string.
n An object. For example, opensocial.Person.Field.CURRENT_LOCATIONreturns an opensocial.Address object.
n An enum. For example, opensocial.Person.Field.GENDER returns anopensocial.Enum enum object.
All responses from the API come in the form of an opensocial.DataResponseobject.The DataResponse object contains some number of opensocial.ResponseItemobjects; each ResponseItem corresponds to the requests we added to the DataRequestqueue. For now, we just have the one request for the Viewer; we’ll look at dealing withmultiple requests and ResponseItem objects in the next chapter.
To get a particular ResponseItem object from an opensocial.DataResponse, youneed to use a key. If you already provided an optional key, use that. Otherwise, you canuse the default key created by the MySpace container.
Tip: Use an Optional KeyIt’s recommended that you always use an optional key, as the default keys can betricky to use. But, if you’re curious, the container-generated keys are found in theMyOpenSpace.RequestType namespace.
19Accessing MySpace User Data 19
Cole_ch02.qxp 9/22/09 6:17 PM Page 19
20 Chapter 2 Getting Basic MySpace Data
/**
* The callback method for the initial request
* @param {opensocial.DataResponse} data
*/
function getDataCallback(data){
// "v" was the key created in the request,
// data is an object of type opensocial.DataResponse
// data.get("v") returns an opensocial.ResponseItem
// data.get("v").getData() will return the actual data,
// in this case an opensocial.Person object
viewer = data.get("v").getData();
// Now let's do something with all that data
printPerson();
}
Let’s take a look at this function more closely.The first thing to notice is that it is thefunction we specified when we called send() in our previous request function.
// Start processing the request and specify the callback function
req.send(getDataCallback);
The function getDataCallback is executed when the server has processed our requestand prepared a response.The first line in getDataCallback takes that DataResponseobject and calls the get() function, passing in our key.Above we named our Viewer request"v"; here we use that key to get the ResponseItem that corresponds to that request.
The function call data.get("v") returns the ResponseItem object that contains theViewer’s opensocial.Person object; we get the Person by calling getData(). Nowthe variable viewer contains an object of type opensocial.Person, which in turn con-tains the details of the Viewer, specifically the four default fields plus the current location,gender, and status.Table 2.3 shows the methods available for the ResponseItem object.
Table 2.3 opensocial.ResponseItem Methods*
Method Purpose
getData() Gets the response data
getErrorCode() If an error was generated by the request, returns the error code
getErrorMessage() If an error was generated by the request, returns the error message
getOriginalDataRequest() Returns the original data request
hadError() Returns true if there was an error in fetching this data from the server
*Portions of this chart are modifications based on work created and shared by Google (http://code.google.com/apis/opensocial/docs/0.8/reference/#opensocial.ResponseItem) and used according to terms described in theCreative Commons 2.5 Attribution License (http://creativecommons.org/licenses/by/2.5/).
20 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 20
The next section of our code calls the function printPerson(), which is a helperfunction that we use to parse out the details of our Viewer and output them to thescreen. Here we will parse out all three types of responses—enums, strings, and objects:
/**
* Output the Viewer data onto the surface
*/
function printPerson(){
if(null !== viewer){
// You can set the src attribute of an
// <img> tag directly with THUMBNAIL_URL
document.getElementById("profile_image").src =
➥viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
// getDisplayName is a shortcut for
// getField(opensocial.Person.Field.NICKNAME)
document.getElementById("name").innerHTML = viewer.getDisplayName();
// Get the Viewer's status
var status = viewer.getField(opensocial.Person.Field.STATUS);
if(status && status.length > 0){
// If the status has been set, append it after the name
document.getElementById("name").innerHTML += " \"" + status + "\"";
}
// Get the opensocial.Address object
var location = viewer.getField(opensocial.Person.Field.CURRENT_LOCATION);
// The Address object is used similarly to the Person object; both pass a
// field into a getField function
document.getElementById("location").innerHTML =
➥location.getField(opensocial.Address.Field.REGION);
// gender is an opensocial.Enum object
var gender = viewer.getField(opensocial.Person.Field.GENDER);
// getDisplayValue is defined by the specific container and can and
// will differ between containers and is designed for displaying only
document.getElementById("gender").innerHTML = gender.getDisplayValue();
// The response of getKey is defined by OpenSocial and therefore
// you can compare the result to some known value
if(gender.getKey() === opensocial.Enum.Gender.FEMALE){
document.getElementById("myinfo").style.backgroundColor =
"#fcf"; // pink
}
21Accessing MySpace User Data 21
Cole_ch02.qxp 9/22/09 6:17 PM Page 21
22 Chapter 2 Getting Basic MySpace Data
else{
document.getElementById("myinfo").style.backgroundColor = "#09f"; // blue
}
}
}
Let’s break down this code.To access the data from the viewer variable, which is oftype opensocial.Person, we’ll typically need to use the getField() function.Afterwe confirm that viewer isn’t null, we call getField(), pass in the field we want as aparameter, and set that value to the src attribute of an image tag.The field we asked for,opensocial.Person.Field.THUMBNAIL_URL, is returned as a string, so we can justaccess it directly.That’s really all there is to parsing out a Person field that is returned asa string. For details on the return type for every supported Person field, refer back toTable 2.2 in this chapter.
The next line uses a shortcut to retrieve the Viewer’s display name.Anothershortcut, getID(), exists to retrieve the Viewer’s ID.All other fields are accessed usinggetField(), as you’ll see in the next few lines.We could have used getField(opensocial.Person.Field.NICKNAME) to retrieve the display name, but the shortcutis cleaner.
Next, we parse out the Viewer’s current location; this field is returned as anopensocial.Address object. You’ll notice that the opensocial.Address objectbehaves similarly to the opensocial.Person object. Both have fields that describe thetypes of data you can retrieve, which in turn are fetched using the getField()function. Many of the objects in OpenSocial follow this pattern.
Finally, we parse out the gender, which is an opensocial.Enum object.There are twouseful types of data in each opensocial.Enum: the display value and the key.The displayvalue is retrieved using getDisplayValue() and is a string that is defined by eachcontainer as it sees fit. For example, the display value for the female gender, depending onthe container, could be “female” or “It’s a girl!” or even “http://example.com/girl.jpg.”Because these display values can be different from container to container, the key istypically used when making comparisons as the key values are defined in theOpenSocial spec.
In our code, we output the display value to the surface but use the key to make alogical comparison; we set the background color to pink if the gender is female (i.e., it’sequal to opensocial.Enum.Gender.FEMALE), or blue otherwise.
In the full code listing for the chapter, which you can find at http://code.google.com/p/opensocialtictactoe/source/browse/#svn/trunk/chapter2, we added a function thatgoes through each Person field and parses it. If you’re wondering how to parse a particu-lar field that wasn’t covered here, take a look at the code and you should be able to findwhat you need.
22 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 22
23
Talking to Your ParentThe MySpace site itself runs on the domain myspace.com. All MySpace apps live on adomain different from that, usually msappspace.com, unless it’s an external iframe app(see Chapter 9, External Iframe Aps, for details on those). Because of this difference indomains, the iframe in which your app runs can’t access the outer page. The app is saidto be in a “jail domain.” Cross-domain access is a security measure built into all modernbrowsers, and MySpace makes use of it to prevent any malicious attacks on themyspace.com domain.
However, there are a few functions that are exposed to apps that do talk to the par-ent page. A cross-domain scripting trick called inter-frame procedure call (IFPC) opens afew holes in the jail domain for apps to take advantage of. Let’s take a look at two ofthe more useful functions.
The first is gadgets.window.adjustHeight(new_height). This function asks theparent page to resize the iframe vertically.
new_height can take on several types of values. It can be an integer greater than 1;in this case the iframe’s height is set to the specified number in pixels.
It can be a fraction greater than 0 and less than or equal to 1. In this case theiframe is resized to try to fill the specified fraction of the page. A new_height of 0.5would cause the iframe to fill half the available space, for example.
Last, new_height can be left out completely; in this case the iframe is resized to fillits contents.
You’ll see in the app that we use adjustHeight like this:
gadgets.window.adjustHeight();
This causes the iframe to be resized to fill its contents. This is usually the best wayto go, as it can be hard to know exactly how big your content is at all times. The otheroption is to resize your app to a very large number when it loads, such as 5000 pixels.This works well on the Canvas page but not on Home or Profile.
The other useful function is gadgets.views.requestNavigateTo(view). Thisfunction causes the browser to navigate away from the current page to the specifiedview. It’s how you take the user from the Home page to your Canvas page, for example.The supported view names are gadgets.views.ViewType.HOME,gadgets.views.ViewType.PROFILE, and gadgets.views.ViewType.CANVAS.
Let’s take a look at a handy wrapper function:
// This function wraps gadgets.views.requestNavigateTo,
// view comes from the enum gadgets.views.ViewType
function rNT(view){
// Get the list of views that the container currently supports;
// This returns a hash table keyed by view name
var supported = gadgets.views.getSupportedViews();
Accessing MySpace User Data 23
Cole_ch02.qxp 9/22/09 6:17 PM Page 23
24 Chapter 2 Getting Basic MySpace Data
Error HandlingJavaScript 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
*/
function requestHadError(data){
// Return true if data is null or undefined
if(!data) return true;
// Check the opensocial.DataResponse for the global error flag
if(data.hadError()){
// Find the specific opensocial.ResponseItem that had the error
var ri = data.get(Tic-Tac-Toe.RequestKeys.VIEWER);
// If the view name passed in is in the supported hash table
if(supported[view]){
// Request to navigate to that view
gadgets.views.requestNavigateTo(supported[view]);
}
}
This function takes in the name of the view to navigate to and then gets the list ofcurrently supported views by calling gadgets.views.getSupportedViews(). Thisfunction returns a hash table of gadgets.views.View objects, keyed by the names ofthe views.
If the list of supported views contains the specified view, requestNavigateTo isinvoked and the View object is passed in. To make use of the rNT function, you mightdo 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.
24 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 24
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 DataResponse object by calling the object’s hadError() function.This flag is set if any of the requests had an error. Each ResponseItem has an error flagas well, so we’ll need to check each ResponseItem in order to find out which requesthad the error, if the global flag was set. We do this by calling the ResponseItem’shadError() function. In this case we had only one request, so there is only oneResponseItem, but in the event of multiple ResponseItem objects we would checkeach one in turn to determine its error state.
Similar to an opensocial.Enum object that has two types of data, one for display andone for logical comparisons, each opensocial.ResponseItem that 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 theopensocial.ResponseItem.Error enum. 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 anINTERNAL_ERROR.This is because an INTERNAL_ERROR can 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
Cole_ch02.qxp 9/22/09 6:17 PM Page 25
26 Chapter 2 Getting Basic MySpace Data
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
Common Error Codes 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, youpassed in a negative value that should bepositive, you didn’t supply a required field,or you passed in an invalid ID for a particu-lar request.
opensocial.ResponseItem.Error. This error is returned only when the server FORBIDDEN responds with a status code of 403 and is
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, itshould be intermittent. It can also occur inopensocial.requestPermission (a topicwe’ll cover in the section on requesting per-missions in Chapter 3) if a permission wasrequested but no new permission wasgranted, or if the server returned anunknown 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’tavailable, or some parameter in a requestisn’t supported. An example of the latterwould be that you requested anopensocial.Person field that isn’tsupported.
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 useopensocial.requestPermission to askthe user to grant your app access to thedata. Again, see Chapter 3 for details.
26 Chapter 2 Getting Basic MySpace Data
Cole_ch02.qxp 9/22/09 6:17 PM Page 26
WarningWhen retrying your request after an error, be careful you don’t code yourself into an infiniteloop! It’s best to keep a retry counter as we do in the code shown previously.
SummaryIn this chapter we covered the basic flow of an OpenSocial application, focusing on theprocess of accessing data on the API and OpenSocial’s request/response pattern.We alsodefined an opensocial.Person object—what it is, how to get it, and what to do with it.
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.
NoteCode listings and/or code examples for this chapter and every other chapter can be foundon our Google Code page under http://opensocialtictactoe.googlecode.com.
27Summary 27
Cole_ch02.qxp 9/22/09 6:17 PM Page 27
Index
Symbols and Numbers${sender} reserved variable, 81–82
0.7 container, 208–211
AAbout section, Profile page, 276–278
access points, application security, 302
Acknowledge button, 267
activities
creating from app’s Canvas surface, 79get_activities_atom, 194–195get_friends_activities_atom, 195getting app listed on Friend Updates.
See opensocial.requestCreateActivity
os:ActivitiesRequest tag, DataPipeline, 223–224
Add App button, 69, 308
add function, 17
Add This App button, 7, 276
adjustheight function, cross-domain access, 23
AdSense, 311–313
advertisements
BuddyPoke app and, 320creating with Cubics, 313–314creating with Google AdSense, 311–313creating with RockYou! ads, 314–316monetizing Flixster Movies app
through, 322monetizing Playdom apps through, 326TK’s apps, 323
Cole_Index.qxp 9/23/09 2:31 AM Page 355
356 aggreggation, of activity feeds
aggregation, of activity feeds, 82
Ajax (Asynchronous JavaScript and XML), 94,200–203
albums
creating with create_album, 195–196fetching, 41–42fetching with get_album, 184–185fetching with get_albums, 183
albums, porting to OpenSocial 0.9
fetching, 333–335updating, 338–339using opensocial.Album, 330–333
ALL, not filtering friend list, 33
ALL_ALL, invariant message bundles, 256
Amazon
cloud storage products, 64Web Service, 174, 298–299
app categories, 308
app data store, 47–56
app data P2P play downsides, 147to avoid scaling bottlenecks, 298hacking, 302limitations of, 153overview of, 47–48refactoring to build local, 51–56saving and retrieving data, 48–51setting up AppDataPlay game,
127–133App Denial and Status Clarification,
MySpace Developer’s Forum, 266–268
App Engine, Google, 64
app gallery, promoting app with, 306–308
app life cycle, 265–281
changing app Profile/landing page,275–278
hiding and deleting app, 274making changes to live app, 274–275
managing developers, 279–280publishing. See publishing apprepublishing live app, 275suspension and deletion of app, 280
app Profile, 275–278, 308
AppDataPlay game object, 125–133
Apple Dashboard widget format, 260
application security, 301–302
&appvers=dev, 275
app.yaml
getting started with Google AppEngine, 157–158
sending messages using IFPC, 209server code for REST API, 181testing OAuth implementation locally,
166updating for friends Web service, 202
Aptana, and Unicode, 65
arrays, responseValues, 74
Asynchronous JavaScript and XML (Ajax), 94,200–203
asynchronous JavaScript requests, 15–17
authentication. See OAuth
AUTHORIZATION parameter,gadgets.io.makeRequest, 95
automation candy, adding feed, 110–111
AWS (Amazon Web Service), 174
Azure, Microsoft, 174–175, 298–299
BBAD_REQUEST error, 26
bandwidth, saving, 164
basic Profile, 204
batch requests, performance optimization,292
blogs, 75–76
body items, 82–83
Cole_Index.qxp 9/23/09 2:31 AM Page 356
body, message, 75
Boku (Mobilcash), 317
Bootstrapper
adding FriendPicker widget, 120–121initializing FriendPicker, 124–125
bottlenecks, identifying scaling, 295–297
branded pokes, 320
breakpoints, using Firebug as debugger,xxv–xxvi
broadband connection speeds, 285
browsers, developing MySpace with, xxiv
BuddyPoke app, 318–319
bulletins, 75–78
button text, customizing between views,232–235
Ccache memory, scaling bottlenecks and,
295–296
callback function
accessing more than just defaultProfile data, 18
accessing Profile information, 15–17checking user permissions to access
media, 44combating permission-denied errors
in activities, 87–88defined, 15paging friend list, 200–202in requestSendMessage, 78–79in requestShareApp, 72–74setting up AppDataPlay game,
130–132using friends list data, 38–39using user data, 20
Canvas page
accessing MySpace data on, 10creating activities from, 79
creating “Hello World” app on, 4–6defined, 5MySpace messaging policies, 70permission model for accessing user
data, 11sending notifications, 89spreading app to other users, 69
case sensitivity, language and countrycodes, 256
CDATA tags
adding other surfaces to gadgets,229–230
fixing parsing errors in gadget code,228–229
JavaScript blocks using, 225CDN (content delivery network), 92
ckeynsecret.py file, OAuth, 155
clearAllGames method, 145clearGame method, 144–145
clearing, P2P game, 144–145
client-side code
Data Pipeline tags processed in,221–222
implementing paging in, 200–203REST APIs, 197–199updating player bio lightbox,
236–237using custom templates in, 242–244
clients, and scaling performance, 298
cloud services
Amazon Web Service, 174Google App Engine, 155overview of, 64pitfalls of deep linking, 93
codeveloper permissions, 279
comments
adding to turn-based games, 135–138as supported message type, 74–76
357comments
Cole_Index.qxp 9/23/09 2:31 AM Page 357
communication
external server. See external servercommunications
viral features and. See viral featuresand communication
connection speeds, and performance, 285
Console tab, Firebug, xxv
constraints
polling interval for real-time play,146–147
static content on external servers, 92
consumer key, MySpace
defined, 153–154OAuth settings, 155–156server code for REST API, 183
container-generator keys, obtaining, 19
Content block, gadget XML
adding surfaces to gadgets, 217–218,229–230
custom tag template definition,240–242
customizing button text betweenviews, 232–235
defined, 215getting information with
os:ViewerRequest tag, 235–236merging Home and Profile with
shared, 230–231reusing common content, 230–231shared style, 231–232subviews, 245–248using basic data, 218–219
content delivery network (CDN), 92
CONTENT_TYPE parameter,gadgets.io.makeRequest, 95, 97
control flow tags, OSML, 226–227
Cookie Jacker, 59–64
cookies, 56–64
building Cookie Jacker app, 59–63
external server security constraints for, 91
overview of, 56reasons to not use, 57–59uses for, 64
country codes, 256
CPUs, scaling bottlenecks in databases and,295–296
crackers, 302
create_album function, 195–196cross-app promotions, 323–325
cross-domain access, 23–24
cross-site scripting (XSS) attacks, 303
CSS styling
editing app Profile page, 276–278responsive performance rules for, 285
Cubics ads, 313–314
culture codes, 255–256
currentGame, clearing, 144–145custom values, passing into app’s Canvas
surface, 86
Ddata, getting additional. See MySpace,
getting additional data
data, getting basic. See MySpace, gettingbasic data
data listeners, OSML, 250–254
Data Pipeline, 219–225
coupling OSML with. See OSML(OpenSocial Markup Language)
data tag os:ActivitiesRequest, 223–224data tag os:DataRequest, 223–224data tag os:PeopleRequest, 222–223data tags, 220–221data tags os:ViewerRequest and
os:OwnerRequest, 222DataContext, 220defined, 214
358 communication
Cole_Index.qxp 9/23/09 2:31 AM Page 358
Data Pipeline, contd.
displaying JSON results with datalistener, 251–252
in-network vs. out-of-network data,221–222
JavaScript blocks in OSML apps, 225overview of, 219–220working with, 235–237
data security, 301
data tags, Data Pipeline
in-network vs. out-of-network data,221–222
os:ActivitiesRequest, 223–224os:DataRequest, 223–224os:PeopleRequest, 222–223os:ViewerRequest and
os:OwnerRequest, 222overview of, 220–221
data types, creating activities, 80–81
data warehouses, for Internet-scale apps, 298
databases
data warehouses vs., 298as primary scaling bottleneck,
295–297DataContext, Data Pipelining, 220, 236–237
DataRequest object
accessing more than just defaultProfile data, 18–19
accessing Profile information, 15–17app data store, saving and retrieving
data, 48–51asynchronous JavaScript requests
and, 15fetching albums, 333–335fetching friend list, 31fetching media, 39–43fetching media items, 335–336fetching Viewer’s photos, 336–338friend list filters and sorts, 32–33
os:DataRequest tag, Data Pipeline,223–225
paging friend list, 32–37updating albums and media items,
338–339DataResponse object
error handling, 25testing for errors, 300using MySpace user data, 19–24
“Death Star” project, Enron, 284
debug flag, POST requests, 165
debugging, using Script tab of Firebug,xxv–xxvi
deep linking, 93
deleting app data, OpenSocial 0.8 and 0.9,341–343
deleting apps, 274, 280
description, app, 307
design
adding feed reader to app, 98–104turn-based games, 118–119
detailtype parameter, 203
Developer Addendum, 266
developers
managing, 279–281signing up for MySpace account, 3–4
Developers & Testers option, My Apps page,279–281
developers, interviews with successful,318–326
Dan Yue (Playdom), 324–326Dave Westwood (BuddyPoke app),
318–319Eugene Park (Flixster Movies),
321–322Tom Kincaid (TK’s apps), 322–324
Development version, changing live app,274–275
Dewoestine, Eric Van, 157
359Dewoestine, Eric Van
Cole_Index.qxp 9/23/09 2:31 AM Page 359
display content, gadgets, 215
display, designing feed reader, 103–104
display value, opensocial.Enum, 22
displayMode property, FriendPicker, 123
DOM (Document Object Model)
adding feed reader to app, 93, 95customizing button text between
views, 233handling raw XML content in, 98JSONP calls and, 112–113modifying script to use subviews and,
247–248processing client-side templates, issues
with, 243processing RSS feed with FEED
content type, 104, 106–107setting up feed reader, 101–102, 104TTT.List object references to, 37
domains, cross-domain access, 23–24
DRY (Don’t Repeat Yourself) acronym, 230
duplicate applications, and app rejection,271–272
dynamic content, creating, 92
Ee-mail accounts
creating “Hello World” app, 4dealing with duplicate applications, 273signing up for MySpace developer
account, 3–4Edit App Information screen, 155, 216–217
Edit App Source, 274–275
Edit Profile, 276
endpoints
Profile, 203–204supported by MySpace SDK. See
REST API listtesting for errors with OpenSocial,
300
Enron, 284
Enterprise-scale applications, 293
enums
defined, 19parsing out, 21–22
error codes, common, 26
error flow, providing, 300
error handling
for fault tolerance and stability,300
fixing parsing in gadget code,228–229
from makeRequest call, 100in on-site vs. off-site app, 200–202OpenSocial DataResponse objects,
300OpenSocial functions for, 24–27for performance optimization, 292
event handling, installs and uninstalls,279–280
extended Profile, 204
external Iframe apps, 177–212
cookie vulnerabilities not applicableto, 64
pros and cons of, 177–178REST APIs. See REST
(REpresentational State Transfer)APIs
sending messages using IFPC,208–212
talking to parent page, 23external server communications
adding feed reader. See feed reader,adding to app
adding image search, 111–114mashups, 92–93overview of, 91–92pitfalls of deep linking, 93posting data with form, 114
360 display content, gadgets
Cole_Index.qxp 9/23/09 2:31 AM Page 360
external servers
defined, 91using Data Pipeline tags to pull in
data from, 221using OAuth. See OAuth
FFacebook, MySpace platform vs., 319, 321,
323, 325
failure array, responseValues, 74
“Fat Boy” project, Enron, 284
fault tolerance, 299–300
FEED content type, 100, 104–105
feed reader, adding to app, 93–111
adding feed refresh option, 109–110feed automation candy, 110–111FEED content type, 104–105gadgets.io.makeRequest overview,
94–96handling JSON content, 97handling partial HTML content, 97handling RSS feed content, 97–98handling XML content, 98overview of, 93–94response structure, 96–97secure communication, 111setup and design of, 98–104TEXT content type, 107–108“user’s pick” feed reader, 98XML content type with parsing,
105–107feedback, for turn-based game play,
135–138
FeedBurner, 105
feedCallback function, 100
fetchFriendList( ) function
fetching friend list, 31paging, 33–34
sorting and filtering, 32using data, 37–39
fetchPhotosList function, 336–338
Fiddler, xxvi
fields
accessing more than just defaultProfile data, 18–19
MyOpenSpace.Album, 42MyOpenSpace.NotificationButton, 89MyOpenSpace.Photo, 40MyOpenSpace.Video, 43opensocial.Person, 11–17Profile endpoint, 203–204using MySpace user data, 19–24
filters
app gallery, 306–308fetched lists, 31–33
finishing, P2P game, 144–145
Firebug, 48, xxiv–xxvi
Firefox, xxiv–xxv
Flixster Movies, 321–322
FORBIDDEN error, 26
form posts, communicating with externalservers, 114
fr-CA (French Canada) culture code, 255
fr-FR (French global) culture code, 255
friend list
calling requestShareApp, 72fetching, 30–31using data, 37–39using filters and sorts, 31–32using paging, 32–37Friend Updates, getting app listed on.
See opensocial.requestCreate ActivityfriendClickAction property, FriendPicker, 123
FriendPicker
adding, 119–121operation modes, 122
361FriendPicker
Cole_Index.qxp 9/23/09 2:31 AM Page 361
FriendPicker, contd.
using in turn-based games, 121–125friends
adding as developers, 279displaying with repeater, 237–238get_friends function, 185–187get_friends_activities_atom function,
195get_friendship function, 187–188interacting with on MySpace,
xxii–xxiiiprefetching record lists for paging,
287–291Web service and paging, 200–203
friends object, 211–212
friendsCatalog property, FriendPicker, 123
friends_obj parameter, 198
friends.py script, 202–203
full Profile, 204
function signatures
defining requestSendMessage, 75defining requestShareApp, 70–71fetching albums, 42fetching photos, 40–41fetching videos, 42
Ggadget XML, 214–219
adding other surfaces, 229–230adding second surface, 217–218basic structure, 215creating “Hello World”, 214–217creating initial file from existing code,
227–228declaring and using basic data, 218–219defined, 214defining basic app meta-information,
216–217
including translations in app andtesting, 259–260
internationalization and messagebundles, 255–260
using UTF-8 encoding, 259
gadgets.io.makeRequest
application security and, 301feed reader, adding to app, 93feed reader, setting up and designing,
100, 102feed refresh option, adding, 109–110Google providing implementation
code for, 105making real MySpace requests,
170–173making requests back to GAE server,
157making signed POST request,
162–166myspace:RenderRequest tag and, 226option parameters to, 95–96os:HttpRequest tag equivalent to, 221overview of, 94–96performance ramifications of, 286requesting data with Data Pipeline
tags using, 221spicing up Home and Profile surfaces,
173–174
gadgets.log, 126
gadgets.util.escapeString, 108
gadgets.views.requestNavigateTo(view)function, 23–24, 245–248
GAE (Google App Engine)
Amazon Web Service vs., 174getting started with, 157–158making signed POST request using
OAuth to, 162–166making simple GET request to,
158–162OAuth settings, 155–157
362 friends
Cole_Index.qxp 9/23/09 2:31 AM Page 362
GAE (Google App Engine), contd.
supported data store properties,158–159
testing OAuth implementation locally,166–169
game engine, supporting P2P game play,133–135
game play. See P2P (person-to-person)game play
GameInfo storage object, 125, 138–139
gameStatus function, 135
GET requests
making to GAE server, 158–162real-world implications of, 164testing OAuth implementation locally,
166–168get_activities_atom function, 194–195
get_album function, 184–185
get_albums function, 183–184
getCurrentGameObject function, 138–139,141
getData function, 20, 72–74
getDataCallback function, 20
getDisplayValue function, 22
getErrorCode function, 73
getErrorMessage function, 25
getField function, 22
getFriendGameData function, 147
get_friends function, 185–187
get_friends_activities_atom function, 195
get_friendship function, 187–188
getGameMovesString function, 143–144
getID function, 22
get_indicators function, 196
getInitialData function, 51
getMarkUp function, 36–37
get_mood function, 187–188
get_moods function, 188
get_photo function, 190
get_photos function, 188–190
get_profile function, 190–191
get_status function, 191
GET_SUMMARIES parameter,gadgets.io.makeRequest, 95, 97
Getter object, MySpace requests, 169–172
get_video function, 193
get_videos function, 192–193
global (invariant) culture, 255, 260
globally unique identifiers (GUIDs), 178
Gmail accounts, 273
AdSense, 311–313App Engine. See GAE (Google App
Engine)cloud storage products, 64Gadgets specification, 260gadgets.io.makeRequest code and, 105Translate, 258
GQL (Graphical Query Language), 162
grid-computing, as storage solution, 64–65
GUIDs (globally unique identifiers), 178
Hhackers
avoiding game play, 166security and, 302
hadError( ) function
checking user permissions to accessmedia, 44
error handling, 25requestShareApp callback, 73
hard disks, scaling bottlenecks in databases,296
hardware
performance issues, 284scaling bottlenecks in databases, 295–297
363hardware
Cole_Index.qxp 9/23/09 2:31 AM Page 363
HAS-APP, 33
hasPermission function, 43–45
HEADERS parameter,gadgets.io.makeRequest, 95
“Hello World”
creating app, 3–4entering app source code, 4–6for gadgets, 214–217installing and running app, 7signing up for developer account, 3–4
Hi5, importing apps to, 326
hiding apps, 274
high priority, defining in OpenSocial, 80
Home page
creating shared style Content blocks,231–232
customizing button text betweenviews, 232–235
defined, 5, xxii–xxiiigetting app listed on Friend Updates,
see opensocial.requestCreateActivityindicating new notification on, 88merging with Profile page, 230–231not accessing MySpace data on, 10spicing up surface, 173–174spreading app to other users, 68–69
horizontal scaling, 297–298
href attribute, opensocial.requestShareApp,85
HTML
adding custom elements to Aboutsection of Profile page, 276–278
adding feed reader to app, 97building feed reader UI, 99–101fragment rendering in OSML using,
248–250Inspect feature of Firebug using, xxvlearning in order to use MySpace, 321widget formats using, 260
Iicon, app, 307
id string, 40, 42
IDs
calling requestShareApp, 72defining requestSendMessage, 75sorting friend list by, 33
IdSpec object
defined, 30–31fetching friend list, 31setting up AppDataPlay game,
131–132IFPC (inter-frame procedure call)
cross-domain access, 23sending messages, 208–212
Iframe apps. See external Iframe apps
iLike, app Profile page for, 276
image search, adding to app, 112–114
importing apps, to other social networks,322
in-network data, Data Pipelining,221–222
incentivized app installs, 310
indicators, get_indicators function, 196
infrastructure, and app data P2P play, 147
initializeGame( ) function, 51
inline tag templates, OSML, 239–244
creating custom tag templatedefinition, 240–242
defined, 239using client-side, 242–244using custom tags, 242
inputs, validating, 299, 302–303
Inspect feature, Firebug, xxv
installing apps, event handling, 279–280
inter-frame procedure call (IFPC)
cross-domain access, 23sending messages, 208–212
364 HAS-APP
Cole_Index.qxp 9/23/09 2:31 AM Page 364
INTERNAL_ERROR, common cause of, 25–26
internationalization, and message bundles,255–260
creating first message bundle,256–257
creating translations of messagebundle, 257–258
culture code processing order, 255including translations in app and
testing, 258–260limitations of message bundles, 260overview of, 255
Internet history, 250
Internet-scale applications, defined, 293
Internet-scale applications, performanceguidelines
data warehouses vs. relationaldatabases, 298
identifying scaling bottlenecks,295–297
knowing scaling point, 294–295load-testing system, 299overview of, 293–294pushing work out to nodes, 298remembering what you know, 297scaling horizontally, 297–298utility computing, 298–299
interviews with developers. See developers,interviews with successful
invariant (global) culture, 255, 260
Invite page
client code for off-site app, 198–199creating link to, 204
Invite tab
implementing, 180–182sending messages to users, 203–208updating to use OSML and Data
Pipeline, 237–238
invite.py, 181, 202
isADraw function, 133–135
ISPs, database storage using, 64
Jjail domain, 23, 91
Java, hardware performance issues, 284
Java Virtual Machine (JVM), 284
JavaScript
blocks in OSML apps, 225error handling in, 24–27information on using, 30learning in order to use MySpace, 321OSML vs., 219–220responsive performance rules for, 285sending messages using IFPC,
208–212TTT namespace, 30understanding asynchronous requests
in, 15JSLoader, 208–209
JSON (JavaScript Object Notation)
adding feed reader to app, 97Ajax using, 94app data game store using, 125displaying results with data listener,
251–254error handling in off-site app, 201evaluating data in app data store, 48handling content for feed reader, 97makeRequest response object
properties and, 96–97processing RSS feed with FEED
content type, 104–105using simplejson file to manipulate
strings, 160JSP EL (JavaServer Pages Expression
Language), 214
JVM (Java Virtual Machine), 284
365JVM (Java Virtual Machine)
Cole_Index.qxp 9/23/09 2:31 AM Page 365
Kkeys
MySpace secret and consumer,153–154
opensocial.Enum object, 22setting up AppDataPlay game, 127
Kincaid, Tom, 322–324
Llanding page, changing app, 275–276
latestGameInfo, 139
legal issues, deep linking, 93
libraries, OAuth, 154
lightbox, updating player bio, 236–237
Lightweight JS APIs, 330
literal data type, 81
literals
defined, 19parsing out, 21–22
live app, making changes to,274–275
Live version, making changes to,274–275
load-testing, 299
loadAppData function, 52–53
loadAppDataCallback function, 130–131
loadFeed function, 100
loadFriendPicker function, 124
loadGame function, 139–142
loading issues, example of app rejection,271–272
localization
creating translations of messagebundle, 257–258
defined, 255localRelay parameter, IFPC, 209
logging, debugging app, 126
logic flows
designing turn-based games, 118for P2P game play, 138–144, 147setting up AppDataPlay game object,
125–133three-way handshakes as, 119
lookForWin function, P2P game play,133–135
low priority, defining OpenSocial, 80
MMail Center, notification folder, 88
makePlayerMove function,134, 135–138
makeRequest calls. Seegadgets.io.makeRequest
marketing and monetizing, 305–327
developer interviews. See developers,interviews with successful
generating revenue with micropayments, 316–318
overview of, 305promoting app on MySpace, 306–309user base and viral spreading. See viral
spreadingmarkup
OSML tags, 226simplifying for responsive
performance, 285mashups, 92–93, 98
MAX, paging friend list, 32–37
MDP (MySpace Developer Platform), xxiv
media items
fetching albums, 41–42fetching photos, 39–41fetching videos, 42–43including on message template, 82–83using opensocial.requestShareApp, 86
366 keys
Cole_Index.qxp 9/23/09 2:31 AM Page 366
media items, OpenSocial 0.9
fetching albums, 333–335fetching in 0.8 and, 335–336fetching media items, 335–336fetching Viewer’s photos, 336–338opensocial.Album, 330–333updating albums and media items,
338–339uploading media items, 340–341
memory, scaling bottlenecks, 295–297
message bundles. See internationalization,and message bundles
message parameter, requestSendMessage,75
messaging
MySpace policies for, 70using requestSendMessage, 74–79
metadata, gadgets, 215
METHOD parameter,gadgets.io.makeRequest, 96
method stubs, for game play, 128–129
methods
opensocial.Person object, 11–14opensocial.ResponseItem, 20
micropayments, generating revenue with, 316–318
Microsoft
Azure, 174–175, 298–299cloud storage products, 64
Mobilcash (Boku), 317
Mobsters, 316, 325
modal dialogs, 69–70
ModulePrefs section, gadgets, 215,216–217
modulo operations, 136
monetizing. See marketing and monetizing
mood
get_mood function, 187–188
get_moods function, 188get_status function, 191set_mood function, 195
multiple submissions, example of app rejection, 270–271
My Application screen, 265
MyAds, MySpace, 308–309
mylocalAppData, 52–53
MyOpenSpace.Album object, 41–42
MyOpenSpace.NotificationButton object, 89
MyOpenSpace.Photo object, 40
MyOpenSpace.requestCreateNotification,88–90
MyOpenSpace.Video object, 42–43
MySpace
Agreement, 266creating “Hello World” app, 3–6Developer’s Forum, 266installing and running app, 7Open Platform, xxivpromoting app on, 306–309Terms of Service, 310Terms of Use. See Terms of Useunderstanding, xxii
MySpace Developer Platform (MDP), xxiv
MySpace, getting additional data, 29–46
fetching albums, 41–42fetching friend list, 30–31fetching photos, 39–41fetching videos, 42–43using data, 37–39using filters and sorts, 31–32using paging, 32–37
MySpace, getting basic data, 9–27
accessing more than just defaultProfile data, 18–19
accessing Profile information, 15–17
367MySpace, getting basic data
Cole_Index.qxp 9/23/09 2:31 AM Page 367
MySpace, getting basic data, contd.
accessing user data, 11–14error handling, 24–27Owner and Viewer concepts, 9–10permissions concepts, 10starting Tic-Tac-Toe app, 10–11using MySpace user data, 19–24
myspace:RenderRequest, 249–250
Nname, app, 307
names
reserved variable, 81–82sorting friend list by nicknames, 33
namespaces
MyOpenSpace, 40–41TTT. See TTT namespace
navigation
away from current page to specifiedview, 23–24
keystrokes used for, 122to subviews, 245–248using cookies for storage across
surface, 64using Pager object, 36
network distance, fetching friend list and, 31
New App Invite, 68–69
newFetchAlbumsRequest function, 333–335
newFetchMediaItemsRequest function, 335
newFetchPeopleRequest function
calling requestShareApp, 72fetching friend list, 30–31using data, 37–39
newFetchPersonRequest, 16
new_height function, for cross-domainaccess, 23
Next button, handling with paging, 36
NotificationButton object, 89
notifications
MySpace messaging policies, 70sending, 88–90send_notification function, 196–197
NOT_IMPLEMENTED error, cause of, 26
NUM_ENTRIES parameter,gadgets.io.makeRequest, 96
OOAuth, 153–175
external server communicationsecurity with, 111
libraries, 154MySpace incompatibilities with, 157overview of, 153secure phone home. See phoning
homesetting up environment, 154–157spicing up Home and Profile surfaces,
173–174testing implementation locally,
166–169understanding, 153–154
objects
defined, 19parsing out, 21–22
off-site apps. See external Iframe apps
online references
Aptana, 259basic, full and extended Profile
data, 204code examples for developing first
app, 7Cookie Jacker, 59Cubics, 313–314Fiddler, xxviFirebug, xxvFriendPicker properties, 121
368 myspace:RenderRequest
Cole_Index.qxp 9/23/09 2:31 AM Page 368
online references, contd.
GAE (Google App Engine), 157Google AdSense, 311–313micropayment companies, 316–318MySpace SDK, 183OAuth, 153OpenSocial, xxiiiPayPal, 316Python download, 155RockYou! ads, 314–316SDKs for accessing MySpace APIs,
154Tic-Tac-Toe installation, 10TortoiseSVN, 155
ONLINE_FRIENDS, filtering friend list, 33
Open Canvas, 10–11
OpenSocial
app data store. See app data storebasic request and response pattern
for, 17container, 40, xxiiiporting app to 0.9, porting app to
OpenSocial 0.9Sandbox tool, 214–217, 227–228understanding, xxiii–xxiv
OpenSocial Markup Language. See OSML(OpenSocial Markup Language)
opensocial.Activity, 221
opensocial.Album, 330–333
opensocial.DataResponse. SeeDataResponse object
opensocial.hasPermission, 43–45
opensocial.IdSpec. See IdSpec object
opensocial.Message
defining requestSendMessage, 75–76defining requestShareApp, 70–71writing requestSendMessage
code, 76–78writing requestShareApp code, 71
opensocial.newUpdatePersonApp-DataRequest, 48
opensocial.Person
accessing more than just defaultProfile data, 18–19
accessing MySpace user data, 11–12accessing Profile information, 15–17Data Pipeline tags resulting in, 221fetching friend list vs. fetching
single, 30request/response pattern, 19–24
opensocial.requestCreateActivity, 79–88
aggregation, 82body and media items, 82–83data types, 80–81defining, 79–80getting app listed on friend updates,
79–88notifications patterned after, 88–89overview of, 79raising the event, 85–86reserved variable names, 81–82using activity callbacks to combat
permission-denied errors, 86–87using Template Editor to create
templates, 83–94using template system to create
activities, 80opensocial.requestCreateActivityPriority, 80
opensocial.requestPermission, 43–45,87–88
opensocial.requestSendMessage, 74–79
callback for, 78–79defining, 75–76overview of, 74–75writing code, 76–78
opensocial.requestShareApp, 67–74
callback for, 71–74calling, 71
369opensocial.requestShareApp
Cole_Index.qxp 9/23/09 2:31 AM Page 369
opensocial.requestShareApp, contd.
communication policies and rules, 70defining, 70–71requestSendMessage signature vs.,
75understanding, 67–69writing code, 71
opensocial.requestUploadMediaItem,340–341
opensocial.ResponseItem
error handling, 25–26requestShareApp callback, 72–74using MySpace user data, 19–24
opponent
always considering computer as, 143creating custom tag template
definition for, 240–242designing logic flow for turn-based
games, 118–119implementing with P2P logic flow,
138–144opponentPickedAction function,
FriendPicker, 122–124
opt_callback parameter
defining requestCreateActivity, 79defining requestSendMessage, 75defining requestShareApp, 71
optional keys, 19
opt_params object
defined, 18–19defining requestShareApp, 71fetching albums, 42fetching photos, 40fetching videos, 42POST request, 172–173
Orkut, importing app to, 322
os-data section, Content block, 235–236
OS Lite, 330
os:ActivitiesRequest tag, Data Pipeline,221–224
os:DataRequest tag, Data Pipeline, 221–224
os:Get tag, Data Pipeline, 248–249
os:HttpRequest tag, Data Pipeline, 221–222,251–252
os:If control flow tag, OSML, 226–227
OSML (OpenSocial Markup Language)
basic display tags, 226control flow tags, 226–227Data Pipeline, 219–225defined, 214gadget XML, 214–219overview of, 213–214remote content display tags, 226understanding, 225–226
OSML (OpenSocial Markup Language),advanced, 239–261
data listeners, 250–254future directions, 260HTML fragment rendering, 248–250inline tag templates, 239–244internationalization and message
bundles, 255–260working with subviews, 245–248
OSML (OpenSocial Markup Language),applying to Tic-Tac-Toe app, 226–238
displaying data lists, 237–238reusing common content, 230–235setting up gadget, 227–230working with data, 235–237
os:OwnerRequest tag, Data Pipeline, 221–222
os:PeopleRequest tag, Data Pipeline
defined, 221displaying friends list with repeater,
237–238overview of, 222–223processed on server, 221–222
370 opensocial.requestUploadMediaItem
Cole_Index.qxp 9/23/09 2:31 AM Page 370
os:ViewerRequest tag, Data Pipeline
defined, 221getting Viewer information with,
235–236overview of, 222processed on server, 221–222
osx:Else control flow tag, OSML, 227
out-of-network data, Data Pipelining,221–222
Own Your Friends app, 325
Owner
app data store. See app data storeconcept of, 9–10fetching app data for, 342fetching friend list for, 30–31getting ID of current, 169–170, 172getting more than just default profile
data, 19os:OwnerRequest tag, 221–222permission model for accessing user
data, 10–11reading app data from, 47–48signed POST requests for
authenticating, 162–163
PP2P (person-to-person) game play,
117–149
adding user feedback, 135–138advantages/disadvantages of, 148finishing and clearing game,
144–145fleshing out game logic, 138–144“real-time” play, 146–148supporting in game engine, 133–135turn-based games. See turn-based
gamingpageSize property, FriendPicker, 123
paging
friend list, 199–203prefetching record lists for
performance optimization, 287–291using, 32–37
parameters
custom tag template definitions, 241gadgets.io.makeRequest, 95–96
Park, Eugene, 321–322
parsing
fixing errors in gadget code, 228–229XML content type with, 105–106
Pay by Mobile button, Boku, 317
PayPal, 316–317
Pending status, publishing app, 266
performance, responsive
designing for, 284–285designing for scale. See scaling
performanceOpenSocial app guidelines, 285–292overview of, 283stability and fault tolerance, 299–300understanding, 283–284understanding scale, 284user and application security, 300–303
permission-denied errors, combating, 87–88
permissions
accessing more than just defaultProfile data, 18–19
checking user settings, 43–45codeveloper, 279error code causes, 26fetching photos uploaded to Profile,
39–41“Hello World” app, 6MySpace model for, 9–11MySpace supported, 44–45notifications, 90
371permissions
Cole_Index.qxp 9/23/09 2:31 AM Page 371
persisting information (between sessions)
setting up AppDataPlay game,129–132
using app data store. See app data storeusing cookies. See cookiesusing third-party database storage,
64–65Person data type, 81
Person objects, see opensocial.Person object
person-to-person game play. See P2P (per-son-to-person) game play
phoning home, 157–173
making real MySpace requests,169–173
overview of, 157signed POST request, 162–166testing OAuth implementation locally,
166–169unsigned GET request, 158–162
photos
adding to Profile page, 276–278checking user permissions to access,
43–45fetching, 39–41fetching for Viewer in OpenSocial 0.9
and 0.8, 336–338fetching with get_photo function, 190fetching with get_photos function,
188–190Play page, 198
Play tab
porting to off-site app, 203–208requiring user’s Profile data, 180
Playdom apps, 324–326
playerBioWrapper ID, 236–237
policies, MySpace communications ormessaging, 70
pollForOpponentUpdatedMove function, 147
polling design, for “real time” play, 146–148
porting app to OpenSocial 0.9, 329–349
fetching albums, 333–335fetching media items, 335–336fetching Viewer’s photos, 336–338opensocial.Album, 330–333overview of, 329–330REST APIs, 343–348simplification of app data, 341–343updating albums and media items,
338–339uploading media items, 340–341
POST requests
making real MySpace requests,172–173
making to GAE server using OAuth,162–166
real-world implications of, 164testing OAuth implementation locally,
166–168POST_DATA parameter,
gadgets.io.makeRequest, 96
Poster object, real MySpace requests, 169,172–173
postTo function, 0.7, 210–211
power users, growing base of, 311
Prev button, 36
Preview Template button, Template Editor,84
printPerson function
getting information with os:Viewer-Request tag, 235–236
updating player bio lightbox,236–237
using MySpace user data, 21priorities
defining in OpenSocial, 80defining
opensocial.requestCreateActivity, 79privacy, cookies and, 57
372 persisting information (between sessions)
Cole_Index.qxp 9/23/09 2:31 AM Page 372
Profile page
accessing information using opensocial.Person, 15–17
accessing more than just default data,18–19
accessing user data, permission modelfor, 11
bulletins, 77changing, 275–276comments on, 74creating shared style Content blocks,
231–232customizing button text between
views, 232–235defined, 5, xxiidefining for app, 4defining requestShareApp on, 70–71editing/updating user’s, 75endpoint, 203–204fetching photos uploaded to, 39–41get_profile function, 190–191installing and running app, 7linking to, 7merging with Home page using
shared Content blocks, 230–231not accessing MySpace data on, 10reserved variable names and, 81spicing up surface using
makeRequest, 173–174as supported message type, 75–76
profileDetail property, 19
promoting app. See marketing and monetizing
properties
FriendPicker, 121–123Google App Engine dat store,
158–159makeRequest response object, 97
proto-mashups, 93
Prototype library, paging friend list, 200
proxy servers, makeRequest calls, 94
Publish button, 265–266
publishing app, 265–273
case study in successful rejectionnegotiation, 268–273
contesting rejection, 267–268dealing with rejection, 267overview of, 265–266republishing live app, 275why apps are not approved, 266
pushing work out to nodes, for Internet-scaleapps, 298
Python editor, OAuth settings, 155
RRAM memory, database performance,
296–297
readers-writers problem, solving, 51–53
“real-time” play, P2P games, 146–148
reason parameter, 70–71
recipients parameter, 70, 75
refactoring, to build local app data store,51–56
refresh option, feed, 109–110
REFRESH_INTERVAL parameter,gadgets.io.makeRequest, 96, 109
registerOnLoadHandler directive, feedrefresh, 109
rejection, app
contesting app, 267–268dealing with app, 266examples of, 270–273reasons for app, 266successful negotiation case study,
268–270relational databases, data warehouses vs.,
298
relay files, using IFPC, 209
373relay files, using IFPC
Cole_Index.qxp 9/23/09 2:31 AM Page 373
remote content display tags, OSML, 226
removeGame method, 144–145
repeater, displaying friends list, 237–238
REpresentational State Transfer APIs. SeeREST (REpresentational State Transfer) APIs
republishing live app, 275
requestCreateActivity function. Seeopensocial.requestCreateActivity
requesting data, and performance, 286
requestPermission function, 43–45, 87–88
requestSendMessage function. Seeopensocial.requestSendMessage
requestShareApp function. Seeopensocial.requestShareApp
reserved variable names, 81–82
response structure, adding feed reader toapp, 96–97
ResponseItem object. Seeopensocial.ResponseItem
responseJSON property, error handling whenpaging, 202
responseValues, arrays, 74
responsive performance. See performance,responsive
REST API list, 183–197
create_album function, 195–196get_activities_atom function, 194–195get_album function, 184–185get_albums function, 183get_friends function, 185–187get_friends_activities_atom function,
195get_friendship function, 187–188get_indicators function, 196get_mood function, 187–188get_moods function, 188get_photo function, 190get_photos function, 188–190
get_profile function, 190–191get_status function, 191get_video function, 193get_videos function, 191send_notification function, 196–197set_mood function, 195set_status function, 195test pages, 197
REST (REpresentational State Transfer) APIs,178–208
client code, 197–199friends response from, 211–212friends Web service and paging,
199–203how Web service is addressed,
178–179os:DataRequest tag resulting in
endpoints, 221overview of, 178porting app to OpenSocial 0.9,
343–348Profile endpoint, 203–208server code, 181–183setting up external Iframe app, 179–180supported endpoints. See endpoints,
supported by MySpace SDKsupporting XML and JSON
formats, 94retrieving, friend’s app data, 131–132
RockYou! ads, 314–316
RPC. See IFPC (inter-frame procedure call)
RSS feeds
adding content to feed reader app,97–98
building feed reader UI, 98–101processing with FEED content type,
104–105runOnLoad function, 198–199
374 remote content display tags, OSML
Cole_Index.qxp 9/23/09 2:31 AM Page 374
SSandbox Editor
declaring and using basic data,218–219
entering and executing code, 215–216using os:ViewerRequest tag, 236
Sandbox tool, 214–217, 227–228
Save Template button, Template Editor, 84
scaling
advantages of app data P2P play, 147BuddyPoke app, 320Flixster Movies app, 322using external cloud servers for
storage, 64–65scaling performance
application scale definitions, 293defined, 284Internet-scale app guidelines. See
Internet-scale applications,performance guidelines
scaling point, 294–295
Script tab, Firebug, xxv–xxvi
scripts, 247–248
SDKs (software development kits)
accessing MySpace APIs, 154, 183endpoints supported by MySpace,
183–197secret key, MySpace, 153–154, 183
security
app data store limitations, 153application, 301–302external server communications, 111fixing vulnerabilities, 311hacking and cracking, 302–303user data, 301
selectedFriend property, FriendPicker, 123
selectedOpponentDataCallback function
app data game store, 131–132
recognizing when new game hasstarted, 145
selecting opponent, 138–140semaphore (flag value), readers-writers
problem, 52–53
send( ) function, 17
Send Message, 74–76
send_notification function, 196–197
servers
code for REST API, 181–183Data Pipeline tags processed on,
221–222external. See external server commu-
nications; external serversSet Lots of Cookies option, Cookie Jacker,
63
setBackgroundClicked function, 43–44
set_mood function, 195
set_status function, 195
setTimeout directive, 52–53, 109–110
shared style Content blocks, 231–232
showCurrentPage method, 290–291
showFeedResults function, 103–104
showViewerBio function, 236–237
signatures
function. See function signaturesOAuth, 162–164
simplejson folder, 156–157, 160
Small/workgroup scale applications,293
software development kits (SDKs)
accessing MySpace APIs, 154, 183endpoints supported by MySpace,
183–197sorting, fetched lists, 31–33
source code
backing up before granting developerstatus, 279
creating “Hello World” app, 4–6
375source code
Cole_Index.qxp 9/23/09 2:31 AM Page 375
stability, and responsive performance,299–300
startGamePlayPolling function, 146–147
static content, and constraints, 92
status
get_status function, 191set_status function, 195
storage
app data store. See app data storecookies. See cookiesthird-party database, 64–65
styles
custom tag, 241–242shared style Content blocks,
231–232Subversion, 155
subviews, OSML, 245–248
success array, responseValues, 74
surfaces
adding to gadget file, 229–230creating “Hello World” app, 4–6MySpace Open Social, 5
suspension of app, 280
Ttabs, converting to subviews, 245–248
tag templates. See inline tag templates,OSML
tags
CDATA, 225Data Pipeline, 219–223OSML, 225–226
TCP (transmission control protocol),three-way handshakes, 119
Template Editor, 83–84
templated apps, 270–271
templates
creating activities using, 80–83
creating with Template Editor, 83–84defining requestShareApp using,
70–71inline tag. See inline tag templates,
OSMLnotification built-in, 89using opensocial.requestShareApp,
85–86Terms of Use
app suspension from violating, 280example of app rejection, 270–273overview of, 266
test pages, REST APIs, 197
testing
managing testers, 279message bundles, 257OAuth implementation locally,
166–169OpenSocial endpoint errors, 300translations, 259–260
TEXT content type, feed readers, 107–108
TEXT format, partial HTML content, 97
third-party database storage, 64–65
threads, solving readers-writers problem,51–53
three-way handshakes, 119, 144
Tic-Tac-Toe app. See data, getting basic
time-outs, providing, 300
title, message, 75
TK’s apps, 322–324
tools, MySpace development, xxiv–xxvi
TOP_FRIENDS, filtering friend list, 33
TortoiseSVN, 155
transferring data, three-way handshake, 119
translations
creating first message bundle for,256–257
including and testing, 258–260internationalization and, 255
376 stability, and responsive performance
Cole_Index.qxp 9/23/09 2:31 AM Page 376
translations, contd.
message bundle, 257–258testing, 259–260
transmission control protocol (TCP),three-way handshakes, 119
Try App link, 307–308
TTT namespace
defined, 30paging, 37using data, 37–39
TTT.AppDataPlay game object
adding support in game engine,133–135
adding user feedback, 135–138clearing game, 144–145implementing logic flow, 138–144setting up, 125–133
TTT.Game (game engine), 133–135
TTT.Record.Getter object, 169–172
TTT.Record.Poster object, 169, 172–173
turn-based gaming, 117–133
adding FriendPicker, 119–121app data game store, 125–133design overview, 118–119overview of, 117–118using FriendPicker, 121–125
UUI (user interface)
adding FriendPicker to game play,119–121
building feed reader, 98–101building using Inspect feature of
Firebug, xxvusing FriendPicker, 121–125
UNAUTHORIZED error, cause of, 26
Unicode encoding, and app gadgets, 258
uninstalling apps, 279–280
universal resource identifiers (URIs), REST,178–179
Updates module, Home page, 68–69
updating
albums and media items inOpenSocial 0.9, 338–339
app data in Open Social 0.8 and 0.9,341–343
translations, 260uploading media items, 340–341
URIs (universal resource identifiers), REST,178–179
URLs
making real MySpace requests,170–173
warning when placing in attributes, 251user data
accessing, 11–14accessing more than just default
Profile data, 18–19accessing Profile information, 15–17using, 19–24
user interface. See UI (user interface)
users
adding feedback to P2P game play,135–138
data security for, 301experience/functionality of app,
271–272, 285implementing logic for selecting
opponent, 140retaining by listening to them, 311viral spreading and. See viral
spreading“user’s pick” feed reader, 98
UTF-8 encoding, for app gadgets, 259
utility computing, 298–299
377utility computing
Cole_Index.qxp 9/23/09 2:31 AM Page 377
Vvalidating inputs, 299
variables, setting up AppDataPlay game,127–128
variables, template
creating templates with TemplateEditor, 84
data types, 80–81notifications, 89reserved names, 81using opensocial.requestShareApp,
86verify function, OAuth, 157
verify_request function, OAuth, 165–166
vertical scaling, 297–298
videos
fetching, 42–43fetching with get_video function, 193fetching with get_videos function,
192–193View Development Version link, “Hello
World” app, 6
Viewer, 236–237
accessing more than just defaultProfile data, 18–19
accessing Profile information, 15–17app data store. See app data storeconcept of, 9–10creating custom tag template
definition for, 240–242declaring data in gadget XML for,
218–219fetching app data for, 342fetching friend list for, 30–31getting information with
os:ViewerRequest tag, 235–236os:ViewerRequest tag, 221–222permission model for accessing user
data, 10–11
viral features and communication,67–90
getting app listed on friend updates,79–88
sending messages and communications, 74–79
sending notifications, 88–90spreading app to other users, 67–74
viral spreading, 309–316
of BuddyPoke app, 319–320Cubics, 313–314Google AdSense, 311–313listening to customers, 311overview of, 309–311Playdom apps using, 325–326RockYou! ads, 314–316
Visit Profile link, 7
WW3C Widgets specification, 260
Watch window, Script tab of Firebug,xxv–xxvi
Web applications, driving performanceplateau, 284
Web references. See online references
Web service, 202–203
Westwood, Dave, 318–319
widget formats, commonly known, 260
Widgets specification, W3C, 260
win/loss record
making MySpace requests,169–173
making simple GET request to save,158–162
testing OAuth locally, 166–169updating with signed POST request,
162–166Windows Sidebar gadget format, 260
Winloss class, 158–162, 164–166
378 validating inputs
Cole_Index.qxp 9/23/09 2:31 AM Page 378
“Word of the Day”, feed reader apps,110–111
ws.py script, 158, 164–166
XXHR (XMLHtppRequest) object
asynchronous JavaScript requests, 15external server security constraints
for, 91makeRequest as wrapper on top of,
94–95overview of, 94
refactoring to build local app datastore, 51–52
XML. See also gadget XML
adding feed reader to app, 98content type with parsing,
105–107handling content for feed reader, 98
XSS (cross-site scripting) attacks, 303
YYahoo! Babelfish, 258
Yue, Dan, 324–326
379Yue, Dan
Cole_Index.qxp 9/23/09 2:31 AM Page 379