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 FranciscoNew York •Toron
Trang 1ptg
Trang 2OpenSocial Apps
Trang 3The Developer’s Library Series from Addison-Wesley provides
practicing programmers with unique, high-quality references and tutorials on the latest programming languages and technologies they
use in their daily work All books in the Developer’s Library are written by
expert technology practitioners who are exceptionally skilled at organizing
and presenting information in a way that’s useful for other programmers
Developer’s Library books cover a wide range of topics, from
open-source programming languages and databases, Linux programming,
Microsoft, and Java, to Web development, social networking platforms,
Mac/iPhone programming, and Android programming
Visit developers-library.com for a complete list of available products
Developer’s Library Series
Trang 4Building OpenSocial Apps
A Field Guide to Working with the
MySpace Platform
Chris Cole Chad Russell Jessica Whyte
Upper Saddle River, NJ •Boston•Indianapolis•San FranciscoNew York •Toronto •Montreal•London•Munich •Paris •MadridCapetown•Sydney•Tokyo •Singapore•Mexico City
Trang 5are 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.
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.
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.
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
Visit us on the Web: informit.com/aw
Library of Congress Cataloging-in-Publication Data
Cole, Chris,
1974-Building OpenSocial apps : a field guide to working with the
MySpace platform/Chris Cole, Chad Russell, Jessica Whyte.
p cm.
Includes bibliographical references and index.
ISBN-13: 978-0-321-61906-8 (pbk : alk paper)
ISBN-10: 0-321-61906-4 (pbk : alk paper)
1 Entertainment computing 2 Internet programming 3 MySpace.com 4 OpenSocial
5 Web site development 6 Social networks—Computer network resources.
7 Application program interfaces (Computer software) I Russell, Chad II Whyte, Jessica III Title.
QA76.9.E57C65 2010
006.7'54—dc22
2009032342 Copyright © 2010 Pearson Education, Inc.
All rights reserved Printed in the United States of America This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited
reproduction, storage in a retrieval system, or transmission in any form or by any means,
electronic, mechanical, photocopying, recording, or likewise For information regarding
permissions, write to:
Pearson Education, Inc
Rights and Contracts Department
501 Boylston Street, Suite 900
Songlin Qiu
Managing Editor
John Fuller
Full-Service Production Manager
Julie B Nahil
Project Management
Cassie Doll Bess Ho Benjamin Schupak
Book Designer
Gary Adair
Compositor
diacriTech LLC
Trang 6This 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
❖
Trang 7Contents at a GlanceContents 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 29
4 Persisting Information 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 153
9 External Iframe Apps 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
Trang 814 Marketing and Monetizing 305
15 Porting Your App to OpenSocial 0.9 329
References 351
Index 355
Trang 9Contents
Foreword xviAcknowledgments xviiiAbout the Authors xixIntroduction xxi
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 3 Step 2: Create an App 4
Step 3: Enter Your Source Code 4 Installing and Running Your App 7 Summary 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 24
Summary 27
3 Getting Additional MySpace Data 29
How to Fetch a Friend List and Make Use of the Data 29
Getting the Friend List 30 Filters and Sorts 31
Trang 10Paging 32 Using the Data 37 Fetching Media 39 Photos 39 Albums and Videos 41 Using opensocial.requestPermission and opensocial.hasPermission to Check a User’s Permission Settings 43
Summary 45
4 Persisting Information 47
App Data Store 47 Saving and Retrieving Data 48 Refactoring to Build a Local App Data Store 51 Cookies 56
Why You Shouldn’t Use Cookies 57 Building the Cookie Jacker App 59 Third-Party Database Storage 64 Summary 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 71 Calling requestShareApp 72
The requestShareApp Callback 72 Using opensocial.requestSendMessage to Send Messages and Communications 74
Defining requestSendMessage 75 Writing the requestSendMessage Code 76 Callback in requestSendMessage 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 80 Data Types 80
Reserved Variable Names 81 Aggregation 82
Trang 11x Contents
Body and Media Items 82 Using the Template Editor to Create Templates 83 Using opensocial.requestCreateActivity 85 Sending Notifications 88
Summary 90
6 Mashups and External Server Communications 91
Communicating with External Servers 91 Mashups 92
Adding a Feed Reader to Our App 93 Overview of gadgets.io.makeRequest 94 Response Structure 96
Handling JSON Content 97 Handling Partial HTML Content 97 Handling RSS Feed Content 97 Handling XML Content 98
“User’s Pick” Feed Reader 98 Setup and Design of the Feed Reader 98 FEED Content Type 104
XML Content Type with Parsing 105 TEXT Content Type 107
Adding a Feed Refresh Option 109 Feed Automation Candy 110 Secure Communication with Signed makeRequest 111
Adding an Image Search 112 Overview of JSONP 112 Implementing the Image Search 113 Posting Data with a Form 114
Summary 114
7 Flushing and Fleshing: Expanding Your App andPerson-to-Person Game Play 117
Turn-Based Games 117 Design Overview 118 Adding FriendPicker 119 App Data Game Store 125 Supporting Person-to-Person Game Play 133
Trang 12“Real-Time” Play 146 Advantages and Disadvantages of App Data P2P Play 148
Summary 148
II: Other Ways to Build Apps
8 OAuth and Phoning Home 153
What Is OAuth? 153 OAuth Libraries 154 Setting Up Your Environment 154 When Is OAuth Not OAuth? 157 Secure Phone Home 157
Unsigned GET Request 158 Signed POST Request 162 Testing Your OAuth Implementation Locally 166 Making Real MySpace Requests 169
Spicing Up the Home and Profile Surfaces Using makeRequest 173
Summary 174
9 External Iframe Apps 177
REST APIs 178 How a REST Web Service Is Addressed 178 Setting Up an External Iframe App 179 The Server Code 181
REST API List 183 The Client Code 197 Friends Web Service and Paging 199 The Profile Endpoint 203
Sending Messages Using IFPC 208 Using the 0.7 Container for postTo 210 The Friends Response from the REST API 211 Summary 212
Trang 13xii Contents
10 OSML, Gadgets, and the Data Pipeline 213
The Big Picture 213 Gadget XML 214 Data Pipeline 214 OSML 214 Writing a Gadget 214
“Hello World” Gadget 214 Adding a Second Surface to the Gadget 217 Declaring and Using Basic Data 218 Data Pipelining 219
DataContext 220 Data Tags 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 223 Data Tag os:DataRequest 223 JavaScript Blocks in OSML Apps 225 OpenSocial Markup Language (OSML) 225 Basic Display Tags 226
Remote Content Display Tags 226 Control Flow Tags 226
Putting It Together: OSML Tic-Tac-Toe 226 Setting Up the Gadget 227
Reusing Common Content 230 Working with Data 235 Displaying Data Lists 237 Summary 238
11 Advanced OSML: Templates, Internationalization,and View Navigation 239
Inline Tag Templates 239 Defining and Using a Tag Template 240 Using Client-Side Templates 242 Working with Subviews 245 Converting Tabs to Subviews 245
Trang 14HTML 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 251 Internationalization and Message Bundles 255 Creating Our First Message Bundle 256 Creating Translations of the Message Bundle 257 Including Translations in an App and Testing 258 Future Directions 260
Summary 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 275 Managing Developers 279
Managing Testers 279 Event Handling—Installs and Uninstalls 279 Suspension and Deletion of Your App 280 Summary 281
13 Performance, Scaling, and Security 283
Performance and Responsiveness 283 What Is Responsive Performance and What Is Scale Performance? 283
Design for Responsiveness 284
Trang 15Rule 1: Validate Inputs 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 300 User Data Security 301 Application Security 301 Hacking and Cracking 302 Summary 303
14 Marketing and Monetizing 305
Using MySpace to Promote Your App 306 The App Gallery 306
App Profile, or Bringing Out the Bling 308 MySpace’s Own MyAds 308
User Base and Viral Spreading 309 Listen to Your Customers 311 Ads 311
Google AdSense 311 Cubics 313
RockYou! Ads 314 Micropayments 316 PayPal 316 Boku 317 Others 318 Interviews with Successful App Developers 318 Dave Westwood: BuddyPoke
(www.myspace.com/buddypoke) 318 Eugene Park: Flixster
(www.myspace.com/flixstermovies) 321
Trang 16Tom Kincaid: TK’s Apps (www.myspace.com/tomsapps) 322 Dan Yue: Playdom
(www.myspace.com/playdom) 324 Summary 326
15 Porting Your App to OpenSocial 0.9 329
Media Item Support 330 opensocial.Album 330 Fetching Albums 333 Fetching Media Items 335 Updating Albums and Media Items 338 Uploading Media Items 340
Simplification of App Data 341 REST APIs 343
Summary 348
References 351
Trang 17ForewordThe Internet is constantly evolving, with vast arrays of information on every topicgrowing at a remarkable pace Google’s 1998 search index had only 26 million Webpages; a decade later it recognizes more than 1 trillion URLs.With so muchinformation, we need a new set of tools to make sense of the Internet.The transition isfrom a strict focus on informational content, to being able to take advantage of our con-text, our relationships, and our activities
Enter the social Web, a relatively new twist to the Internet, which is being built up bysocial networks, portals, and even more traditional businesses.The “Open Stack” is a set
of specifications being developed by grass-roots communities all over the world, enablingdevelopers to create new products and services enhanced by user-specific data.TheOpen Stack includes specifications such as OAuth, which provides secure access to data;
OpenID, a global identity standard; and OpenSocial, a common API for building tions.These specifications are becoming the underlying infrastructure for the social Web,weaving a social fabric throughout the Web
applica-OpenSocial enables developers to learn a single core programming model that can
be applied to all “OpenSocial containers,” those sites that support the OpenSocialspecification With standards-based tools, including a JavaScript-based gadget API,
a REST-based data access API, lightweight storage capabilities, and access to commonviral channels, developers can build inside those containers as well as create applicationsfor mobile phones or other sites In late 2009, less than two years after its introduction,more than 50 sites have implemented support for the OpenSocial specification Inaggregate, these sites provide developers with access to more than 750 million users allover the world
By taking advantage of the OpenSocial API and the information available in thisbook, you will have a great opportunity to reach a lot of users For example, you’llfind the OpenSocial API supported by many major sites that span the globe:Yahoo!,iGoogle, Xiaonei and 51.com (China), Mixi (Japan), orkut (Brazil), Netlog (Europe),and, of course, MySpace Beyond that, OpenSocial is also supported by moreproductivity-oriented sites like LinkedIn and by Fortune 100 companies as diverse asIBM and Lockheed Martin
With this book, you can quickly get up and running with OpenSocial on MySpace,and you’ll be poised to leverage that experience to reach users on other sites as well.Thein-depth programming examples provide a good introduction to the design optionsavailable when building with the OpenSocial API, and the code is open source for ease
of use and future reference Additionally, the MySpace Platform tips sprinkledthroughout will help you avoid common mistakes and understand the intricacies of theirplatform policies Getting a feel for how social platforms operate will be valuable as youcontinue to explore the wide world of OpenSocial
OpenSocial is constantly evolving, just like the rest of the Internet.The OpenSocialspecification is managed through an open process where anyone can contribute their ideas
to influence the next version of the specification and help move the social Web forward
Trang 18for new developers to start using OpenSocial As you’re getting into the OpenSocial API,
be sure to contribute back to the OpenSocial.org community your ideas on how toimprove the specification
It’s open It’s social It’s up to you
—Dan Peterson, president, OpenSocial Foundation
San Francisco, California
August 2009
Trang 19Acknowledgments
Chris Cole:I’d like to acknowledge the great team at MySpace that helped build thedeveloper platform and all the people who’ve contributed to refining the OpenSocialspecification 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 writeour 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 slippedthrough the cracks
Jessica Whyte:Thank you to Trina MacDonald and Olivia Basegio at Addison-Wesley foryour 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
Trang 20Chris Coleis a software architect at MySpace and is a major contributor to buildingthe MySpace Open Platform and keeping it committed to OpenSocial He’s been a corecontributor to the OpenSocial 0.9 specification and is the primary architect and imple-menter of OSML (OpenSocial Markup Language) on the MySpace platform Chris hasbeen in software for fifteen years and has spent much of that time riding the variouswaves of the Internet and pushing the boundaries of the Web
Chad Russellis the lead developer on the MySpace OpenSocial team He knows theOpenSocial spec front to back, in addition to every tip, trick, and nuance of theMySpace platform itself Chad holds an engineering degree from the University ofToronto and currently resides in Seattle,Washington
Jessica Whytehas worked for several years as a journalist, most recently with Journalistsfor Human Rights, and is currently a graduate student at the University of Washington,studying Human-Centered Design and Engineering She lives in Seattle with herhusband and coauthor, Chad Russell
Trang 21This page intentionally left blank
Trang 22Welcome to the wonderful world of social apps.You are about to enter—or have alreadyentered—a fast-paced and treacherous landscape that can be exciting, frustrating,intellectually challenging—and yes, it can even be pretty profitable
We hope to be your guide through both the hidden pitfalls and the soaring peaks
There is much to gain from this exciting new market; social apps have been aroundfor only a few years, after all Many successful apps have yet to be created and thendiscovered by the millions upon millions of passionate MySpace users
In this book we’ll start from scratch and walk you through the entire process ofbuilding apps, from signing up as a developer all the way to building highly complexsocial apps that can scale out to thousands of users.We have extensive experience on theMySpace Development Platform (MDP), from building apps to helping build theplatform itself.We’ll point out the many idiosyncrasies and quirks of the platform, as well
as the many ways to squeeze out a little better performance by making a few tweaks toyour existing apps
Throughout this book we’ll demonstrate best practices and show lots of samplecode as we take a step-by-step approach to app development Starting with a simple
“Hello World”–style app, we’ll add functionality until we have a fully built,feature-rich app We’ll fetch data on the current user, get the user’s friend list andphotos, and parse all the data that comes back to display it on the screen We’ll sendapp invitations and notifications to help spark viral growth and send requests back toWeb services running on a third-party server in order to process and store data
Finally, and possibly most important, we’ll show you how to make money developingapps using ads and micropayments
When it comes to developing social apps on the MySpace platform, the sky is thelimit As of this writing, the most popular app on MySpace has more than 13 millioninstalls Maybe your app will be the next big thing All it takes is a good idea and a littlebit of knowledge If you provide the former, we can provide the latter
Our hope is that this book is accessible both to experienced social app developers and
to those developers who have only heard about it on the news.To that end, if you’restanding in the technology section of your local bookstore reading this, and you have abit of computer programming knowledge mixed in with some free time and curiosity,this book is for you
We’ll start from scratch in this introduction to ramp you up on MySpace andOpenSocial For those who already have apps up and running out in the wild, this book
is also for you, as we’ll dig pretty deeply into the platform a little later on.You may befamiliar with the ideas and terms we introduce here, so feel free to skip ahead a bit
(Check out the section on tools, though!)
Trang 23How to Read This BookThere are a couple of ways to read this book If you’re an experienced app developer,you can use this as a reference book.The index will direct you to specific topics, whereyou can consult the various tables, sample code, and tips Or, if you need to learn a newaspect of the platform, you can skip directly to that chapter and dive right in
If you’re not an experienced app developer, we suggest you start from the beginning
We’ll start off with a “Hello World”–style app in Chapter 1 and add to it in eachsubsequent chapter By the time the app is completed, you’ll have a broad knowledgebase of the entire platform.We then branch out into some advanced topics to take you
a step further
Assumptions Made by the AuthorsThis is not a book about how to code in JavaScript or Python or any other language.Wewill try to follow good practice in our sample code throughout the book, and we’llpoint out a few interesting tidbits along the way, but that’s all.This is a book on how towrite OpenSocial apps on MySpace
To that end, we assume the following:
n You have basic knowledge of computer programming in general Maybe you work
at a software company and write PHP every day, or you’ve taken a few ming classes, or you’ve taught yourself by constructing your own Web page
program-n You have basic knowledge of JavaScript or are willing to pick up the basics.We’renot talking advanced stuff here, just the basics like calling functions, giving values
to variables, and that kind of thing
With all that said, let’s get started!
“bling” out their Profiles in ways both beautiful and stunningly, shockingly bad
In addition to a Profile page, you are given a Home page (shown in Figure I.1),which only you can see It contains your notifications, “You have new mail!” and thelike, along with various links to other parts of the site and updates from your friends
It is the friend aspect that truly makes a social network.The idea is simple; you sign
up and are assigned a single solitary friend:Tom, one of the cofounders of MySpace
xxii Introduction
Trang 24Through various means, such as searching, browsing, or having a robot guess “People YouMay Know,” you can find new friends and add them to your list Having other users asfriends grants you certain privileges to their information You may have access to theirProfiles even if they’re set to “Private”; you see their updates on your feed; and, mostimportant to us, friends can interact inside apps
That’s MySpace in a nutshell You sign up, bling out your Profile, add some friends,upload some pictures, install some apps, and send some messages
What Is OpenSocial?
OpenSocial is a specification that defines how Web sites allow third-party apps to run ontheir sites.That means many things For example, OpenSocial defines what information aWeb site can and must expose for each of its users It defines a client-side JavaScript run-time environment with a set of APIs that describe how to fetch and update that userdata.This environment is commonly called an “OpenSocial container.” Likewise, itdefines a set of server-side APIs that manipulate the same data but can be called from aserver running your language of choice, such as PHP It also defines a markup languagecalled OSML that can be used to draw your app and fetch data
This specification was started by the folks at Google, along with the help of MySpace,Hi5, and other initial early adopters Maintenance of the spec has since been passed tothe OpenSocial Foundation and the community.That means any implementers, such asMySpace, Orkut, and LinkedIn, app developers, or really anyone at all can suggestmodifications to the spec and participate in setting the direction.Those modifications arethen voted on in a public forum and either brought into the spec (found at http://
opensocial.org) or rejected
Figure I.1 A MySpace Home page.
Trang 25Any 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 ofapps already created using OpenSocial If a site has correctly implemented all the variousAPIs, an app running on MySpace should run just as well anywhere else.That’s thetheory, anyway In practice there are differences, some small, some large, between thevarious OpenSocial implementers, which can make it tricky to maintain an app onmultiple sites
What Is the MySpace Open Platform?
The MySpace Open Platform (sometimes called MySpace Developer Platform or MDP)
is simply MySpace’s implementation of the OpenSocial spec MDP is a blanket term thatcovers how to sign up as a developer, how to update your app, and how to actually runyour app
MySpace tries its best (we really do) to fully implement the OpenSocial spec, butthere are bound to be some inconsistencies Most of these inconsistencies are small, butwe’ll cover them as they come up throughout this book MySpace has also implementedsome features that aren’t in the spec; we’ll cover these as well
More than on any other OpenSocial-enabled site, developing apps on the MySpaceplatform gives you access to a huge number of users and potential customers As of thiswriting, MySpace has more than 130 million monthly active users and is growing everyday Forty-five million of those users have installed apps.To give you an idea of thedemographics, 53% of app users are female, with an average age of 18 to 24.That is avery marketable demographic to have at your fingertips
What Tools Will You Need?
Here’s where we finally start to get a little technical After many long nights spentdebugging why that callback wasn’t being fired or where that stupid 401 unauthorizederror was coming from, we’ve found some really useful tools that will make your lifeeasier Let’s repeat that for effect:These tools will make your life easier
Browsers
First, a quick note on browsers Install Firefox right now Go to www.firefox.com In ouropinion it’s best to develop on Firefox, get your app running the way you like it, thenworry about running it in Internet Explorer (IE) as well Developing on the Web is still
an “IE and everyone else” process You get an app working in Firefox, and that means itwill probably work just fine in Safari, Chrome, and Opera.Then you can bang your headfor a few hours (days?) fighting floating divs and onclick handlers in IE
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
xxiv Introduction