Announcement

Collapse
No announcement yet.

How to access facebook from an application developed with AutoPlay Media Studio

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to access facebook from an application developed with AutoPlay Media Studio

    In order to retrieve data from the user profile, news feed, photo albums or any other kind of content provided by facebook, a software developer using AutoPlay Media Studio needs to follow a series of steps. This article attempts to explain the basic procedure for the integration of a multimedia application and the facebook platform.

    The explanations and links were current when this document was written. However, as facebook makes changes to their API permanently, things may change in the future, and this tutorial may need to be revised. When something does no longer work as described here, please refer to the latest official documentation and look for changes.

    Requirements
    1. AutoPlay Media Studio
    2. My free Unicode plugin
    3. JSON Lua and DelimitedStringFunctions libraries
    4. A facebook developer account
    5. A web server with scripting support, for example PHP or ASP


    For this tutorial, you will need to have AutoPlay Media Studio installed on your developer computer. Any version will do: evaluation, Personal, or commercial.

    If you don’t have my Unicode actions plugin, you can download and install it as a separate download from here. Once downloaded and installed, add it to your new project , in Project > Plugins:



    This plugin is required to process the data sent by facebook properly. Without converting the text from Unicode to ANSI, AutoPlay Media Studio may be unable to display it properly.

    Facebook sends data as JSON, and while you probably can use the standard HTTP and String actions to retrieve and parse the data, using a JSON library makes much more sense because it leaves your code so much easier to write and maintain. The Lua library I will be using in this tutorial is the “dkjson” JSON package, version 2.3 or more recent, which you can find at http://dkolf.de/src/dkjson-lua.fsl/home

    To use this library, simply download the dkjson.lua file and copy it into the “Scripts” sub folder of your project’s AutoPlay folder. To enable it in your project, add the line

    json = require("dkjson");

    at the start of your “On Startup” event script. Another thing you probably want to add to your project is the DelimitedStringFunctions script, which is provided as part of the AutoPlay Media Studio distribution, and can be found in the “Gallery\Scripts” sub folder for the AMS program folder. Copy the file also to the “Scripts” folder of your project , and enable the function with

    require "DelimitedStringFunctions";

    in the “On Startup” event, right after the line requiring the JSON library.

    Now that these two scripts are in place, the final requirement before we can start writing code is the facebook developer account.

    Registering as a facebook developer and setting up an app

    Log on to facebook, using your normal user account. Then visit https://developers.facebook.com/, and click the option to register as a developer.



    You should read the terms and conditions carefully, and if you agree with them, enter the required information and set up your account.

    Now it is time to set up your first App.



    You can set a Display Name such as “MyTestApp” or something like it. Set the appropriate category for the app you want to develop, and confirm the captcha on the following dialog. Your app will receive an “App ID” and an “App Secret”. This pair of codes is extremely important for the proper communication between your application and facebook. You should never share the App Secret with anybody else.

    Also, for the App Domain, set “localhost”, and the Web Site URL should be set to “http://localhost”.



    In the Advanced settings, you may want to set the App as a “native or desktop app”. Your AutoPlay Media Studio project will run on the user’s desktop and not in a browser, so this would be the proper setting. Also, if you are following my instructions, you should not embed the App Secret in your program, so leave this option set to “No”.



    As you will need the App ID repeatedly in the script of your project, it is a good idea to assign this to a global variable in your Lua code, right in the “On Startup” event script:

    g_sAppId = "123456789012345";

    Now you can refer to g_sAppId without needing to type the App ID repeatedly, which also helps if you want to create a new project from an existing one, refactoring the work already done. Just update the App ID in the “On Startup” event, instead of searching and replacing it on multiple pages and scripts.

    Authenticating a user account at facebook

    Facebook uses the OAuth protocol for user authentication. This kind of authentication requires a series of exchanges of messages between your application and facebook, which may appear a bit daunting at first, but using the project template and instructions here, you will spend much less time to make it work.

    The first step requires a call to facebook, using the address https://www.facebook.com/dialog/oauth. In this call, you will need to pass a few parameters:
    • client_id for the App ID;
    • scope for the requested permissions;
    • redirect_uri fror the page you should be sent to if authentication succeeds, this address should be kept as “https://www.facebook.com/connect/login_success.html”;
    • display for the way the login form should be shown, we will use “popup” here.

    Instead of attempting to implement everything in the AutoPlay Media Studio project, we will use a Web object to display the login form. Your application will not receive the information which is entered here, and you do not need to know the user account or password. If the authentication succeeds, facebook will return an access “token”, which you can store on the computer for later use. If you wish, this token can be re-used for up to 60 days after it was supplied by facebook, meaning that you can communicate directly with facebook for two months before needing to ask the user to re-enter the credentials and refresh the token. Of course, you can also expire the token when closing the application, and the user would need to login to facebook each time the application is executed. It is entirely up to you what you do with the token, once you got it. It is best showing the Web object on a Dialog instead of a Page, because in the manner we can size the window exactly to the required size for the popup. This is how the login page looks currently:



    Once the login form was displayed in the Web object and submitted to facebook, the Web object will receive a response. This response will allow you to continue the login process, or you should stop immediately, and perhaps ask the user to restart from the beginning.
    1. Login Successful

      If the credentials were properly entered, the page which will be shown in the Web object will be “https://www.facebook.com/connect/login_success.html”, which is the URL you set as the redirect_uri parameter.

      A parameter will be sent back with this page, named code. You need to retrieve the code and pass it back to facebook in the next handshake. This is done not from your application, but from a script hosted on your remote web server. The script will send the code, and your application secret, to the facebook service https://graph.facebook.com/oauth/access_token and retrieve the token I mentioned before. Please note that the application secret should not be stored anywhere in the code of the application. If somebody reverse engineers your application, he could find both the application id and the corresponding secret embedded in your scripts, and could exploit this to perform actions you have not designed in your application, causing you and the users of your application serious headaches.

      A very short sample script in PHP could look like this:
      PHP Code:
      <?php
           
      if (isset($_GET['code'])) {
              
      $url "https://graph.facebook.com/oauth/access_token";
              
      $redirect_uri "https://www.facebook.com/connect/login_success.html";
              
      $client_id "012345678912345";
              
      $secret "0123456789abcdef0123456789abcdef";
              
      $code $_GET['code'];
              
      $get $url "?client_id=" $client_id "&client_secret=" $secret "&redirect_uri=" $redirect_uri "&code=" $code;
              
      $json file_get_contents($get);
              
      // return facebook's reply
              
      print $json;
          }
          else {
              
      // return nothing (error)
              
      print "{}";
          }
      ?>
      Once the script on your web server sent the code and the secret, facebook will answer with the token. The URL of the reply coming from facebook should contain "access_token=", followed by a new code. This is the token you will need for all further communication with the social network. Also present in the reply will be a parameter "expires", which will tell you how long you can use this token. Extract the token from the URL using the default String actions, and save it for further use (i.e. save it in the registry).

    2. Login failed

      If the login failed, the Web object will show the another page instead, containing the string “login_success.html?error=access_denied”. If you can find this string in the document URL loaded in the Web object, you should stop right here, and close the browser window, perhaps giving the user an appropriate error message.


    Fetching information from facebook

    Assuming that you were able to obtain a valid token, you can now start communicating with the facebook Graph API, which is how you get the information from them. Some examples:

    If you want to see the news feed, you would access https://graph.facebook.com/me/home?access_token=

    For getting the list of friends, you would reach https://graph.facebook.com/me/friends?access_token= ...

    For listing the photo albums, you can use the URL https://graph.facebook.com/me/albums?access_token=

    All replies are formatted in JSON, and luckily not too hard to work with them. It also helps that facebook provides an interactive web interface, where you can build and test the URLs for retrieving the information. You can see how the information is returned by the Graph, allowing you to set up the Lua code as desired.

    For building the queries you need, you can and should use the facebook Graph API Explorer, which you can find on this address: https://developers.facebook.com/tools/explorer/.

    The Graph Explorer allows you to build a request and check what data will be returned, which makes debugging pretty easy:



    How to check at program start if a token is still valid or if it is expired?

    At program start, attempt to use the token you retrieved (from the Registry or whe it was stored) to access the facebook profile. If the operation fails, then the token is expired and you must ask the user to log in again:
    Code:
    local sReply = HTTP.SubmitSecure("https://graph.facebook.com/me", {access_token = sAccessToken},
        SUBMITWEB_GET, 20, 443);
    local obj, pos, err = json.decode(sReply, 1, nil);
    if not err then
        bHaveValidToken = true;
    else
        bHaveValidToken = false;
    end
    Every application developed with AutoPlay Media Studio will be different, but I hope that my sample helps in getting you started. The attached project will show you how to perform the login and retrieve the token, how to extract some items from the news feed and display them in them in a Web object, and how to inspect photo albums shared on facebook. You can see the application in action here.
    Attached Files
Working...
X