This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Building OpenSocial Apps A Field Guide to Working with the MySpace Platform Chris Cole Chad Russell Jessica Whyte
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are 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 initial capital letters or in all capitals.
Editor-in-Chief Mark L. Taub
The screenshots and other depictions of myspace.com contained in this book may not accurately represent myspace.com as it exists today or in the future, including without limitation with respect to any policies, technical specs or product design.
Development Editor Songlin Qiu
The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
Managing Editor John Fuller
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 covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 [email protected]
Full-Service Production Manager Julie B. Nahil Project Management diacriTech LLC Copy Editor Barbara Wood Indexer Jack Lewis
For sales outside the United States, please contact: International Sales [email protected]
Technical Reviewers Cassie Doll Bess Ho Benjamin Schupak Book Designer Gary Adair Compositor diacriTech LLC
❖
This book is dedicated to my ever-suffering wife, Kristen, and our two crazy and wonderful children, Darien and Reece.Thanks for working overtime with the kids, baby. —Chris Cole To the reader, we hope this book serves you well. —Chad Russell and Jessica Whyte ❖
Contents at a Glance Contents
viii
Foreword
xvi
Acknowledgments
xviii
About the Authors
xix
Introduction
xxi
I: Building Your First MySpace Application 1 Your First MySpace App
3
2 Getting Basic MySpace Data
9
3 Getting Additional MySpace Data 4 Persisting Information
29
47
5 Communication and Viral Features
67
6 Mashups and External Server Communications 91 7 Flushing and Fleshing: Expanding Your
App and Person-to-Person Game Play
117
II: Other Ways to Build Apps 8 OAuth and Phoning Home 9 External Iframe Apps
153
177
10 OSML, Gadgets, and the Data Pipeline
213
11 Advanced OSML: Templates, Internationalization, and View Navigation 239
III: Growth and How to Deal with It 12 App Life Cycle
265
13 Performance, Scaling, and Security
283
Contents at a Glance
14 Marketing and Monetizing
305
15 Porting Your App to OpenSocial 0.9
References Index
355
351
329
vii
Contents Foreword xvi Acknowledgments About the Authors Introduction xxi
xviii xix
I: Building Your First MySpace Application 1 Your First MySpace App
3
Creating the App—“Hello World”
3
Step 1: Sign Up for a Developer Account Step 2: Create an App
Step 3: Enter Your Source Code Installing and Running Your App Summary
3
4 4
7
7
2 Getting Basic MySpace Data
9
The Two Concepts That Every Developer Should Know 9 Basic Concepts: Owner and Viewer
9
Basic Concepts: Permissions for Accessing MySpace Data 10 Starting Our Tic-Tac-Toe App
10
Accessing MySpace User Data
11
Accessing Profile Information Using the opensocial.Person Object 15 Getting More than Just the Default Profile Data
18
opensocial.DataResponse and opensocial. ResponseItem (aka, Using MySpace User Data)
19
Error Handling Summary
24
27
3 Getting Additional MySpace Data
29
How to Fetch a Friend List and Make Use of the Data 29 Getting the Friend List Filters and Sorts
31
30
Contents
Paging
32
Using the Data Fetching Media Photos
37
39
39
Albums and Videos
41
Using opensocial.requestPermission and opensocial.hasPermission to Check a User’s Permission Settings 43 Summary
45
4 Persisting Information App Data Store
47
47
Saving and Retrieving Data
48
Refactoring to Build a Local App Data Store Cookies
56
Why You Shouldn’t Use Cookies
57
Building the Cookie Jacker App Third-Party Database Storage Summary
51
59
64
65
5 Communication and Viral Features
67
Using opensocial.requestShareApp to Spread Your App to Other Users 67 Defining requestShareApp
70
Writing the requestShareApp Code Calling requestShareApp
71
72
The requestShareApp Callback
72
Using opensocial.requestSendMessage to Send Messages and Communications 74 Defining requestSendMessage
75
Writing the requestSendMessage Code Callback in requestSendMessage
76
78
Getting Your App Listed on the Friend Updates with opensocial.requestCreateActivity Basics 79 Defining opensocial.requestCreateActivity
79
Using the Template System to Create Activities Data Types
80
Reserved Variable Names Aggregation
82
81
80
ix
x
Contents
Body and Media Items
82
Using the Template Editor to Create Templates Using opensocial.requestCreateActivity Sending Notifications Summary
88
90
6 Mashups and External Server Communications Communicating with External Servers Mashups
91
92
Adding a Feed Reader to Our App
93
Overview of gadgets.io.makeRequest Response Structure
94
96
Handling JSON Content
97
Handling Partial HTML Content Handling RSS Feed Content Handling XML Content
97
97
98
“User’s Pick” Feed Reader
98
Setup and Design of the Feed Reader FEED Content Type
98
104
XML Content Type with Parsing TEXT Content Type
105
107
Adding a Feed Refresh Option Feed Automation Candy
109
110
Secure Communication with Signed makeRequest 111 Adding an Image Search Overview of JSONP
112 112
Implementing the Image Search Posting Data with a Form Summary
83
85
113
114
114
7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play 117 Turn-Based Games Design Overview
117 118
Adding FriendPicker App Data Game Store
119 125
Supporting Person-to-Person Game Play
133
91
Contents
Adding P2P Game Play Support in the Game Engine 133 Adding User Feedback
135
Fleshing Out P2P Game Logic
138
Finishing and Clearing a Game “Real-Time” Play
144
146
Advantages and Disadvantages of App Data P2P Play 148 Summary
148
II: Other Ways to Build Apps 8 OAuth and Phoning Home What Is OAuth?
153
153
OAuth Libraries
154
Setting Up Your Environment When Is OAuth Not OAuth? Secure Phone Home
154 157
157
Unsigned GET Request Signed POST Request
158 162
Testing Your OAuth Implementation Locally Making Real MySpace Requests
166
169
Spicing Up the Home and Profile Surfaces Using makeRequest 173 Summary
174
9 External Iframe Apps REST APIs
177
178
How a REST Web Service Is Addressed Setting Up an External Iframe App The Server Code REST API List The Client Code
181
183 197
Friends Web Service and Paging The Profile Endpoint
199
203
Sending Messages Using IFPC
208
Using the 0.7 Container for postTo
210
The Friends Response from the REST API Summary
212
178
179
211
xi
xii
Contents
10 OSML, Gadgets, and the Data Pipeline The Big Picture
213
Gadget XML
214
Data Pipeline OSML
213
214
214
Writing a Gadget
214
“Hello World” Gadget
214
Adding a Second Surface to the Gadget Declaring and Using Basic Data Data Pipelining
219
DataContext
220
Data Tags
217
218
220
In-Network versus Out-of-Network Data
221
Data Tags os:ViewerRequest and os:OwnerRequest 222 Data Tag os:PeopleRequest
222
Data Tag os:ActivitiesRequest Data Tag os:DataRequest
223
223
JavaScript Blocks in OSML Apps
225
OpenSocial Markup Language (OSML) Basic Display Tags
Remote Content Display Tags Control Flow Tags
226
226
Putting It Together: OSML Tic-Tac-Toe Setting Up the Gadget
230
235
Displaying Data Lists Summary
226
227
Reusing Common Content Working with Data
225
226
237
238
11 Advanced OSML: Templates, Internationalization, and View Navigation 239 Inline Tag Templates
239
Defining and Using a Tag Template Using Client-Side Templates Working with Subviews
242
245
Converting Tabs to Subviews
245
240
Contents
HTML Fragment Rendering
248
Adding Content with os:Get
248
Adding Targeted Content with myspace:RenderRequest 249 Data Listeners
250
Displaying JSON Results with a Data Listener Internationalization and Message Bundles Creating Our First Message Bundle
256
Creating Translations of the Message Bundle Including Translations in an App and Testing Future Directions Summary
260
261
III: Growth and How to Deal with It 12 App Life Cycle
265
Publishing Your App
265
What’s Allowed, or Why So Many Apps Get Rejected 266 Dealing with Rejection
267
Contesting a Rejection
267
Managing Your App
274
Hiding and Deleting an App
274
Making Changes to a Live App (Multiple Versions) 274 Republishing a Live App
275
Changing the App Profile/Landing Page Managing Developers Managing Testers
275
279 279
Event Handling—Installs and Uninstalls Suspension and Deletion of Your App Summary
279
280
281
13 Performance, Scaling, and Security Performance and Responsiveness
283
283
What Is Responsive Performance and What Is Scale Performance? 283 Design for Responsiveness
284
251
255 257 258
xiii
xiv
Contents
Responsive OpenSocial App Performance Guidelines 285 Design for Scale
292
App Guidelines for Internet-Scale Performance Stability and Fault Tolerance Rule 1: Validate Inputs
299 299
Rule 2: Test OpenSocial DataResponse Objects for Errors 300 Rule 3: Provide Time-Outs and Error Flow
300
Rule 4: Don’t Assume That Weird Error Was an Anomaly 300 User and Application Security User Data Security
301
Application Security
301
Hacking and Cracking Summary
300
302
303
14 Marketing and Monetizing
305
Using MySpace to Promote Your App The App Gallery
306
306
App Profile, or Bringing Out the Bling MySpace’s Own MyAds
308
User Base and Viral Spreading Listen to Your Customers Ads
308
309 311
311
Google AdSense Cubics
RockYou! Ads Micropayments PayPal Boku Others
311
313 314 316
316 317 318
Interviews with Successful App Developers Dave Westwood: BuddyPoke (www.myspace.com/buddypoke) Eugene Park: Flixster (www.myspace.com/flixstermovies)
318 321
318
293
Contents
Tom Kincaid: TK’s Apps (www.myspace.com/tomsapps) Dan Yue: Playdom (www.myspace.com/playdom) Summary
322 324
326
15 Porting Your App to OpenSocial 0.9 Media Item Support opensocial.Album Fetching Albums
330 333
Fetching Media Items
335
Updating Albums and Media Items Uploading Media Items
340
Simplification of App Data
341
REST APIs Summary
343 348
References Index
355
351
329
330
338
xv
Foreword The Internet is constantly evolving, with vast arrays of information on every topic growing at a remarkable pace. Google’s 1998 search index had only 26 million Web pages; a decade later it recognizes more than 1 trillion URLs.With so much information, we need a new set of tools to make sense of the Internet.The transition is from a strict focus on informational content, to being able to take advantage of our context, our relationships, and our activities. Enter the social Web, a relatively new twist to the Internet, which is being built up by social networks, portals, and even more traditional businesses.The “Open Stack” is a set of specifications being developed by grass-roots communities all over the world, enabling developers to create new products and services enhanced by user-specific data.The Open Stack includes specifications such as OAuth, which provides secure access to data; OpenID, a global identity standard; and OpenSocial, a common API for building applications.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 can be applied to all “OpenSocial containers,” those sites that support the OpenSocial specification.With standards-based tools, including a JavaScript-based gadget API, a REST-based data access API, lightweight storage capabilities, and access to common viral channels, developers can build inside those containers as well as create applications for 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. In aggregate, these sites provide developers with access to more than 750 million users all over the world. By taking advantage of the OpenSocial API and the information available in this book, you will have a great opportunity to reach a lot of users. For example, you’ll find 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 more productivity-oriented sites like LinkedIn and by Fortune 100 companies as diverse as IBM 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.The in-depth programming examples provide a good introduction to the design options available when building with the OpenSocial API, and the code is open source for ease of use and future reference. Additionally, the MySpace Platform tips sprinkled throughout will help you avoid common mistakes and understand the intricacies of their platform policies. Getting a feel for how social platforms operate will be valuable as you continue to explore the wide world of OpenSocial. OpenSocial is constantly evolving, just like the rest of the Internet.The OpenSocial specification is managed through an open process where anyone can contribute their ideas to influence the next version of the specification and help move the social Web forward.
Since its creation, there have been several significant revisions to the specification, introducing some new programming methodologies and improvements that make it easier for 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 to improve the specification. It’s open. It’s social. It’s up to you. —Dan Peterson, president, OpenSocial Foundation San Francisco, California August 2009
Acknowledgments Chris Cole: I’d like to acknowledge the great team at MySpace that helped build the developer platform and all the people who’ve contributed to refining the OpenSocial specification. Compromise is hard, but a bad spec would have been even harder. Chad Russell: Thank you to Dan Peterson, for being a resource and agreeing to write our Foreword. And, of course, a big thanks to our technical editors, Bess Ho, Cassie Doll, and Ben Schupak, who all found a number of issues that would otherwise slipped through the cracks. Jessica Whyte: Thank you to Trina MacDonald and Olivia Basegio at Addison-Wesley for your support. I’d also like to acknowledge Tom Kincaid, Eugene Park, Dave Westwood, Dan Yue, Jon Nguyen, and Katie Simpkins for taking the time to answer all of my (many) questions about the platform.
About the Authors Chris Cole is a software architect at MySpace and is a major contributor to building the MySpace Open Platform and keeping it committed to OpenSocial. He’s been a core contributor to the OpenSocial 0.9 specification and is the primary architect and implementer of OSML (OpenSocial Markup Language) on the MySpace platform. Chris has been in software for fifteen years and has spent much of that time riding the various waves of the Internet and pushing the boundaries of the Web. Chad Russell is the lead developer on the MySpace OpenSocial team. He knows the OpenSocial spec front to back, in addition to every tip, trick, and nuance of the MySpace platform itself. Chad holds an engineering degree from the University of Toronto and currently resides in Seattle,Washington. Jessica Whyte has worked for several years as a journalist, most recently with Journalists for Human Rights, and is currently a graduate student at the University of Washington, studying Human-Centered Design and Engineering. She lives in Seattle with her husband and coauthor, Chad Russell.
This page intentionally left blank
Introduction Welcome to the wonderful world of social apps.You are about to enter—or have already entered—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 around for only a few years, after all. Many successful apps have yet to be created and then discovered by the millions upon millions of passionate MySpace users. In this book we’ll start from scratch and walk you through the entire process of building apps, from signing up as a developer all the way to building highly complex social apps that can scale out to thousands of users.We have extensive experience on the MySpace Development Platform (MDP), from building apps to helping build the platform itself.We’ll point out the many idiosyncrasies and quirks of the platform, as well as the many ways to squeeze out a little better performance by making a few tweaks to your existing apps. Throughout this book we’ll demonstrate best practices and show lots of sample code 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 and photos, and parse all the data that comes back to display it on the screen. We’ll send app invitations and notifications to help spark viral growth and send requests back to Web 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 developing apps using ads and micropayments. When it comes to developing social apps on the MySpace platform, the sky is the limit. As of this writing, the most popular app on MySpace has more than 13 million installs. Maybe your app will be the next big thing. All it takes is a good idea and a little bit 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 and to those developers who have only heard about it on the news.To that end, if you’re standing in the technology section of your local bookstore reading this, and you have a bit 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 and OpenSocial. For those who already have apps up and running out in the wild, this book is also for you, as we’ll dig pretty deeply into the platform a little later on.You may be familiar with the ideas and terms we introduce here, so feel free to skip ahead a bit. (Check out the section on tools, though!)
xxii
Introduction
How to Read This Book There 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, where you can consult the various tables, sample code, and tips. Or, if you need to learn a new aspect 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 each subsequent chapter. By the time the app is completed, you’ll have a broad knowledge base of the entire platform.We then branch out into some advanced topics to take you a step further.
Assumptions Made by the Authors This is not a book about how to code in JavaScript or Python or any other language.We will try to follow good practice in our sample code throughout the book, and we’ll point out a few interesting tidbits along the way, but that’s all.This is a book on how to write OpenSocial apps on MySpace. To that end, we assume the following: n
n
You have basic knowledge of computer programming in general. Maybe you work at a software company and write PHP every day, or you’ve taken a few programming classes, or you’ve taught yourself by constructing your own Web page. You have basic knowledge of JavaScript or are willing to pick up the basics.We’re not talking advanced stuff here, just the basics like calling functions, giving values to 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 the planet, 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”; the Profile page is a Web page that others can view and you can edit. On your Profile you can add information about yourself, pick a display name, and upload a picture. Others who 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 the like, 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 sign up and are assigned a single solitary friend:Tom, one of the cofounders of MySpace.
Introduction
Figure I.1
A MySpace Home page.
Through various means, such as searching, browsing, or having a robot guess “People You May Know,” you can find new friends and add them to your list. Having other users as friends grants you certain privileges to their information. You may have access to their Profiles even if they’re set to “Private”; you see their updates on your feed; and, most important 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 on their sites.That means many things. For example, OpenSocial defines what information a Web site can and must expose for each of its users. It defines a client-side JavaScript runtime environment with a set of APIs that describe how to fetch and update that user data.This environment is commonly called an “OpenSocial container.” Likewise, it defines a set of server-side APIs that manipulate the same data but can be called from a server running your language of choice, such as PHP. It also defines a markup language called 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 to the OpenSocial Foundation and the community.That means any implementers, such as MySpace, Orkut, and LinkedIn, app developers, or really anyone at all can suggest modifications to the spec and participate in setting the direction.Those modifications are then voted on in a public forum and either brought into the spec (found at http:// opensocial.org) or rejected.
xxiii
xxiv
Introduction
Any site on the Web is free to implement the OpenSocial spec.The idea is that when a site becomes OpenSocial-compliant, it is able to run almost any of the thousands of apps already created using OpenSocial. If a site has correctly implemented all the various APIs, an app running on MySpace should run just as well anywhere else.That’s the theory, anyway. In practice there are differences, some small, some large, between the various OpenSocial implementers, which can make it tricky to maintain an app on multiple 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 that covers how to sign up as a developer, how to update your app, and how to actually run your app. MySpace tries its best (we really do) to fully implement the OpenSocial spec, but there are bound to be some inconsistencies. Most of these inconsistencies are small, but we’ll cover them as they come up throughout this book. MySpace has also implemented some 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 MySpace platform gives you access to a huge number of users and potential customers. As of this writing, MySpace has more than 130 million monthly active users and is growing every day. Forty-five million of those users have installed apps.To give you an idea of the demographics, 53% of app users are female, with an average age of 18 to 24.That is a very 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 spent debugging why that callback wasn’t being fired or where that stupid 401 unauthorized error was coming from, we’ve found some really useful tools that will make your life easier. Let’s repeat that for effect:These tools will make your life easier.
Browsers First, a quick note on browsers. Install Firefox right now. Go to www.firefox.com. In our opinion it’s best to develop on Firefox, get your app running the way you like it, then worry about running it in Internet Explorer (IE) as well. Developing on the Web is still an “IE and everyone else” process. You get an app working in Firefox, and that means it will probably work just fine in Safari, Chrome, and Opera.Then you can bang your head for a few hours (days?) fighting floating divs and onclick handlers in IE.
Firebug Firebug is the main reason Firefox is the Web developer’s browser of choice. Firebug is an incredible tool for all Web developers, and every single one of us should install this
Introduction
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 are a few that we use every single day. To follow along at home, install the Firebug extension, 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. Inspect The 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 and hover your cursor over a Web page. You’ll see that the various HTML elements become highlighted. Clicking on one will show you the HTML markup of that element in the left pane and its current style in the right pane. You can then add a style or modify the existing style on the fly. This is very useful for building up user interface (UI) elements quickly. Instead of making a change, saving a file, uploading it, and reloading the page in a browser, you can just edit the style very quickly and try different values.When you find what works in Firebug, you can make one edit to your page and it should be good to go. Console The Console tab shows you a couple of useful things. The first useful bit of information is that any and all JavaScript errors are displayed here, with a description of the error along with its file name and line number. The second is that any outgoing Web service requests are shown here. You’ll be able to view the exact outgoing URL, any parameters and headers sent along, and the response from the server. As most MySpace requests are sent as outgoing Web service requests, this is an invaluable debugging tool. You’ll be able to see if the correct parameters were appended to the request, and you won’t have to output the response onto a div on the UI to see if you got the correct response or some sort of error. Script The Script tab is your debugger. You can load any HTML or JavaScript file into the left pane by selecting the file in the drop-down above that pane. You can then set breakpoints at any line with a green line number. In the right pane you can set watches on variables, view the current stack, and manipulate the breakpoints you’ve set. With the Watch window you can interrogate any object by simply typing the variable name into the New Watch Expression bar. Doing so displays the object’s current state and value. But you can also directly manipulate objects. Say you wanted to see what would happen if a Boolean variable were true instead of false; you can set that directly 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 line and inspect the objects and variables that are causing the issue. Need to figure out exactly what the response looks like from a request to the MySpace servers? Set a
xxv
xxvi
Introduction
Figure I.2
Interrogating the response from MySpace’s servers using Firebug.
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 in general, but we can’t discuss them all here.We hope we’ve sold you on its usefulness and that you’ll discover the many great features it has to offer.
Fiddler Fiddler 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 as opposed to the JavaScript APIs.We’ll discuss what that means later on in the book, but keep this tool in mind when you get there.To give you a little bit of a preview, you’ll be sending requests for data to MySpace, and those requests need to be sent using an authentication scheme. Using the authentication scheme is tricky, but Fiddler will help you see exactly what you’re sending to MySpace and exactly what MySpace is sending back to you. Get it here: www.fiddler2.com. One other thing to note is that Fiddler works natively in Internet Explorer but not Firefox. If you do a little bit of Googling, you can get it up and running in both browsers.
I Building Your First MySpace Application
1
Your First MySpace App
2
Getting Basic MySpace Data
3
Getting Additional MySpace Data
4
Persisting Information
5
Communication and Viral Features
6
Mashups and External Server Communications
7
Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
This page intentionally left blank
1 Your First MySpace App Tarehiscommonly book is primarily a guide to writing OpenSocial applications (or “apps” as they known and as we’ll refer to them throughout this book), but with a focus on the MySpace platform. This first chapter is designed to give you an overview of what to expect from developing with OpenSocial for MySpace.To do that, we’ll start with a “Hello World” app, something simple to introduce you to MySpace and OpenSocial. As we make our way through Chapter 1, we’ll refer to any other chapters that may delve deeper into a particular topic. Feel free to skip to the more detailed chapters if something is not clear. Now, let’s get started.
Creating the App—“Hello World” No programming book is complete without the requisite “Hello World” program. And who are we to flout tradition? We’ll create our version of “Hello World” with the small addition of personalizing it for the current MySpace user—also known as the “Viewer” in OpenSocial parlance. In a few easy steps we’ll sign up for a developer account and build our first app.
Step 1: Sign Up for a Developer Account Before you can do anything, you’ll need a basic MySpace user account. Once you have that, the next step is to sign yourself up as a developer. MySpace recently changed this procedure from a manual approval process that could take a few days to a self-serve one.You simply need to have a valid e-mail account associated with your MySpace account. 1. Log on and go to the MySpace developer site at http://developer.myspace.com. 2. Click the MyApps link.This sends you to the Signup page. 3. Fill out the form and accept the terms of service. Click Next.
4
Chapter 1 Your First MySpace App
4. Solve the “CAPTCHA” puzzle and click Finish.This sends a confirmation message to your e-mail account. 5. When you get the verification e-mail, click the embedded link.You must be currently signed in to MySpace under the user account requesting developer status for the verification to be successful.
Step 2: Create an App Before you can create a “Hello World” app, you must first create your app record.This defines the app Profile, a contact e-mail address, and some meta-information about your app. Here’s how to do it: 1. Log on and go to the MySpace developer site at http://developer.myspace.com. 2. Click the MyApps link. 3. Click the Create New App button. 4. Click the Create On-Site App button. A general information form will appear. 5. Fill in the form with some values for your sample app: Application Title: Hello World E-mail: [email protected] Password: <something_you_will_remember> Terms: The e-mail address used for each app must be unique—a sometimes frustrating requirement that’s covered in more detail in Chapter 12, App Life Cycle. 6. Solve the nigh-impossible word puzzle by entering the correct “CAPTCHA” letters. 7. On the Upload Application XML screen, click Skip This Step since we’ll be doing a simple, direct edit of the app’s details. 8. Complete the form on the next screen.You must set values for all the required fields, but it’s not critical what the values are. Application Description: “Hello World” app Primary Category: 9. Click Save. 10. Click the Edit App Source tab. You are now ready to write code. Go to the next section and collect $200.
Step 3: Enter Your Source Code The first thing we need to do is pick a “surface” on which to build our app. Canvas is typically the easiest surface to work with, so we’ll use that. There are two basic formats for entering app source code: as gadget XML or in one of the surface source editors. Since this is just an introduction, we’re sticking with the
Creating the App—“Hello World”
What are Surfaces? Surfaces—sometimes also referred to as “views”—are a notion OpenSocial inherits from the Google Gadgets spec. A surface denotes a drawing surface on which an app can live. Currently there are three surfaces for MySpace OpenSocial apps: Home: The user’s private Home portal page. This is what is displayed to the user when he or she first logs in to MySpace. In the future, you may want to use this space to show vital app stats, news, or specific user details. Profile: The user’s public Profile page. This is what is displayed on the user’s public page, meaning it’s visible to the world. This surface is a great way to promote and advertise your app. See Chapter 14, Marketing and Monetizing, for more information on this topic. Canvas: A full page usable by the app. This is typically where the user plays and interacts with the app.
surface source editor. Authoring your app as gadget XML brings you a little more power but a lot more complexity. Now, let’s enter the following “Hello World” code and run it:
OpenSocial Hello World
<script type = "text/javascript"> var viewer = null; /** * Initial data request to load Viewer */ function getViewerData(){ var req = opensocial.newDataRequest(); req.add(req.newFetchPersonRequest( opensocial.IdSpec.PersonId.VIEWER), "viewer"); req.send(getDataCallback); } /** * Callback handler to process the response * @param {Object} data */ function getDataCallback(data){ if (data.hadError()) { var err = "Processing Error: " + data.get("viewer").getErrorMessage(); writeMessage(err + " You should install the app"); return; }
5
6
Chapter 1 Your First MySpace App
viewer = data.get("viewer").getData(); if(viewer){ writeMessage("Hello, " + viewer.getDisplayName()); } else{ writeMessage("Wow, you don't exist"); } } /** * Convenience method to write our message to the page * @param {Object} msg */ function writeMessage(msg){ var elem = document.getElementById("message"); elem.innerHTML = msg; } //Register to look for initial data gadgets.util.registerOnLoadHandler(getViewerData);
Once you’ve entered the code, click Save Application Source and you’ll notice a View Development Version link. Click this now. It will open a new window running the app. Any predictions on what you’ll see? Processing Error: Permission denied to all viewer resources. You should install the app. Chances are your prediction was wrong. Privacy is of the utmost concern at MySpace, so only apps that you have installed may see your data.We’ll get more into privacy in Chapter 3, Getting Additional MySpace Data.To make matters even more confusing for you as a developer, it may actually work and show your display name.This happens when a feature called Open Canvas is enabled.This feature has been on and off about ten different times over a year-long period. Just be ready to open up Firebug, a browser debugging tool identified in the book’s Introduction. To solve this permission problem, let’s install the app for your current developer account.
Summary
Installing and Running Your App You must first install your app before you can truly interact with it. From the developer site this is fairly easy: 1. On the MySpace developer site (http://developer.myspace.com) click the MyApps link. 2. Find your target app in the list. Click the Edit Details link for your app. 3. In the upper right corner you will see a Visit Profile link. Click this link to go to the app’s Profile page. 4. Click the Add This App button. Select the Add button in the lightbox dialog. You will then continue to the app’s Canvas page. Now, see the magic. Hello, John Doe The app is running and should now display your publicly visible name (not your full name). Welcome to the brave new world of social applications.You are now one of the elite who will be defining what’s shaping up to be a billion-dollar industry over the next decade.
Summary In this chapter we hit the ground running and covered a lot of it.You may not realize it yet, but we touched on asynchronous network processing, user privacy, app error handling, app life-cycle management, and some of the Byzantine ins and outs of the MySpace Developer Platform.That’s a lot of work to get to “Hello World.” If you’re sweating a little bit, don’t worry. We’ll guide you through this thing in a way that makes sense and helps you start making more apps, and sooner than you thought possible. If you find yourself saying, “What’s this simplistic stuff?” don’t worry either. While this book is designed to build a single app in increasing steps of complexity, it’s also laid out in such a way that you can skip over sections that are not of interest and still get useful, focused information from the chapters that are of interest. Note Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
7
This page intentionally left blank
2 Getting Basic MySpace Data Ithenn thisexpand chapter we’ll start with a very basic version of the Tic-Tac-Toe application and 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. On the way, we’ll cover how MySpace and OpenSocial define an opensocial.Person object 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 example app, and over the course of the book we’ll take you from a basic game to a fully functional and feature-rich application. At each step along the way we’ll teach you new methods and programming tricks for accessing and using the OpenSocial API. Code examples will be shown in full and then broken down into segments for further explanation, allowing you to zero in on a specific feature or trouble spot.
The Two Concepts That Every Developer Should Know Before we begin, there are two basic concepts that every MySpace and OpenSocial app developer should know about: n n
In the world of MySpace apps, everyone is either an Owner or a Viewer. 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 Viewer The 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
10
Chapter 2 Getting Basic MySpace Data
Once you start accessing MySpace data, all the requests you make are made in the context of the Owner and the Viewer. For example, let’s say John has the app installed and Jane is viewing John’s MySpace Profile. John is the Owner and Jane is the Viewer. Alternatively, if John is looking at the app 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 or the Viewer.
Basic Concepts: Permissions for Accessing MySpace Data Not all user data is accessible to apps, and the data that is accessible is subject to a sometimes convoluted permission model. The key idea behind the MySpace permission model (dubbed Open Canvas) is that under certain circumstances an app can access a user’s data even if that user hasn’t installed the app. However, this access can 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 determine whether 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 access to the Viewer’s data. Figure 2.1 is a quick reference chart for Open Canvas; remember, though, that these permissions can change. So stay on your toes and watch out for permission traps when accessing user data.
Starting Our Tic-Tac-Toe App The first thing we need to do is to get the basic Tic-Tac-Toe app started. Since this app is just scaffolding on which to hang OpenSocial concepts, we’re going to gloss over a lot of the details. At this initial level our app could just as easily be a JavaScript game embedded in a Web page. It is the OpenSocial code that we will add later that will make the game come alive. Note Before we start, you should have the basic version of Tic-Tac-Toe installed as an app on your MySpace developer account. You will find the code on our Google Code page at http://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 handler to record player moves. Underneath the surface is a state-of-the-art computer AI (i.e., random-move engine) to play against.
Accessing MySpace User Data
Viewer has added the app
Viewer hasn’t added the app
Viewer is logged out
Viewer has blocked the app
Basic Owner data* (Home)
Yes
Yes
Yes
Yes
Basic Owner data* (Profile)
Yes
Yes
Yes
Yes
Basic Owner data* (Canvas)
Yes
Yes
Yes
Yes
Basic Viewer data* (Home)
Yes
No
No
No
Basic Viewer data* (Profile)
Yes
No
No
No
Basic Viewer data* (Canvas)
Yes
Yes
No
No
Owner’s friend list
Yes
Yes
Yes
Yes
Viewer’s friend list
Yes
No
No
No
Owner’s public media**
Yes
Yes
Yes
Yes
Viewer’s public media**
Yes
No
No
No
*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.
The remainder of this chapter will introduce some basic concepts that are central to 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 Profile image.
Accessing MySpace User Data MySpace 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 supported person fields along with their return types.
11
12
Chapter 2 Getting Basic MySpace Data
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 the Creative 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. Field.ABOUT_ME
A general statement about the person
String
opensocial.Person. Field.AGE
Person’s age
Number
opensocial.Person.Field. BODY_TYPE
An object containing the person’s body type; MySpace returns only opensocial.
opensocial. BodyType
BodyType.Field.BUILD
and opensocial. BodyType.Field.HEIGHT opensocial.Person.Field. BOOKS**
Person’s favorite books
Array of strings
opensocial.Person.Field. CHILDREN
Description of the person’s children
String
opensocial.Person.Field. CURRENT_LOCATION
Person’s current location; MySpace returns only
opensocial. Address
opensocial.Address. Field.REGION, opensocial. Address.Field.COUNTRY, and opensocial.Address. Field.POSTAL_CODE opensocial.Person.Field. DATE_OF_BIRTH
Person’s date of birth
Date
opensocial.Person.Field. DRINKER
Person’s drinking status (with the enum’s key referencing
opensocial. Enum
opensocial.Enum.Drinker)
Accessing MySpace User Data
Table 2.2
Continued
MySpace-Supported Person Field
Description
Return Type
opensocial.Person.Field. ETHNICITY
Person’s ethnicity
String
opensocial.Person.Field. GENDER
Person’s gender (with the enum’s key referencing opensocial. Enum.Gender)
opensocial. Enum
opensocial.Person.Field. HAS_APP
Whether or not the person has added the app
Boolean
opensocial.Person.Field. HEROES**
Person’s favorite heroes
Array of strings
opensocial.Person.Field.ID
MySpace user ID
String
opensocial.Person.Field. INTERESTS**
Person’s interests, hobbies, or passions
Array of strings
opensocial.Person.Field. JOBS
Jobs the person has held; MySpace returns only
Array of
opensocial.Organization. Field.NAME and opensocial. Organization.Field.TITLE
opensocial. Organization
opensocial.Person.Field. LOOKING_FOR
Person’s statement about whom or what he or she is looking for or what he or she is interested in meeting people for
opensocial. Enum
opensocial.Person.Field. MOVIES**
Person’s favorite movies
Array of strings
opensocial.Person.Field. MUSIC**
Person’s favorite music
Array of strings
opensocial.Person.Field. NAME
An object containing the person’s name; MySpace returns only
Medium-sized version of the image returned by THUMBNAIL_URL; MySpace returns opensocial.Url. Field.ADDRESS and
opensocial. Url
opensocial.Url.Field. TYPE. This field is not part of
the OpenSocial spec and is a MySpace-specific extension. MyOpenSpace.Person.Field. LARGE_IMAGE
Large version of the image returned by THUMBNAIL_URL; MySpace returns opensocial. Url.Field.ADDRESS and
opensocial. Url
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 the Creative 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 is because these fields on a MySpace Profile are free text.
Accessing MySpace User Data
Accessing Profile Information Using the opensocial.Person Object The first thing we’re going to add to our basic Tic-Tac-Toe app is the ability to get the default fields for our Viewer by fetching the corresponding opensocial.Person object using an opensocial.DataRequest. MySpace defines these default opensocial. Person.Field values for the Person object: n n n n
Profile URL, or opensocial.Person.Field.PROFILE_URL Image URL, or opensocial.Person.Field.THUMBNAIL_URL Display name, or opensocial.Person.Field.NAME User ID, or opensocial.Person.Field.ID
These are the bare-minimum default fields that, as long as you have access to the Person object, will always be returned.
One thing to note is that all requests to the MySpace API are asynchronous, meaning you launch them as “fire and forget” requests.Typically you make a request and specify a callback function; when the server is done processing your request, it passes the results as a parameter into your callback function. One result of this is that you’re probably going to want to put your data requests at the start of the code.That way the MySpace API can start processing your request as soon as possible, and your app won’t be stuck waiting for data to come back.
How Asynchronous JavaScript Requests Work JavaScript is capable of making synchronous or asynchronous data requests back to servers on the current page’s originating domain. Under the hood this is accomplished via the XMLHttpRequest object. This may be alternately referred to as XHR or Ajax. OpenSocial wraps this functionality up in the opensocial.DataRequest object, so you don’t need to know all the gory details. Because this is always done asynchronously with OpenSocial, your code needs to specify a callback function to handle the server response. JavaScript in the browser is inherently single-threaded, which basically means that it can 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 callback 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 the VIEWER as a parameter 3. Adds the request to the queue by calling add(), passing in a key to name the request
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.While developing our app, we’ll make heavy use of it. opensocial.IdSpec.PersonId.VIEWER is one of many enums you’ll encounter in OpenSocial. In JavaScript this actually resolves into a string, and on MySpace specifically it is equal to the string VIEWER.You can use the string and enum interchangeably, but we recommend using the enum for two reasons: n
n
If you mistype the enum, your mistake triggers a JavaScript error, but if you mistype the string, it isn’t immediately obvious that something went wrong, so it is harder to debug. The values to which the enums resolve aren’t yet clearly outlined in the OpenSocial spec, so different containers might resolve enums to different strings.
We use opensocial.IdSpec.PersonId.VIEWER here to state that we want to fetch the Viewer’s data. Had we wanted to fetch the Owner’s data, we would have used opensocial.IdSpec.PersonId.OWNER. newFetchPersonRequest takes the ID of the user you want to request as a parameter (in this case the Viewer) and returns an object.That object is actually unnamed by OpenSocial, and the documentation simply refers to it as a “request.”This object is never used directly beyond how it’s used here—passed into DataRequest’s add() function. Essentially, the DataRequest object creates “request” objects that are passed into its own add function. It may seem a little confusing, but remember—you’ll never have to use that mysterious, unnamed “request” object directly, and all OpenSocial API calls follow this general pattern.
Accessing MySpace User Data
The add function takes that request and adds it to a queue that is stored in the DataRequest 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 later when we talk about how to parse responses. The last line tells the container to start processing the request queue by calling send().We pass the name of our callback function into send() as a parameter; when the server is done processing our request, it calls this function while passing in the response. You can see the flow of the OpenSocial data request and response pattern in Figure 2.2.
1. Create an opensocial.DataRequest object
CODE EXAMPLE: var req 5 opensocial.newDataRequest();
Instantiate an opensocial.DataRequest object. The DataRequest object can hold several requests at once which can be sent as a batch to the server.
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 each request (the first request) or no key at all (the second request). When you parse the response you’ll use the key to identify each request. If you don’t pass in a key, the MySpace container will add a default key.
3. Send the request to the server and request a callback
CODE EXAMPLE: req.send (callback_func);
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 creates the response. Once the response is ready, the callback function is executed and the response is passed in.
4. Receive and parse the response from the server CODE EXAMPLE: function callback_func(data){ data.get("your_owner_key").getData(); }
Figure 2.2
The server will return an opensocial.DataResponse object which will, in turn, contain a number of opensocial.ResponseItem objects. Each of these will correspond to a request made in step 2.
Basic request and response pattern for OpenSocial.
17
18
Chapter 2 Getting Basic MySpace Data
Getting More than Just the Default Profile Data Fields beyond the default person fields typically follow a slightly different request pattern and may also require higher permission levels for access. As an example of this, we’ll be requesting our Viewer’s status message (like a headline or shout-out), address, and gender.We’ve modified the function shown previously to now 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 an opensocial.DataRequest object. In the next line we create an array of opensocial.Person.Field enums; this list corresponds to the specific Person fields
we want from the API. Next, an empty object is created called opt_params.This is another OpenSocial pattern 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
Accessing MySpace User Data
define what you want to do.You do this by adding certain properties to an object and passing that object into the request. When the MySpace container is processing a request for Viewer or Owner data, it checks the parameters sent in for a property named profileDetail. If it finds such a property, it knows that additional fields were requested. So let’s take a look at that line again: // Add the list of fields to the parameters opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = fields;
On MySpace, opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS resolves to the string profileDetail. We’re creating that property and setting it equal to the array of opensocial.Person.Field values we created earlier.The container now knows that additional fields were requested. The rest of the function is the same as before—we create the request, add it to the queue, 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 three types of responses: n
n
n
A literal, such as a string or a number. For example, opensocial.Person.Field.STATUS returns a string. An object. For example, opensocial.Person.Field.CURRENT_LOCATION returns an opensocial.Address object. An enum. For example, opensocial.Person.Field.GENDER returns an opensocial.Enum enum object.
All responses from the API come in the form of an opensocial.DataResponse object.The DataResponse object contains some number of opensocial.ResponseItem objects; each ResponseItem corresponds to the requests we added to the DataRequest queue. For now, we just have the one request for the Viewer; we’ll look at dealing with multiple requests and ResponseItem objects in the next chapter. To get a particular ResponseItem object from an opensocial.DataResponse, you need to use a key. If you already provided an optional key, use that. Otherwise, you can use the default key created by the MySpace container. Tip: Use an Optional Key It’s recommended that you always use an optional key, as the default keys can be tricky to use. But, if you’re curious, the container-generated keys are found in the MyOpenSpace.RequestType namespace.
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 the function 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 request and prepared a response.The first line in getDataCallback takes that DataResponse object 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 the Viewer’s opensocial.Person object; we get the Person by calling getData(). Now the variable viewer contains an object of type opensocial.Person, which in turn contains 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 the Creative Commons 2.5 Attribution License (http://creativecommons.org/licenses/by/2.5/).
Accessing MySpace User Data
The next section of our code calls the function printPerson(), which is a helper function that we use to parse out the details of our Viewer and output them to the screen. 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 // 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 }
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 of type opensocial.Person, we’ll typically need to use the getField() function. After we confirm that viewer isn’t null, we call getField(), pass in the field we want as a parameter, 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 just access it directly.That’s really all there is to parsing out a Person field that is returned as a string. For details on the return type for every supported Person field, refer back to Table 2.2 in this chapter. The next line uses a shortcut to retrieve the Viewer’s display name. Another shortcut, getID(), exists to retrieve the Viewer’s ID. All other fields are accessed using getField(), 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 shortcut is cleaner. Next, we parse out the Viewer’s current location; this field is returned as an opensocial.Address object. You’ll notice that the opensocial.Address object behaves similarly to the opensocial.Person object. Both have fields that describe the types 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 two useful types of data in each opensocial.Enum: the display value and the key.The display value is retrieved using getDisplayValue() and is a string that is defined by each container as it sees fit. For example, the display value for the female gender, depending on the 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 is typically used when making comparisons as the key values are defined in the OpenSocial spec. In our code, we output the display value to the surface but use the key to make a logical comparison; we set the background color to pink if the gender is female (i.e., it’s equal 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 that goes through each Person field and parses it. If you’re wondering how to parse a particular field that wasn’t covered here, take a look at the code and you should be able to find what you need.
Accessing MySpace User Data
Talking to Your Parent The MySpace site itself runs on the domain myspace.com. All MySpace apps live on a domain 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 in domains, the iframe in which your app runs can’t access the outer page. The app is said to be in a “jail domain.” Cross-domain access is a security measure built into all modern browsers, and MySpace makes use of it to prevent any malicious attacks on the myspace.com domain. However, there are a few functions that are exposed to apps that do talk to the parent page. A cross-domain scripting trick called inter-frame procedure call (IFPC) opens a few holes in the jail domain for apps to take advantage of. Let’s take a look at two of the more useful functions. The first is gadgets.window.adjustHeight(new_height). This function asks the parent 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 the iframe is resized to try to fill the specified fraction of the page. A new_height of 0.5 would 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 fill its 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 way to go, as it can be hard to know exactly how big your content is at all times. The other option 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). This function causes the browser to navigate away from the current page to the specified view. 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();
23
24
Chapter 2 Getting Basic MySpace Data
// 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 of currently supported views by calling gadgets.views.getSupportedViews(). This function returns a hash table of gadgets.views.View objects, keyed by the names of the views. If the list of supported views contains the specified view, requestNavigateTo is invoked and the View object is passed in. To make use of the rNT function, you might do something like this in the onclick handler of a button: rNT(gadgets.views.ViewType.CANVAS);
That will cause the browser to navigate to the app’s Canvas page.
Error Handling JavaScript errors from apps seem to be an all-too-common occurrence, but they don’t have to be. Most developers don’t expect errors to occur, and so they don’t test or prepare for them as a result, but errors do happen.Your best defense against them is to admit that 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 following example 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);
Error Handling
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 error flag 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 flag as well, so we’ll need to check each ResponseItem in order to find out which request had the error, if the global flag was set. We do this by calling the ResponseItem’s hadError() function. In this case we had only one request, so there is only one ResponseItem, but in the event of multiple ResponseItem objects we would check each one in turn to determine its error state. Similar to an opensocial.Enum object that has two types of data, one for display and one for logical comparisons, each opensocial.ResponseItem that encounters an error also has two types of data.The error message, accessed by getErrorMessage(), is an arbitrary string that should describe the error and help you debug what happened.The error code, accessed by getErrorCode(), matches up to one of the codes found in the opensocial.ResponseItem.Error enum. Common causes for each type of error code may be found in Table 2.4. You’ll notice that we also attempted to retry the request in the event of an INTERNAL_ERROR.This is because an INTERNAL_ERROR can sometimes occur because of network congestion or other temporary problems.Your request might succeed if you wait a second or so and try again.
25
26
Chapter 2 Getting Basic MySpace Data
Table 2.4
Common Error Code Causes
Common Error Codes
Causes
opensocial.ResponseItem.Error. BAD_REQUEST
The most common cause of this error is that some part of your request didn’t make sense to the container. For example, you passed in a negative value that should be positive, you didn’t supply a required field, or you passed in an invalid ID for a particular request.
opensocial.ResponseItem.Error. FORBIDDEN
This error is returned only when the server responds with a status code of 403 and is not commonly seen.
opensocial.ResponseItem.Error. INTERNAL_ERROR
This is a catchall error that typically occurs when something unknown happens on the MySpace side of the request. As such, it should be intermittent. It can also occur in opensocial.requestPermission (a topic we’ll cover in the section on requesting permissions in Chapter 3) if a permission was requested but no new permission was granted, or if the server returned an unknown status code.
opensocial.ResponseItem.Error. NOT_IMPLEMENTED
This error is returned if you’ve requested some OpenSocial functionality that MySpace doesn’t support. If you receive this error, either the entire function you’re calling isn’t available, or some parameter in a request isn’t supported. An example of the latter would be that you requested an opensocial.Person field that isn’t supported.
opensocial.ResponseItem.Error. UNAUTHORIZED
This error most commonly happens when you’ve requested data to which you don’t have access. It may be possible to use opensocial.requestPermission to ask the user to grant your app access to the data. Again, see Chapter 3 for details.
Handling errors offers two benefits: n
n
There are no embarrassing JavaScript errors when you try to retrieve objects that don’t exist. There’s a possibility that you can recover from your error by retrying the request.
Summary
Warning When retrying your request after an error, be careful you don’t code yourself into an infinite loop! It’s best to keep a retry counter as we do in the code shown previously.
Summary In this chapter we covered the basic flow of an OpenSocial application, focusing on the process of accessing data on the API and OpenSocial’s request/response pattern.We also defined 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 it every time you request data from the server, so we hope you were paying attention. Note Code listings and/or code examples for this chapter and every other chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
27
This page intentionally left blank
3 Getting Additional MySpace Data I
n the preceding chapter we covered how to fetch and make use of the Person object on the MySpace platform. But there’s a lot more data out there—such as the user’s friend list and the photos the user has uploaded. It’s the use of all this data that will propel your app from a lifeless Web game to a dynamic and social application with viral potential. Most application developers use the friend list in order to spread and share their applications (see Chapter 5, Communication and Viral Features, to learn how) and other endpoints like albums and videos to make their apps more personal and engaging for the user. In this chapter we’ll do just that by covering how to access and use your users’ data to make your app more dynamic and appealing.We’ll show how to retrieve your users’ friends; use paging to sort, sift, and display the data; as well as explore viewing albums, photos, and videos.We’ll also discuss some extras, such as how to check whether a user already has an app installed and how to check for and request permissions from a user. As we start to request more and more sensitive data, such as a user’s photos, permissions will start to come into play more and more. From now on, our Tic-Tac-Toe game is no longer a boring JavaScript applet. It’s a feature-packed app that actually uses the power of the MySpace social network.
How to Fetch a Friend List and Make Use of the Data This section will show you how to fetch a list of friends and then page through that list. You’ll also learn the various ways you can sort and filter a friend list, such as restricting it to only friends who have the app installed.
30
Chapter 3 Getting Additional MySpace Data
In our example Tic-Tac-Toe app, we’ll use the list of friends in two ways: n
n
Provide a list of all the Viewer’s friends so the Viewer can send invitations to those friends to add the app. Provide a list of friends who already have the app installed so the Viewer can challenge those friends to a game of Tic-Tac-Toe.
The actual invitation sending and game play challenges will be covered in Chapter 5, Communication and Viral Features.This section will lay the foundation for those functions by showing you how to pull out the friend list and filter it accordingly.
A Quick JavaScript Lesson Up until now, we’ve kept the code simple by sticking to OpenSocial-specific JavaScript. We did this by separating the Tic-Tac-Toe game logic from the OpenSocial code and keeping everything globally namespaced (meaning the code can be called from anywhere; this is its “scope” in programming terms). Moving forward, our app will become more and more complex. This added complexity requires us to start introducing more advanced JavaScript techniques such as object notation and object-oriented programming. This is not a book on JavaScript programming but on how to build dynamic OpenSocial apps on MySpace. You’ll find, however, that you’ll learn a lot about JavaScript along the way! To this end you’ll start to notice the use of the TTT namespace. This is where we’ll keep all the code for game-specific functionality. For example, in Chapter 2, Getting Basic MySpace Data, we provided a key of "v" when we requested the Viewer data. In this chapter we move all of those keys into an enum: TTT.RequestKeys. So instead of using key "v", we use key TTT.RequestKeys.VIEWER. We concentrate on the OpenSocial code in this book, but feel free to dig into the full code listings found at our Google Code site: http://opensocialtictactoe.googlecode.com.
Getting the Friend List This is the same request/response idea from Chapter 2, Getting Basic MySpace Data, that helps define OpenSocial. In fact, the friend list is just an opensocial.Collection of opensocial.Person objects, but instead of dealing with just one Person as in Chapter 2, we’re dealing with a list of them. There are two major differences between fetching a single Person and fetching a friend list: n n
Call newFetchPeopleRequest instead of newFetchPersonRequest. Instead of passing in an ID (such as Viewer or Owner), pass in an opensocial.IdSpec object.
An IdSpec object is a different way to specify a group of IDs. It requires you to define two parameters: the user ID and the network distance.The user ID specifies the
How to Fetch a Friend List and Make Use of the Data
context for the IdSpec—basically letting MySpace know if you’re asking for a group involving the Owner or the Viewer. MySpace supports the contexts of only Viewer and Owner. In other words, you can’t get a friend list for a random user; it has to be for either the Viewer or the Owner. The network distance defines how far out the connections go. For example, specifying a network distance of 0 would denote just the Owner or the Viewer, and a network distance of 1 would denote the friends of the Owner or the Viewer. At this time MySpace supports a network distance only to a maximum of 1, so you can’t fetch the friends of your friends. Let’s create a fetchFriendList()function to get a basic friend list.This function wraps the newFetchPeopleRequest. Our example is heavily simplified, though, so it isn’t our final version of the function. We’ll expand on it as we see what else you can do with a friend list. We’ll be inserting this function into the code of our Tic-Tac-Toe app found in Chapter 2. For those of you following along at home, place this function anywhere in the script tag in that code: function fetchFriendList(callback){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial.newIdSpec(params); // Create the DataRequest object var request = opensocial.newDataRequest(); // Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS); // Send it off request.send(callback); }
First, the IdSpec object is created using a user ID of VIEWER and a network distance of 1 to specify that we want the friends of the Viewer. Next, an opensocial.DataRequest object is instantiated and the request is added to the queue with a custom key of TTT.RequestKeys.VIEWER_FRIENDS. Finally, the request is sent off (and the response will find its way back to the specified callback).
Filters and Sorts The first example we showed you just fetches an arbitrary subset of friends of the Viewer. This list is typically returned in the order in which the friendships were made and is not
31
32
Chapter 3 Getting Additional MySpace Data
terribly complex. OpenSocial, however, defines a number of ways to sort and filter fetched lists, making them a lot more useful. Before getting to the code, let’s look at the available options.The MySpace-supported filter types and sorts are shown in Table 3.1. Let’s revisit the fetchFriendList() function, but this time with support for sorts and filters. Again, we’re not quite at the final version of our function, but this code brings us a step closer: function fetchFriendList(callback, filter, sort){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial.newIdSpec(params); params = {}; // Add any filters if(filter && filter.length > 0){ params[opensocial.DataRequest.PeopleRequestFields.FILTER] = filter; } // Add any sorts if(sort && sort.length > 0){ params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = sort; } // Create the DataRequest object var request = opensocial.newDataRequest(); // Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS); // Send it off request.send(callback); }
You can see that the filters and sorts are specified by adding opensocial. DataRequest.PeopleRequestFields.FILTER and opensocial.DataRequest. PeopleRequestFields.SORT_ORDER to the parameters.
Paging According to the OpenSocial spec, the default number of items returned for a request is 20. That means our fetchFriendList() function returns the first 20 friends in the list. But what if a user has more than 20 friends? Enter paging.
How to Fetch a Friend List and Make Use of the Data
Table 3.1
Supported Friend List Filters and Sorts on MySpace
Filter Type
Details
opensocial.DataRequest.FilterType. ALL
The default filter, essentially no filter
opensocial.DataRequest.FilterType. HAS_APP
Fetches only those friends who have added the app
opensocial.DataRequest.FilterType. TOP_FRIENDS
MySpace allows users to define top or favorite friends; these are the friends who appear at the top of the user’s Friend Space, and this filter fetches only those friends.
Not a filter; allows you to sort a friend list by ID (ascending). Note that this sort is applied after the page is fetched, so it doesn’t take the user’s entire friend list, sort it, and return a particular page. What happens is that a page of friends is taken and that list is sorted. This is not particularly useful.
opensocial.DataRequest.SortOrder.NAME
Another sort; sorts the returned list by nickname (ascending). Like the preceding sort, this one isn’t the most useful as the entire friend list isn’t sorted up front, only the returned page.
Paging is a way to get a large collection of data one chunk at a time.That means that once we have fetched friends 1 to 20, we can then fetch friends 21 to 40, then 41 to 60, and so on. OpenSocial also provides a way to specify which chunk of friends you want for a given request. To demonstrate paging, let’s expand one final time on our fetchFriendList() function: function fetchFriendList(first, max, callback, filter, sort){ // Create the IdSpec object var params = {}; params[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
33
34
Chapter 3 Getting Additional MySpace Data
params[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1; var idspec = opensocial.newIdSpec(params); params = {}; // Set the paging parameters if(first){ params[opensocial.DataRequest.PeopleRequestFields.FIRST] = first; } if(max){ params[opensocial.DataRequest.PeopleRequestFields.MAX] = max; }
// Add any filters if(filter && filter.length > 0){ params[opensocial.DataRequest.PeopleRequestFields.FILTER] = filter; } // Add any sorts if(sort && sort.length > 0){ params[opensocial.DataRequest.PeopleRequestFields.SORT_ORDER] = sort; } // Create the DataRequest object var request = opensocial.newDataRequest(); // Add the request to the queue request.add(request.newFetchPeopleRequest(idspec), TTT.RequestKeys.VIEWER_FRIENDS); // Send it off request.send(callback); }
You’ll notice that opensocial.DataRequest.PeopleRequestFields.FIRST and opensocial.DataRequest.PeopleRequestFields.MAX have been added to the parameters. MAX defines the maximum number of friends to fetch at a time, so if you specified a MAX of 100 (the maximum allowed by MySpace), you’d get the friend list in chunks of 100. FIRST specifies which friend to start fetching from, so if you specified that FIRST is 201 and MAX is 100, you’d get friends 201 to 300. That means you’ll want to keep MAX at a constant value and increment FIRST by that value for each request. Assume we define MAX to be 50; we’d start out with a value of FIRST as 1. If the user requested the next page, we’d change FIRST to 51, and then 101, and so forth.The API provides you with the total number of friends in the list (in addition to the number fetched with the current request) to aid you in paging. In our Tic-Tac-Toe app we fetch 20 friends at a time. You can see a successful friend list request in Figure 3.1.
How to Fetch a Friend List and Make Use of the Data
Figure 3.1
Screen shot of a successful friend list request.
Let’s take a look at the paging object we used: TTT.Lists.Pager = { pager_wrap:"
{0}
", pager_prev:"<span onclick='TTT.Lists.Pager.prev();'><< prev ", pager_next:" <span onclick=’TTT.Lists.Pager.next();’>next >>", page_size:20, getMarkUp:function(){ var current_list = TTT.Lists.getCurrentList(); if(current_list.list.length < this.page_size){ // If the length is less than the amount requested // there is only one page, no need for a pager return ""; } var markup = ""; if(current_list.first > this.page_size){ // If the first index is greater than the size of // a page then there will be a previous page markup += this.pager_prev; } if(current_list.total > current_list.first + current_list.list.length - 1){ // If the total number of records is greater than
35
36
Chapter 3 Getting Additional MySpace Data
// the current index, plus the amount in the current // result set, minus 1, then there's another page. // e.g., first = 1, current set = 20, total = 55 // 1 + 20 - 1 = 20 records fetched, < 55 // e.g., first = 21, current set = 20, total = 55 // 21 + 20 - 1 = 40 records fetched, < 55 // e.g., first = 41, current set = 10, total = 55 // 41 + 15 - 1 = 55 records fetched, == 55 markup += this.pager_next; } if(markup.length > 0){ markup = this.pager_wrap.replace("{0}", markup); } return markup; }, prev:function(){ var current_list = TTT.Lists.getCurrentList(); current_list.first -= this.page_size; fetchFriends(current_list.list_type); }, next:function(){ var current_list = TTT.Lists.getCurrentList(); current_list.first += this.page_size; fetchFriends(current_list.list_type); } };
The Pager object in our Tic-Tac-Toe app does three things: 1. Provides HTML markup for Next and Prev buttons that we can use to allow the user to actually navigate between pages. 2. Stores the value of FIRST that is the current value. 3. Handles what happens when the Next and Prev buttons are clicked. Meanwhile, the getMarkUp() function handles the actual paging algorithm. With this function there are three possible outcomes: 1. The number of records fetched is less than the number requested (MAX). This means there is only one page of data, so no paging is required. 2. The value of FIRST is greater than the size of a page.Therefore, there is at least one previous page, so we need the Prev link. 3. The total number of friends is greater than all the friends fetched so far. Therefore, there are more friends who can be fetched, so a Next link must be added.
How to Fetch a Friend List and Make Use of the Data
Tip: Advanced Technique You’ll see as we progress through this chapter that our Tic-Tac-Toe app presents the user with three lists. One is the entire friend list, one is the list of friends who have the app installed, and the third is the list of photos the user has uploaded to his or her MySpace Profile. The lists all appear fairly similar—each item is in a box that can be clicked, each has a picture, and each has some text underneath. If all these lists are so similar, why not abstract the code so you can use the same functions to generate all three lists? This is exactly what we did. We created a TTT.List object to represent a list, a TTT.Lists object that keeps track of all the current lists that are on the page (note the s at the end), and a TTT.ListTypes enum to differentiate the types of lists. The TTT.List object contains the status of a particular list, including which type it is. It also has references to the actual Document Object Model (DOM) elements that get displayed, the OpenSocial objects that were fetched, paging parameters, what to do when it’s clicked, and the keys used to access the stored OpenSocial data. It’s essentially an interface for what a list should look like. The TTT.Lists object stores the collection of lists and which list is currently selected. We also do something similar for the set of tabs along the top of the app. Check out the TTT.Tab and TTT.Tabs objects for more abstraction fun!
Using the Data We’ve now defined a function that wraps the OpenSocial function newFetchPeopleRequest(). In our Tic-Tac-Toe app we call that function like so: function fetchFriends(list_type){ // Make sure the correct list is set TTT.Lists.setCurrentList(list_type); // Get the current list var current_list = TTT.Lists.getCurrentList(); // Do we need to add any filters? var filter = ""; if(TTT.ListTypes.HASAPP_FRIENDS === list_type){ // Add the HAS_APP filter filter = opensocial.DataRequest.FilterType.HAS_APP; } // Call the fetch friends wrapper fetchFriendList(current_list.first, current_list.max, TTT.Lists.callback, filter); }
First we get a reference to the currently selected list. If it’s the list of friends who have the app installed, we add that filter (TTT.ListTypes.HASAPP_FRIENDS) and send it into the wrapper.
37
38
Chapter 3 Getting Additional MySpace Data
The callback function we passed in, TTT.Lists.callback, will be executed once the friend request has been made and the API responds with some data. Let’s take a look at the callback function’s code and walk through it in detail. You’ll recognize a lot of the OpenSocial aspects from when we discussed callbacks and data parsing in Chapter 2, Getting Basic MySpace Data: TTT.Lists.callback = function(response){ var current_list = TTT.Lists.getCurrentList(); var retryRequest = function(){ current_list.retries--; window.setTimeout(fetchFriends, 250); }; // Check for an error if(!response.hadError()){ var data = null; // Loop through the available keys to // find the actual data in the response for(var key in TTT.RequestKeys){ if(response.get(TTT.RequestKeys[key])){ data = response.get(TTT.RequestKeys[key]).getData(); break; } } // Something bad happened to it if(null === data){ retryRequest(); return; } else{ // Save the actual data to the TTT.List object current_list.list = data.asArray(); // Save the total number of items in the list current_list.total = data.getTotalSize(); // Draw the list TTT.Lists.draw(); } } else{ // If there was a permission issue if(data.getErrorCode() === opensocial.ResponseItem.Error.UNAUTHORIZED){ var reason = "To set a custom background for the game board!"; opensocial.requestPermission(
Fetching Media
[MyOpenSpace.Permission.VIEWER_ACCESS_TO_PUBLIC_VIDEOS_PHOTOS], reason, TTT.Lists.permCallback); } // If there was an error and there are retries left, go for it else if(current_list.retries > 0){ retryRequest(); return; } // Out of retries ... else{ log("Oops, there was an error! Try refreshing the page."); } } };
The callback checks for errors in the request and handles any retry attempts. Each list maintains its own retry count, and a failed request is retried the specified number of times. If there was no error, the response is looped through in an attempt to find out what data it contains.This allows the callback to handle any kind of response. It can currently handle the friend list responses, and as you’ll see later on, it can also handle the response for the photo list. If everything works (and it should), the data is saved to the TTT.List object, along with the total size of the collection for paging purposes, and the filtered list is drawn. Since each friend is represented by an opensocial.Person object, actually parsing out the data for each friend is similar to how it was done in Chapter 2. For details, refer to that chapter, or for a complete code reference for the function TTT.Lists.draw(), check the Chapter 3 sample code found here: http://code.google.com/p/opensocialtictactoe/source/ browse/#svn/trunk/chapter3. Note You can get only the basic person fields for friends; you can’t get extended data. Basic person fields are the friend’s ID, display name, thumbnail URL, and Profile URL.
Fetching Media Media includes a user’s albums, photos, and videos. Dealing with media items is very similar to the other requests we’ve covered so far, including how they’re fetched, how you page through a list, and how the response is parsed.
Photos You can fetch all of the photos your user has uploaded to his or her MySpace Profile, provided the user grants your app proper permissions. Users can limit permissions, but we’ll explore how to deal with that later in the permissions section of this chapter. By default, though, you should have access to all of a user’s public photos. Photos are
39
40
Chapter 3 Getting Additional MySpace Data
defined by the MyOpenSpace.Photo object, which contains the fields shown in Table 3.2.These fields are accessed in the same way as for a Person, for example, photo.getField(MyOpenSpace.Photo.Field.CAPTION). Let’s take a look at the function signature that’s used to fetch photos.You’ll notice that it’s slightly different from how we fetch people: MyOpenSpace.DataRequest.newFetchPhotosRequest = function(id, opt_params)
id is a string used to identify who owns the photos.The value can be either opensocial.IdSpec.PersonId.VIEWER or opensocial.IdSpec.PersonId.OWNER. opt_params is an object that specifies optional parameters. In this case only the paging parameters opensocial.DataRequest.PeopleRequestFields.FIRST and opensocial.DataRequest.PeopleRequestFields.MAX are allowed.
The reason the function signature is in a different format from the other request functions is that it is a MySpace-specific extension.The OpenSocial spec defines ways for containers to extend the core functionality of the OpenSocial spec. In this case MySpace has added several new endpoints. Because it’s an extension, the function exists in the MyOpenSpace namespace and not the opensocial namespace. In our Tic-Tac-Toe app we fetch the list of photos for the user and allow the user to select one. That photo then becomes the background for the Tic-Tac-Toe game board. Let’s take a look at a function that wraps MyOpenSpace.DataRequest.newFetchPhotosRequest: function fetchPhotosList(first, max, callback){ // Add some paging parameters var params = {}; params[opensocial.DataRequest.PeopleRequestFields.FIRST] = first; params[opensocial.DataRequest.PeopleRequestFields.MAX] = max; // Create the DataRequest object var request = opensocial.newDataRequest(); // Add the request request.add(MyOpenSpace.DataRequest.newFetchPhotosRequest( opensocial.IdSpec.PersonId.VIEWER, params), TTT.RequestKeys.VIEWER_PHOTOS); // Send it off request.send(callback); }
Table 3.2
Fields for the MyOpenSpace.Photo Object
Field
Description
PHOTO_ID
The ID number—a photo’s unique identifier
PHOTO_URI
The RESTful API URI that corresponds to this photo
IMAGE_URI
The URL of the photo, which can be used to output the photo to the UI
CAPTION
The photo’s caption
Fetching Media
Figure 3.2
Screen shot of a successful photo request.
We set some paging parameters, create the opensocial.DataRequest object, and send off the request.You’ll notice the other big difference here, besides the namespace change, of executing one of the MySpace extensions.Typically the fetch request, such as newFetchPeopleRequest, is called via an instance of an opensocial.DataRequest object. However, when using this MySpace extension, we call it statically from the MyOpenSpace.DataRequest namespace.You can compare and contrast this function with the fetchFriendsList function to see the slight differences.This code can be seen in action in Figure 3.2.
Albums and Videos The pattern for fetching albums and videos is actually the same as it is for fetching photos. So, if you know how to request photos, you know how to fetch albums and videos. Obviously, the fields and objects differ depending on what you’re fetching, but the basic structure remains the same.That said, we’ve included the fields and function signatures here as a reference for you. Albums Albums are defined by the MyOpenSpace.Album object, which contains the fields outlined in Table 3.3.
41
42
Chapter 3 Getting Additional MySpace Data
Table 3.3
Fields for the MyOpenSpace.Album Object
Field
Description
ALBUM_ID
The ID number—an album’s unique identifier
ALBUM_URI
The value (RESTful URI) that the API recognizes
TITLE
The album’s title
LOCATION
The geographic location where the album’s photographs were taken
DEFAULT_IMAGE
A URL that points to the album’s default image
PRIVACY
A string indicating the album’s privacy settings; set to either “Private” or “Public”
PHOTO_COUNT
An integer indicating the number of photos in an album
PHOTOS_URI
The value (RESTful URI) for accessing the photos within the album
The function signature is as follows: MyOpenSpace.DataRequest.newFetchAlbumsRequest = function(id, opt_params)
id is a string used to identify who owns the albums.The value can be either opensocial.IdSpec.PersonId.VIEWER or opensocial.IdSpec.PersonId.OWNER. opt_params is an object map that specifies optional parameters. In this case only the paging parameters are allowed: opensocial.DataRequest.PeopleRequestFields. FIRST and opensocial.DataRequest.PeopleRequestFields.MAX.
Videos Videos are defined by the MyOpenSpace.Video object, which contains the fields outlined in Table 3.4. The function signature is as follows: MyOpenSpace.DataRequest.newFetchVideosRequest = function(id, opt_params)
id is a string used to identify who owns the videos.The value can be either opensocial.IdSpec.PersonId.VIEWER or opensocial.IdSpec.PersonId.OWNER. opt_params is an object map that specifies optional parameters. In this case, only the paging parameters are allowed: opensocial.DataRequest.PeopleRequestFields. FIRST and opensocial.DataRequest.PeopleRequestFields.MAX.
Since the implementation of both the video and album endpoints is so similar to that of photos, which we’ve already discussed, we leave it to you to experiment with these as you wish.
Using opensocial.requestPermission and opensocial.hasPermission
Table 3.4
Fields for the MyOpenSpace.Video Object
Field
Description
VIDEO_ID
The ID number—a video’s unique identifier
VIDEO_URI
The value (RESTful URI) that the API recognizes
TITLE
The video’s title
DATE_CREATED
The date when the video was created
LAST_UPDATE
The date when the video was last updated
MEDIA_TYPE
An integer indicating the media type of the video
DESCRIPTION
A description of the video
THUMB_URL
A URL pointing to the thumbnail image associated with the video
MEDIA_STATUS
The current status of the video
RUN_TIME
The run time, or length, of the video
TOTAL_VIEWS
The total number of views a video has received
TOTAL_COMMENTS
An integer indicating the number of comments the video has received
TOTAL_RATING
An integer representing the video’s overall rating
TOTAL_VOTES
An integer representing the total number of votes the video has received
COUNTRY
A string indicating the video’s country of origin; typically used to identify culture, not geographic location
LANGUAGE
A string indicating the video’s language
Using opensocial.requestPermission and opensocial.hasPermission to Check a User’s Permission Settings Permission settings are applied to both data and actions. A user can specify permissions on a per-app basis, but there are a couple of global permission settings that you’ll need to either work with or work around (see Chapter 2, Getting Basic MySpace Data, for details). In our Tic-Tac-Toe app we display a list of the user’s photos to the user. But public and private photos each have their own permission setting, so we should first check to see if we have permission before we send out the request. In our app we check whether we at least have access to the user’s public photos: function setBackgroundClicked(){ // Create a permission object var perm = MyOpenSpace.Permission.VIEWER_ACCESS_TO_PUBLIC_VIDEOS_PHOTOS; // Can we get the photos? if(opensocial.hasPermission(perm)){ // Yep fetchPhotos(TTT.ListTypes.SET_BACKGROUND); }
43
44
Chapter 3 Getting Additional MySpace Data
else{ // We can't; let's request the permission to do so var reason = "To set a custom background for the game board!"; opensocial.requestPermission([perm], reason, photosPermCallback); } } function photosPermCallback(response){ // If no new permissions were granted, the // response will have an error if(!response.hadError()){ // No error, so a permission was granted, // try again setBackgroundClicked(); } }
setBackgroundClicked() is called when the appropriate tab is clicked at the top of the app.We’re looking for permission to access public photos, so we call opensocial. hasPermission() to see if we can make this call. If we can, we fetch the photos. If we can’t, we request permission.To do this, we first must provide a reason.The reason is just a string that is displayed to the user.Then we call opensocial.requestPermission(), passing in a callback function. Note that MySpace supports only one permission at a time here, but you’ll need to put the Permission object into an array anyway. Finally, once the user closes the permission window, the callback function is executed. The main piece of information the response provides is whether or not a permission was granted. If no new permissions were granted, hadError()will be true. If a new permission was granted, hadError()will be false. If there was no error, we know the permission was granted and we can continue on to fetch the photo list.Table 3.5 presents all of the supported Person fields along with their return types.
Table 3.5
Permissions You Can Request on MySpace
MySpace-Supported Permission
Description
MyOpenSpace.Permission. DISPLAY_ON_PROFILE
Posts the app on the user’s MySpace Profile
MyOpenSpace.Permission. DISPLAY_ON_HOME
Posts the app on the user’s Home surface
MyOpenSpace.Permission. SEND_UPDATES_TO_FRIENDS
Sends activities updates to the user’s friends; for example, “Susan just won a game of Tic-Tac-Toe”
MyOpenSpace.Permission. SHOW_UPDATES_FROM_FRIENDS
Shows friends’ activities updates about the app; for example, “Your friend Bob just won a game of Tic-Tac-Toe”
Grants access to the app for all public photos and videos; enabled by default
MyOpenSpace.Permission. ACCESS_TO_IDENTITY_ INFORMATION
Grants access to the user’s identity information
MyOpenSpace.Permission. ADD_PHOTOS_TO_ALBUMS
Allows the app to upload photos directly to a user’s photo albums
MyOpenSpace.Permission. UPDATE_MOOD_STATUS
Allows the app to update a user’s status and mood
MyOpenSpace.Permission. CONTACT_INFO
Allows the app to view and use the user’s full contact info (full name, age, sex, location, and birthday)
MyOpenSpace.Permission. FULL_PROFILE_INFO
Allows the app to view the user’s full Profile information, such as favorite books, television shows, etc.
MyOpenSpace.Permission. UPDATE_PROFILE
Allows the app to make updates to the user’s Profile data; no endpoint currently makes use of this, however
MyOpenSpace.Permission. SEND_NOTIFICATIONS
Allows the app to send notifications to other users while the user is interacting with the app; see Chapter 5 for details on notifications
MyOpenSpace.Permission. RECEIVE_NOTIFICATIONS
If set, the user receives notifications from the app; see Chapter 5 for details on notifications
Summary One of the nice things about OpenSocial is that the basic techniques for most tasks are fairly similar. For example, requesting a friend list follows a similar request/response pattern to requesting a photo. Once you have that basic technique down, you can extrapolate and use it again and again. Just be careful and watch out for permissions—they’re one of the biggest causes of unexpected behavior in apps, and they will trip you up if your code doesn’t work to accommodate them. If you’re running into problems with any requests, always check your permissions. Note Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
45
This page intentionally left blank
4 Persisting Information A s your ambitions for what you want to do with OpenSocial grow, so will your needs. One of the first needs you’ll have is persisting information between sessions.Without the help of an external server, you have two options for storing persistent data: the app data store and cookies. In this chapter we’ll compare different methods of persistent storage and show you how to use them. We’ll grow our sample application and show you how to use persistent storage to allow users to set a custom name for themselves in the game and keep track of their high scores from session to session.
App Data Store The app data store is your premier option for serverless storage.This is the only storage mechanism that is officially supported in OpenSocial.The app data store works as a simple key/value storage mechanism. If you’re not familiar with a key/value store, it looks something like what is shown in Table 4.1. The app data store allows you to get away with not building or setting up an infrastructure for your app, provided your needs are simple.You may store only text and are limited to 20K of total data and 1024 bytes (characters) per key (at the time of this writing). App data is fairly flexible.Your app is allowed only read/write access to the Viewer’s data, but it may read app data from any of the following people/groups: n
n n n
Viewer Owner Viewer friends Owner friends
48
Chapter 4 Persisting Information
Table 4.1
Basic Key/Value Stores
Key
Value
Name
Joe
FavoriteColor
Green
According to the spec, anything placed in the app data store is supposed to be able to evaluate to a valid JSON object. Depending on the version of OpenSocial being used, the data stored will behave slightly differently. If your app is under version 0.7, it can store just about any string value—JSON or not. With the 0.8 and later versions of the OpenSocial spec implementation, the data has to be properly parsable JSON data. There is currently discussion among those who participate in the development of the OpenSocial spec about whether the app data store should be only JSON objects, or JSON-parsable data—like simple strings.Your safest bet is to store data as JSON objects. If you do choose to store JSON data, you need to make use of the gadget JSON parser to evaluate it.The call is simple enough: gadgets.json.parse(your_json_string). In practice, however, the gadget JSON parser is a little temperamental, so you need to get used to formatting your JSON “just so.” Firebug is an invaluable tool in sorting this out (Firebug, along with how to get it, is mentioned in the Introduction). Now, let’s write some code.
Saving and Retrieving Data Saving data involves creating an opensocial.newUpdatePersonAppDataRequest request object and sending it to the server in a data request. Each edit or add of any key in the Viewer’s app data store requires a new request, so the following code is a handy utility method for doing this (the callback parameter is optional, but it’s good practice to include it for error processing): function setAppDataKey(key, value, callback) { var req = opensocial.newDataRequest(); req.add(req.newUpdatePersonAppDataRequest( opensocial.IdSpec.PersonId.VIEWER, key, value), "set_" + key); req.send(callback); };
Data retrieval is a little more involved.You can’t just ignore the callback since this is how the data actually arrives. On the retrieval you also have the option of specifying one, some, or all of the data in the app data store for the current user. For our Tic-Tac-Toe app we’re going to add a little customization by making use of the app data store.We’re going to allow the user to specify a game name that is different from his or her standard MySpace display name.We’re also going to add a placeholder key to the app data store for tracking the user’s high score.
App Data Store
First we’re going to add some markup to the app.This markup includes the following: n
A text box for entering data
n
A button to invoke our action handler A div element for displaying our custom name with ID myinfo
n
Here is the code for the markup; add it as the first element inside the div with an ID of right_column:
Next, we’re going to add some methods for storage and retrieval of the app data keys we’re going to define. In our Tic-Tac-Toe code, which you can find in our Google Code listing (http://opensocialtictactoe.googlecode.com), we’ve defined the two keys as constants: TTT.Keys.NAME and TTT.Keys.SCORE. Here is the code for adding the storage and retrieval methods.We’re using a slight variation on the generalized setAppDataKey function defined earlier. Add it within the first script block on the Canvas surface. function setNameData(){ var elem = document.getElementById("txtName"); if(elem){ setAppDataKey(TTT.Keys.NAME, elem.value, getInitialData); } } function setAppDataKey(key, value, callback) { var req = opensocial.newDataRequest(); req.add(req.newUpdatePersonAppDataRequest( opensocial.IdSpec.PersonId.VIEWER, key, value), "set_" + key); req.send(callback); };
/** * Get the discrete app data and initialize the view */ function getInitialData(){ var req = opensocial.newDataRequest();
49
50
Chapter 4 Persisting Information
var fields = [ TTT.Keys.NAME, TTT.Keys.SCORE ]; var idparams = {}; idparams[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; idparams[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; var id = opensocial.newIdSpec(idparams); req.add(req.newFetchPersonAppDataRequest( id, fields), TTT.RequestKeys.VIEWERDATA); if(viewer == null){ req.add(req.newFetchPersonRequest( opensocial.IdSpec.PersonId.VIEWER), TTT.RequestKeys.VIEWER); } req.send(getDataCallback); } /** * Callback handler for getting app data and Viewer * @param {Object} data */ function getDataCallback(data){ logDataError(data); var mydata = data.get(TTT.RequestKeys.VIEWERDATA).getData(); if(!viewer){ viewer = data.get(TTT.RequestKeys.VIEWER).getData(); } //This happens if app not installed if(!viewer){ log("APP NOT INSTALLED!") return; } else{ var key; var realData = null; for(key in mydata){ realData = mydata[key]; break; } writeNameAndScore( realData[TTT.Keys.NAME], realData[TTT.Keys.SCORE]); } }
App Data Store
/** * Write the name value and score value to the myinfo div * @param {Object} name * @param {Object} score */ function writeNameAndScore(name, score){ var elem = document.getElementById("myinfo"); if(elem){ var str = "
To make it all work, we also plugged in a call to our new function getInitialData() in the initializeGame() function previously defined, and we’re good to go.
Refactoring to Build a Local App Data Store Our code can be significantly cleaned up and made more efficient, however. In most scenarios and for most Ajax-like Web applications, your biggest performance cost is going to be your wire time.This means that the bulk of the latency that users notice comes in the form of waiting for an XMLHttpRequest (XHR) to a remote server to complete. In our case, this means getting all our app data to the client in a single request instead of making a separate request for each data key.
The Readers-Writers Problem, Ajax-Style In computer science there is a well-known threading problem known as the “readerswriters problem.” The crux of the problem is this: Writing isn’t instantaneous. If one thread reads data from a common store while another thread is in the middle of a write operation, the first thread may get corrupt or invalid data.
51
52
Chapter 4 Persisting Information
JavaScript is a single-threaded environment, so we don’t normally consider threading problems when designing client code. The inclusion of asynchronous calls and wire time for reading and writing the data essentially creates a pseudo-multithreaded environment. To solve this problem, we simply make use of a flag value (aka semaphore). This “write” flag indicates to the code that a write operation is occurring. The callback from the write operation clears the flag. The read function in turn must honor that flag and reinvoke itself with a setTimeout call until the write flag has been cleared or the maximum number of retries has been reached. While our sample code does not do this, it is something your production code should do.
The following code shows some convenience methods that can be used for app data retrieval. It provides a method for loading all data into a variable called myLocalAppData. It can be invoked to gather only specified fields or to gather all data fields if the fields parameter is null. We will invoke it with the call loadAppData(null).The parameter for the callback method is optional. It does, however, allow your code to be notified when the data has loaded. var myLocalAppData = {}; //Empty object hash for local app data var appdataKey = "mydata"; //Key to use in DataRequest for retrieval
/** * Loads some or all of the app data into a local store variable * myLocalAppData * @param {Array} fields Array of fields to retrieve, * or null for all fields * @param {Function} loadedCallback Callback handler * to fire when the app data has loaded. */ function loadAppData(fields, loadedCallback){ var req = opensocial.newDataRequest(); if(fields == null){ fields = "*"; //Default to all data } var idparams = {}; idparams[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; idparams[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; var id = opensocial.newIdSpec(idparams); req.add(req.newFetchPersonAppDataRequest (id, fields), appdataKey);
App Data Store
req.send(function(data){ loadAppDataCallback(data, loadedCallback) }); } /** * Callback wrapper method for loadAppData. * This loads all the data into myLocalAppData * and triggers the loadedCallback function, if specified * @param {Object} data * @param {Function} loadedCallback */ function loadAppDataCallback(data, loadedCallback){ logDataError(data); if (data.hadError()) { return; //Exit if nothing found } var mydata = data.get(appdataKey).getData(); //App data has an additional layer of indirection. //We reassign mydata object to the data map object //Circumvent viewer lookup by getting key var ok = false; var vkey; for( vkey in mydata){ mydata = mydata[vkey]; ok = true; break; } if(ok){ for(vkey in mydata){ myLocalAppData[vkey] = mydata[vkey]; } } if(loadedCallback && typeof(loadedCallback) == "function"){ loadedCallback(myLocalAppData); } }
The big “gotcha” in using this technique is when your app is performing multiple reads and writes of data. Then you have to make sure the local store stays synchronized with the remote store or provide some mechanism for publishing unsaved changes in a reliable manner.This is a classic “readers-writers problem” and is easily solved with a semaphore and some retry time-out calls on the read operation (see the “ReaderWriters Problem, Ajax-Style” sidebar for more information).
53
54
Chapter 4 Persisting Information
Now that we have this nifty method, we’ll refactor the storage methods to be a little more generic and configurable.They may be set to use direct app data accessors (V1) or local store accessors (V2). Here is the example code to refactor the storage methods: //App data store code version - V1 (direct) //or V2 (local store) var getAppDataV1 = false; /** * Data initializer to load stored information */ function getInitialData(){ if(getAppDataV1){ getInitialAppDataV1(); } else{ getInitialDataV2(); } } /** * Get the discrete app data and initialize the view */ function getInitialAppDataV1(){ var req = opensocial.newDataRequest(); var fields = [ TTT.Keys.NAME, TTT.Keys.SCORE ]; var idparams = {}; idparams[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; idparams[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; var id = opensocial.newIdSpec(idparams); req.add(req.newFetchPersonAppDataRequest (id, fields), TTT.RequestKeys.VIEWERDATA); if(viewer == null){ req.add(req.newFetchPersonRequest (opensocial.IdSpec.PersonId.VIEWER), TTT.RequestKeys.VIEWER); } req.send(getDataCallbackV1); }
App Data Store
/** * Refactored load of initial data. * This utilizes the local store */ function getInitialDataV2(){ if(viewer == null){ getViewerData(); } loadAppData(null, getDataCallbackV2); } /** * Callback handler for getting app data and Viewer * @param {Object} data */ function getDataCallbackV1(data){ logDataError(data); var mydata = data.get(TTT.RequestKeys.VIEWERDATA).getData(); if(!viewer){ viewer = data.get(TTT.RequestKeys.VIEWER).getData(); } //This happens if app not installed if(!viewer){ log("APP NOT INSTALLED!") return; } else{ var key; var realData = null; for(key in mydata){ realData = mydata[key]; break; } writeNameAndScore( realData[TTT.Keys.NAME], realData[TTT.Keys.SCORE]); } }
/** * Loads the data from a hash object passed in * @param {Object} localAppData */
55
56
Chapter 4 Persisting Information
function getDataCallbackV2(localAppData){ writeNameAndScore(localAppData[TTT.Keys.NAME], localAppData[TTT.Keys.SCORE]); } /** * Get just the Viewer data from a personRequest */ function getViewerData(){ ... }
/** * Callback handler to initialize the Viewer object from a DataRequest * @param {Object} data */ function getViewerCallback(data){ logDataError(data); viewer = data.get(TTT.RequestKeys.VIEWER).getData(); if(!viewer){ log("APP NOT INSTALLED!") return; } }
Cookies Cookies are one of the most convenient quasi-persistent storage mechanisms known in the Web today.There is no other mechanism so convenient to read and write on both the server and the client. Cookies are also a no-no when it comes to apps. Back in the old days of the Web, circa 1997, everyone used to believe that cookies were the path to ultimate damnation and loss of privacy. Criminals were going to steal your credit card number, or the G-men were going to track your every move on the Web, loading your FBI file with a list of whoopee cushion suppliers and midget porn sites you had visited. Well, it turns out the criminals did steal your credit card number, but by hacking the database, not your cookies. And someone is tracking your every move, but it’s not the government. And your Web usage is only going into your ad-targeting profile. None of this has anything to do with why you shouldn’t use cookies.
Cookies
Why You Shouldn’t Use Cookies The single biggest issue with cookies is this: Your app is sharing a domain, and hence a cookie collection, with every other app in the MySpace universe. Why does this matter? Here are a couple of reasons: n
n
Reason #1: Your cookie is prone to being purged or overwritten by cookies from other apps. Reason #2: Your cookies may be read by any other app the user has installed or viewed.
Most modern browsers have a per-domain cookie limit of 20. It’s not uncommon for a user to have more than 20 apps installed. It’s also not uncommon for developers to be greedy or wasteful in their usage of cookies, should they go down that path. A single app could push your otherwise persistent data out of the browser’s cookie collection. It should also go without saying that you should never store sensitive data in a cookie. But let’s say it anyway: Never store sensitive data in a cookie. Especially on MySpace. Every single app has access to every single app-created cookie, so there is no privacy.The app data store, on the other hand, is nominally locked to the app. It’s also not secure enough to store any sensitive data, however, since data for any user is readable by your app. To illustrate all this, we’ll modify our Tic-Tac-Toe app to use a cookie instead of the app data store to store the player’s game name.Then we’ll write another app that hijacks our cookies.We have to modify our app so it can switch between app data store and cookie storage using a flag value.Then we’ll modify both the initialize and the save methods to check that flag to determine whether they should use app data storage or cookie storage. Here is how we add cookie storage to the app: var useCookieStorage = true; var getAppDataV1 = true; /** * Data initializer to load stored information */ function getInitialData(){ if(useCookieStorage){ writeNameAndScore(readCookie(TTT.Keys.NAME), readCookie(TTT.Keys.SCORE)); } else if(getAppDataV1){ getInitialAppDataV1(); }
57
58
Chapter 4 Persisting Information
else{ getInitialDataV2(); } }
/** * Set a new persistent cookie (or overwrite existing) * @param {Object} key * @param {Object} value */ function setCookie(key, value){ var cook = key + '=' + value + '; expires=1 Jan 2050; path=/'; document.cookie=cook; } /** * Read the given cookie * @param {Object} key */ function readCookie(key){ var cookies = document.cookie; var keyName = key + '='; var pos = cookies.indexOf(keyName); if(pos > -1){ pos += keyName.length; var endPos = cookies.indexOf(';', pos); if(-1 == endPos){ endPos = cookies.length; } return cookies.substring(pos, endPos); } return null; } /** * Sets the persistent value for the game in the * chosen data store * @param {String} key * @param {String} value */ function setGameData(key, value){ if(useCookieStorage){ setCookie(key, value); getInitialData(); }
Cookies
else{ setAppDataKey(key, value); } }
As you can see, the cookie mechanism is much more direct. It feels comfortable, easy, and as if it’s the right solution. It’s not.To show you why, we’ll build our Cookie Jacker app.
Building the Cookie Jacker App The Cookie Jacker is a fairly simple app for manipulating cookies. It has the facilities to set a specific cookie, display all current cookies for the site, set a bunch of cookies, and delete all your site-specific cookies. And all in just 170 lines of code, most of that being display logic. If you don’t want to type it all in, you can download it from our Google Code site (http://opensocialtictactoe.googlecode.com). If you just want to use it, you can install the app at www.myspace.com/cookiejacker. We’ll list just the methods of interest here.The following code should be fairly straightforward—there are set and read methods for specific cookies.There is one method (writeAllCookies) that steps through all cookies currently available and displays them in a table.There is a method to loop and add 200 cookies to your browser (setLotsOfCookies), and there is a method to clear all the cookies (deleteAllCookies). Here are the Cookie Jacker’s mere 170 lines of code:
Cookie Jacker
<script type="text/javascript"> function setNewCookie(){ var key = document.getElementById('txtCookieName').value; var val = document.getElementById('txtCookieValue').value; if(key.length == 0) return; setCookie(key, val); writeAllCookies(); }
function setLotsOfCookies(){ var i; for(i=0; i < 200; i++){ setCookie("testCookie_" + i, i); } writeAllCookies(); }
59
60
Chapter 4 Persisting Information
function setCookie(key, value){ var cook = key + '=' + value + '; expires=1 Jan 2050; path=/'; document.cookie=cook; } function readCookie(key){ var cookies = document.cookie; var keyName = key + '='; var pos = cookies.indexOf(keyName); if(pos > -1){ pos += keyName.length; var endPos = cookies.indexOf(';', pos); if(-1 == endPos){ endPos = cookies.length; } return cookies.substring(pos, endPos); } return null; } /** * First round design to load app data and Viewer */ function getInitialData(){ writeAllCookies(); }
function deleteAllCookies(){ var cookies = document.cookie.split(';'); var expires = ";expires=1 Jan 1950;path=/"; var kparts; for(var i=0; i < cookies.length; i++){ kparts = cookies[i].split('='); document.cookie = kparts[0] + '=' + expires; } writeAllCookies(); }
function writeAllCookies(){ var tbl = document.getElementById('cookieTable'); var body = tbl.getElementsByTagName("tbody")[0];
Cookies
while(body.childNodes.length > 0){ body.removeChild(body.firstChild); } var cookies = document.cookie.split(';'); if(cookies.length == 1 && cookies[0] == "") return; var kparts; for(var i=0; i < cookies.length; i++){ kparts = cookies[i].split('='); addTableRow(body, kparts[0], kparts[1]); } var ht = Math.min((25 * (1 + body.childNodes.length)), 400); body.style.height=ht+"px"; }
function addTableRow(table, cell1, cell2){ var row = document.createElement("tr"); row.appendChild(document.createElement("td")); row.appendChild(document.createElement("td")); row.childNodes[0].innerHTML = cell1; row.childNodes[1].innerHTML = cell2; table.appendChild(row); }
function log(message){ var errFeed = document.getElementById("messages"); if(errFeed){ errFeed.innerHTML += message + " "; } }
//Register to look for initial data gadgets.util.registerOnLoadHandler(getInitialData);
Add this code as a new app on the developer site (the full listing is on our Chapter 4 Google Code listing, http://code.google.com/p/opensocialtictactoe/source/browse/ #svn/trunk/chapter4). Now go back to the Tic-Tac-Toe app and change the flag to use cookie storage: var useCookieStorage = true;
Save and run this app now. Go ahead and set a name for yourself (we used “Melba”). Now go back to the Cookie Jacker app and view (or reload).What do you see? There it is—my name is “Melba,” as shown in Figure 4.1. Look closely and you’ll see a couple of other surprises—some other app (or apps) is placing what looks to be a tracking cookie on the browser as well. Take some time to play around with the Cookie Jacker app. If you push the Set Lots of Cookies button, you will see all your current cookies go away and be replaced with new cookies.This is actually an interesting way to see how many cookies your browser will store for a domain (Firefox stores 50).
Figure 4.1
Cookie Jacker app exposing cookies.
63
64
Chapter 4 Persisting Information
I hope the point has been made: Cookies are not a viable persistent storage mechanism for apps (though they can be used for transitory storage across surface navigation or page reloads). Note Apps (and any Web pages, for that matter) store their cookies under the context of the domain from whence they originated. All our examples show MySpace-hosted apps. Iframe apps that are hosted on a third-party server do not suffer from the same cookie vulnerabilities as are outlined in this chapter.
Third-Party Database Storage In recent years there has been a blossoming of third-party storage and server services available on the Internet (collectively referred to as “cloud services”).We’re not going to implement the use of third-party storage for this app, but it warrants mention. In ancient times (circa 1996), one could get a persistent IP address with a cable modem and set up a private server with a database.Then came dynamic IP addresses, which could be handled by a dynamic DNS service. Over time, database-hosting costs came down from the stratosphere to where using an ISP for your data and app services made more sense than personal hosting. Costs came down because of many factors: the rise of open-source databases like MySQL, the crash in per-megabyte storage costs, and a general increase in the knowledge and ease of hosting databases. A database is now a standard add-on for all but the most vanilla, Kmart-blue-light-special hosting packages. An ISP-provided dedicated database solution has many advantages. Most of these advantages involve the level of control you have over the underlying data structures. However, they have one fatal flaw that can be summed up in a single word: scale.We cover scaling in more depth in Chapter 13, Performance, Scaling, and Security, but we mention it here because it can have a dramatic effect on your app’s design. A single database server can easily handle tens of thousands of records.The heavier-weight databases might manage one to two million records on a dedicated server without too much trouble, provided the data architecture is reasonably well designed.The problem is that social network scale goes into the hundreds of millions. As a solution, a handful of cloud-computing (which used to be called “gridcomputing”) solutions are coming online.The most attractive aspects of these types of cloud services are that you pay only a sliding usage cost, and they handle both the infrastructure and the 3:00 a.m. calls. For service providers, you have a number of options. Amazon seems to have the most complete set of cloud storage products, from key/object storage to queryable data storage, and at a cost much lower than that of buying a rack system,T3, and full-time network admin. Google has a hosting service known as App Engine that has become very popular among app developers. Microsoft also has cloud services in beta for both data (SSDS, or SQL Server Data Services) and computing (Azure Platform). Aptana
Summary
(maker of the IDE being used in the course of this book) is also pushing a service (Aptana Cloud), and the word is that Sun Microsystems also has plans in the works. Expect this space to become even more crowded and competitive in the very near term. So to sum up, MySpace has over 150 million users as of this writing.The most popular apps have over ten million users. Don’t let database scaling limit your success.
Summary There are two persistence mechanisms available to apps for which you do not want to use an external storage mechanism: the app data store and cookies. Both provide simple key/value storage. Cookies, however, are vulnerable to being manipulated by other apps and are suited only for very transitory storage. Meanwhile, app data provides a private store on a per-app and per-user basis but should not be considered secure. External cloud services may be used for more complex and data-intensive storage needs. Ideally, you should pick a service that can scale to multiple servers, as single-server storage will be inadequate should your app gain widespread adoption. Note Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
65
This page intentionally left blank
5 Communication and Viral Features M
ost successful apps are spread through a few users; these users install the app, and then they tell their friends about it, and they tell their friends, and so on and so on. MySpace and OpenSocial have four built-in viral features designed to speed up and improve that process: 1. 2. 3. 4.
These four features make up the communication components that will help you spread your app virally. If you’d like to learn more about actually marketing and growing an app, see Chapter 14, Marketing and Monetizing. In this chapter we’ll cover each of these four viral features in detail, using examples built into our Tic-Tac-Toe application.
Using opensocial.requestShareApp to Spread Your App to Other Users Let’s start by looking at how opensocial.requestShareApp works.The requestShareApp function is essentially a request to install the app that is sent from one MySpace user to another. For example: 1. Susan has the Tic-Tac-Toe app installed. 2. The app provides the requestShareApp functionality via a button on the Canvas surface. 3. Susan invokes requestShareApp (see Figure 5.1) to invite Matt to also install the app and clicks Send.
68
Chapter 5 Communication and Viral Features
Figure 5.1
Figure 5.2
Screen shot of the requestShareApp function prompting a user to send an add request to friends.
Screen shot of the requestShareApp function inviting another user to add the app.
4. Matt logs in and sees a New App Invite in the Updates module on his Home page and clicks it, which takes him to the app invite. 5. Matt sees each app invite under Notifications S App Invites in his Mail Center (see Figure 5.2).
Using opensocial.requestShareApp to Spread Your App to Other Users
6. Matt clicks the Add Tic-Tac-Toe button and the Add App install modal dialog pops up, as shown in Figure 5.3. 7. Matt clicks Add and is taken to the app’s Canvas page, as shown in Figure 5.4.
Figure 5.3
Screen shot of the requestShareApp function prompting the user to install the app.
Figure 5.4
The user is transported to the app’s Canvas page.
69
70
Chapter 5 Communication and Viral Features
Communication Policies and Rules MySpace has several policies concerning communications or messaging in apps. The first policy is that most message types (requestShareApp, requestCreateActivity, requestSendMessage, etc.) require the user to agree to send the message. This is accomplished through the use of a modal pop-up dialog. The second policy is that the modal dialog can be shown only while on the app’s Canvas surface. Because of this requirement, all messaging happens on the Canvas surface. There is one exception to this rule, and that is app notifications. App notifications do not require the pop-up modal dialog and are not restricted to the Canvas. We’ll go into notifications in detail later in the chapter. The third policy is that there can be no reward for a user sending out a message. This means you can’t give players ten free carrots to feed their pet rabbit if they send out a bulletin. You’ll have to be a little slyer to get that bulletin sent!
Defining requestShareApp opensocial.requestShareApp has the following signature: opensocial.requestShareApp = function(recipients, reason, opt_callback,
opt_params)
The recipients parameter can be either an array of strings or a single string.This means that you can send an invite to multiple recipients, something that isn’t possible with requestSendMessage on the MySpace platform. MySpace actually allows integer IDs like 6221, integer IDs as strings, like "6221", or IDs in the form "myspace.com:6221". Any combination of these IDs can be placed inside an array or passed individually. The maximum number of recipients, as of this writing, is 20. Once the modal pop-up loads, the user also has another chance to manipulate the recipient list.The To: box in the pop-up actually has autocomplete functionality; after clicking inside the box, the user can type the name (display name, user name, or real name) of another recipient and select that user from the drop-down (see Figure 5.5).The user can also delete any current recipient. The reason object is an object of type opensocial.Message and is defined by OpenSocial as “the reason why the user wants the gadget to share itself.”The reason contains the content of the message that appears in the recipient’s Mail Center page.The intention is to make the app sound fun or interesting so the recipient will install it.The sender also sees a preview of the message before it’s sent, so it should be something the sender approves. The reason parameter does not allow HTML markup, but it does provide a simple templating system.The message can be up to 150 characters long, but that limit doesn’t include the following template variables: n
[sender]: Turns into a link to the sender’s Profile; the text is the sender’s display name.
n
[app]: Turns into a link to the app’s Profile; the text is the app’s name.
n
[recipient]: Turns into a link to the recipient’s Profile; the text is the recipient’s
display name.
Using opensocial.requestShareApp to Spread Your App to Other Users
Figure 5.5
As the user starts typing, a drop-down list of friends appears.
For example, your reason might read “[sender] wants you, [recipient], to install [app]” or “Hey, you, install this: [app].”The first example might render to something like this: “Susan wants you, Matt, to install Tic-Tac-Toe.” The last two parameters, opt_callback and opt_params, are optional. opt_ callback specifies the function to call once the request has been processed and the user has closed the Add App pop-up. opt_params is used to provide the function with additional parameters; however, MySpace doesn’t support any of the additional parameters, so opt_params can be safely ignored.
Writing the requestShareApp Code Now that we’ve defined our requestShareApp function, let’s take it for a test drive. The following code wraps the requestShareApp functionality so that you can use it throughout your application: function requestShareAppWrapper(id, body, callback){ // Create the message object var reason = opensocial.newMessage(body); // Initiate the share app modal opensocial.requestShareApp(id, reason, callback); }
This simple code starts out by creating an opensocial.Message object to use as our reason parameter. Only the body field of the message object is used, though; all other fields are ignored. Next, the recipient IDs, along with the callback function, are used to initiate the opensocial.requestShareApp function.
71
72
Chapter 5 Communication and Viral Features
Calling requestShareApp But how will we use this function throughout our Tic-Tac-Toe application? How will it be called? Typically, the IDs of the recipients are found by running a newFetchPeopleRequest API request and presenting your user with a list of the friends whom they can then invite to the app. Once the user selects some friends, their IDs will be passed into the requestShareApp function. We showed how to fetch a list of friends in Chapter 3, Getting Additional MySpace Data, so let’s build on that. Assume that each div tag containing a friend’s information has an onclick event handler.When invoked, that handler takes the ID of the clicked friend and adds it to an array. In the app we have a button with the following code: function rsaInviteButtonClicked(){ // TTT.Lists.itemClicked contains the list of friends // that were clicked if(TTT.Lists.itemClicked.length > 0){ // Create some catchy body text var body = "Hi [recipient]... [sender] wants you to come"; body += "play Tic-Tac-Toe, add [app] now!"; // Then pass the values into our wrapper requestShareAppWrapper(TTT.Lists.itemClicked, body, rsaWrapperCallback); } }
First, we check to see that at least one friend has been picked.We then define the actual reason text and pass it, along with the array of IDs, into the requestShareAppWrapper function we created earlier. But what about the callback? What’s it for?
The requestShareApp Callback The callback function is invoked either after the user has closed the modal pop-up prompt or if an error occurred before the pop-up prompt could be displayed. Once invoked, the callback is passed an opensocial.ResponseItem as a parameter.This ResponseItem behaves similarly to the way it did in API callbacks (see Chapter 2, Getting Basic MySpace Data, to learn how basic callbacks work).The difference is that the API callbacks were passed an opensocial.DataResponse object that contained opensocial.ResponseItem objects. Here we just have the opensocial.ResponseItem object as the response, so you can directly access things like hadError(), getErrorCode(), or getData(). Once the pop-up is shown, there are four possible outcomes: 1. The user accepts the request to share the app. In this case the value of getData() is the number 1. 2. The user cancels the request; in this case the response is 0.
Using opensocial.requestShareApp to Spread Your App to Other Users
3. Some error occurred with the page that loads inside the pop-up; in this case the response is the number ⫺1. 4. There was an error with your request syntax.This causes the hadError() function to return true. Details of this error are found using getErrorCode() and getErrorMessage(). One thing to remember is that once the pop-up has been shown, the user can adjust the recipients. So you may think you know who the recipients are going to be, but the user can completely alter that list.To get around that problem, MySpace pushes a couple of additional bits of data down into the callback function. In the following function we make use of this data; let’s take a look at how it works: function rsaWrapperCallback(response){ // Get the first clicked friend var current_list = TTT.Lists.getCurrentList(); var clicked; // Check for some kind of bad response, and show an error message if(!response || response.hadError() || -1 === response.getData()){ log("Oops, there was an error, try refreshing the page!"); } else{ // Revert all the friend boxes to a white background for(var i = 0; i < TTT.Lists.itemClicked.length; i++){ clicked = current_list.list_dom[TTT.Lists.itemClicked[i]]; if(clicked) clicked.style.backgroundColor = "white"; } // Reset the list TTT.Lists.itemClicked = []; // Was the pop-up not canceled? // i.e., were the invites sent? if(0 !== response.getData()){ // Array of IDs of recipients who were sent invites, // and those for whom the invite failed var success = response.responseValues.success; var failure = response.responseValues.failure; // Update the UI for the successes for(var i = 0; i < success.length; i++){ clicked = current_list.list_dom["myspace.com:" + success[i]]; if(clicked) clicked.style.backgroundColor = "green"; }
73
74
Chapter 5 Communication and Viral Features
// Update the UI for the failures for(var i = 0; i < failure.length; i++){ clicked = current_list.list_dom["myspace.com:" + failure[i]]; if(clicked) clicked.style.backgroundColor = "red"; } } } }
So, there is a lot going on here.The callback for requestShareApp is especially important.The first thing that really happens is that the various types of errors are trapped, and an error message is displayed if one is found. If there was no error, we cycle through the list of currently selected users, revert the background of the corresponding div tags to white, and reset the list.There are now two possibilities: the user either canceled the pop-up or hit Send. If the pop-up was canceled, there’s no more work to do. If the pop-up wasn’t canceled, the user must have hit the Send button, so we need to figure out who the actual recipients were.We do this by accessing the responseValues object in the ResponseItem that’s passed back to us. responseValues contains two arrays: One, success, contains the list of users who were successfully sent an invite.The other, failure, contains the list of users who had an error occur when the invite was sent. Both arrays contain the integer IDs of the specified users. There are a couple of things to note when accessing the success and failure arrays. First, users who already have the app installed won’t get the invite, but neither will they show up in either array. Second, the IDs in the array are integers, so they don’t exactly match the IDs that are sent by the API (in the format "myspace.com:6221"). Back to the function at hand.We extract the success and failure arrays and loop through them.We turn the background color of all the successful recipients to green, and that of all the failures to red.You’ll notice that we have to append "myspace.com:" to the beginning of each ID so it matches up with the IDs we fetched from the API. It may be useful to add a More button to your app, something like “Select Random 20” that will randomly select 20 of the user’s friends.This will help encourage users to share the app with a larger group of friends; turning 20 clicks into one click makes it much easier for your users.
Using opensocial.requestSendMessage to Send Messages and Communications Let’s examine how opensocial.requestSendMessage works.The requestSendMessage function provides a number of ways for apps to communicate with users. MySpace supports the following message types: n
n
Send Message: a private one-to-one message that will arrive in the user’s Mail Center in-box Comment: a public one-to-one message that will appear on the user’s Profile page in the Comments section
Using opensocial.requestSendMessage to Send Messages and Communications
n
n n
Bulletin: a one-to-many message that will appear in the Bulletins module of each of the user’s friends’ Home pages Blog: a one-to-many message that will appear on a MySpace user’s Blog Profile: not a message per se; allows an app to edit/update the user’s Profile.The following Profile sections can be edited and are chosen by the user in a dropdown menu: About Me I’d Like to Meet Interests Edit Artist Profile Movies Television Books Heroes
Defining requestSendMessage opensocial.requestSendMessage has the following signature: opensocial.requestSendMessage = function(recipients, message, opt_callback, opt_params)
You probably noticed that the signature for opensocial.requestSendMessage is very similar to that of opensocial.requestShareApp.The big difference is that you’re allowed to define only one recipient ID at a time; the container will reject an array of IDs. Similar to requestShareApp, however, are opt_callback, which is the function that’s invoked when the pop-up modal has closed, and opt_params, which is unused. Note Some targets don’t require a recipient; these are Bulletin, Profile, and Blog. Any recipient value passed in for these targets will be ignored.
The message parameter is an object of type opensocial.Message.The supported content of the message depends on the message type; here’s a quick breakdown: n
Types that support a message title are Send Message, Comment, Bulletin, and Blog. The title doesn’t support any HTML markup.
n
All of the message types support a message body. All support some HTML markup in the body.Tags like
Since bulletins don’t use any template messaging, we have to generate all the links ourselves.To do this, we make use of the instance of a MyOpenSpace.Application object for this app.When an app is rendered, the MySpace platform pushes down a script-accessible representation of the app’s information.This object may be accessed from the environment with the call opensocial.getEnvironment().currentApplication
Specific data that may be found in this object includes: 1. App ID, accessed via the field enum MyOpenSpace.Application.Field.ID 2. Name, accessed via the field enum MyOpenSpace.Application.Field.Name 3. Profile URL, accessed via the field enum MyOpenSpace.Application.Field. PROFILE_URL
4. Install URL, which for right now is the same as the Profile URL (which is where the app is installed from), accessed via the field enum MyOpenSpace. Application.Field.INSTALL_URL
5. Canvas URL, accessed via the field enum MyOpenSpace.Application. Field.CANVAS_URL
6. The 64⫻64 icon URL, accessed via the field enum MyOpenSpace.Application. Field.ICON_LARGE
7. The 16⫻16 icon URL, accessed via the field enum MyOpenSpace.Application. Field.ICON_SMALL
The Application object behaves just like the Person object—data is accessed through the getField function. For example, to access the app’s name in your script code, you would make the following call: opensocial.getEnvironment().currentApplication.getField( MyOpenSpace.Application.Field.NAME);
Here we use the app’s Profile URL and the large icon to generate the bulletin message. Some of the supported HTML tags are also used for the body.Then the wrapper function is called and voilà! We’ve sent our first message! Bulletins are great for getting the word out to a large audience, but they lack a personal touch. In our Tic-Tac-Toe app, one user can challenge another user to a game.
77
78
Chapter 5 Communication and Viral Features
When this challenge is initiated, we send out a message from the challenger to the challenged.The code for that looks like this: function rsmMessage(){ var current_list = TTT.Lists.getCurrentList(); var id = this.list_index; TTT.Lists.itemClicked = id; var this_app = opensocial.getEnvironment().currentApplication; var profile_link = this_app.getField(MyOpenSpace.Application.Field.PROFILE_URL); var image_link = this_app.getField(MyOpenSpace.Application.Field.ICON_LARGE); var subject = "I challenge you to a TTT duel!"; var name = ""; for(var i = 0; i < current_list.list.length; i++){ if(current_list.list[i].getId() == id){ name = current_list.list[i].getDisplayName(); break; } } // If the name isn't empty, add a space before the name name = ("" === name) ? name : " " + name; var body = "Hey" + name + "! You've been challenged to "; body += "a game of Tic-Tac-Toe, click "; body += "here to accept the challenge!
This code is fairly similar to the bulletins code.We use the MyOpenSpace. Application object to generate a message and then invoke the wrapper.There is also some app-specific code in this function that determines the ID and name of the challenged user; this ID is sent into the wrapper while the name is used to personalize the message. Adding a person’s name to a message is an old trick that helps the message seem a little less like a form letter.
Callback in requestSendMessage The callback for requestSendMessage works the same as requestShareApp. An error could be generated before the modal dialog is shown; otherwise the value 1, 0, or ⫺1 is returned.
Getting Your App Listed on the Friend Updates
Let’s take a look at one quick example: function rsmMessageCallback(response){ var div = TTT.Tabs.getCurrentContainer().firstChild; if(response && !response.hadError()){ if(0 === response.getData()){ div.innerHTML += "challenge cancelled..."; } else if(1 === response.getData()){ div.innerHTML = "challenge sent!"; } } else{ log("Oops, there was an error, try refreshing the page!"); } }
First we check for an error. If one was found, we display an error message asking the user to refresh the page. Most errors that occur with the messaging system are intermittent and can be fixed with a refresh. If there was no error, a simple message is displayed reaffirming the user’s action.
Getting Your App Listed on the Friend Updates with opensocial.requestCreateActivity Basics On every user’s MySpace Home page there is a module that displays the user’s Friend Updates.These updates are a feed and might include information like “John added a new photo,”“Mary and John are now friends,” or “Susan installed the Tic-Tac-Toe application.”These updates are ordered by date, and the newest information is always displayed on top. When an app creates an activity, the activity appears in this feed.That makes any app activity a one-to-many message that will appear in the Friend Updates feed for each of the user’s friends.With activities, applications can define numerous custom messages that will appear in a user’s Friend Updates. Activities can be created only from the app’s Canvas surface, but they’re a great way to embed your app into a user’s MySpace experience and promote your application at the same time.
Defining opensocial.requestCreateActivity opensocial.requestCreateActivity has the following signature: opensocial.requestCreateActivity = function(activity, priority, opt_callback)
This means it’s a function that must include an activity (opensocial.Activity), a priority (opensocial.CreateActivityPriority) setting for the request, and opt_callback as the function to call once the request has been processed.
79
80
Chapter 5 Communication and Viral Features
Note At the time of this writing, opensocial.CreateActivityPriority is not being checked or used by MySpace. You’ll notice in the code that follows that we always pass in a value of high (opensocial.CreateActivityPriority.HIGH) as opposed to low (opensocial.CreateActivityPriority.LOW). If you have opensocial.CreateActivityPriority in your code and MySpace starts making use of it, the behavior of your app may be affected, so it’s good to keep this in mind should your app suddenly start doing something.
Let’s take a quick look at how OpenSocial defines the priorities: High: If the activity is of high importance, it is created even if this requires asking the user for permission.This might cause the container to open a user flow that navigates away from your gadget. Low: If the activity is of low importance, it is not created if the user has not given permission for the current app to create activities.With this priority, the requestCreateActivity call never opens a user flow.
Using the Template System to Create Activities One of the most important elements of creating and raising activities is the template system. In fact, it’s so important that it needs to be explained before we start looking at code. Unlike messages, which are completely defined and passed into the function as static text, activities make use of a custom template system. Basically, you create a template for your activities’ messages and the variables are resolved at runtime.Templates must be used for activities. Every template must have a title containing up to a maximum of 160 visible characters. Each template may also optionally specify a body having up to 260 visible characters. Your message template is based on a text string with some optional variables (which you may occasionally hear referred to as “tokens”) thrown in.These variables are replaced by real data once the activity is raised. A basic activity’s message might look something like this: "Susan installed Tic-Tac-Toe on: ${date}."
When the template is run, you’ll specify that ${date} will be replaced with a string containing the current date and time. So, if you give the variable ${date} a value like “September 28, 2010,” the resulting message would read “Susan installed Tic-Tac-Toe on: September 28, 2010.”
Data Types In our first example, the ${date} variable was a string. However, you can also specify the data type of a variable.The two currently available data types are Literal and Person.
Getting Your App Listed on the Friend Updates
A Literal data type, used in our first date example, is any string.Your variable is then simply replaced by that straightforward string. A Person data type is slightly more complex. If a variable is defined as a Person data type, the variable is then replaced by a person’s display name and a link to the person’s Profile when it appears in the feed. For example, let’s say we have a template where the variable ${opponent} is of type Person. It might look like this: "You've been bested at Tic-Tac-Toe by ${opponent}."
To get this template message to display correctly, you need to pass in the opponent’s user ID. For example, if we pass in the string "6221" (Tom’s ID) for our ${opponent} variable, our message would read “You’ve been bested at Tic-Tac-Toe by Tom.” The word Tom would then link to Tom’s Profile.
Reserved Variable Names There are a number of variables that are reserved (see Table 5.2), but the most interesting one is ${sender}. This is because ${sender} is actually a required variable in your template title, meaning you’ll be using it a lot. The variable ${sender} is a Person-type variable, which means it’s replaced by the Viewer’s name and Profile link. For example, let’s say we changed our template to read "${sender} raised this event, making ${sender} the Viewer!"
If Susan were to raise an event with that variable, the resulting message would read “Susan raised this event, making Susan the Viewer!” Table 5.2
Reserved Variable Names
Reserved Variable Name
Use
${subject}
Replaced with a link to the Viewer’s Profile and the Viewer’s display name as the corresponding text
${subject.DisplayName}
Replaced by the Viewer’s display name (no link)
${subject.Id}
Replaced by the Viewer’s ID
${subject.ProfileUrl}
Replaced by the Viewer’s Profile URL
${canvasUrl}
Replaced by the app’s Canvas URL
${variable_name.Count}
Used when variables are aggregated and where variable_name is the name of a variable used in the template
81
82
Chapter 5 Communication and Viral Features
But if her arch-nemesis,Tom, raised the event, the message would read “Tom raised this event, making Tom the Viewer!” In each instance the Viewer’s information is used for the ${sender} variable.
Aggregation When a user has a large number of applications, and friends who like applications, the user’s feeds can get crowded with information and updates. Because of this, activity feeds are aggregated. If a user has five friends all playing Tic-Tac-Toe and raising activities for the app, all of those activities are aggregated into a single feed entry for Tic-Tac-Toe. For example, let’s create a new message template and see what would happen when it’s raised multiple times. Let’s start with a new template: "${sender} is playing Tic-Tac-Toe with ${opponent}."
In this example we’d want to aggregate the ${opponent} variable (you can learn how to specify aggregated variables by skipping ahead to the section on using the Template Editor). The first time I raise the event, my opponent’s ID is "6221" (Tom, again!).The resulting message reads “Susan is playing Tic-Tac-Toe with Tom.” If Susan raises the event again, this time challenging her friend Matt to a game, the resulting message reads “Susan is playing Tic-Tac-Toe with Tom and Matt.” And if Susan raises the event a third time, but this time challenging Tila Tequila to a battle of Tic-Tac-Toe, the resulting message would read “Susan is playing Tic-Tac-Toe with Tom, Matt, and Tila!” Now that’s a game I would like to see. Notice that not only does the templating system keep aggregating your message feeds, it also makes them grammatically correct by adding commas and the word and.
Body and Media Items We have variables and data types, but there’s more to a message template than that. What about pictures and the message itself? That’s where body and media items come into play. The body is similar to a template’s title, but it’s optional and can hold more characters. If you include a body, it displays on the second line under your specified title.
Getting Your App Listed on the Friend Updates
Media items can be any picture on MySpace that’s accessible to the Viewer. In Chapter 3, Getting Additional MySpace Data, we fetched a list of the Viewer’s photos, displayed them on the page, and allowed the player to select one for a custom board background. If a custom background is selected, it is used as a media item in any raised activity. You’re allowed to include a maximum of three media items in a message template. All will be rendered on the second line of the message.
Using the Template Editor to Create Templates Now that you know how templates work, you’re ready to create some new templates for your app.To do this, you’ll use the Template Editor tool found on your My Apps page. Under each application there is a tool entitled Templates (Figure 5.6); click it to be taken to your Templates page (shown in Figure 5.7). Click on Create Template to create new templates for your app.This will take you to the template creation screen. From this screen (Figure 5.8) you can edit existing templates or create a new one. Let’s look at an existing template for our Tic-Tac-Toe application.
Figure 5.6
Screen shot of My Apps S Templates link
Figure 5.7
Screen shot of an existing Templates list
83
84
Chapter 5 Communication and Viral Features
Figure 5.8
Screen shot of the Templates screen
On the individual Template screen, you can see all of the pertinent template information. Under Content you’ll find the template’s name and unique identifier along with the title and the body.There are also separate tabs for Single Form instances (when just one activity is raised) and Aggregate Form instances (multiple activities are raised). Under Variables, you can add and specify data types and even test values for each of your variables. Below this section are sample media items that you can use to test how they’ll appear when you preview or run your template. To test your template, click the Preview Template button.This creates a preview of your template in the bottom portion of the screen using the test data you indicated under Variables and Media Items. You’ll also be provided with sample JavaScript code that can be used to raise the event.You can actually just cut and paste this code into your app to begin raising activities, but you’ll most likely want to customize it (see “Raising the Event” in the following section). If you’re satisfied with your template, click the Save Template button to save your template for later use. Once your template is saved, you can switch it from development status to live status. To do this: 1. Go back to your Templates page. 2. Click the Publish button next to the template you want to make live. 3. Click OK when prompted. From your Templates page you can also delete or edit an existing template.
Getting Your App Listed on the Friend Updates
Using opensocial.requestCreateActivity Now that we understand what opensocial.requestCreateActivity looks like and how to construct a template, let’s actually use the function. Raising the Event The template we’re using for our activity is the following: ${subject} has started a game of Tic-Tac-Toe against ${opponent}
We’re doing something a bit tricky with the href attribute in the anchor tag.This actually allows us to send custom parameters into the Canvas surface of the app if the link is clicked.This can be especially useful for tracking purposes.You can try different messages, each with a different ${params} value, and see which one is clicked more often. The actual code to raise the event looks like the following: function raiseActivity(){ // Create the parameters var param = {}; // Required template name param[opensocial.Activity.Field.TITLE_ID] = "x_and_y_started_game"; // The actual parameter values param[opensocial.Activity.Field.TEMPLATE_PARAMS] = { "opponent" : currentGame.opponentId, "params" : "{\"from\":\"act\"}" }; // Check if a custom background is set to use for // a media item if(currentGame.customBG.usingCustomBG()){ // Get the photo object var photo = currentGame.customBG.photo; // Parse out the URI var uri = photo.getField(MyOpenSpace.Photo.Field.PHOTO_URI); // Create the opensocial.MediaItem object var media_item = opensocial.newMediaItem("image/jpeg", uri) // Stick it in an array var media_item_array = [ media_item ]; // Insert the array into the parameters param[opensocial.Activity.Field.MEDIA_ITEMS] = media_item_array; }
85
86
Chapter 5 Communication and Viral Features
// Create the opensocial.Activity object var activity = opensocial.newActivity(param); // Raise the activity! opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, raiseActivityCallback); }
First, the activity template is defined as "x_and_y_started_game".This is the unique identifier for the desired template and can be found in the Template Editor under Template Name. The template variables are then given actual values; the ${opponent} variable is assigned the value of the ID of the opponent, and the ${params} variable is assigned a JSON object.This is an example of how you might use different template messages for tracking purposes, since here we’re saying the user got to the Canvas page from an activity. Meanwhile, the two variables correspond to the list of variables in the Template Editor under Variables. The next block of code attaches a media item to the activity. A couple of things to note here: First, the media item URI must conform to an API-style URI and not a regular old URL, such as www.example.com/my_picture.jpg.The best way to get these API URIs is through the API itself, as we do here in the app. In our code we fetch the list of photos for a user and save those values into a list. When a photo is selected, we match it to the correct entry in the list and parse out the URI.This URI is accessed from the MyOpenSpace.Photo object using the MyOpenSpace.Photo.Field.PHOTO_URI. The second thing to note is that an activity requires an array of media items. So, even if you have only one media item, make sure to stick it in an array. Once all the parameters are set up, the opensocial.Activity object is created and it’s passed into requestCreateActivity. Note What are we doing there with the custom parameters in the template? Well, custom values can be passed into an app’s Canvas surface by appending an "appParams" key to the query string. So, for example, by appending &appParams={"hello"%3A"goodbye"%2C"from"%3A"act"} to the end of the Canvas URL, we pass the JSON object { "hello" : "goodbye", "from" : "act" } into the app. These values can be picked up inside the Canvas by doing the following: gadgets.views.getParams().hello; gadgets.views.getParams().from;
In this case, the first line resolves to "goodbye" and the second to "act".
Getting Your App Listed on the Friend Updates
Using Activity Callbacks to Combat Permission-Denied Errors Uh-oh! Permission denied? It turns out that a separate permission is required to raise an activity for a user. If this permission isn’t set, the container blocks the request and returns an error. So that’s that, I guess. Oh well, better luck next time… Not necessarily; opensocial.requestPermission to the rescue again! In a method similar to one used in Chapter 3, Getting Additional MySpace Data, where we requested permission to fetch photos, we can request permission here to raise an activity: function raiseActivityCallback(response) { // Check for an error if(response.hadError()){ // Was the error a permission issue? if(response.getErrorCode() === opensocial.ResponseItem.Error.UNAUTHORIZED){ // Beg for permission var reason = "To inform your friends of your upcoming match!"; // Pick which permission // STICK IT IN AN ARRAY!! var perm = [MyOpenSpace.Permission.VIEWER_SEND_UPDATES_TO_FRIENDS]; // Pretty please ... opensocial.requestPermission(perm, reason, actPermCallback); } else{ // Some other error log("Oops, there was an error, try refreshing!"); } } }
If there was an error, we first check whether it was a permissions error. If so, we specify why we want the permission and which permission we want. Again, don’t forget to stick the MyOpenSpace.Permission object into an array or it will be rejected. Once requestPermission is closed, it will invoke the specified callback function. Let’s take a look at it: function actPermCallback(response){ // Was permission granted? if(!response.hadError()){ // Yay! raiseActivity(); } }
87
88
Chapter 5 Communication and Viral Features
Very simple; if no new permissions were granted, the response has an error. No error means the permission has been granted, so retry the activity.This is a great way to ensure that the activity is sent while also providing a nice flow for the user.
Sending Notifications The fourth and final way to communicate with your users is the app notification. Notifications are great for turn-based games as they are a quick and easy way to let players know when it’s their turn in the game.This is exactly how we use them in our Tic-Tac-Toe app. It’s also highly regarded because it’s the only message type that doesn’t require the user’s confirmation. When using notifications, you have to watch that you’re not spamming your users.You could be shut down, or worse, you’ll annoy your user base and lose installs. But, if you keep it reasonable, notifications are a great way to increase user engagement. When a user gets a notification, he or she gets an indicator on the Home page saying a new notification has arrived. Clicking on the indicator takes the user to the Mail Center, where he or she will see the message in the notification folder. Each notification can have zero to two buttons to allow the user to take some action. In our Tic-Tac-Toe app, we tell users it’s their turn and provide one button to take them back to the Canvas page to play the game. Notifications are a MySpace-specific extension, but they are patterned after requestCreateActivity, so the code should be somewhat familiar. Let’s take a look at what that means: // Wrap requestCreateNotification function rsmNotification(recipient, game_id){ // Create the body text var body = "Hi ${recipient}, it's now your turn"; body += "in Tic-Tac-Toe!"; // Create the button that links to the Canvas var url1 = MyOpenSpace.NotificationButton.UrlTypes.CANVAS; var params1 = { "game_id" : game_id, "recipient" : recipient }; var text1 = "Take Your Turn!"; var button1 = MyOpenSpace.newNotificationButton(url1, text1, params1); // Create the button that links to the app's Profile var url2 = MyOpenSpace.NotificationButton.UrlTypes.APP_PROFILE; var text2 = "Check out Tic-Tac-Toe"; var button2 = MyOpenSpace.newNotificationButton(url2, text2); var param = {};
Notifications use a built-in template, similar to requestShareApp. However, only the variables ${recipient} and ${canvasUrl} are available, and you’ll need to use the activities-style variable format ${variable_name}, as opposed to the requestShareApp style of [variable_name]. The button is defined by a MyOpenSpace.NotificationButton object.This object has three fields: n
MyOpenSpace.NotificationButton.URL
n
MyOpenSpace.NotificationButton.PARAMS
n
MyOpenSpace.NotificationButton.TEXT
The URL can be one of two values: MyOpenSpace.NotificationButton. UrlTypes.CANVAS or MyOpenSpace.NotificationButton.UrlTypes. APP_PROFILE. You probably won’t want to take your users back to your app Profile, especially considering that only users who have installed the app receive notifications. Here, we want to take the user back to the Canvas instead. The PARAMS field allows us to define custom parameters that are sent into the Canvas page. In our Tic-Tac-Toe app, we append three custom parameters—essentially creating a tracking parameter.This parameter is used to let us know that a user came to the Canvas from a notification, what action the user wants to take, and which game the user wants to play. Once the button is created, we’re ready to create the MyOpenSpace.Notification object itself.We assign the body text first, using MyOpenSpace.Notification.Field.BODY, and then add the button using MyOpenSpace.Notification.Field.BUTTONS.The button has to be placed in an array, so if you have more than one button, you’d add each one to the array. Omitting the BUTTONS parameter or passing in an empty array would just attach no buttons to the message.
89
90
Chapter 5 Communication and Viral Features
Figure 5.9
The notification in the recipient’s Mail Center page
The notification is then sent off using a recipient ID, the notification object, and a callback.The recipient can be a single ID or an array of IDs, up to a maximum of ten. The callback behaves exactly like the other callbacks mentioned earlier, so we won’t go into detail. A sent notification will appear in the recipient’s Mail Center page; see Figure 5.9 for exactly how it’ll look. Tip Notifications use the permission MyOpenSpace.Permission.VIEWER_SEND_ NOTIFICATIONS. You may want to use opensocial.hasPermission (followed possibly by opensocial.requestPermission) to check that permission before attempting to send the message. See Chapter 3 to learn how to check and request permissions.
Summary The primary source of growth for most apps is friend-to-friend advertising. A user installs the app and then invites a few friends, or a posting appears in the Friend Updates feed with a link to the app. Either way, the app developer has written various activities, messages, and invitations as a way of advertising and seeding the application. It’s important to remember that while these tools must be used, they should never be abused. An app that’s spammy will quickly annoy users, leaving you with few installs and a declining user base. Note Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
6 Mashups and External Server Communications Tandheclever Web is a big place. A very big place.With lots of smart people doing lots of smart things. Sometimes other people get to use their smart ideas. Sometimes your needs are so specific that you have to write your own services.Whatever your needs, you will likely reach a point where the “out-of-the-box” offerings from OpenSocial on MySpace are just not enough to satisfy your needs.Thankfully, OpenSocial recognizes these needs and provides you with a mechanism or two for communicating with external servers. In this chapter we’ll add two different features to our app that are dependent on external server communications. Each feature will use a different technique.We will make use of existing services on the Web to create a “mashup”-style app. Communication with your own servers, and securing those channels, will be covered when we discuss other styles of applications.
Communicating with External Servers What Is an External Server? An external server is any server whose DNS address does not resolve to the same top-level domain as the main hosting page. The Web browser imposes multiple security constraints when dealing with an external server, particularly with regard to cookies and XMLHttpRequest (XHR) calls. In the case of apps, an external server can also be considered any server that is not under the control of MySpace. The two notions are close enough to be interchangeable for most discussions in this book. The main MySpace top-level domain is myspace.com, but all apps are hosted in the domain msappspace.com, also referred to as a “jail domain” since it restricts apps’ access to the parent page via the same-origin policy regarding source domains.
92
Chapter 6 Mashups and External Server Communications
OpenSocial recognizes that it can’t be all things to all people. In fact, it’s designed to be just some things to all people—namely, an API for exposing social information.To that end it really is designed for use in external applications and mashups. There are a multitude of techniques for communicating with external servers. If all you are doing is referencing static content, there are almost no constraints. If you want to do something a little more dynamic, like invoke a Web service, things are a little more complicated. As we said before, static content on external servers has very little in the way of constraints. So long as you use a fully qualified address, the image file will resolve from any server.This is a common technique for large Web sites.They make use of a content delivery network, or CDN. A CDN may be simple or complex. A simple CDN just offloads the bandwidth that would be used to serve static content from the dynamic app servers, leaving more bandwidth and processing power for handling dynamic requests. Most browsers also throttle the number of concurrent connections back to a single domain, so this technique allows the browser to download more files at once; therefore the page loads faster. Dynamic content is another story.There are a handful of well-established techniques for creating dynamic content, some legitimate, some nefarious.We’ll cover the wellestablished techniques here and touch on the nefarious ones in Chapter 13, Performance, Scaling, and Security.
Mashups Origin of Mashups A mashup is a Web site or Web application that seamlessly combines content from more than one source into an integrated experience. The first mashups were simply hackers reverse-engineering the map APIs from companies like Yahoo! and MapQuest to make interesting overlays, such as laundromats near you. Over time, the mashup was recognized as not cannibalizing business but being a new business and application model in the Web 2.0 universe. While direct information is cloudy, the term mashup itself is likely derived from a practice in music where two different-source music tracks are combined, often through digital manipulation, to create something entirely new. An example of this would be mixing Madonna’s “Like a Virgin” vocals over heavy drum and bass instrumentals.
Mashups are a combination of one or more services in a new way to make a new service or product that is different from the original. As companies have recognized the value of allowing external parties to use their services and infrastructure, the number of open APIs catering to mashup-style applications has proliferated widely. Several new business models have emerged, allowing larger
Adding a Feed Reader to Our App
providers to leverage their services and infrastructure for new revenue streams by providing so-called cloud services to third parties.This is in sharp contrast to the reaction to what we’ll call “proto-mashups” from the early days of the Web. Back then it was common practice for preportal aggregation sites to either deep-link to buried services within another site (for example, linking to buying concert tickets via TicketMaster from a band review site) or completely hijack a competitor’s content by using framesets to make their site look like the competitor’s.
Pitfalls of Deep Linking A number of court cases have resulted in deep linking being declared illegal. The decisions were largely based on the fact that the deep linker/framer (utilizing site) used the content for commercial gain without the consent of the content generator (service site). The practical reasoning is that the utilizing site was using the service site as a nonconsenting content provider and bypassing the service site’s advertising to show the utilizing site’s own ads. This was a contentious issue for some time—so contentious, in fact, that the W3C felt the need to publish a paper arguing that deep linking should be legal since that is one of the major ways information interacts on the Web. In practice, deep linking has been difficult to prosecute. A cease-and-desist letter has been the action of choice for any company attempting to protect its content, and it has usually been successful. Almost every major Internet player has some sort of open API to cater to mashup applications. Content feeds continue to be a major component. As we transition to “Web 2.5/3.0,” consisting of cloud services and user-generated content, a number of new APIs are also emerging. More obvious and pedestrian applications come in the form of hosted databases (like Amazon’s SimpleDB service) and various app-hosting services. Among the newer services are those that help spread the reach of user-generated content across the Web, like Google’s Blogger Data API, Digg’s user ratings, and MySpace’s own PostTo endpoints.
Adding a Feed Reader to Our App We’ll now extend our app by adding a feed reader.This feature allows your users to never have to leave their game to keep up with the latest happenings on the Web. In the interest of theatrics, we’ll do this as a contrasting implementation in three parts.We’ll add a standard set of feeds for the user to select from.Then we will demonstrate three different implementations using makeRequest: n n n
Manual display using the FEED content type Manual display using the DOM content type Raw text response of the feed with TEXT content type
93
94
Chapter 6 Mashups and External Server Communications
XMLHttpRequest The technique of using an XMLHttpRequest (XHR) object to communicate with a backend server without completely rewriting the page is often alternately referred to as “Ajax” (Asynchronous JavaScript and XML). The term Ajax continues in common usage, though most sites employing this technique have now dropped XML as the transport mechanism in favor of the JSON (JavaScript Object Notation) format for a number of reasons: its ease of use from within JavaScript code, poor cross-browser compatibility and coding overhead associated with client-side XML processing, and JSON’s typically smaller packet size. All the OpenSocial REST endpoints support both XML and JSON return formats, with JSON being the default and the format used within the JavaScript client library. The term REST stands for Representational State Transfer. The REST endpoints and how to use them are discussed at length in Chapter 9, External Iframe Apps. XHR may be used synchronously or asynchronously, but most implementations are asynchronous since asynchronous implementations don’t cause the page to stop functioning during communication and generally deliver a better user experience.
Overview of gadgets.io.makeRequest The call gadgets.io.makeRequest is the standard way for apps to call out to an external server.This is the only officially supported technique for making external server calls in the OpenSocial specification. It is also the only technique that is allowed on all three surfaces. A makeRequest call is a powerful and flexible wrapper on top of the XMLHttpRequest (XHR) object built into all modern browsers.The makeRequest call wraps a batching mechanism on top of the XHR request and hides the ugly implementation details. If you have a special, well-known data type, it also provides several convenience formatters that will preprocess the response.You as the developer only need to supply a callback function that receives the response and does something useful with it. As you may have gleaned, makeRequest uses the same underlying communication mechanism as all the built-in OpenSocial endpoints.The difference is that the makeRequest call is designed to handle external server communication. In order to get around the same-origin policy applied to all XHR calls, the call to an external server is bounced off a proxy server that lives within the msappspace.com jail domain. The proxy is a resource shared by all apps on MySpace. As such, MySpace imposes some throttling restrictions on the number of requests an app may make within a certain time period. Particularly bad or sloppy apps have been known to take the proxy down entirely in the early days of the MySpace Open Platform. Now these apps are more likely to be suspended if they start adversely affecting the proxy servers’ performance. Even with this policy, the proxy is subject to slowed responses during peak load hours.
Adding a Feed Reader to Our App
The makeRequest call may be invoked as follows: gadgets.io.makeRequest(url, callback, opt_params)
where url indicates the URL of the service being invoked, callback is a function that is invoked when the data is received, and opt_params is an optional object hash of parameters to the request. By default, this call issues a GET request to url and invokes the function callback with the unprocessed raw text in the data response. As we alluded to before, makeRequest is more than just a wrapper on top of an XHR request. It provides many optional parameters that, depending on what kind of data service you are invoking, can prove extremely useful.These parameters can specify things like content preprocessing, security authorization, raw headers, and a specific HTTP method. For reference, optional parameters to gadgets.io.makeRequest are specified in Table 6.1. All optional keys are enum values from the enum gadgets.io. RequestParameters. In general, the string specified in the “Key” column will work, but it is good programming practice to use the enum value. For example, the key AUTHORIZATION is specified as gadgets.io.RequestParameters.AUTHORIZATION.
Table 6.1
Option Parameters to gadgets.io.makeRequest*
Key
Description
AUTHORIZATION
The type of authentication to use in the request; can be one of gadgets.io.AuthorizationType.NONE, gadgets.io.AuthorizationType.SIGNED, or
CONTENT_TYPE
The type of content you want to treat the response as; can be one of gadgets.io.ContentType.DOM, gadgets.io.ContentType.FEED, gadgets.io.ContentType.JSON, or
GET_SUMMARIES
If the content is a feed, whether to retrieve the summary fields for the feed, can be either true or false (default).
HEADERS
Headers to pass along in the request; should be an object containing key/value pairs corresponding to the headers to be sent to the server; for example,
Chapter 6 Mashups and External Server Communications
Table 6.1
Continued
Key
Description
METHOD
The HTTP method of the request; can be one of gadgets.io.MethodType.DELETE, gadgets.io.MethodType.GET, gadgets.io.MethodType.HEAD, gadgets.io.MethodType.POST, or gadgets.io.MethodType.PUT
NUM_ENTRIES
If the content is a feed, the number of entries from the feed to retrieve; should be specified as a number (the default at the time of this writing is 3).
POST_DATA
If the method is a POST, the data to pass to the other server. Data can be passed to the MySpace container either as an object containing key/value pairs or as an encoded string. The OpenSocial specification currently states that data should be only a string, but the MySpace OpenSocial container still honors both the object and the string format. Example as an object: { data1 : "test", data2 : 123456 }
Example as a string: data1=test&data2=123456
In order to convert simple objects to a string, you may make use of either the utility method gadgets.io.encodeValues or gadgets.json.stringify. REFRESH_INTERVAL
How long in seconds the response from this request should be kept in the container’s cache; should be specified as a number. The default interval is one hour, but this is subject to the browser and container’s cache implementation.
*Reprinted from Google (http://code.google.com/apis/opensocial/articles/makerequest-0.8.html) and used according to terms described in the Creative Commons 2.5 Attribution License (http://creativecommons.org/licenses/by/2.5/). Find the latest specification at www.opensocial.org or http://wiki.opensocial.org/index.php?title=Gadgets.io_(v0.9).
Response Structure The response that is returned as a parameter to the callback method is a JSON object and follows a predictable structure.This structure includes error messages, raw response, security information, and processed data.Table 6.2 identifies the properties of the makeRequest response object.
Parsed/processed data if a CONTENT_TYPE other than gadgets.io.ContentType.TEXT is specified
errors
Array of any errors that occurred when making the request, typically request errors, for example, 404 or 500
text
Raw text of the response; useful if you are performing partial content rendering, as is common when using Ruby on Rails
The actual content of the data field varies depending on the CONTENT_TYPE specified in the initial request. In the case of a TEXT content type request, the value of data is the raw text response and matches the value of the text field. For all other content types, it is some sort of JSON object representation of the data.
Handling JSON Content MySpace disallows the use of an eval statement, so the only two ways to process JSON data are by calling gadgets.json.parse or by using makeRequest.The CONTENT_TYPE parameter must be set to gadgets.io.ContentType.JSON for the response text to be processed as JSON. When a makeRequest call is made with the JSON content type, the parsed JSON object is placed in the response data property.The content of the text property is the raw, unevaluated JSON text.This method works on any app surface (Home, Profile, or Canvas). On the Canvas surface, only you can use a JSONP request to get JSON data (discussed later in this chapter in the section “Overview of JSONP”).
Handling Partial HTML Content When making a request for partial HTML content to be rendered directly into the page, your best bet is to use the default TEXT format (gadgets.io.ContentType.TEXT). Since the raw HTML is written directly into the innerHTML of some element on the page, no processing is needed.This technique is analogous to Ruby on Rails’s partials or using the Ajax.Updater from the Prototype JavaScript library.
Handling RSS Feed Content RSS feeds can be directly processed in the makeRequest call by specifying a CONTENT_TYPE of gadgets.io.ContentType.FEED.When this is done, the makeRequest response contains a processed JSON object that represents the feed.This can also be used in conjunction with the GET_SUMMARIES parameter to include summaries in the feed request.
97
98
Chapter 6 Mashups and External Server Communications
RSS feeds are widely available services on the Internet. Many sites make use of this fact to act as content aggregators. Later in this chapter, under “Setup and Design of the Feed Reader,” we will use a feed to add our own news reader to our Tic-Tac-Toe game.
Handling XML Content Raw XML content may be handled in one of two ways: by using the default TEXT format and managing your own XML processor in the browser, or by specifying a CONTENT_TYPE of gadgets.io.ContentType.DOM and having the XML document loaded into an actual DOMImplementation.This Document object is placed in the data property, and the raw response XML text is placed in the text property. Once you have the content loaded into the data DOM object, you are able to use the full DOM API in all its glory. Statements like the following may be used to select nodes: response.data.getElementsByTagName("item");
This can prove to be very useful when dealing with proprietary APIs. Even on occasion a well-known data type must be handled this way if the provider is not well conforming. This allows you as the developer to write more robust code, if you have a need. Another way in which this is useful is when applying XSLT transforms to the XML for display. If you wish to look further into this technique, it involves using the following methods (depending on your browser): n
DOMDocument.transformNode() (Internet Explorer)
n
XSLTProcessor.importStylesheet() and XSLTProcessor.transformToFragment() functions (Firefox and Safari)
Creating the XSLT object can be a little cumbersome because of browser compatibility issues. Maintaining the transforms can be problematic as in-browser debugging tools are poor at best and there are some minor implementation differences between browsers. It is not impossible, but we leave it to the reader to explore this technique.
“User’s Pick” Feed Reader Our mashup example is a user-driven feed reader.The user can pick a feed from our market-tested and carefully peer-reviewed (read: random) drop-down list of available feeds.The user can then choose to do a one-time read or have the list refresh periodically, à la PointCast Network.
Setup and Design of the Feed Reader This is a simple reader.The user can pick one of a preselected list of RSS source feeds from a drop-down.The user can also choose to have the feed continuously updated by selecting a check box. The first step is building the UI for our feed reader. It will consist of a drop-down list, a format (content type) radio button selector, an action button, and a display surface.
Adding a Feed Reader to Our App
For our feed reader we’ve selected the following RSS feeds: n n n n n n
Digg CNET Lolcats Mashable Slashdot Hulu
Following is the HTML that constructs the user interface. Add this code to our app on the Canvas surface code immediately below the "myinfo" div element.
Feed Items
<select name="feedSource" id="selFeedSource" >
Feed XML Text
99
100
Chapter 6 Mashups and External Server Communications
The basic elements we just added are
n
Select list of feeds Request format radio buttons (for testing—will be removed later) Action button to load the feed
n
Empty element "rssFeed" that will display the feed
n n
Now that the UI is built (as shown in Figure 6.1), we need to add the loadFeed() function, which is called from the button click event.This function controls the makeRequest call for the feed. Add the following code in our JavaScript source block below the TTT object: function loadFeed(){ var feedUrl = "http://www.digg.com/rss/index.xml"; //Default to Digg var params = {}; var format = gadgets.io.ContentType.FEED; params[gadgets.io.RequestParameters.CONTENT_TYPE] = format; params[gadgets.io.RequestParameters.NUM_ENTRIES] = 5; gadgets.io.makeRequest(feedUrl, feedCallback, params); }
As listed, this call is hard-coded to pull the Digg feed and take the result in the FEED format. It also specifies to send down the first five entries. By default only the top three entries are loaded when the FEED content type is specified. In this method is a callback reference to a function called feedCallback.This function processes the response and formats it for display.The simple implementation of the callback looks like this: function feedCallback(response, format){ if(response.errors && response.errors.length > 0){ showFeedError(); } else{ showFeedResults(response.data); } }
You will notice that the error handling from a makeRequest call is somewhat different from that of some of the other OpenSocial data calls.The makeRequest call holds its errors in a simple array, whereas the other OpenSocial calls use getter functions to test for errors. In that regard, the error handling from a makeRequest call is a little more straightforward.We just have to check the error’s property and make sure it is empty. Our simple example must be expanded upon to satisfy the behavior specified earlier in this section. The first order of business is some display housecleaning and
Adding a Feed Reader to Our App
Figure 6.1
Feed reader user interface in our application.
the addition of support for the user-selected values. The DOM elements are first cleaned up on each request. Because we are supporting multiple possible sources and multiple possible content type formats, the code must also read which items the user has selected. The expanded listing of our code follows: function loadFeed(){ var errElem = document.getElementById(“feedItemErrors"); errElem.innerHTML = ""; var elem = document.getElementById("rssFeed"); elem.innerHTML = "...Loading feed..."; var picked = document.forms[0].elements['feedSource']; var feedUrl = getSelectValue(picked) || "http://www.digg.com/rss/index.xml"; //Default to Digg;
101
102
Chapter 6 Mashups and External Server Communications
var typeRadio = document.forms[0].elements['feedformat']; var formatVal = getRadioValue(typeRadio); var format; switch(formatVal){ case "FEED": format = gadgets.io.ContentType.FEED; break; case "DOM": format = gadgets.io.ContentType.DOM; break; default: //text format = gadgets.io.ContentType.TEXT; break; } // Initialize the request to treat it as a feed var params = {}; params[gadgets.io.RequestParameters.CONTENT_TYPE] = format; params[gadgets.io.RequestParameters.NUM_ENTRIES] = 5; var callback = function(response){ feedCallback(response, format); } gadgets.io.makeRequest(feedUrl, callback, params); } function feedCallback(response, format){ var errElem = document.getElementById("feedItemErrors"); if(response.errors && response.errors.length > 0){ errElem.innerHTML = "Error:" + response.errors[0]; showFeedResults(response.text, gadgets.io.ContentType.TEXT); } else{ showFeedResults(response.data, format); } }
/** * Obtains the selected radio from radio input control(s) * @param {Object} radioInput */
Adding a Feed Reader to Our App
function getRadioValue(radioInput){ var checkedId=0, i; if(radioInput){ for(i=0; i < radioInput.length;i++){ if(radioInput[i].checked){ checkedId=i; break; } } return radioInput[checkedId].value; } return null; } /** * Obtains the selected option from a single item select list * @param {Object} selectInput */ function getSelectValue(selectInput){ if(!selectInput) return null; if(selectInput.selectedIndex == -1){ return null; } return selectInput[selectInput.selectedIndex].value; }
In order to carry the specified format value forward for the purpose of understanding how the response data is to be displayed, we have wrapped our callback in an anonymous function that passes down the response as well as the data format in a closure variable named format. Added to the listing are two convenience methods for getting correct values from the form fields. Now we will move on to actual data display.The display is handled by a function showFeedResults.This function determines what format is being consumed and takes proper action.You can see the skeletal listing here: /** * Display feed results. Parsing depends on format specified. * @param {Object} feed * @param {Object} format */ function showFeedResults(feed, format){ var elem = document.getElementById("rssFeed"); elem.innerHTML = ""; var titleElem = document.createElement("h3"); titleElem.style.marginTop="0"; titleElem.style.paddingTop="0";
103
104
Chapter 6 Mashups and External Server Communications
var title, copyright, items, desc; var i, entries; var line, link, body; var item; copyright=null; var tmpElem, tmp; var feedBody = document.createElement("div"); if(format==gadgets.io.ContentType.FEED){ // Do JSON FEED formatting } else if(format==gadgets.io.ContentType.DOM){ // Do XML parsing } else{ // Show raw text } titleElem.innerHTML = title; elem.appendChild(titleElem); //Honor the copyright if(copyright != null){ var cp = document.createElement("div"); cp.style.fontSize="7pt;" cp.style.color="#FFA"; cp.style.fontWeight="bold"; cp.style.fontFamily="Arial"; cp.innerHTML = "Copyright " + copyright; elem.appendChild(cp); } elem.appendChild(feedBody); }
FEED Content Type The FEED content type is the most obvious choice to use when processing an RSS feed.The makeRequest object automatically processes the raw XML feed data and parses it into a JSON object to be consumed.The structure of the JSON object mirrors the structure of the RSS feed. Constructing the display is a simple matter of iterating over the item array and building up our listings. Since all items are in JSON format, the code can directly access the values as properties. In the case of our code, we build up DOM elements for each entry (item) in the feed. Each line consists of a hyperlinked title and a truncated description.
XML Content Type with Parsing Why, you might ask yourself, would I want to manually parse an RSS feed as an XML document when there is a perfectly good feed reader built into makeRequest? The answer partially lies in the false premise of the question. Specifically, the feed reader built into makeRequest is not “perfectly good.” It is good, true, but it also has many flaws. Most noticeably, at the time of this writing, when it encounters a feed that doesn’t parse cleanly or is missing some required elements, it just dies. No error you can trap. No notification. It just dies, and the exception is swallowed.The irony of this situation is that this error occurs most often on feeds from FeedBurner, which was recently acquired by Google (Google also provides the underlying implementation code for gadgets.io.makeRequest). The second half of why you, as a developer, might want to do things the hard way is a simple and unfortunate truism of developing against an external API:You can never fully trust the stability or robustness of someone else’s API. This is a general
105
106
Chapter 6 Mashups and External Server Communications
coding truth learned by the authors over many years and through many scars. To that end, we will be equipping you with some tools and skills to overcome life’s little challenges. In the case of our code, it is almost identical in structure to process this as XML or as a JSON object.The only difference is in the use of the DOM API methods. Since the data coming back is a DOMImplementation, you are able to use all the familiar DOM API methods, such as getElementsByTagName.You are used to using the DOM API directly and aren’t one of those lazy developers who’s hooked on some fancy-schmancy JavaScript framework like jQuery or Prototype, aren’t you? Since the elements in this DOM object do not have explicit ID values for selection, they must be selected by traversing the node tree.To that end, we have created a convenience method for safely extracting the value of an element from a selected DOMElement list, getFirstDomNodeContents, which is at the bottom of this code listing: else if(format==gadgets.io.ContentType.DOM){ /* * Structure of an RSS XML document: * /rss/channel/[title,link,description,...] | /[copyright]|item/** */ var allChannels = feed.getElementsByTagName("channel"); var channel; if(allChannels && allChannels.length > 0){ channel = allChannels[0]; if(channel){ title = getFirstDomNodeContents(channel.getElementsByTagName("title")); copyright = getFirstDomNodeContents( channel.getElementsByTagName("copyright")); items = channel.getElementsByTagName("item"); if(items && items.length){ entries = Math.min(5, items.length); for(i=0; i < entries; i++){ item = items[i]; line = document.createElement("div"); body = document.createElement("div"); link = document.createElement("a"); line.appendChild(link); link.href = getFirstDomNodeContents( item.getElementsByTagName("link")); link.target = "_blank"; link.innerHTML = getFirstDomNodeContents( item.getElementsByTagName("title")); desc = getFirstDomNodeContents( item.getElementsByTagName("description")); if(desc){ body.innerHTML = desc.substr(0, Math.min(120, desc.length)); }
/** * Convenience method to get first items from a nodelist * @param {Object} nodelist */ function getFirstDomNodeContents(nodelist){ if(nodelist && nodelist.length > 0){ return nodelist[0].textContent; } else{ return null; } }
Because the use of the DOM (aka XML) content type is slightly more robust than the use of the FEED content type, your code can be designed to accommodate some error conditions. In the case of a FEED parse failure, the code simply dies.The underlying cause is often malformed or invalid XML in the feed.When the DOM content type is used, the response continues processing and allows your code to handle the error. A parsing error is reported, but the original response text is still placed in the text property of the response, so you have an opportunity to recover.This is where using the TEXT content type can come into play.
TEXT Content Type If our feed encounters an error, we’ll simply display the raw response as text, along with an error message.We’ll also make available the TEXT content type for raw debugging and demonstration purposes. In the case of an error in XML processing, the code changes the response format reported to showFeedResults as being TEXT. At this point we can just dump the results with a little escaping. Almost. function feedCallback(response, format){ var errElem = document.getElementById("feedItemErrors"); errElem.innerHTML = ""; if(response.errors && response.errors.length > 0){ errElem.innerHTML = "Error: " + response.errors[0]; showFeedResults(response.text, gadgets.io.ContentType.TEXT); }
107
108
Chapter 6 Mashups and External Server Communications
else{ showFeedResults(response.data, format); } }
function showFeedResults(feed, format){ if(){ //... (Code not shown for brevity)
else{ //Text title = "[RAW RESPONSE]" var pre = document.createElement("pre"); if(feed && typeof(feed) === "string"){ // App source is incorrectly escaped, // so you need to construct the escape sequence with two strings var es = "&"; var gt = "gt;"; var lt = "lt;"; tmp = feed.replace("<", es + lt, "g"); tmp = tmp.replace(">", es + gt, "g"); pre.innerHTML = tmp; feedBody.appendChild(pre); } else{ feedBody.innerHTML = "Huh?"; } } ... }
There are three curious lines in this code snippet. Instead of simply using a standard angle bracket escape sequence (> and <) when formatting the response text for display, our code needs to build them up.This is because of an oddity of the MySpace platform and how it saves app source. As part of the saving process, the code is run through a minimal security filter.This filter resolves any escape sequences in the app code to ensure that nothing nefarious slips past the reviewers.The usefulness and wisdom of running this sort of a processor over app code may be a subject that is open to debate.The reality is that this is a subtle yet significant “gotcha” that you must be aware of. As an alternative, you can make use of the utility method gadgets.util.escapeString instead of performing manual string manipulation.This accomplishes encoding the markup without the headache of confusing the MySpace security filters.
Adding a Feed Reader to Our App
Adding a Feed Refresh Option Contrary to what you might think, the makeRequest parameter REFRESH_INTERVAL does not control an autorefresh.This is a directive to aid the container in understanding whether it can local-cache the results of a feed request. Instead we will use a simple setTimeout directive. The first step is to create a new wrapper function for the load event that safely loads the Word of the Day feed and initializes the game. Each function call is wrapped in a try/catch to ensure that if one fails, it doesn’t kill the app entirely.We also have to change the gadget registerOnLoadHandler call to point to this new method. function loadInitializer(){ try{ loadWordOfTheDay(); } catch(ex){} try{ initializeGame(); } catch(ex){} }
//Register to look for initial data gadgets.util.registerOnLoadHandler(loadInitializer);
Note that the call to gadgets.util.registerOnLoadHandler must be placed after the loadInitializer function is declared. Otherwise the function pointer will be undefined and the code won’t work.We’ve also placed every initialization call into a try/catch block.This is so that if one fails, it will not affect the other. The next step is to tie the autorefresh check box (the code is not shown—the ID of "chkRefreshFeed") to a parameter and refactor out the actual makeRequest call into an independent function that can be invoked via a setTimeout call.The refactored function takes all the values we trapped as variables.This way, the setTimeout call can carry forward the calculated parameter values within closure variables and not lose the information. Any interval larger than zero is recognized as a call to autorefresh via a setTimeout call. function loadFeed(){ //... (Not showing code section for clarity) var refreshFeed = document.getElementById("chkRefreshFeed").checked; var interval = 0; if(refreshFeed){ interval = 3 * 60 * 1000; // Every three minutes } ...
109
110
Chapter 6 Mashups and External Server Communications
loadFeedWithOptions(feedUrl, format, interval); } /** * MakeRequest call with resolved parameters. * @param {Object} url * @param {Object} format */ function loadFeedWithOptions(url, format, refreshInterval){ // Initialize the request to treat it as a feed var params = {}; params[gadgets.io.RequestParameters.CONTENT_TYPE] = format; params[gadgets.io.RequestParameters.NUM_ENTRIES] = 5; var callback = function(response){ feedCallback(response, format); } gadgets.io.makeRequest(url, callback, params); if(refreshInterval && refreshInterval > 0){ window.setTimeout(function(){ loadFeedWithOptions(url, format, refreshInterval); }, refreshInterval); } }
In the code we hard-coded the interval to three minutes (3 min ⴱ 60 sec/min ⴱ 1000 ms/sec). If you make this interval too short, your app will just start thrashing the proxy. If MySpace determines that your app is adversely affecting the proxy through too many calls within too short a time, your app could be subject to throttling (just disregarding or denying extra requests) or, in the worst case, suspension.
Feed Automation Candy No proper push app (now commonly known as a feed reader) is complete without taking the user action out of the user experience.To that end, we’ll close this section out by adding a “Word of the Day” feature to our app. After all, nothing says Tic-Tac-Toe like the Word of the Day. We need a few divs for data display ("wordoftheday", "wodDesc", and "wodcopyright").Then we need to modify the loader function to also load the Word of the Day:
Word of the day is: <span id="wordoftheday">
Wordsmith.org word of the day
Adding a Feed Reader to Our App
The implementation of getting the Word of the Day and displaying it should be fairly familiar by now. It entails a function to encapsulate the makeRequest call and a callback handler to display the results. /** * Word of the Day */ function loadWordOfTheDay(){ var feedUrl = "http://wordsmith.org/awad/rss1.xml"; // Initialize the request to treat it as a feed var params = {}; params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.FEED; params[gadgets.io.RequestParameters.NUM_ENTRIES] = 1; gadgets.io.makeRequest(feedUrl, loadWODCallback, params); } function loadWODCallback(response){ var feed = response.data; var elem = document.getElementById("wordoftheday"); var desc = document.getElementById("wodDesc"); var copy = document.getElementById("wodcopyright"); elem.innerHTML = ""; copy.innerHTML = feed.copyright; if(response.errors && response.errors.length > 0){ elem.innerHTML = "error" } else{ var wod = feed.items[0]; elem.innerHTML = "" + wod.title + ""; desc.innerHTML = wod.description; } }
Secure Communication with Signed makeRequest Secure communications are extremely important when calling home to your own servers. OpenSocial makes use of OAuth to make secure calls back to an external server. This technique involves the use of a shared secret in order to verify the source of the request and that the request hasn’t been altered.This topic is large and complex enough to warrant its own chapter so will not be covered here. See Chapter 8, OAuth and Phoning Home, for more information on secure server communications.
111
112
Chapter 6 Mashups and External Server Communications
Adding an Image Search The second feature we’ll add is an image search. In case your user is in the middle of an intense Tic-Tac-Toe session but suddenly receives a tweet on his or her phone about Angelina Jolie’s new beehive hairdo and needs to search for what that looks like, the user will be able to perform that search without ever leaving the game. For this feature we’ll make use of the Yahoo! image search API. Many of the public APIs on the Web allow themselves to be called using a technique called JSONP. JSONP is a technique that allows JavaScript-only calls to an external server to be made in a way that removes the need for a proxy to make the call.
Overview of JSONP You may or may not be familiar with JSONP. Do not confuse this with JSON (JavaScript Object Notation). JSONP stands for “JSON with padding.”While JSON and JSONP share some similar characteristics, JSONP is more akin to an XSS (cross-site scripting) attack used for good. Most of the major client script libraries now have JSONP support, but we’re still going to describe the mechanism since it’s really not that complex. A JSONP call requires the current page’s code to manipulate the host page’s DOM to dynamically add a script tag.The source of this script tag is set to the remote server endpoint (REST/Web service). Since there is no cross-domain scripting policy in the browser for static content, the browser happily downloads the new script code. However, unlike an XSS attack, for JSONP to work the server must cooperate.The magic pixie dust involves adding a callback method name to the query string of the JSONP request.The server then invokes the named JavaScript method by appending the method call to the body of the response.The actual response payload from the API call is wrapped as a parameter to the method call; hence the “padding.” Warning There are a few “gotchas” for using JSONP. Firefox blocks until the JSONP call returns. This gives you slower page execution, but you can reliably call methods in the returned script block without waiting for the callback. Since it works that way only in Firefox, you are ill advised to rely on this behavior and execute code prior to getting the callback. Internet Explorer and Safari begin full-page rendering and execution prior to handling any dynamically generated DOM elements, so they do not block on JSONP calls. The long and short is that you must make use of the callback.
So why bother using JSONP instead of makeRequest? Your JSONP calls will be both faster and more reliable. In essence, you are cutting out the middleman. A makeRequest call has to be proxied off to another server, then the proxy has to wait for the response and write it back if and when the answer comes. It creates more network hops and multiple points of failure. If the MySpace proxy goes down, all your makeRequest calls will fail.Your JSONP calls won’t even notice.
Adding an Image Search
JSONP is much more restrictive in what can be done than makeRequest. As stated before, the MySpace terms of service disallow JSONP calls on any surface other than Canvas, so you are quite limited in when you can use it.The request may be only a GET call, so anything requiring form POST data is off the table. It is also restricted to JSON data, since the packet will be JavaScript. If your needs are simply for data on the Canvas, though, JSONP is a superior option.
Implementing the Image Search For the user interface, we’ll add a text field and a button to invoke the search in our code. Results will be displayed in the same area as the RSS feed results.
The basic mechanism used in most instances is to manipulate the DOM to add a new script tag with the source pointed to the target URL. Many JavaScript libraries provide this mechanism, but it is easy enough to write your own.The de facto standard for services providing a JSONP mechanism is to specify the callback function name in a query string parameter named callback.This function creates a script tag and appends it to the head element. /** * Make a JSONP request to any URL serving JSON data by using * the Google Ajax feed service * @param {Object} url * @param {Object} callback */ function makeJsonpRequest(url, callback){ var ajaxurl =url + "&callback=" + callback; var headElem = document.getElementsByTagName("head")[0]; var scriptElem = document.createElement("script"); scriptElem.src = ajaxurl; headElem.appendChild(scriptElem); }
The next step is to specify the entry point function and the callback to display results. The entry function pulls the search term from the input field imageTerm, constructs the search URL, and invokes the makeJsonpRequest function.The callback constructs DOM elements to display the search results. function searchImage(){ var searchUrl = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query= ➥##term##&output=json";
113
114
Chapter 6 Mashups and External Server Communications
var term = document.getElementById("imageTerm").value; if(!term || term == "") term = "world"; var searchUrl = searchUrl.replace("##term##", term); makeJsonpRequest(searchUrl, "loadSearchCallback"); } function loadSearchCallback(data){ // data.ResultSet.Result[@Title, @Url] var elem = document.getElementById("rssFeed"); elem.innerHTML = ""; var line, img; var result; for(var i=0;i < data.ResultSet.Result.length; i++){ result = data.ResultSet.Result[i]; line = document.createElement("div"); img = document.createElement("img"); line.appendChild(img); img.src = result.Url; img.setAttribute("height", "60"); elem.appendChild(line); } }
Posting Data with a Form Good old-fashioned forms remain an effective way to communicate with external servers. Using a form to send data involves either placing the form in an iframe inside your app or passing the current app’s URL along as a parameter to the form. In this way, the form can issue a redirect back to your app after processing. Many third-party payment gateways make use of this technique.We leave it to the reader to explore using forms as a mechanism to communicate with payment gateways. From a MySpace-specific perspective, the terms of service allow form posts to external sites only from the Canvas view.This restriction can be circumvented by using a makeRequest call and specifying a method of gadgets.io.MethodType.POST (or gadgets.io.MethodType.GET for a query-string-encoded form) in the parameters to the makeRequest call.
Summary There are pros and cons to the methods of external communication discussed in this chapter. gadgets.io.makeRequest is a shared resource and can become a single point of failure if the service is having issues. However, it offers many useful features such as
Summary
built-in RSS feed support, along with being well defined by the OpenSocial specification. This is also the only mechanism that allows for signed and secure communications with an external server under your control.You should refer to Chapter 8, OAuth and Phoning Home, for a complete discussion of secure communications. JSONP, on the other hand, is a bit of a hack. Browsers and the HTML specification weren’t really intended to do some of the things that JSONP does, and it’s limited in what it can do. Only GET requests are permitted; POST, DELETE, and other verbs aren’t possible. It’s also hard to debug JSONP requests; depending on where an error occurred, your callback function may never be executed. In that case, how do you know what went wrong? But what JSONP does, it does well. It’s a quick and easy way to make cross-domain requests from JavaScript. HTML forms aren’t as exciting, but they are reliable. Form posts continue to be a common mechanism used to access third-party payment gateways. In the end, it’s up to you to figure out which method you use to talk to external servers, given the specific needs of your app. Note Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
115
This page intentionally left blank
7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play A
t this point in development, there are a number of options for expanding our Tic-Tac-Toe game. In this chapter we’re going to delve into person-to-person game play but continue to focus for now on what can be done within the confines of the MySpace walls. Many games available on MySpace currently use external servers for their actual person-to-person game play.We’re going to explore an option for person-to-person play without external servers, and in the course of fleshing out our game, we’ll introduce the MySpace FriendPicker widget.
Turn-Based Games Turn-based gaming is a very broad genre. At its simplest, this is the kind of gaming performed in most card games or board games.Think Go Fish, Checkers, or even Chess. In computer gaming, turn-based gaming was often typified by war-and-conquest-style games where the player faced off against one or more human or computer opponents. As computers became more powerful, turn-based games were eclipsed in popularity by real-time games.Think Doom or Castle Wolfenstein or any number of other first-person shooters. But, luckily for us, turn-based games have resurfaced as so-called casual gaming has regained popularity. We’re going to show how to make a turn-based Tic-Tac-Toe game, but this same technique could easily be adapted to card games, board games, or something else of similar complexity.We’ll leverage the ability of the app data store to be read by friends in order to trade off turns of game play. Our user interface will be modified to include some new elements on the Play tab. It will also include a FriendPicker to select the appropriate friend to play against. It will
118
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
also display current games in progress and allow the user to activate an in-progress game in order to make a move.
Design Overview Most turn-based computer games make use of a shared database. In our case we have to make do with a different kind of structure.App data can be considered a shared-read, private-write design. Getting this to work takes a lot of cooperation and a little sprinkling of pixie dust. The best way to understand these complex workflows is to draw a picture of our logic. The first part we need to understand is the flow of starting a game between two opponents. Figure 7.1 outlines the basic logic flow of picking an opponent and starting a game.
Viewer (Opponent A) picks Opponent B to play
Get Viewer and Opponent B game AppData
Yes
Game in progress?
Identify most recent data and synchronize Viewer data
No
Create Viewer game data and save
Yes
Is Viewer’s turn?
No
Viewer takes turn and saves game data
Figure 7.1
Display “Not your turn” message
Logic flow of starting an app data game.
Turn-Based Games
When Opponent A selects Opponent B, a delicate dance between the two shared app data stores ensues.The code has to determine first if there is a game in progress. An in-progress game is identified by a matching object containing the game info being discovered in both the Viewer’s app data store and the opponent’s app data store.The next step is to reconcile the two versions of the game to determine whose is the more recent and contains the latest snapshot of the game with all moves.The final step is to determine whose move it is and allow or disallow a new move to be made, saving the latest results to the common store.
Connecting Two Nodes for Transferring Data The “three-way handshake” is a technique used to establish a connection between two nodes for transferring data. This technique is most widely used in the transmission control protocol (TCP) that helps make the Internet function. A rough example is this conversation: First person: “I’m telling you something.” Second person: “I hear that you told me something.” First person: “I hear that you heard that I told you something.” After this conversation, both parties have the information, and both parties know that the other party has the information.
Things get a little more interesting when we try to reconcile the winner and clear out the game.This requires mutual agreement between both players’ data stores that the game is indeed over. We could use a technique called a “three-way handshake” to accomplish this. A secondary variable is used to move the game from a “playing” state to a “pending removal” state. In this way we would clear out old games and allow new games to be played. Figure 7.2 outlines the logic required to complete a game in this manner. A three-way handshake ends up having a fairly complex logic flow.The upside is that games are cleared out after they are finished.The downside is that the user gets only one chance to see the result of the game. What if your players are true students of the art and science of tic-tac-toe? They may wish to review the winning strategy for days or even weeks. It might be something they obsess over for a lifetime. Given all that, the simpler solution ends up being the better path.When a game is finished, the user has the option of pushing a button to delete the game.Then our logic only has to be able to start new games from one side. Enough talk. Let’s code.
Adding FriendPicker The first thing we’ll do is build up a UI to facilitate the game play.To that end, we’ll make use of the FriendPicker widget.
119
120
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
Player A makes final move and winner is declared
Game placed in “Finished Queue” for Player A
(B to A) is game over?
Yes
B displays results, writes game to “Finished Queue”, and deletes game
(A to B) B has game in FQ?
No No
Allow B to make move
Figure 7.2
Do nothing
Yes
Delete game, FQ and ready for next game
Logic flow of finishing and clearing an app data game.
The FriendPicker is a powerful and evolving widget provided by MySpace for quickly adding friend selection to your app. It supports quick scrolling of people, autocomplete search, headless (search box only) operation, and dynamic interaction with your page. Figure 7.3 shows an open FriendPicker pop-up with default settings. The FriendPicker is loaded by making use of the MySpace dynamic loader and the Bootstrapper.While powerful, it is a fairly heavy piece of code, weighing in at almost 2000 lines.The Bootstrapper is a general-purpose object loader for handling dynamically included widgets. It has the following signature: MyOpenSpace.Widgets.Bootstrapper.createWidget( <widget_object>, loadFinishedCallback, initializationObject);
Turn-Based Games
Figure 7.3
FriendPicker.
Through the use of this Bootstrapper, your code can safely create one or more FriendPickers in your app.Table 7.1 shows the different operation modes. The FriendPicker has numerous other property settings to control its display. Some can be set with the intializationObject; some must be set in the loadFinishedCallback function.All are poorly documented. In order to figure out the subtleties, check the forums on the MySpace developer site or simply download the source code.At the time of this writing, the location of the latest code is http://api.msappspace.com/OpenSocial/MyOpenSpace004.Widgets.js.You can also use Firebug to determine where the latest script source is being downloaded from when you view our app.Table 7.2 shows a short list of some of the most useful properties of the FriendPicker widget. Using the FriendPicker The FriendPicker allows the user to select a friend easily. It is one component in the standard MySpace widgets library. Using the FriendPicker is a snap with a few easy steps: 1. Include the MYSPACE_WIDGETS library at the beginning of your Canvas surface. This is done by using the MyOpenSpace.ClientLibraries.includeScript call to dynamically include one of several available add-on libraries. At the top of the
121
122
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
Table 7.1
FriendPicker Operation Modes
Mode
Initialization Property Setting
Notes
Full FriendPicker interface
displayMode = 1
This is the default mode. The full interface includes both paging of friends with thumbnail images as well as autocomplete search.
Selected friend shown
buildSelectedUI
By default, the selected friend is shown after being picked. To disable this feature, set buildSelectedUI to false.
Text-only mode
displayMode=2
This mode shows only the autocomplete search box. When the user starts typing, a list of possible matches is shown. The user may use keystrokes or the mouse to select a friend. Keystrokes used for navigation and selection are standard arrow keys and Enter. This mode is useful on Home and Profile surfaces where space is limited.
Canvas surface code, within the first script block, add the following statements to dynamically include the latest widgets script: var scriptLibraries = MyOpenSpace.ClientLibraries.Scripts; var includeLib = MyOpenSpace.ClientLibraries.includeScript; includeLib(scriptLibraries.MYSPACE_WIDGETS);
2. Find the opponentinfo div in the source for Canvas view. Immediately below this div, add two new div elements identified as opponentPicker and availableGames:
3. In the script block, immediately after the function initializeGame, add the following opponentPickedAction function. For the time being, this will display
Turn-Based Games
Table 7.2
FriendPicker Useful Properties
Property
Values
Notes
pageSize
Numeric
This property identifies how many friends to display on each page when scrolling through the friends list. This applies only when in full interface mode. Default value is 4.
friendClickAction
Function reference
A callback function to trigger when the user selects a friend. This can be used for updating the UI or for using the FriendPicker to create a multiselect interface. The opensocial.Person
object for the selected friend is passed as a parameter to the callback function. displayMode
1 or 2
Sets the UI as full UI (1) or text-only (2). This value must be set in the initializationObject
to have any effect. selectedFriend
opensocial.Person
or null (read-only)
friendsCatalog
This property can be used to retrieve the currently selected person object at any time. If no person is selected, this value is null. An internally used catalog of all downloaded friends. This object can be used as a shortcut to reference the list of friends without setting up your own data requests and callbacks. The most useful internal property is friendMap. This contains a map of all the downloaded opensocial.Person
objects used internally by the FriendPicker.
123
124
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
only the picked opponent in the availableGames div. Later on we’ll make it do something more interesting. function opponentPickedAction(person){ var elem = document.getElementById("availableGames"); elem.innerHTML = person.getDisplayName(); }
4. Immediately after the opponentPicked function, add the following loadFriendPicker function.This function makes use of the widget Bootstrapper object to initialize the FriendPicker widget.The Bootstrapper allows us to safely create a widget from a dynamically included script library.The call to createWidget takes three parameters: the object name of the widget being created, an initializer function to fire when the widget has been created, and an object of parameters to pass into the widget at initialization. In this case, we’re passing in the ID of our target div element, a callback function to execute whenever a friend is picked, and a flag to build the “Selected User” user interface element. function loadFriendPicker(){ MyOpenSpace.Widgets.Bootstrapper.createWidget( "MyOpenSpace.Widgets.FriendPicker", function(p){ window.friendPicker = p; }, { element: "opponentPicker", buildSelectedUI: true, friendClickAction: opponentPicked }); }
5. In our loadInitializer function, add a call to loadFriendPicker: function loadInitializer(){ try{ loadWordOfTheDay(); } catch(ex){} try{ initializeGame(); } catch(ex){} loadFriendPicker(); }
Turn-Based Games
Figure 7.4
FriendPicker below player info.
Warning The call to initialize a FriendPicker must be made from a gadgets.util. registerOnLoadHandler-triggered function. If we try to initialize from an inline call, the initializer will fail in some browsers. Not all browsers handle dynamic script loading in the same manner, so we must use the least common denominator behavior.
If we save and view our app, we’ll see the FriendPicker initialized below the current viewer UI. Clicking on the [Click for Recipient] item shown in Figure 7.4 brings up the FriendPicker UI and allows the user to pick a friend.
App Data Game Store Our game store in app data will consist of some JSON objects in an array.We’ll build on some of the code shown previously in the book for using the app data store.This time we’ll clean things up a bit by placing all our code under the TTT namespace, instead of leaving a bunch of dangling functions hanging off the global window object. Storage JSON Objects The first step is to create the GameInfo storage object. In your script code, add the following code: TTT.GameInfo = function(opponentId){ this.opponentId = opponentId; this.dataSourceId = window.viewer.getId(); this.boardLayout = null; this.moveNumber = 0; this.currentPlayer = 0; this.winner=0; }
With this object, our game can track the opponent, whose move it is, if there is a winner, and all the moves on the board.The active games are stored as an array of these objects. AppDataPlay Game Object The next step is to set up our basic game data manager.This will contain the logic described earlier in the chapter. It will also encapsulate some utility methods for managing the data store.
125
126
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
Logging to Debug Apps The gadgets spec provides for a logging mechanism similar to the one popularized by log4j under the gadgets.log call. Logging is an incredibly useful way to debug an app. It’s not always convenient to set breakpoints and single steps. A log lets you dissect the execution sequence after the fact. At the time of this writing, gadgets.log isn’t implemented in the MySpace container. It’s simple to add, though. In our case, we just want to write out to a scrolling div. After development we can hide the div and leave the log calls in place. Here’s how: <style type="text/css"> #log{ float:left; margin:5px; padding:5px; border:5px solid #888; width:350px; height:350px; overflow:auto; background:white; }
... if(!gadgets.log){ gadgets.log = function(msg){ var el = document.getElementById("log"); if(!el) return; var m = document.createElement("div"); m.innerHTML = msg; el.appendChild(m); } }
In earlier chapters we’ve shown some techniques by making use of global functions.While convenient for small projects, it is good practice to namespace your script code.We’re going to encapsulate all of this in a static object namespace of TTT.AppDataPlay.
Turn-Based Games
1. Create the basic object skeleton and add it into your script source.The code is shown here: TTT.AppDataPlay = { }
2. Add a Keys object to this namespace that will encapsulate all the app data keys used for game play: TTT.AppDataPlay = { /** * Keys into the AppData store */ Keys: { activeGames: "activeGames", AppDataGetKey: "getData", finishedGames: "finishedGames" } }
3. Now we will add some empty object key definitions to hold our data. Even though JavaScript allows for dynamic creation of variables, it is good practice to explicitly declare and comment any variables that are used in multiple places. Add this code inside our TTT.AppDataPlay object: TTT.AppDataPlay = { . . . /** * Local cache of game app data for Viewer. */ myGameAppData: { "activeGames":null }, /** * Local cache of opponent game app data */ myOpponentAppData: {}, /** * Local cache of opponent in current game */ myOpponentCurrentGame: {},
127
128
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
/** * Current opponent being played against */ currentOpponentId: null, . . . }
4. Add method stubs for game play support.These functions are set up as placeholders so that our code won’t break as we build it out.We will fill in the functions with real logic later. TTT.AppDataPlay = { . . .
/** * Retrieves the gameInfo object for the specified opponent. * If one doesn't exist, a new gameInfo object is created. */ getCurrentGameObject: function(opponentId){}, /** * Convenience method to save the data currently in * this.myGameAppData to the backing app data store. */ updateStoredGameObject: function(){}, /** * Loads the specified gameInfo object into * window.currentGame and updates the board */ loadGame: function(gameInfo){}, /** * Displays a message regarding game play */ updateGameStatusMessage: function(message){}, /** * Serializes the board information into a string for storage */
Turn-Based Games
getGameMovesString: function(game){}, . . . }
5. Add the methods for retrieval and saving of the Viewer’s app data.These methods are adaptations of what we wrote in Chapter 4, Persisting Information.The only real difference is that we include them in our TTT.AppDataPlay namespace. TTT.AppDataPlay = { . . . /** * Retrieve the current Viewer's app data. * This is an upgrade of the method introduced in * Chapter 4, Persisting Information. */ getMyAppData: function (){ var idparams = {}; idparams[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; idparams[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 0; idparams[opensocial.IdSpec.Field.GROUP_ID] = opensocial.IdSpec.GroupId.SELF; var id = opensocial.newIdSpec(idparams); var req = opensocial.newDataRequest(); req.add( req.newFetchPersonAppDataRequest(id, "*"), TTT.AppDataPlay.Keys.AppDataGetKey); req.send(function(data){ TTT.AppDataPlay.loadAppDataCallback(data, TTT.AppDataPlay.myGameAppData); }); }, /** * Sets an AppData key for the current Viewer * @param {String} key * @param {JSON object} value */ setAppDataKey: function (key, value) { var req = opensocial.newDataRequest();
129
130
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
6. Referenced in the methods just shown is a general-purpose app data callback handler adapted from Chapter 4, Persisting Information. Add the function loadAppDataCallback in as well.This function places all the AppData keys and values in the response into the specified object hash. In that way we make only one call for all the data. TTT.AppDataPlay = { . . . /** * Callback wrapper method for loadAppData. * This loads all the data into myLocalAppData * and triggers the loadedCallback function, if specified * @param {Object} data * @param {Function} loadedCallback */ loadAppDataCallback: function (data, targetCollection, loadedCallback){ logDataError(data); if (data.hadError()) { return; //Exit if nothing found } var mydata = data.get(TTT.AppDataPlay.Keys.AppDataGetKey).getData(); //App data has an additional layer of indirection. //We reassign mydata object to the data map object //Circumvent Viewer lookup by getting key var ok = false; for(var vkey in mydata){ mydata = mydata[vkey]; ok = true; break; } if(ok){ if(targetCollection == null){ gadgets.log("Bad collection in load callback");
7. Finally, add in the function that retrieves a friend’s app data.We touched on this briefly in Chapter 4, Persisting Information, but did not write the code for retrieving other people’s app data.You can read, but cannot write, your friend’s data, provided the friend has the app installed as well.The main differences between this and Viewer are the idSpec used and the callback function. TTT.AppDataPlay = { . . . /** * Retrieve app data for an opponent. */ getFriendGameData: function (friendId){ var idparams = {}; idparams[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER; idparams[opensocial.IdSpec.Field.NETWORK_DISTANCE] = 1; if(!friendId){ friendId = window.friendPicker.selectedFriend.getId(); } idparams[opensocial.IdSpec.Field.GROUP_ID] = friendId; //If MySpace fixes the idSpec bug, use this /* if(!friendId){ friendId = window.friendPicker.selectedFriend.getId(); } idparams[opensocial.IdSpec.Field.USER_ID] = friendId; idparams[opensocial.IdSpec.Field.GROUP_ID] = opensocial.IdSpec.GroupId.SELF; */
131
132
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
Warning You may notice a commented-out block of code within this function. At the time of this writing, MySpace had an inconsistency in its interpretation of the idSpec object from how other OpenSocial implementations interpret the same object. MySpace requires the user ID to always be VIEWER and the target friend ID to be placed in the GROUP_ID field. Other implementations put the target friend ID in the user ID field and use the reserved enum value opensocial.IdSpec.GroupId.SELF for the GROUP_ID value.
8. Stub out the callback function TTT.AppDataPlay. selectedOpponentDataCallback.This function holds much of the logic for game management. For now, we’re just going to stub it out and add a log statement so our code will run. TTT.AppDataPlay = { . . . selectedOpponentDataCallback: function(data){ gadgets.log("Got opponent data: " + data); } . . . }
Supporting Person-to-Person Game Play
At this point, we have the skeleton of the AppDataPlay object built and the utility methods required for communicating with the app data store of both players.
Supporting Person-to-Person Game Play Thus far, our actual game engine (TTT.Game) has supported only human-versus-computer game play.We need to make a few tweaks to allow for dual-mode play (person-to-person, or P2P). In our game engine, we’ll always consider our opponent to be “Computer,” even when the opponent is another person.This saves us from a broader rewrite of the display logic and game engine. A simple flag value will give us enough information to differentiate computer from human opponents.
Adding P2P Game Play Support in the Game Engine The first step is to make a few minor modifications to the original Tic-Tac-Toe game engine in order to support a human opponent in a turn-based system. We must change the “made a move” trigger to store data and wait instead of triggering a computer move. We also now need to handle cases when the game ends in a draw. 1. Add a property in the TTT.Game object to flag the game as being against a human opponent.This will be used in the game logic to trigger a computer move or trigger an app data store update. var TTT = { . . . Game: function(){ . . . /** * Flag to set if this is a vs. computer * or vs. human game */ this.isHumanOpponent = false; . . . } }
2. Add a new method to the TTT.Game prototype object to test for a draw. In human-versus-computer play we didn’t need to test for a draw. When no squares were available, there were no moves to make.With a human opponent we need to be able to identify the end of a game when there is no winner. Search for the lookForWin function and add the isADraw function immediately below.
133
134
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
/** * Checks to see if the current game is a draw (all cells filled) * */ isADraw : function(){ var openCell = false; for(var i=0; i < 9; i++){ if(!this.moves[i]){ openCell = true; break; } } return (!openCell); },
3. Edit the game play event handler makePlayerMove to support P2P game play. Previously, this function would trigger a computer move if a winner was not discovered.We need to update this if statement with an else and include a check for isHumanOpponent. function makePlayerMove(e){ . . . if(!currentGame.hasWinner && !currentGame.isHumanOpponent){ window.setTimeout(function(){ currentGame.makeComputerMove(); }, 500); } else{ . . . } }
4. Add the game logic for taking a turn within the else statement in the makePlayerMove function from the preceding step.You will notice some new methods on the TTT.AppDataPlay object.We’ll fill in those methods in the next section. else{ // USER FEEDBACK MESSAGES HERE var adGame = TTT.AppDataPlay.getCurrentGameObject( TTT.AppDataPlay.currentOpponentId); adGame.moveNumber = adGame.moveNumber+1; if(currentGame.hasWinner){ msg = "You Win!";
Supporting Person-to-Person Game Play
adGame.winner = window.viewer.getId(); } else{ msg += " Waiting for your opponent"; } adGame.boardLayout = TTT.AppDataPlay.getGameMovesString(currentGame); adGame.currentPlayer = TTT.AppDataPlay.currentOpponentId; TTT.AppDataPlay.updateStoredGameObject(adGame); if(currentGame.isADraw()){ msg += " IT'S A DRAW!"; } else if(!currentGame.hasWinner && !currentGame.isADraw()){ //Wait for next move } TTT.AppDataPlay.updateGameStatusMessage(msg); }
Adding User Feedback Feedback to the user is an important part of the game play. In turn-based game play, sometimes it’s simply just not the Viewer’s turn.Without feedback the Viewer has the impression that the game is broken. When our Tic-Tac-Toe game is in P2P game play mode instead of P2C (personto-computer), the computer takes on the role of commentator/narrator instead of opponent. Since this is a game, we like to add some sass to the commentary. Feel free to customize the messages to your liking. 1. Above the table with an ID of gameboard, add a div element with an ID of gameStatus.This is where the feedback messages are displayed.
2. In the makePlayerMove function, add a check and associated message to short-circuit processing if it is not the Viewer’s turn to make a move. Place this code immediately after the line where the var cell = ... statement is located. if(currentGame.isHumanOpponent && (currentGame.currentPlayer == TTT.Players.Computer)){ TTT.AppDataPlay.updateGameStatusMessage( "YO! I said you have to wait your turn."); return; }
135
136
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
3. In the makePlayerMove function, add a random message generator within the else block that is executed during P2P game play. In our case we’ll create three messages and use a modulo operation coupled with a timestamp to pick a message in a quasi-random fashion.To the end user this will appear as a running commentary by the computer. var quotes = ["Nice Move!", "...interesting strategy", "What were you thinking?"]; var d = new Date(); var ndx = d.getMilliseconds() % 3; var msg = quotes[ndx]; //Random quote
Modulo Magic Modulo operations can be one of the most useful bits of programming pixie dust to put in your bag of tricks. A modulo operation calculates the remainder after a division operation between two numbers. To illustrate, if we divide the number 5 by 2, it divides evenly into two parts with 1 left over. The modulo (or “mod”) operation returns the 1. 5/2 = 2 with remainder of 1, or 5 mod 2 = 1
In JavaScript the statement would be written as 5 % 2. By far the most common usage is for displaying rows with alternating colors. This is accomplished with the following if statement: for(var i=0; i
There are many more uses for modulo operations. Modulo is great any time you want a quasi-random distribution of data. All it takes is an incrementing counter (like a timestamp) and the number of buckets to test for. True random numbers are much more cumbersome and computationally expensive than a modulo operation.
The following code is the final code listing for makePlayerMove: function makePlayerMove(e){ if(!e) var e = window.event; var cell = (e.target) ?
Supporting Person-to-Person Game Play
e.target.getAttribute("gamecell") : e.srcElement.getAttribute("gamecell"); if(currentGame.isHumanOpponent && (currentGame.currentPlayer == TTT.Players.Computer)){ TTT.AppDataPlay.updateGameStatusMessage( "YO! I said you have to wait your turn."); return; }
currentGame.makeMove(TTT.Players.Human, cell); if(!currentGame.hasWinner && !currentGame.isHumanOpponent){ window.setTimeout(function(){ currentGame.makeComputerMove(); }, 500); } else{ var quotes = [ "Nice Move!", "...interesting strategy", "What were you thinking?"]; var d = new Date(); var ndx = d.getMilliseconds() % 3; var msg = quotes[ndx]; //Random quote var adGame = TTT.AppDataPlay.getCurrentGameObject( TTT.AppDataPlay.currentOpponentId); adGame.moveNumber = adGame.moveNumber+1; if(currentGame.hasWinner){ msg = "You Win!"; adGame.winner = window.viewer.getId(); } else{ msg += " Waiting for your opponent"; } adGame.boardLayout = TTT.AppDataPlay.getGameMovesString(currentGame); adGame.currentPlayer = TTT.AppDataPlay.currentOpponentId; if(currentGame.isADraw()){ msg += " IT'S A DRAW!"; adGame.winner = -1; } else if(!currentGame.hasWinner && !currentGame.isADraw()){
137
138
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
Fleshing Out P2P Game Logic We have now created all the underpinnings of the game play. Now it’s time to glue it all together and implement our logic flows from the beginning of this chapter. Logic for Selecting an Opponent and Loading the Game Selecting an opponent and activating a game constitute the bulk of the workflow outlined at the beginning of the chapter.The app has to get both the Viewer’s and the opponent’s game data, reconcile which version is the latest, and determine whose move it is. If there is no active game, a new one is created. Find the function selectedOpponentDataCallback in the TTT.AppDataPlay object namespace that we stubbed out earlier.This is a big function, so we will discuss each section of it in turn. The first section of this function retrieves the GameInfo object for the two associated players by examining all the games stored in the selected opponent’s app data store until it finds one where the current Viewer’s ID matches the opponentId value in the GameInfo object.This object is then assigned to the variable TTT.AppDataPlay. myOpponentCurrentGame. At the very end of this section the code block similarly retrieves the GameInfo object associated with this opponent from the Viewer’s local copy of the app data store by calling getCurrentGameObject. if(!data){ return; } //Since we're in a callback, "this" has lost scope var thisObj = TTT.AppDataPlay; var myId = window.viewer.getId(); thisObj.myOpponentCurrentGame = null; var opponentStoredGames = data[thisObj.Keys.activeGames]; if(opponentStoredGames != undefined && opponentStoredGames != null){ opponentStoredGames = gadgets.json.parse(opponentStoredGames); if(opponentStoredGames.length){ var curGame; for(var i=0; i < opponentStoredGames.length; i++){
The second section of the selectedOpponentDataCallback function reconciles the two GameInfo objects. It does this by identifying which object has the latest move. The boardLayout is then copied into the Viewer’s GameInfo object to ensure that the Viewer’s copy is the latest copy. var latestGameInfo; if(thisObj.myOpponentCurrentGame != null){ //Reconcile to latest game version if(myGameInfo.moveNumber <= thisObj.myOpponentCurrentGame.moveNumber){ latestGameInfo = thisObj.myOpponentCurrentGame; //Sync the player's game board with most current board myGameInfo.boardLayout = latestGameInfo.boardLayout; myGameInfo.moveNumber = latestGameInfo.moveNumber; myGameInfo.currentPlayer = latestGameInfo.currentPlayer; } else{ latestGameInfo = myGameInfo; }
Once the latestGameInfo has been determined, the code tests to see if a winner has been declared.When a winner has been declared, the ID of the winning player is placed in this field. If there is no winner, this value is 0 (equivalent to false). If there is a winner, the board is loaded, a message is displayed to state who won, and the game is marked as finished. If there isn’t a winner, the game is loaded into view via a call to the loadGame function (described later in this section). User feedback is generated to indicate whose turn it is. if(latestGameInfo.winner != 0){ if(latestGameInfo.winner == myId){ thisObj.updateGameStatusMessage("YOU WON!!!"); }
139
140
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
else if(latestGameInfo.winner == -1){ thisObj.updateGameStatusMessage("ITS A DRAW!!!"); } else{ thisObj.updateGameStatusMessage("YOUR OPPONENT WON!!!"); } //debugger; thisObj.loadGame(latestGameInfo); thisObj.markGameFinished(latestGameInfo.gameId); thisObj.cancelPolling(); return; } thisObj.loadGame(latestGameInfo); if(latestGameInfo.currentPlayer==myId) { //My turn msg += " It is your turn"; } else{ msg += " Still waiting on opponent"; thisObj.startGameplayPolling(); }
The preceding code describes what occurs when a game is discovered to be in progress.The second branch of this is what occurs when this is a new game or the opponent has not yet accepted the game. In that instance the Viewer’s game is loaded and appropriate user feedback is displayed. } else{ latestGameInfo = myGameInfo thisObj.loadGame(latestGameInfo); //Save the new game back if(latestGameInfo.moveNumber==0){ msg += " New game started - make your move"; } else{ msg += " Waiting for your opponent to move"; } } thisObj.updateGameStatusMessage(msg);
That finishes the selectedOpponentDataCallback function.There were two other functions touched on in the preceding description: getCurrentGameObject and loadGame. Both methods are fairly simple.
Supporting Person-to-Person Game Play
The function getCurrentGameObject retrieves the GameInfo object from the Viewer’s app data store for the associated opponent. If there is no game in progress, a new GameInfo object is initialized for this opponent and returned. /** * Retrieves the gameInfo object for the specified opponent. * If one doesn't exist, a new gameInfo object is created. * */ getCurrentGameObject: function(opponentId){ var result = null; if(this.myGameAppData && this.myGameAppData.activeGames != null){ var items = this.myGameAppData.activeGames; var i; if(items.length){ for(i=0; i < items.length; i++){ if(items[i].opponentId == opponentId){ result = items[i]; break; } } } else{ //Is object var x; for(x in items){ if(items[x].opponentId == opponentId){ result = items[x]; break; } } } } if(result == null){ result = new TTT.GameInfo(opponentId); if(!this.myGameAppData.activeGames){ this.myGameAppData.activeGames = []; } this.myGameAppData.activeGames.push(result); } return result; }
The function loadGame loads the GameInfo into the game board and initializes the window.currentGame object.The bulk of this method is display logic. In our
141
142
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
implementation, the Viewer’s moves are always represented by an X (TTT.Players. Human) and the opponent’s moves are always represented by an O (TTT.Players. Computer). The board layout is represented by a pipe-delimited list of moves.This represents the nine squares of the Tic-Tac-Toe board. Each move is either an X, an O, or nothing. Depending on the originating source of the GameInfo object (Viewer’s object or opponent’s object), as determined by matching the Viewer’s ID against gameInfo.dataSourceId, these moves are transcribed to be appropriate for the Viewer. For example, if the latest GameInfo object originated from the Viewer’s app data store, the X’s and O’s remain the same. If the latest GameInfo object was from the opponent’s app data store, the X’s and O’s have to be flipped. /** * Loads the specified gameInfo object into * window.currentGame and updates the board */ loadGame: function(gameInfo){ if(currentGame){ currentGame.clear(); } else{ currentGame = new TTT.Game(); } currentGame.isHumanOpponent = true; //Flag to not make computer moves var myId = window.viewer.getId(); var fromMe = (gameInfo.dataSourceId == myId); if(gameInfo.boardLayout){ var moves = gameInfo.boardLayout.split("|"); var nOneMark, nZeroMark; if(fromMe){ nOneMark = TTT.Players.Human; nZeroMark = TTT.Players.Computer; } else{ nOneMark = TTT.Players.Computer; nZeroMark = TTT.Players.Human; } //1 == game owner, 0 == viewer for(var i=0; i < moves.length; i++){ if(moves[i]==""){ continue; } else{ if(moves[i]=="1"){
To wrap up this section, we’ll look at how the board is serialized into a string for storage in the app data store.The function getGameMovesString takes care of those details by interpreting the game board from currentGame and turning it into a pipedelimited string. Remember that the opponent is always considered the computer. /** * Serializes the board information into a string for storage */ getGameMovesString: function(game){ var i=0; var result = ""; for(i=0; i < 9; i++){ if(game.moves[i] === undefined || game.moves[i] == "" || game.moves[i] == null){ result += "|"; } else{ if(game.moves[i] == TTT.Players.Computer){ result += "0|"; } else{ result += "1|"; } }
143
144
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
} return result; }
Finishing and Clearing a Game Finishing a game ends up being a complex problem. If you remember the earlier discussion, we had two options to handle finishing and clearing a game.The first was through a complex three-way handshake.The second was to allow for manual clearing. We’re going to implement the latter. 1. The first step is to add in some methods for removal of a game.This deletes the current client snapshot of the app data store games, saves an updated app data store key back to the server, and clears currentGame. Add the three methods removeGame, clearGame, and clearAllGames to the TTT.AppDataPlay object: removeGame: function(opponentId){ if(this.myGameAppData && this.myGameAppData.activeGames != null){ var items = this.myGameAppData.activeGames; var newItems = []; var i; if(items.length){ for(i=0; i < items.length; i++){ if(items[i].opponentId != opponentId){ newItems.push(items[i]); } } } else{ //Is object var x; for(x in items){ if(items[x].opponentId != opponentId){ newItems.push(items[x]); } } } } this.myGameAppData.activeGames = newItems; this.updateStoredGameObject(); }, clearGame: function(opponentId){ //debugger; this.cancelPolling();
2. Create two buttons to trigger both the clearGame and clearAllGames methods:
3. Now we have to modify the selectedOpponentDataCallback function to recognize when one person has started a new game.The following code listing demonstrates identifying a winner. It is the first thing checked after identifying that the opponent’s current game is not null with the call if(thisObj. myOpponentCurrentGame != null). Download the full app code for Chapter 7 from our Google Code listing (http://code.google.com/p/opensocialtictactoe/ source/browse/#svn/trunk/chapter7) if you wish to see it in place. var isNewGame = false; if(myGameInfo.winner != 0 && thisObj.myOpponentCurrentGame.moves < 3){ thisObj.removeGame(thisObj.currentOpponentId); myGameInfo = thisObj.getCurrentGameObject(thisObj.currentOpponentId); isNewGame = true; latestGameInfo = myGameInfo; } else if(thisObj.myOpponentCurrentGame.winner != 0){ isNewGame = true; latestGameInfo = myGameInfo; }
145
146
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
“Real-Time” Play We use quotes to signify the air quotes we’d use if this conversation was happening face to face. It’s not actually real-time play.That would require an event-routing system, which we don’t have at our disposal in this design. Instead we’ll set up a polling system so that the game can periodically update without reloading the page. A simple polling design sets a time-out after the player makes a move.This time-out continues to retrigger at intervals until the code detects that the other player has made a move and control has returned to the Viewer. In practice, however, a polling design requires numerous safety checks and throttling mechanisms. Throughout this section we’ll talk about each part of the code in turn.You may also have noticed calls to the polling triggers in the code we’ve introduced already.We won’t be reviewing those calls in detail but will leave it to the reader to explore how they all interact in depth. Before we start, there are two constraints to put in place.The first is the polling interval.The second is the maximum number of times to retrigger the poll test. If a user walks away from the machine for half a day, we don’t want the game to continue polling every ten seconds, so we set a maximum count it can trigger before getting a reply. /** * Time (in seconds) that the system will wait * between polling to see * if the opponent has made a move */ OPPONENT_POLLING_TIME: 10, /** * Maximum number of times the poll will fire * without a response before * polling stops */ MAX_POLLING_COUNT: 100,
The first function to explore is startGameplayPolling. It’s the initial trigger to begin the polling system.The following is the first design we worked on: startGameplayPolling: function(){ gadgets.log("starting Poll"); if(!this.currentOpponentId){ return; } this.gamePollTimer = window.setTimeout(function(){ TTT.AppDataPlay.gamePollTimer = 0; TTT.AppDataPlay.pollForOpponentUpdatedMove();
This code sets the initial time-out trigger, which in turn calls the function pollForOpponentUpdatedMove.The pollForOpponentUpdatedMove function makes
a call to re-retrieve the opponent’s app data and reinitialize the game. pollForOpponentUpdatedMove: function(){ var thisObj = TTT.AppDataPlay; thisObj.gamePollTimer = null; thisObj.isPollingForActiveGame = false; thisObj.getFriendGameData(thisObj.currentOpponentId); if(thisObj.isPollingForActiveGame && thisObj.currentGamePollCount++ < thisObj.MAX_POLLING_COUNT){ thisObj.startGameplayPolling(); } gadgets.log("Polling fired: " + thisObj.currentGamePollCount); }
Within the code path of getFriendGameData is a trigger to cancel the polling.This involves clearing the time-out handle we saved in startGameplayPolling and resetting all the flags and counters. cancelPolling: function(){ window.clearTimeout(TTT.AppDataPlay.gamePollTimer); TTT.AppDataPlay.isPollingForActiveGame = false; TTT.AppDataPlay.currentGamePollCount = 0; }
In practice, this design worked. But we noticed that the updates were happening quite fast, much faster than the ten seconds that was set earlier. As it turned out, there were several user interaction code paths that would trigger multiple timers to be active. And the timers seemed to stack up and grow in number.This called for adding an if block to simply kill timers if a previous timer was already doing the job.The following code was added to startGameplayPolling: if(this.gamePollTimer && this.gamePollTimer > 0){ return; }
Unfortunately, this was too heavy-handed, as the timers would simply die out in some situations.To combat this, we added an additional counter to allow the trigger to sleep a few times before triggering the die code path: if(this.gamePollTimer && this.gamePollTimer > 0){ if(TTT.AppDataPlay.pollSleepCount++ > 5){
147
148
Chapter 7 Flushing and Fleshing: Expanding Your App and Person-to-Person Game Play
TTT.AppDataPlay.pollSleepCount = 0; return; } }
That seemed to work.We may have been able to get there more cleanly by using window.setInterval instead of a retriggering time-out.We’ll leave it to the reader to
explore different permutations of this design. Asynchronous processing, as many of you may know, can be a complicated problem.
Advantages and Disadvantages of App Data P2P Play There are a few advantages and a few disadvantages to this kind of architecture for P2P game play. First, let’s go with the advantages: n n
There’s no infrastructure required for your game to operate. There are no explicit scaling considerations—the problem of scaling the game is pushed onto MySpace.
Now let’s consider the downsides of this technique: n n
n
Logic can be much more complex than in a shared read/write database. The app data store can be read and written to by anyone with a little knowledge of Firebug, essentially allowing a malicious user to cheat. If your app takes off, it could flatten the MySpace app data infrastructure.
Oh, we didn’t mention that before? App data in its current state is not explicitly designed for high-volume read/write operations. Its initial conception was more for storage of settings, such as background colors and default fonts.There is much discussion within the spec group (those involved with the development of the OpenSocial spec) about the shortcomings of the app data store. Currently the main discussions center around both a private (not friend-readable) store and a real-time messaging system. As always, you can download the source code for this chapter from the Google Code site, http://code.google.com/p/opensocialtictactoe, or directly from the source repository at http://code.google.com/p/opensocialtictactoe/source/browse/#svn/trunk/chapter7. We looked at a lot of the code in small pieces, so it may be helpful to see it all together.
Summary P2P game play is one of the most attractive aspects of social gaming. If a user wants to play a game on his or her own, a multitude of casual and not-so-casual gaming sites are available online. Most of them have games of much greater polish and budget than are found on social networks. It is the social interaction aspect that makes building P2P games on MySpace interesting.
Summary
The technique we’ve shown in this chapter allows you to explore P2P apps, even beyond games, without an infrastructure investment. However, Caveat emptor—let the buyer beware.You will be limited in what can be done, and if the MySpace infrastructure hiccups, your app will be left out in the cold. In the authors’ opinion, you will be time and money ahead if you explore using an external database, such as those discussed in the chapters on external iframe apps (Chapter 9) and persisting information (Chapter 4). Making a system do something it wasn’t designed to do, while technically interesting, is not always the most prudent path. Note Code listings and/or code examples for this chapter can be found on our Google Code page under http://opensocialtictactoe.googlecode.com.
149
This page intentionally left blank
II Other Ways to Build Apps
8
OAuth and Phoning Home
9
External Iframe Apps
10
OSML, Gadgets, and the Data Pipeline
11
Advanced OSML: Templates, Internationalization, and View Navigation
This page intentionally left blank
8 OAuth and Phoning Home U
p until this point our app has lived in, and been hosted on, MySpace’s servers. MySpace provides a wide range of services that allow quite a few apps to function perfectly well completely in that environment.You can provide markup that will render out to the page, save data in the app data store, send various types of messages, and fetch information on your users—all within the confines of MySpace—and possibly most important, all for free. However, there are some limits to what you can accomplish with this. For example, the app data store has some severe limitations.There are inherent security concerns (see Chapter 13 for details) and a 1kB limit imposed on each item saved. And what about larger apps that may have gigabytes of data that needs to be properly indexed and stored in a relational database? Obviously the app data store can’t meet all of these needs. Also, there are the submission and approval headaches brought on each time you want to update your app, and the lack of complete control over the rendering surface, as MySpace wraps a header and footer around your app’s code. This chapter and the following one will show you how to get around these limitations by hosting some or all of your app on external servers.There are many hosting services out there with a wide range of price and performance, but for this chapter we chose to use one of the “cloud-computing” services: Google App Engine. Using OAuth, we will demonstrate how to validate calls made from your app to your servers using the gadgets.io.makeRequest functionality.This allows you to host a database on an external server but still be able to safely communicate between your app hosted on MySpace and your servers hosted on Google App Engine.
What Is OAuth? OAuth is the authentication mechanism used by the MySpace API servers.The oauth.net site summarizes OAuth as “an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.” MySpace gives each app a consumer key and a secret key; only MySpace and the app know the secret key.With knowledge of the secret key you can use the protocols defined
154
Chapter 8 OAuth and Phoning Home
by OAuth to either construct or validate requests. An app uses the secret key to construct a request to MySpace. MySpace uses the secret key to validate that the request actually came from the app. Because a user can deny or grant various permissions to an app, it is very important that MySpace be able to confirm that a request actually came from a specific app. The typical flow is something along the lines of the following: 1. A user installs an app, thereby granting it certain permissions. 2. The user navigates to the app’s Canvas page to use it. 3. The app builds an OAuth request to fetch data from MySpace, such as the user’s friend list. 4. MySpace receives the request and uses OAuth to validate that the request came from the app. 5. MySpace then looks up what permissions that user has granted to that app. If the user has granted access to the requested data, it is returned to the app. Otherwise a 401 permission-denied error is returned. 6. The app receives either the data or an error.
OAuth Libraries You can dig into the fairly complicated guts of OAuth if you’d like to know more; a good starting point is http://oauth.net. Because OAuth is an open protocol, anyone is free to implement it and release it for everybody else to use. That means there are libraries out there for use, written in almost every language you can think of. One of the great tenets of software development is code reuse, so to us it doesn’t make sense to reinvent the OAuth wheel for the purpose of this book.We will be using an OAuth library written in Python to communicate securely with MySpace, and we suggest you do the same. Not only is it a huge time-saver, but it abstracts all the complexity of OAuth and MySpace’s APIs. MySpace provides several software development kits (SDKs) for accessing its APIs. From the following link you can find libraries written in PHP, Python, Ruby, C#, and Java: http://code.google.com/p/myspaceid-sdk/. We will be using the Python SDK found through that site.
Setting Up Your Environment Your mileage may vary depending on what language you are writing in, but the process is essentially the same for all languages, so we hope this Python example will help you along even if you choose a different SDK. First, create a working folder somewhere in your file system, say, c:\working.We’ll refer to this as your root folder from here on out, or .
What Is OAuth?
Next, you’ll need to do some setup work.We suggest the following: 1. Download and install TortoiseSVN, which is a Subversion client. Subversion is an open-source version control system and is used by Google Code, where the MySpace SDKs are hosted, to provide convenient access to source code. Installation instructions and downloads can be found at http://tortoisesvn.tigris.org/. 2. Sign up for Google App Engine (GAE) and download the GAE SDK. GAE is a “cloud-computing” service provided by Google.You upload your source code to their servers and they do all the rest. As of this writing, small amounts of usage of the service are free, but this could change. The GAE SDK provides a useful test Web server that you run on your local co