Labels

Thursday, December 8, 2011

Facebook Graph API cookbook page

Working with the Graph API

Overview

The graph API is a collection of RESTful web services facebook provides. Using the graph api, you can publish, interact with or create almost anything in facebook. Developers make GET, POST and DELETE requests to different parts of https://graph.facebook.com. These requests can require an access token, which grants read/write privileges.

Facebook provides a tool at https://developers.facebook.com/tools/explorer that lets users generate access tokens for their account with any combination of permissions and make graph api calls. Try using this tool to interact with your facebook accounts. You can read facebook’s graph api documentation here: https://developers.facebook.com/docs/reference/api/

Body

GETing https://graph.facebook.com/1206427506 (my facebook user id) with no access token returns this JSON:
{
 "id": "1206427506",
 "name": "Paul Kinsky",
 "first_name": "Paul",
 "last_name": "Kinsky",
 "link": "https://www.facebook.com/people/Paul-Kinsky/1206427506",
 "gender": "male",
 "locale": "en_US",
 "type": "user"
}

The same call with an access token granting the user_about_me privilege to my account returns this JSON:
{
 "id": "1206427506",
 "name": "Paul Kinsky",
 "first_name": "Paul",
 "last_name": "Kinsky",
 "link": "https://www.facebook.com/profile.php?id=1206427506",
 "hometown": {
   "id": "113001432047882",
   "name": "Wareham, Massachusetts"
 },
 "location": {
   "id": "105596609473837",
   "name": "Worcester, Massachusetts"
 },
 "gender": "male",
 "timezone": -5,
 "locale": "en_US",
 "languages": [
   {
     "id": "113301478683221",
     "name": "American English"
   }
 ],
 "verified": true,
 "updated_time": "2011-11-02T16:50:18+0000",
 "type": "user"
}




The facebook php sdk handles graph api calls with the Facebook::api() method.

$facebook->api('/me/feed', 'POST',
                                   array(
                                     'link' => 'www.example.com',
                                     'message' => 'Posting with the PHP SDK!'
                                ));

Graph API reference:



Components:
  1. $facebook
    1. a Facebook object initialized with your application’s APP_ID and APP_SECRET
  2. '/me/feed'
    1. the part of the facebook graph api to contact
    2. in this case, the feed of the current user
  3. ‘POST’
    1. the type of request
    2. in this case, we’re POSTing to the current user’s feed
  4. array(...)
    1. parameters specific to the graph api call
    2. in this case, we’re posting a link to 'www.example.com' and the message that we’re 'Posting with the PHP SDK!' to the currently logged in user’s feed, or news feed.





Here’s an example using this code from facebook’s documentation:


Example code

<?
 // Remember to copy files from the SDK's src/ directory to a
 // directory in your application on the server, such as php-sdk/
 require_once('php-sdk/facebook.php');


//These parameters can be viewed when you create your test app here: //https://developers.facebook.com/apps
 $config = array(
   'appId' => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 );

 $facebook = new Facebook($config);
 $user_id = $facebook->getUser();
?>
<html>
 <head></head>
 <body>

 <?
   if($user_id) {

     // We have a user ID, so probably a logged in user.
     // If not, we'll get an exception, which we handle below.
     try {
       $ret_obj = $facebook->api('/me/feed', 'POST',
                                   array(
                                     'link' => 'www.example.com',
                                     'message' => 'Posting with the PHP SDK!'
                                ));
       echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';

     } catch(FacebookApiException $e) {
       // If the user is logged out, you can have a
       // user ID even though the access token is invalid.
       // In this case, we'll get an exception, so we'll
       // just ask the user to login again here.
       $login_url = $facebook->getLoginUrl( array(
                      'scope' => 'publish_stream'
                      ));
       echo 'Please <a href="' . $login_url . '">login.</a>';
       error_log($e->getType());
       error_log($e->getMessage());
     }   
     // Give the user a logout link
     echo '<br /><a href="' . $facebook->getLogoutUrl() . '">logout</a>';
   } else {

     // No user, so print a link for the user to login
     // To post to a user's wall, we need publish_stream permission
     // We'll use the current URL as the redirect_uri, so we don't
     // need to specify it here.
     $login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
     echo 'Please <a href="' . $login_url . '">login.</a>';

   }

 ?>      

 </body>
</html>

Facebook Auth cookbook page

Facebook Authentication

Overview

Most actions on Facebook require some sort of authentication token. For example, sending a request for information about a user without the relevant auth token returns only their public information: name, user id, and a few other fields. However, a request with the proper token can GET several pages of JSON describing a user who’s authorized the requesting app.

Body

There are several ways to acquire such a token, but we will be focusing on a simple method using the PHP SDK. Complete documentation can be found here.

First, working with the PHP SDK requires initializing an instance of the Facebook object with your App_ID and App_Secret. These values are unique to each app, and can be thought of as you username and password.

The Facebook::getLoginUrl(params) method generates a url that takes the user to a facebook dialouge where the user is asked if they would like to grant your application the permissions specified in params, after which the user is redirected to either a url specified in params or the originating page

From the documentation:
$params = array(
  scope => 'read_stream, friends_likes',
  redirect_uri => 'https://www.myapp.com/post_login_page'
);

$loginUrl = $facebook->getLoginUrl($params);

the scope parameter can be any of these permissions. Remember that requesting unnecessary permissions will make users suspicious.

The auth token obtained is temporary, meaning that this method can only be used when the user is online or shortly after.

There is also a Facebook::getLogoutUrl() method, see the example below for a full example (source)

Example Code

<?
 // Remember to copy files from the SDK's src/ directory to a
 // directory in your application on the server, such as php-sdk/
 require_once('php-sdk/facebook.php');

 $config = array(
   'appId' => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 );

 $facebook = new Facebook($config);
 $user_id = $facebook->getUser();
?>
<html>
 <head></head>
 <body>

 <?
   if($user_id) {

     // We have a user ID, so probably a logged in user.
     // If not, we'll get an exception, which we handle below.
     try {

       $user_profile = $facebook->api('/me','GET');
       echo "Name: " . $user_profile['name'];

     } catch(FacebookApiException $e) {
       // If the user is logged out, you can have a
       // user ID even though the access token is invalid.
       // In this case, we'll get an exception, so we'll
       // just ask the user to login again here.
       $login_url = $facebook->getLoginUrl();
       echo 'Please <a href="' . $login_url . '">login.</a>';
       error_log($e->getType());
       error_log($e->getMessage());
     }   
   } else {

     // No user, print a link for the user to login
     $login_url = $facebook->getLoginUrl();
     echo 'Please <a href="' . $login_url . '">login.</a>';

   }

 ?>

 </body>
</html>

Thursday, November 3, 2011

Associating facebook and ASM accounts

Here's how it's done:

http://developers.facebook.com/docs/plugins/registration/
This pops up an iframe that has in it a form prefilled with your facebook data. It also supports custom fields. You can fill out or change any fields you want to and then submit the form as a signed request to the server.

If a user only has a Facebook account, they can just register with this to create an associated ASM account.

When an ASM account is already logged in, we should be able to use the same form with different parameters to associate the two accounts.

Edit: Code is here: http://pkinsky.com/register.html

Share pages with friends

 Like shares with all, send allows you to choose recipients from among your friends.

http://www.pkinsky.com/askhelp.html

Sunday, October 30, 2011

API progress

As of now, I've made a test api call that gets a database object, saves data to it, and then reads other data from it. I've also managed to create 'watcher' database objects via API and retrieve data from them (a callback url) elsewhere.

The next step is to send a POST request to that callback_url when the relevant event happens. This can be expanded to cover assignments being added, achievements, etc.

EDIT: and then I uploaded the code - my api call is test_call in lib/gwt/ajax.rb

EDIT2: now featuring working post/response of JSON data to and from an external php script! Proof of concept finished, time to start on the actual product.

Wednesday, October 26, 2011

Sunday, October 23, 2011

Source Code and Documentation

First, I want to say that I’ve open-sourced LcAlg, my program for generating laser-cut polygonal sculptures from 3d models. There’s a link a little bit farther down on the page if that’s what you came here for.

Second, the majority of this post will be about an interesting method of connecting coroplast sheets using acrylic connectors that I’ve developed.

Source Code

svn co https://lcalg.svn.sourceforge.net/svnroot/lcalg lcalg    
https://sourceforge.net/projects/lcalg/files/
  1. Check out the code. Download either of the two obj files and put them in the input folder.
  1. Adjust constants in util.constants.py to change most values in the program. Currently it’s set to use 2.5mm acrylic and ~3.5mm coroplast.
  1. Run LcAlg by running LcAlg.py. You’ll need python 2.7.
  1. Watch for updates. This is an early beta that I’ll be updating regularly.
Connectors

Coroplast is essentially plastic cardboard. It is lightweight and flexible, and bends rather than breaking. I now use it for the triangles, or faces, in my models.

I used to use acrylic plates for both the faces and the connectors. It was shatter-prone, heavy and expensive. I secured the faces to the connectors with first solvent glue and then cotter pins. This worked, but was labor intensive and in some cases fragile.

The solution is to use acrylic connectors and coroplast sheets. This leverages the strength of both materials. Because the coroplast is flexible, I use retaining tabs - the coroplast deforms around the rigid acrylic tabs and is locked into place

This forms a very strong connection. I have to pull very hard to force the pieces apart. However, I can easily remove a connector by slipping the retaining tabs over the coroplast retainer. Think zip ties - all it takes is a small piece of metal to jimmy one open but brute force will get you nowhere.



(By vector-cut I mean vector-etched)

Unfortunately, sharp angles lead to an issue that can be seen in this diagram: if angle A increases much more, distance B will decrease until there is not enough material there to hold the connector together

Large angle A’s can also lead to intersecting faces: In the diagram below, imagine if angle A were to increase. The two coroplast panels would quickly be intersecting. LcAlg solves this issue by calculating an offset and then removing that much material from the relevant edge.


Faces




A face is a flat coroplast triangle with 3 pairs of two mounting points for the acrylic connectors.

They’re cut out as below, to save laser time and material.

LcAlg

I've made an algorithm that transforms a 3d model (a mesh of triangles) into the autoCAD files neccesary to laser-cut a set of triangles and angled connectors that, when assembled, form a real life version of that 3d model.

You can see an example here

This is an intro post. In later posts I'll go over how it works and how to use it.


Source code can be found here: https://sourceforge.net/projects/lcalg/

Wednesday, October 5, 2011

Assistments API

We've decided that the best way to go forwards is to work with Assistments as a service. We'll be extending the existing API to do what we need, instead of trying to add new functionality directly to Assistments.


Fortunately, Assistments already has at least the beginnings of an API.

Monday, October 3, 2011

PHP and JS Guidlines for FB: Acronyms!

I've put together a guide on the php and javascript sdks for facebook. It mostly consists of links to facebook's own documentation, which is amazing. This needs to be cleaned up, but these links show examples on pretty much every part of facebook's api.


php:
login/out and requesting permissions, posting to a user’s wall, getting a user’s information all with graph api, newest api http://developers.facebook.com/docs/reference/php/facebook-api/
methods for login/logout http://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/ http://developers.facebook.com/docs/reference/php/facebook-getLogoutUrl/
what to show depends on result of http://developers.facebook.com/docs/reference/php/facebook-getUser/
You should also authorize your app using the values from you facebook developer app page http://developers.facebook.com/docs/reference/php/facebook-setAppId/ http://developers.facebook.com/docs/reference/php/facebook-setAppSecret/
i dont see it in the docs explicitly but in the examples this method is used to init facebook object:
$config = array( 'appId' => 'YOUR_APP_ID', 'secret' => 'YOUR_APP_SECRET', );
$facebook = new Facebook($config);
javascript
info, how to load sdk http://developers.facebook.com/docs/reference/javascript/
FB.login() -- login and/or request extended permissions FB.logout() -- logout (only if the user is connected with your application) FB.getLoginStatus() -- get current login status from facebook.com FB.getSession() -- synchronous accessor for the current session. Note that in OAuth 2.0, this function will no longer function and you should use FB.getAuthResponse(). FB.getAuthResponse() -- accessor for the current authorization response record, which for connected users includes an access token, a signed request, and a user ID.
api calls: http://developers.facebook.com/docs/reference/javascript/FB.api/
can trigger dialogs with ui methods http://developers.facebook.com/docs/reference/javascript/FB.ui/
lots of useful methods - can control position, size, etc for canvas page, login/out, etc
you can make calls in facebook query language to get info http://developers.facebook.com/docs/reference/fql/

Wednesday, September 28, 2011

AppRequest functionality added to fb_graph gem

The developer of the fb_graph facebook graph api gem helped me out by adding the ability to post app-generated requests! Thanks, Nov Matake!

(https://github.com/nov/fb_graph/wiki/App-Request)

Everything I need to do in Ruby, but in PHP

I've had 9/10ths of this working for about a week, I've just been stuck getting it into ruby. I'm just going to post some code for sending notifications, getting a user's notifications, and deleting them. It also handles login.

<?php

require 'facebook-php-sdk/src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '168953989848835',
  'secret' => '60359e93359d47a9d349c3dd263a479a',
));

// Get User ID
$user = $facebook->getUser();

// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}


?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <head>
    <title>php-sdk</title>
    <style>
      body {
        font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
      }
      h1 a {
        text-decoration: none;
        color: #3b5998;
      }
      h1 a:hover {
        text-decoration: underline;
      }
    </style>
  </head>
  <body>
    <h1>php-sdk</h1>

    <?php if ($user): ?>
      <a href="<?php echo $logoutUrl; ?>">Logout</a>
    <?php else: ?>
      <div>
        Login using OAuth 2.0 handled by the PHP SDK:
        <a href="<?php echo $loginUrl; ?>">Login with Facebook</a>
      </div>
    <?php endif ?>

    <h3>PHP Session</h3>
    <pre><?php print_r($_SESSION); ?></pre>

<?php

  $app_id = '168953989848835';
  $app_secret = '60359e93359d47a9d349c3dd263a479a';

  $token_url = "https://graph.facebook.com/oauth/access_token?" .
    "client_id=" . $app_id .
    "&client_secret=" . $app_secret .
    "&grant_type=client_credentials";

  $app_access_token = file_get_contents($token_url);

  $user_id = substr($user.id, 0, -2);

  $apprequest_url ="https://graph.facebook.com/" .
    $user_id .
    "/apprequests?message='INSERT_UT8_STRING_MSG'" .
    "&data='INSERT_STRING_DATA'&"  .  
    $app_access_token . "&method=post";

  $result = file_get_contents($apprequest_url);
  #echo $user_id;
  echo "App Request sent?";
  echo "request id = " . $result;
 
  #$pieces = explode("=", $app_access_token);
  #echo $pieces[1];
    //Get all app requests for user
   
  $request_url ="https://graph.facebook.com/" .
    $user_id . "/apprequests?" .
     $app_access_token;
  $requests = file_get_contents($request_url);

  //Print all outstanding app requests
  echo '<pre>';
  print_r($requests);
  echo '</pre>';
 
  //Process and delete app requests
  $data = json_decode($requests);
  foreach($data->data as $item) {
    $id = $item->id;
    $delete_url = "https://graph.facebook.com/" .
      $id . "?" . $app_access_token . "&method=delete";

    $result = file_get_contents($delete_url);
    echo("Requests deleted is " . $result. ", message = " . $item->message);
  } 
 
?>

Tuesday, September 27, 2011

Welp

I was talking with the author of the fbgraph gem about how to do something, at least I ended up getting him to add it to his TODO list:

https://github.com/nov/fb_graph/issues/126

Go go gadget unsupported language!

Project Outline

In the past few years there has been an industry-wide trend towards Facebook integration. It can even be seen on WPI’s JobFinder website. Essentially, the goal is to let users of your website engage with it through facebook. Apps can deliver alerts and news stories to users. Facebook also provides access to many other core features via API. Some examples are sending requests, awarding achievements, and creating events. It also gives apps their own page on Facebook’s site, where they can fill a ‘canvas’ which covers most of the page with anything they want.
We plan to build a facebook application that will accomplish these functions:
    1. handle authentication:
      1. Our application will allow users to associate their Facebook account with their Assistments account using the OAUTH 2.0 protocol.
      2. It will also request any necessary permissions from the user.
    2. manage notifications
      1. When an event, such as a problem set being assigned, occurs, the application will generate a notification of some type.
      2. When a user arrives at our app via a notification, we can redirect the user to the relevant page.
    3. It will also provide the infrastructure necessary to integrate Assistments further with facebook. For example, awarding achievements to users will be as simple as a single post request.

This will be beneficial to students using Assistments because many younger children use facebook. With our application, assistments will be immediately visible to students in a place they already go. We hope that if we increase the convenience of using assistments, students will be more likely to do their assignments.

Monday, September 26, 2011

Issues with ROR and FB

I've been having a lot of trouble getting rails to work with facebook. They only support PHP and javascript SDKs, so I'm going to try using a ruby gem I found that integrates javascript and rails.

https://github.com/cowboyd/therubyracer

Sunday, September 18, 2011

Progress with Facebook API

I've been tinkering with the facebook API. So far, I have working versions of:
  1. Users can login and logout through my page.
  2. Send requests from my app to registered users. Once issued they can be:
    1. updated with new info ("DUE IN 2 HOURS!" or "3 out of 5 questions completed")
    2. read ("A good common practice for Apps on Facebook.com is to detect if a user has any requests pending when your application loads and then prompt the user to complete the actions associated with the requests before continuing.")
    3. deleted (clear request when associated problem set is completed)
  3. Register achievements that can then be awarded to users. They can then be:
    1. read
    2. deleted
  4. Award users scores for the app. They can then be:
    1. read
    2. deleted
This is all PHP implementations of html POST requests. It will be easy to transfer to ROR once we get our version of ASSISTments running
 
Also, Screenshots!
Achievements and scores. It also autogenerates notifications about how you have x of y achievements for an app, or the highest score.
 
 
 
 
 
 
 
 
 
 
 
 
Requests from an app to a user: These show up in a few different places, including the main page.
(I left the default text in)

Tuesday, September 13, 2011

Assisments Facebook App Users

The potential users for our Facebook app fall into three groups:. Here's some examples of how each group could use our app.
  1. students:
    1. The student logs onto facebook and sees a private notification through one or more of Facebook's notification systems. Notification examples:
      1. New assignment
      2. Assignment grade available
    2. The student logs onto Facebook and completes a problem set through the Assistments app
  2. teachers
    1. unknown
  3. parents
    1. get notifications about their students grades and assignments
We recently got the results from a survey given to the parents of children using Assistments. We haven't been able to go through all of them, but there is some interest in getting notifications through Facebook.



    Assistments ISP First Post

    Hi! My name is Paul Kinsky. I'm a Computer Science major at Worcester Polytechnic Institute, WPI.

    I'm working on a project for several professors at integrate a to extend a piece of educational software called Assistments with social media. Right now we're working on a facebook app that would allow students to complete problem sets within facebook.

    We've been granted access to the source code today, by the end of the week we hope to have a working prototype. I'll be posting details as we go.