Donnerstag, 3. Februar 2011

Facebook JS API & YouTube API & AppEngine and you have CrackUp.tv

Today I wanted to look into Facebook integration for MiuMeet.

I decided to play with the Facebook Graph Javascript SDK and build a small application.

So what should I build? How'bout this:

  • A website that shows YouTube videos that your friends thought were funny on facebook.
  • Whenever a clip ends, the user needs to rate how funny the video is in order to see the next video.
  • Depending on his rating we show different videos to the users in the future.
  • If the user liked the video, "Like" it on facebook, if he loved it, post it on his facebook wall.
I was able to build and launch a version within 48h it was that easy.

See the result here: www.crackup.tv




Core parts of the code

Initialize Facebook GraphAPI Javascript:

FB.init({ appId: '186752184677345', status: true,
            cookie: true, xfbml: true });
The "cookie" part is quite important, because that's how I authenticate the user afterwards on the AppEngine server-side.

Once the user is logged in I request from facebook all the friends that also used this app.
For this you need to do a legacy call, the Graph API doesn't support it directly, but it's still very easy:

FB.api( { method: 'friends.getAppUsers' }, callback});
After this, I send a request to the AppEngine server to load all videos that the users friends rated high.
I can limit the number of datastore lookups drastically, by only looking up the friends of the user that have installed this facebook app too by using the legacy call above instead of loading /friends/. This is quite nice. If you would just use the normal friend list I would have to lookup tons of entries in the datastore that wont exist.

In AppEngine I authenticate the user by just looking at the facebook cookie:


def getAuthProfileUID(request):
  if "fbs_186752184677345" not in request.cookies:
    return None
  try:
    cookie = request.cookies["fbs_186752184677345"]
    uid = cookie[cookie.find("uid=") + 4:]
    if "&" in uid:
      uid = uid[:uid.find("&")]
    if "\"" in uid:
      uid = uid[:uid.find("\"")]
    return uid
  except:
    return None
Then I magically create the playlist for this user and hope that he posts many of them on his wall :)

Simple.

Key take-aways
  • The Facebook JS API is very simple to use and quite nicely structured
  • You don't need to talk to facebook from the server-side to authenticate the user.
  • If you want to load all the friends of a user that you have in your datastore, use the Javascript call friends.getAppUsers instead of /friends/ because you can limit the numbers of friends you need to look up drastically.
Cheers,
-Andrin

0 Kommentare:

Kommentar veröffentlichen