一. MySpace开发简介:
Opensocial在MySpace platform中的应用,是
OpenSocial on the MySpace Developer Platform
Reading this should give you a brief introduction to OpenSocial and how it fits into MySpace.
Why is MySpace doing OpenSocial?
Let's start with an explanation of where we're coming from. MySpace has a very interesting history with applications written by users. You, gentle reader, may very well have participated in that history.
User coded, installable JavaScript applications have been on MySpace since it first launched. For those of you who were around since the beginning, you may recall that your user profile was a blank canvas on which you could paint with an unfettered pallette of HTML, JavaScript, and CSS. There were no constraints on what you could do, so long as a browser could render it.
MySpace was certainly not the first site to allow such things--there were many sites and services that allowed you to build your own "personal website" using any technology you desired. What set MySpace apart was that it was both personal site and social networking application: you could customize your site to your heart's content and you could interact with your friends in a variety of ways.
While unrestrained CSS and HTML provided users with limitless ways to make their profiles look a certain way, it was JavaScript that allowed them to really plug into the MySpace experience. After MySpace launched, users began building JavaScript widgets that did anything from customizing friends lists to sending MySpace Mail. And applications they coded were not limited to their own profiles. Through a little known technology known as "cut and paste", users could "install" applications they liked on their own profiles.
Where did all this functionality come from? While no specific XML/JSON api was provided, users quickly wrote and disseminated scripts that used JavaScript to screen scrape the existing MySpace markup (in order to gather data), and to emit the proper http values to manipulate the data they gathered.
Of course, a completely open MySpace was a utopic ideal. The exploitation began. As nefarious people began perceiving value in having lots of illegitimate friends, causing mischief, and/or making a profit through spam, they began writing applications that broke the rules. While a well thought out, law abiding "send me a message" app would send messages only at the request of the user, an app built by a spammer would send as many messages as the user's bandwidth would allow.
As spammers propagated through the site, MySpace began blacklisting certain types of JavaScript, HTML, and CSS. We tried very hard to keep as much JavaScript as possible, but slowly and surely illegitimate users hacked away at our filters until finally JavaScript was banned entirely. That left third party application developers with only one dyanmic alternative: Flash. Sites like YouTube saw their birth as widely disseminated Flash decorations for MySpace profiles. Unfortunately, by this time such applications were completely locked out of the MySpace data stream.
So--why is MySpace doing OpenSocial? Because every time we locked down a new JavaScript exploit we were sad, because we knew that legitimate application developers were getting hobbled as a result. For every ten spammers we blocked, we were blocking at least a few people trying to make a living by entertaining our users in a positive way. The OpenSocial platform gives us a chance to let MySpace users play again--this time in a safer, more structured, but at the same time more flexible way.
Enough history. Time for some code. By the time you're done with this document, you should be able to create a few sample OpenSocial apps on MySpace.
What is the MySpace Developer Platform?
The MySpace Developer Platform is a combination of services that provides third party application developers with hooks into MySpace's data and functionality. These services include:
- A suite of online tools for creating and publishing applications (and debugging them).set of RESTful APIs (provided in json, xml, and other formats as needed) that provide endpoints for browser-to-site and site-to-site interaction. These are implemented over the http protocol using a simple, intuitive uri scheme.
- A mechanism for your application to exchange data with your own site.
- A system for end users to find and install applications on their profiles.
- Security mechanisms for protecting end users' identity, as well as communications verification between MySpace servers and your site.
In short, the MySpace Developer Platform allows you to create stable, secure applications that (if you add the magic sauce) entertain MySpace users and allow them to explore the "social graph" in new and interesting ways. It also enables you to integrate your own site's functionality into MySpace. What do you get out of it? By writing an application that successfully entertains MySpace users (and believe us when we say they are fickle), you will gain fame, recognition, and traffic to your own site or service.
What is OpenSocial?
OpenSocial is a JavaScript API (Application Programming Interface) built in collaboration with Google and several other social networking sites. OpenSocial sits between your code and the MySpace Developer Platform. You call into OpenSocial, and OpenSocial in turn calls into the MySpace Developer Platform.
OpenSocial also provides guidelines for extensibility. For example, a MySpace user has a section called "Heroes", which is not in the OpenSocial spec. As you will see later on, there is a way to get special MySpace properties through the OpenSocial interface.
A Demonstration of an OpenSocial MySpace Application
In the video below, Chris Bissell, Chief Software Architect at MySpace, provides a brief demonstration of an OpenSocial MySpace Application at the Six Apart headquarters in San Francisco.
OpenSocial MySpace Application Demo - Chris Bissell
Add to My Profile | More Videos
How do OpenSocial and the MySpace Developer Platform fit together?
OpenSocial and the MySpace Developer Platform are a series of JavaScript and server-side components that work together to provide you with a standard interface to write your apps against.
Below is a rough picture of the communication between your app, MySpace, and OpenSocial. As you can see, OpenSocial lives completely on the client. There is no OpenSocial server and no communication between your app and some "OpenSocial" entity out there on the Internet.
figure 1 : Diagram of OpenSocial and MySpace Developer Platform Components
When you run your own app, you'll see that it's hosted in an IFrame. If you view the source around your code, you'll see a reference first to "opensocialreference.js", then to "MyOpenSpace.js". You should study these files carefully, for they contain the meat of the OpenSocial implementation, as well as MySpace's extensions on it.
Communication between your code, the browser, OpenSocial, and the server
How do opensocialreference.js and MyOpenSpace.js communicate? MyOpenSpace.js is dependent on opensocialreference.js. OpenSocial defines several basic social networking objects, as well as implementations for how to get and update those objects. MyOpenSpace, meanwhile, maps those objects to MySpace server-side API calls. At times, it also extends the objects (more on that later). Your code will hit the opensocial namespace almost exclusively, but be aware that it is the MyOpenSpace code that is doing the dispatching and data mapping. For example, the following code is the official OpenSocial request for the friends of the "Owner" (the person who has installed the application):
code snippet 1 : Basic DataRequest for Owner's Friends
function init()
{
var dataRequest = opensocial.newDataRequest();
//Create a request for the owner's friends
var friendRequest = dataRequest.newFetchPeopleRequest(opensocial.DataRequest.Group.OWNER_FRIENDS);
//Add the request for processing.
dataRequest.add(friendRequest);
//Send the request, passing in a callback.
dataRequest.send(response);
}
Underneath the covers, that request issues an Ajax call to the MySpace RESTful APIs, which return the results in JSON format. Below is an example of what the request looks like:
http://api.msappspace.com/opensocial/OWNER/profile.JSON...(params and security token)
...and below is what the response looks like. Note that the response is in the JSON format--it gets evaluated into JavaScript objects and therefore doesn't need to be human readible:
code snippet 2 : Internal Api Response: Friends (in JSON format)
{"count":3,
"friends":
[{"__type":"User:#MySpace.Services.DataContracts",
"image":"http:"/"/b2.ac-images.myspacecdn.com"/00000"/20"/52"/2502_s.jpg",
"name":"Tom",
"onlineNow":false,
"uri":"http:"/"/api.msappspace.com"/opensocial"/users"/6221",
"userId":6221,
"userType":"RegularUser",
"webUri":"http:"/"/www.myspace.com"/tom"},
{"__type":"User:#MySpace.Services.DataContracts",
"image":"http:"/"/x.myspace.com"/images"/no_pic.gif",
"name":"VipyApp 6",
"onlineNow":false,
"uri":"http:"/"/api.msappspace.com"/opensocial"/users"/313945780",
"userId":313945780,
"userType":"Application",
"webUri":"http:"/"/www.myspace.com"/313945780"},
{"__type":"User:#MySpace.Services.DataContracts",
"image":"http:"/"/x.myspace.com"/images"/no_pic.gif",
"name":"V2",
"onlineNow":false,
"uri":"http:"/"/api.msappspace.com"/opensocial"/users"/313921193",
"userId":313921193,
"userType":"RegularUser",
"webUri":"http:"/"/www.myspace.com"/313921193"}],
"next":null,
"prev":null,
"topFriends":null,
"user":{"__type":"User:#MySpace.Services.DataContracts",
"image":"http:"/"/x.myspace.com"/images"/no_pic.gif",
"name":"V1",
"onlineNow":false,
"uri":"http:"/"/api.msappspace.com"/opensocial"/OWNER",
"userId":313915716,
"userType":"RegularUser",
"webUri":"http:"/"/www.myspace.com"/vipymyspace1"}}
With OpenSocial, you don't need to parse the above code yourself. MyOpenSpace.js, MySpace's OpenSocial glue, will parse the response for you and map it to a set of OpenSocial Person objects.
Below is how you might work with the above code:
code snippet 3 : Simple response handler for OWNER_FRIENDS
function responseCallback(dataResponse)
{
var friendsData = dataResponse.get(opensocial.DataRequest.Group.OWNER_FRIENDS).getData();
friendsData.each(
function(friendData) {
var friendName = friendData.getField(opensocial.Person.Field.NAME);
var friendThumbnailUrl = friendData.getField(opensocial.Person.Field.THUMBNAIL_URL);
//Do work here with the friend's name and the friend's profile image...
}
);
}
That's the meat of OpenSocial: the DataRequest and the DataResponse. You batch the data you want into DataRequest--and you get back your results from DataResponse. Batching as much as you can into single calls will make your app perform better and give your users a better experience.
Stuff that isn't Implemented
Navigating between Profile and Canvas Panels
This does not currently work. When it does, you will call a function "requestNavigateTo()" to make your way between profile and canvas pages.
Activities and App Data
App Data is a way for your app to store data. Activities are ways for your app to notify users of events that have occurred.
二.MySpace与Facebook开发比较:
这部分内容多从相关的Blog和论坛中摘录.是Facebook开发人员转向Open Social遇到的问题,Myspce Platform现阶段存在的问题.其中很多是我们遇到的问题.在其中标记出来.
另外读这些讨论和Blog中得到这样的信息.
1. 现阶段,有很多Facebook的开发者都在考虑将自己的app移到Myspace中.可能有一些是我们在Facebook中熟人.感觉到竞争比较激烈.
2. 在Myspace上的开发都还在尝试阶段. 很多人都问到同样的问题, 就是和Facebook比较Myspace使用的Open social更像一个Widget而不是一个能够deeper integration and interaction between users的app.当然这也只是观察到的现象,可能有很多很强的开发者已经走在前面,我们的工作应该很急迫.
Facebook vs. MySpace/OpenSocial Development
(一个Blog描述了Myspace和Facebook的不同,比较全面 http://thoughtlabs.com/cs/blogs/cappy/archive/2008/02/08/facebook-vs-myspace-opensocial-development.aspx)
After having looked at MySpace's OpenSocial implementation I wanted to provide a comparison between it and the Facebook development platform. They are based upon completely different models and moving from one to the other is not as easy as one would hope.
Here's what's different in MySpace's Open Social Development Platform from what I've seen using the Facebook/Bebo platform. Where the items are known issues I have indicated as such. Some of these items have been derived from research and some from the MySpace forums. I have given links where available.
- Your MySpace application code is hosted on MySpace servers, NOT YOURS. There is no callback URL that you can provide that MySpace can use to call back to your server.
- It appears that the only way to communicate with your own server from your MySpace app is to use the makeRequest() API call.
- Currently this is ONLY supported for endpoints running on port 80! Out of luck if your development server runs on a different port.
- Supposedly MySpace is going to open some ports in a higher range to alleviate this issue. This is really, really frustrating.
- "MakeRequest gets around the XHR cross-domain restriction by utilizing a custom http proxy hosted by MySpace. This proxy relays incoming requests to other sites and pipes the results back to the browser. It also optionally signs the requests using the OAuth methodology…It is important to note that this is not a standard open proxy--it does its best to verify that the request came from a valid OpenSocial application hosted on MySpace."from <http://developer.myspace.com/Community/blogs/devteam/archive/2008/02/05/example-app-rss-reader.aspx>
- Maybe only able to send as GET params - unknown how to send as POST variables
- Currently only working on some URLs (does not work for http://www.google.com for example – known issue)
- Currently only returns responses in uncompressed format (known issue – they are working on this one)
- MySpace will be providing an 'App Data' 'something' to store application data but this is currently unavailable.
- Currently the only way to actually get code into your MySpace app is to paste it in a ridiculously small textarea control on the app profile page. Seriously. And doing so results in:
- Currently every time you update the code in your app it puts a NEW copy of the app on the respective page. Known Bug.
- During the 'sandbox phase' (length unknown) of the MySpace Development Platform only friends can add apps
- Only 3 installs of any given app allowed
- If not a friend, cannot see app
- There is no directory of apps yet
- Have to log in as the app (because you have to use a unique email address for each) and friend people as that user in order for them to see and add it
- More details here.
- There are no callbacks for any application events (post-add, pre-remove, etc.)
- You cannot encrypt or obfuscate your JavaScript code per the MySpace TOS…
- There is no datastore support
- There are 3 different places the app can be installed into a user's profile, height is modifiable (to some degree?), but NOT width
- Home page
- Profile page
- NOTE: any portion of your MySpace Applications and MySpace Application Content that will appear on a MySpace Profile must not:
- contain or create an
<iframe>
- cause their containing
<iframe> to be navigated to new location, for example, by using JavaScript code, form posts, or containing links;
- contain or create
<script> tags pointing to external sources except those that are explicitly allowed; and
- contain or create links to external CSS style sheets.
- Canvas page
- Your app code always runs in an iframe (provided by their container I guess).
- There is no formatting language (like FBML) or controls available other than straight (D)HTML. Kind of strange, this one. Facebook uses FBML that it converts to HTML (on its side) which it then pumps to the user's browser. Profile data can be cached on their servers. Very speedy. Could be me but it looks like MySpace is going to require all of your JavaScript to be executed on every refresh of the page – add to that a few calls back and forth to the container/ your server… What is going to happen to MySpace when there are 20 apps installed on each person's profile? Ewwww.
- All your JavaScript runs under/is subject to manipulation by Google's Caja; this may limit what your JavaScript can do but makes it safer for MySpace to run 3rd-party scripts. This could slow your JavaScript down as Caja may modify or restrict it.
- No/very limited support for 3rd-party JavaScript libraries so far; unknown when more will be available. Appears that jQuery is available based on this post. But if you have existing Facebook code that heavily uses Prototype/Scriptaculous/mootools/EXT/YUI/et.al. you are going to have a lot of reimplementation to do!
- Perhaps I am confused but there currently appears to be no obvious/legal way to go from one page of your application to another (from profile->canvas for example). There is an API for this (requestNavigateTo()) but it's not implemented yet. TOS explicitly forbids redirection of the browser window.
- No popups are allowed – not sure if this would include Facebook-style AJAX dialogs and their ilk or if this just means browser popup windows. Facebook also disallows popups but does have the FBJS Dialog object available.
- oAuth is required to ensure that the user making the request from your MySpace application is valid/trusted. See this post. I am not sure if this API's behavior is fully baked yet, though.
Facebook to MySpace Document (Is there one?)
http://developer.myspace.com/Community/forums/t/140.aspx
(Myspace论坛中的讨论如何从Facebook向Myspace转变,只是民间的讨论,没有Myspace的管理员参与.所以也没有很权威的结果.但反映了Facebook开发者转向Myspace后遇到的共同问题和困惑. 只摘录了其中比较有意义的Post)
http://forum.developers.facebook.com/viewtopic.php?id=8779
"Went to Hackathon last night, came out with the realization that to
port my Facebook app to OpenSocial, I need to rewrite a lot of my
code. The OpenSocial API is all in JavaScript. I played with Google
Map before, debugging JavaScript is a nightmare. JS is cool for
writing simple application or basic dynamic contents, but if you plan
to develop apps that may grow into something fancy, I would stay away
from OpenSocial until Google builds out a REST API that can map to
what Facebook has.
From a performance perspective, with Facebook, you use FBML and
facebook translates the FBML into simple HTML before serving it to
browser. But with OpenSocial, all you stuffs sit in xxxKB of JS, which
the browser downloads, then execute. You end up making zillions of
AJAXie calls; it is slow, taxing to your server, and if not careful,
crashes the browser.
That was my impression. I could be wrong because I only spent couple
hours looking into OpenSocial. But here is my problem:
1. My app belongs to the long tails that is not making any money. I am
willing to put 5-10 more hrs, but not 50-100 hrs to learn another
language to rewrite the whole thing.
2. Looks like the OpenSocial API is still rapidly evolving, old stuffs
are getting deprecated. I don't want to waste my time and have to redo
everything again.
3. Four months into making, opensocial is still not opened to the
public. So even if I spend that 100-200 hrs, there is no guarantee
that my app will get approved and get listed by Google. (According to
the presentation, Google will evaluate whether your app is a good
"fit" before it will list it).
4. Even after my app is listed, there is no guarantee that it will get
traction and make money.
5. There is the breach of TOS problem with showing Facebook contents
(brought up by one of the developer last night). I don't want to get
sued. Without pre-existing contents from Facebook, "What's your
Stripper Name" is no different from "What's your Stripper Knock-Off".
The dog-eat-dog game has to start all over again. Not sure if I want
to deal with that again.
6. Finally, my time is limited. On one hand, Bebo allows me to reuse
most of all my Facebook code, and it is ready, open to all developer.
On the other hand, Google is asking me to rewrite a lot of things, and
there is no guarantee my app will get listed.
The choice is simple. I am going to pass for now. Bebo, if you are
reading this thread, let me know if you have a Hackathon."
I have a simple facebook application that I need someone to convert to opensocial(specifically for myspace, but I would like to use it on the other social networks that utilize opensocial for apps). Is there anyone out there that is willing to do it for some money? Like I said it's simple so it wouldn't be a big job at all.
The issues raised by the OP and others on this thread are valid, and as someone involved with the MySpace Developer Platform (including OpenSocial) I wanted to take some time to give an alternative perspective.
Some of the comments on this thread seem to suggest that MySpace should have adopted FBML as it's markup language. However, it's worth remembering that FBML is a proprietary format, maintained and controlled by Facebook. It's great at what it does, and I tip my hat to our friends over at the Facebook Platform for creating it.
But remember, MySpace wouldn't be allowed to just 'take' FBML and there's no reason to assume Facebook would let Myspace use it if they wanted to. It would also mean that MySpace would be unable to offer differentiating functionality that occurred outside the FBML spec.
So with that in mind the choice was either create yet another proprietary markup language controlled by MySpace, or use more open and common tools that people already know - ie Javascript and HTML.
Take that train of thought to the next level - how can you implement something that will be even more common? Something that once you have learned it has maximum utility elsewhere on the internet... and you have OpenSocial. Not only is the scripting language familiar but the calls themselves and syntax in general is usable on other social networks and containers too.[l2]
You might complain that your existing FBML app won't work in MySpace, and I feel the frustration. But remember you have built it using a proprietary language controlled by a single company. Porting over to OpenSocial will take some time, but the upside is that it should be very easy to get your app working on other social networks too - maximizing the time spent.
If your app is a 'longtail' one in the Facebook environment, remember that MySpace offers are whole new frontier with a new first mover advantage when the platform is opened to consumers in March. To me, that makes it worth the time to convert to OpenSocial.
And no one is telling you not to continue developing your Facebook version too - although we hope that you'll find great success on MySpace!
I hope this explains some of the decisions made with the MySpace Developer Platform - and that this is about MySpace committing to open, familiar and common standards and formats with it's developer program that benefit the app developer in the long run - and in turn benefit users.
一个Facebook的开发者的问题,正是我们的问题.遗憾的是只有问题,还至今没有回答.
Hi Ben, Thanks for your response. Its nice to hear the reasoning behind choosing a more 'open' framework as the platform for Myspace Apps, however I think the complaint isn't that we've all learned this proprietary language and are now railing against Myspace because they didn't choose that proprietary language as their own platform. Rather, the problem seems to be that building a feature rich application, like suppose, Friends for Sale from Facebook Platform, will be a tough proposition on Myspace. Loading up generic templates with blank holes in them, and sending AJAX requests to Myspace for data about users to fill those holes, and AJAX requests to ones own server for application specific data to fill those holes seems error prone, slow, and performance intensive. Does myspace plan to address this? The above situation sounds LESS like any other web application I've developed, and FBML apps seem MORE like other web application I've developed. [l3] Also, how do you deal with the issue of canvas page apps that have more than one page of content? You now have to rebuild all of your server side application logic (which is not built in a proprietary language) to work in JS. OpenSocial is a widget platform, not an application platform. [l4]
Google Open Social feedback
(从facebook讨论版看到的一个讨论,对两者区别的一个比较经典评论)
Facebook and opensocial are completely different. Facebook is more of a way to integrate functionality within a service. Open social is more of a way to standardize putting a widget on a profile. Facebook allows much deeper integration and interaction between users, but if all you want is to make a profile badge that works on lots of different sites, open social isn't bad.
My personal experience is that learning from code is always better then going through pages of docs.
I couldn't agree more!
三.在Beta版的Myspace platform上开发安装App.
第一个Myspace的创建步骤
2. You will need to use an email address that has not been used to create any other accounts on MySpace.
3. 按邀请输入App的信息就进入Application Builder页,在文本框中输入HTML/Javascript Source 或Flash.
4. Save application source后就创建成功了.
7. 点击install则该App就被安装成功.则在用户的三个地方会有显示.
Canvas页http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?id=101814
附:例子的代码,这个例子及介绍见http://developer.myspace.com/Community/blogs/devteam/archive/2008/02/05/example-app-rss-reader.aspx?CommentPosted=true#commentmessage
Example app: RSS Reader
In this post I hope to get you off the ground in terms of how to request data from other sites using the OpenSocial API. Remember that in OpenSocial your application is hosted in the browser and served off the container's domain (in this case, MySpace). XHRs (XML Http Requests) cannot be issued across domains (for example, Javascript hosted off of http://www.myspace.com cannot access data from http://www.google.com). Because of that restriction, you can't make a straight call to another domain. The OpenSocial API provides a simple mechanism called "makeRequest" that allows you to request data from any domain you want.
MakeRequest gets around the XHR cross-domain restriction by utilizing a custom http proxy hosted by MySpace. This proxy relays incoming requests to other sites and pipes the results back to the browser. It also optionally signs the requests using the OAuth methodology (the specifics will be covered in another article). It is important to note that this is not a standard open proxy--it does its best to verify that the request came from a valid OpenSocial application hosted on MySpace.
MakeRequest method signature:
opensocial.makeRequest(url,callback,opt_param)
url
The url you wish to be called.
callback(data)
The function you wish to be called with the results. The signature of the function should have at least one parameter (which will contain a reference to the data returned by the call).
opt_param
A bucket for a set of standard OpenSocial parameters that tell the proxy how to behave. There is quite a bit of functionality accessible through the manipulation of this object. To give you a taste of what you can do, below is some example code that exercises opt_param to its fullest.
code snippet 1 : Drill down into makeRequest parameters
function getRss(){
var url = "http://www.codeproject.com/webservices/articlerss.aspx?cat=1";
var params = {};
//Lets makeRequest know that the result will be an XML document.
params[opensocial.ContentRequestParameters.CONTENT_TYPE] =
opensocial.ContentRequestParameters.ContentType.XML;
//Sets the request method to POST (default is GET).
params[opensocial.ContentRequestParameters.METHOD] =
opensocial.ContentRequestParameters.MethodType.POST;
//Adds two custom headers to the request. These headers will be passed on to the target.
params[opensocial.ContentRequestParameters.HEADERS] =
{"x-myheader":"myheadervalue", "x-myotherheader":"myotherheadervalue"};
//Tells the proxy to sign the request using OAuth.
params[opensocial.ContentRequestParameters.AUTHORIZATION] = opensocial.ContentRequestParameters.AuthorizationType.SIGNED;
opensocial.makeRequest(url, makeRequest_callback, params);
}
So goes the request. opt_param takes a bucket of constants that you can use to tweak the request:
opensocial.ContentRequestParameters.CONTENT_TYPE
(takes a value from: opensocial.ContentRequestParameters.ContentType)
opensocial.ContentRequestParameters.METHOD
(takes a value from: opensocial.ContentRequestParameters.MethodType)
opensocial.ContentRequestParameters.HEADERS
(takes a key-value bucket)
opensocial.ContentRequestParameters.AUTHORIZATION
(takes a value from: opensocial.ContentRequestParameters.AuthorizationType)
This is not the official documentation for makeRequest, so I won't go into many details--instead I'll go on to create the app:). The code that parses the response is quite simple:
code snippet 2 : Response handling code
function makeRequest_callback(data,error){
if (data == null) {
$("rssDisplay").innerHTML = "no data returned--check your RSS url!";
return;
}
var channelList = data.getElementsByTagName("channel");
var channel = new RSSChannel(channelList[0]);
$("header").innerHTML = getTag("h1", channel.Title);
$("rssDisplay").innerHTML = channel.render();
}
The example application in this post is an RSS reader that uses a custom bit of code that translates XML into JavaScript objects. Parts of that code will be a lovely exercise in redundancy. Why? Because OpenSocial exposes an RSS implementation that is more robust than the one in this article. This article is more about how to call a third party site and parse the results (be they XML, JSON, or some other format). A lot of sites happen to expose XML in RSS, so I'm using such exposure as an example. In other words, this article continues the long and storied tradition of useless demo-code--sit back and enjoy!
MakeRequest: Simple RSS Reader Application
MakeRequest is for pasing data to and receiving data from your site (or, in the case of a mashup, a third party's site). Its method signature is:
First, let's set up some chrome and an initialization function:
code snippet 3 : Simple chrome for application
<style>
body {
background-color: whitesmoke;
}
h1 {
font-size: medium;
}
#rssDisplay {
border: 1px solid;
height: 240px;
overflow: auto;
padding: 3px;
background-color: white;
}
#rssDisplay p {
font-size: small;
}
</style>
<div id="container">
<div id="header">
</div>
<div id="rssDisplay">
</div>
<script>
function getRss(){
//this will get the feed
}
getRss(); //initialize the application
</script>
</div>
Above we have the trappings of an application--with no functionality. We'll now fill in the getRss() call with Javascript that calls the RSS feed (which happens to be the latest articles from "The Code Project").
<style>
body {
background-color: whitesmoke;
}
h1 {
font-size: medium;
}
#rssDisplay {
border: 1px solid;
height: 240px;
overflow: auto;
padding: 3px;
background-color: white;
}
#rssDisplay p {
font-size: small;
}
</style>
<div id="container">
<div id="header">
</div>
<div id="rssDisplay">
</div>
<script>
/*
* makeRequest implementation
*/
function getRss(){
var url = "http://www.codeproject.com/webservices/articlerss.aspx?cat=1";
var params = {};
//This parameter lets makeRequest know that the result will be an XML document.
params[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.XML;
opensocial.makeRequest(url, makeRequest_callback, params);
}
function makeRequest_callback(data, url, error){
if (data == null) {
$("rssDisplay").innerHTML = "no data returned--check your RSS url!";
return;
}
var channelList = data.getElementsByTagName("channel");
var channel = new RSSChannel(channelList[0]);
$("header").innerHTML = getTag("h1", channel.Title);
$("rssDisplay").innerHTML = channel.render();
}
/*
* Utility functions
*/
//Cross browser grabber for text in an xml element
function getNodeText(node){
if (node.text != null)
return node.text;
else
return node.textContent;
}
//Simple, non-performant tag renderer
function getTag(tag, txt){
return "<" + tag + ">" + txt + "</" + tag + ">";
}
//Adds a tag to a string
function appendTag(str, tag, txt){
str += getTag(tag, txt);
}
/*
* RSS Feed Wrapper Objects
*/
function RSSChannel(node){
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes.item(i);
switch (childNode.nodeName) {
case "title":
this.Title = getNodeText(childNode);
break;
case "link":
this.Link = getNodeText(childNode);
break;
case "description":
this.Description = getNodeText(childNode);
break;
}
}
var items = node.getElementsByTagName("item");
this.RSSItems = [];
for (var i = 0; i < items.length; i++) {
var item = items.item(i);
var rssItem = new RSSItem(item);
this.RSSItems.push(rssItem);
}
}
RSSChannel.prototype.render = function(){
var output = "";
// output += "<h1>" + this.Title + "</h1>";
for (var rssItemId inthis.RSSItems) {
var rssItem = this.RSSItems[rssItemId];
if (rssItem.IsValid != null && rssItem.IsValid())
output += rssItem.render();
}
return output;
};
function RSSItem(node){
this.Title = "";
this.Description = "";
this.Link = "";
this.Author = "";
if (node.childNodes == null)
return;
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes.item(i);
switch (childNode.nodeName) {
case "description":
this.Description = getNodeText(childNode);
break;
case "title":
this.Title = getNodeText(childNode);
break;
case "link":
this.Link = getNodeText(childNode);
break;
case "author":
this.Author = getNodeText(childNode);
break;
}
}
}
RSSItem.prototype.render = function(){
var output = "<p>";
output += "<a target=""_top"" href=""" + this.Link + """ title=""" + this.Description + """>";
output += this.Title;
output += "</a>";
output += "<br />";
output += "<i>by " + this.Author + "</i>";
output += "</p>";
return output;
};
RSSItem.prototype.IsValid = function(){
if (this.Title != null && this.Title != "")
returntrue;
};
getRss();
</script>
</div>
And there you have it. A simple RSS reader. Don't expect the code to parse all types of RSS feeds :).
Let me see my app!
Here's a walkthrough on how to work with some of the restrictions during the current developer sandbox phase that Kyle pointed out here.
So let's assume you've gotten on the whitelist, logged in to the developer site, started creating an app and you're at the point of saving your chunk of code (for a walkthrough of that process, see here )... now how do you actually see your app live?
First you need to install it by getting to the App Profile:
An App Profile (see "Anatomy of a MySpace App" for a more complete explanation) is your app's very own MySpace profile. It's automagically created along with each app. Most importantly, it's the *only* place where anyone (including yourself as the developer) can install the app.
To get to it from the Application Builder, click on the "Edit App Information" link on the left nav:
From the Edit App Information page you can click the "Visit Profile Link"
From the app profile you can click the "Install Application" button and the page will redirect you to the app after installing.
Great! Now you have your app installed and YOU can see it… but how come no one else can see it!?
All apps are hidden from viewers unless the viewer is friends with the app's profile during the developer sandbox phase. Likewise, App Profiles are private by default. Keep in mind that the app’s friends are not the developer’s friends. Remember your app has its OWN distinct profile! As the developer of the app, you're automatically the app’s first friend and that's why you're allowed to see the app.
Thus, in order for another user to install or view an app, they must be:
- logged in to MySpace (even if the app is on a publicly viewable profile)
- a friend of that app
So the natural question that follows is: "How does my app add friends?"
Well you can actually login to MySpace as your app. Remember the email and password you entered when you first created your app on the developer site (on this very first page)?
Hopefully you have them handy... just use those credentials to sign back in to MySpace as your App Profile:
Now you're logged in under the app’s profile and can add friends:
To add a someone as a friend of the app, go to their profile, for example:
Click "Add To Friends" and continue to follow the standard MySpace procedure for adding friends.
Once your app's new friend accepts the request, she can install the app (if the three installation limit hasn't been reached yet!) or view the app on profile's where the app is installed.
Understandably, some of the above can be somewhat cumbersome and confusing, however in the future this “private” state is fundamentally designed to allow your app to be in “stealth” development mode, while still allowing for your app to be shared amongst a controlled set of users.
四.Myspace关于开发平台一些问题声明.
When can I release my application?
We cannot give an exact release date, as the release of this platform depends largely on the results of this initial beta test. We hope to release the platform in the earlier part of 2008.
Can I develop a MySpace Application?
Anyone over the age of 18 (or over 14 with their parents’ permission) can develop applications for MySpace! Although the documentation here is currently very technical, we hope to add more tutorials and walkthroughs in the future to make our platform accessible to members of all skill levels.
What will I do with the application I’m building here?
Any application built now is for testing purposes only. A developer may add the application to a maximum of three MySpace profiles for testing. Once the Developer Platform is ready for prime time, you will be able to release your application to the MySpace community, and showcase it in the Application Gallery.
Where’s the Open Social Activity Feed?
The API set currently documented on this site is not intended to be complete. The Activity Feed API is just one example of additional API’s that will be added in the near future.
Who hosts my application?
You application will need to be hosted on MySpace servers. This may change in the future.
When can I release my application?
We cannot give an exact release date, as the release of this platform depends largely on the results of this initial beta test. We hope to release the platform in the earlier part of 2008.
Can I use advertising?
You are welcome to add advertising to any page that is primarily controlled by you: your application and developer profile pages, and your application canvas page. You may not place an advertisement on a members’ profile.
Where can I learn more about Open Social?
Check out the Open Social site for more information.
You can also find answers and ask questions in our Forums.
Why am I asked to provide a unique email address for each application I create?
Every application is given a MySpace profile, which requires an email address for creation. All application profiles will remain private during this beta phase.
How can I contact someone at MySpace?
Developers who work on the Platform and other MySpace employees are aways available in the forums, and posting in the blog. However, if you can't find an answer there, you can email us at developerrelations (at) myspace.com.
An App Profile (see "Anatomy of a MySpace App" for a more complete explanation) is your app's very own MySpace profile. It's automagically created along with each app. Most importantly, it's the *only* place where anyone (including yourself as the developer) can install the app.
五.Tips
Per Google/OpenSocial, the makeRequest callback returns the explicit object based on the content type you requested.
HTML will return the responseText.
XML will return the responseXML.
FEED will return our RSS2 feed object (soon to include ATOM).
六.朋友添加一个App
1.以这个App的注册邮箱登录,和一个myspace的普通用户登录一样.
2.在这一个朋友的profile页,添加一个朋友,和一个普通用户添加朋友一样.
3.那个被添加的朋友访问这个App的Profile页,就可以install这个App了.
当前这个rss test的profile页是: http://profile.myspace.com/index.cfm?fuseaction=user.viewprofile&friendid=334581169
七. 实用问题:
1.userId
http://developer.myspace.com/Community/forums/t/402.aspx
http://developer.myspace.com/Community/blogs/devteam/archive/2008/02/19/where-s-my-data-api.aspx
Jonathan, I think I know what you're asking.. let me rephrase and see if I'm right.. "How can I pass the user's myspace userid to my server-side script so I can return that user's information?" Is that right?
MySpace (OpenSocial) doesn't do what Facebook does. Facebook's servers act as an intermediary between the Facebook user and your server-side script! That way, FB can pass along variables to your server-side script when your canvas is activated... thus allowing you to figure out the user by the parameters FB passes along.On your server-sidescripts, you can make requests back to FB's servers, which the client library you're probably uses conveniently signs according to FB's API authorization algorithm (which verifies that YOUR SERVER can access FB's servers for info).
To do the equivalent on OpenSocial / MySpace REST API. OpenSocial provides a way using Javascript to get the user who is viewing the script's ID. Again, to compare to Facebook: Whereas FB acts as a middleman, OpenSocial lets you explicitly get the user's info...The developer's blog has a good post: http://developer.myspace.com/Community/blogs/devteam/archive/2008/02/19/where-s-my-data-api.aspx
<div id="output"></div>
<script type="text/javascript">
var user_id = 0;
function init() {
//Set the owner id so we don't have to use it later
var personId = opensocial.DataRequest.PersonId.OWNER;
//Create our DataRequest object
var dr = opensocial.newDataRequest();
//Set up an empty params object so we can use it for functions that require params.
var opt_params = {};
//Request Person data
var personReq = dr.newFetchPersonRequest(personId);
//Add all the requests to the DataRequest
dr.add(personReq,'SmallPerson');
//send request
dr.send(response);
}
//Response callback...
function response(data) {
var person = data.get('SmallPerson').getData();
user_id = person.getField("id");
}
init();
</script>
Now, once you have the users id, you can do a makeRequest call and pass that id back IN! If you'd like to verify it on your server, you'll THEN have to implement OAuth on your server to verify it make from opensocial... I'm still looking into how to do that.
makeRequest is a commonly used in OpenSocial development (for our purposes we’ll be using the MySpace Developer Platform) to gather, store, and retreive remote data.
The opensocial.makeRequest() method is an enhancement to the current gadget methods. The opensocial.makeRequest() method allows for POSTs as well as GETs, and you can specify whether you want your data fetch to be signed or even authenticated. Once containers implement this call, your external servers can be more secure. (…more)
makeRequest uses GET as it’s default method, but I’ll show you how to use makeRequest to access your server-side scripts using GET or POST params (or an even simpler alternative method: appending the variables to the URL).
Rather than recite the Google docs I’ll jump right in. Below is a very simple makeRequest call that fetches the contents of an HTML page and prints it inside a given element.
1
2
3
4
5
6
7
8
9
10
|
<script type="text/javascript">
function init() {
var url = "http://www.spacebuz.net/blog/wp-content/uploads/2008/02/makerequest1.php";
var params = {};
opensocial.Container.get().makeRequest(url, function(response) {
document.getElementById("toReturn").innerHTML = response;
}, params);
}
init();
</script>
|
1
|
<divid="toReturn"></div>
|
As per the Google docs, there are three arguments to makeRequest. The first is the URL we’re requesting to return content (in this case, a PHP file with simple text in it). The second argment is a function whose argument is the content the url responds with, which you can manipulate accordingly. The third argument are our parameters to pass through the request, which we’ll ignore for now. Copy and paste this code anywhere openSocial is implemented and you’ll see it return the text located in makerequest1.php
Yes, it’s that simple.
As mentioned, GET is the default method used in makeRequest. To use POST, we simply set ContentRequestParameters.MethodType to POST in our params variable. In addition, we add a parm for all of the POST content we want to send. This content is in the same format of GET variables appended to a URL. Let’s take a look at our new code that makes a call to another (similar by dynamic) script that uses the variable $_POST[’name’].
1
2
3
4
5
6
7
8
9
10
11
12
|
<script type="text/javascript">
function init() {
var url = "http://www.spacebuz.net/blog/wp-content/uploads/2008/02/makerequest2.php";
var params = {};
params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.POST;
params[opensocial.ContentRequestParameters.POST_DATA] = "name=Buz";
opensocial.Container.get().makeRequest(url, function(response) {
document.getElementById("toReturn").innerHTML = response;
}, params);
}
init();
</script>
|
makerequest2.php looks like this:
1
|
<p>Here's the text you requested, <?php echo $_POST['name']; ?>!</p>
|
Run this code and watch it return information from makerequest2.php to your page.
This is the basic functionality of makeRequest that should get you started. makeRequest also allows you to set other options like contentType (html by default, as well as xml and feed) and of course if you’re developing a user based application, the authenticationType
3. Pass User Id to Iframe app
There have been some questions on how to pass the myspace user id to an application that runs in an iframe on the canvas surface, so here is what worked for me:
Code for the Canvas Surface:
<iframe id="msiframe" name="msiframe" src="" height="1000" width="790" frameborder="0"></iframe>
<script type="text/javascript">
var serverURL='http://www.myserver.com/MSAuthenticate'; // change this to your server & authentication routine
function init() {
var params = {};
params[opensocial.ContentRequestParameters.METHOD] = opensocial.ContentRequestParameters.MethodType.GET;
params[opensocial.ContentRequestParameters.CONTENT_TYPE] = opensocial.ContentRequestParameters.ContentType.HTML;
params[opensocial.ContentRequestParameters.AUTHENTICATION] = opensocial.ContentRequestParameters.AuthenticationType.SIGNED;
opensocial.Container.get().makeRequest(serverURL, loadiframe, params);
}
function loadiframe(targetURL) { frames['msiframe'].location.href = targetURL; }
init();
</script>
You then need to build a routine on your server called MSAuthenticate. This routine will receive the following parameters (HTTP GET):
oauth_nonce '-100735'
opensocial_viewer_id 'xxx'
oauth_timestamp '34'
oauth_consumer_key 'http://www.myspace.com/xxx'
oauth_signature_method 'HMAC-SHA1'
oauth_version '1.0'
oauth_token ''
opensocial_owner_id 'xxx'
oauth_signature ''
The MSAuthenticate routine authenticates the request (or not) and returns a URL (eg. http://www.myserver.com/Homepage?uid=<opensocial_viewer_id>, or possibly http://www.myserver.com/InvalidRequest) which will be loaded into the iframe.
The 'oauth_signature' parameter is currently empty, so my MSAuthentication routine is just 'approving' every request for now. Hopefully, this will be remedied prior to launch.
Thanks to "Mike" for the makeRequest code.
八.Related Concepts
1.High REST versus Low REST
REST (Representational State Transfer) is a type of software architecture used on distributed hypermedia systems such as the World Wide Web.
The MDP (MySpace Developer Platform) is based on REST principles and has the following functionality:
1. Allows server-to-server requests to expose user information
of installed users.
2. Allows an application to modify a user's data if the user has
granted appropriate permission to the application.
3. Exposes communication functionality for friend activities,
messaging, bulletins, and application notifications.
REST architecture defines how the network resources are described and addressed, and a distinction is made between "high REST" and "low REST." The distinctions between the high REST and low REST architectures are described below.
High REST uses the four main HTTP verbs - GET, POST, PUT, DELETE - to manipulate resource representations. XML files serve as message carriers that insert meta data into HTTP headers.
Low REST is also known as "Plain Old XML" over HTTP or POX. Low REST architecture uses only HTTP GETs to access all APIs, and conforms to the constraints of the HTTP GET and POST verbs associated with non-XML web architecture.
[l1]Show the result in profile.
[l2]Why use JS in opensocial
[l3]Myspace中如何开发如Facebook的Friends for Sale的功能复杂的App.
[l4]OpenSocial is a widget platform, not an application platform. [l4]
刚开始写博客! 呵呵,主要是记录下自己的一些东西,期望和大家交流.
posted on 2008-03-03 14:25
pinuo 阅读(965)
评论(0) 编辑 收藏 所属分类:
PHP