Building an AOL Video Upload Application for Facebook

By John Fronckowiak
March 24, 2008

People are learning how to use the site and what's OK to share. As time goes on, people will learn what's appropriate, what's safe for them--and learn to share accordingly. - Mark Zuckerberg, Facebook Founder

Facebook Application Development

In this article I show you how to integrate the AOL Video Upload API into a Facebook application. Facebook is a leading social networking site, with over 64 million active users. As of September 2007, it ranked 7th in Internet traffic, according to Alexa. It is also the most popular web site for uploading photos, with 14 million photos uploaded daily. Providing a tool to upload videos to AOL Video has great use potential, and also is illustrative for developers looking to leverage AOL technologies into Facebook.

Since the release of the Facebook Platform, a system in which third-party developers can create applications to run inside the service, nearly 16,000 Facebook applications have been developed. This article illustrates the key technologies needed to create a Facebook application, and provides an introduction to FBML (Facebook Markup Language) and Facebook's PHP libraries. I will show you the steps you need to take to get started with Facebook application development, and how to integrate the AOL OpenAuth and Video Upload APIs.

AOL Video Upload Application Overview

Figure 1 shows the AOL Video Upload application in a Facebook account. Facebook applications are typically loaded in the left nav bar. Your application is displayed in the Facebook application Canvas area. Click the AOL Video Upload link in the left nav bar to launch the application.

Figure 1. The AOL Video Upload application added to a Facebook account

As shown in Figure 2, before uploading a video with the AOL Video Upload API, a user must authenticate through the OpenAuth API. If not yet authenticated, the user must click the Login link. If a recent authentication is available, the user will be redirected past this screen, and right into the upload application.

Figure 2. OpenAuth authentication link

As shown in Figure 3, the AOL screen is presented for authentication. Users can log in using their AOL or ICQ screen names, or an OpenID identifier. The AOL Video Upload application does not store the username or password, but instead receives an authentication token that is used by the AOL Video Upload API.

Figure 3. OpenAuth authentication screen

As shown in Figure 4, after the user is authenticated, the user must specify the title, description, and video file. Users must agree to the AOL Video standards before they can upload a video. After providing the necessary information, the user clicks the Submit button to process the upload. Note that a video file cannot exceed 100 MB.

Figure 4. The video upload form

As shown in Figure 4, when the upload has been processed, users receive an e-mail notification. They can then click the link provided to upload another video, as shown in Figure 5.

Figure 5. The video upload result page

Platform Requirements

Facebook applications are hosted on your own server. The Facebook API provides the infrastructure necessary to interact with Facebook, but you must provide the processing power. The AOL Video Upload Facebook application is written using PHP. Although you can use PHP version 4 with Facebook, I highly recommend using version 5. You'll also need the Facebook PHP client library. Other than that, creating a Facebook application is similar to the process of creating and deploying any typical PHP-based web application on your own web server.

Obtaining Developer Accounts

You must obtain developer accounts and information to be able to create a Facebook application, and to use the AOL APIs.

Facebook

The process of obtaining Facebook developer status for your application is detailed at Step-by-Step Guide to Creating a Facebook Application, so I won't repeat that here. Obviously, your first step will be to establish a Facebook account, and then to add the Developer application to your account.

AOL

To use the OpenAuth and Video Upload APIs, you first have to obtain an AOL Developer ID (devId). The devId uniquely identifies developers and the specific applications that implement AOL technologies. Fortunately, obtaining a devId is simple. First, you must have an AOL, ICQ, or OpenID account. If you don't already have one, you can get an AOL screen name at https://reg.my.screenname.aol.com/_cqr/registration/initRegistration.psp?sitedomain=dev.aol.com&authLev=1&siteState=OrigUrl=http%3A%2F%2Fdev.aol.com%2Fkeys=en&locale=us&uitype=flex&createSn=1&mcAuth=%2FBcAG0eKl4QAAK81A+pMj0eKl8AInP5TVAshGecAAAh.

To obtain a devId for your application, go to http://dev.aol.com/keys. I discuss this process in great detail in an earlier article, Open House On Demand, Part 1: A Video Open House Powered by OpenAuth, Video Uploads, Truveo, and the AOL Video Player.

AOL Video Upload and OpenAuth Usage Rules

As a developer, before you integrate OpenAuth into your applications, you must understand and agree to the OpenAuth API usage rules. Important highlights of these rules include:

  • You will use the API only for authentication purposes.
  • You will not store or duplicate your authentication token.
  • Your application will not request more than 10,000 tokens per day or 150,000 tokens per month.
  • If you are going to use the API in a commercial application, you must first contact AOL at http://dev.aol.com/contact.

Just like the OpenAuth API, developers must adhere to specific Video Upload API usage rules. Important highlights of these rules include:

  • You must clearly state that the video will be uploaded to AOL Video.
  • Users must agree to the AOL Video standards before they can upload a video.
  • The upload API cannot be called more than 50 times in a 24-hour period. If you believe your application will exceed these limits, contact AOL at http://dev.aol.com/contact for a site review.
Facebook Application - Main Page

Listing 1 shows the source for the AOL Video Upload application. The Facebook PHP libraries and configuration information are included. Config.php contains the definition of the required Facebook application, and shared keys. A Facebook object is created, and users are required to authenticate into their Facebook account, if they haven't already. A greeting is displayed, which includes the Facebook username. The AOL Video Upload application is actually contained in an iFrame in the Facebook Canvas area, as shown in Figure 6.

Listing 1. Index.php - the application's main page
<?php
// *****
// File: index.php 
// Purpose: Set up the main facebook page....
//
// Author: Fronckowiak
// *****

	// the facebook client library
	include_once '../client/facebook.php';

	// include facebook keys
	include_once 'config.php';

	$facebook = new Facebook($api_key, $secret);
	$facebook->require_frame();
	$user = $facebook->require_login();

	// Greet the currently logged-in user!
	echo "<p><img src='http://www.idcc.net/facebook/VideoUpload/aol_video.jpg'/></p>";
	echo "<p><h3><fb:name uid=\"$user\" useyou=\"false\" /> - Welcome to AOL Video Upload!</h3></p></div>";
?>

<!-- Include the authentication frame -->
<fb:iframe src='http://www.idcc.net/facebook/VideoUpload/login.php' smartsize='true' frameborder='0' />

Figure 6. The Canvas and iFrame areas on the main application page

The iFrame is created using the Facebook Markup Language (FBML) <fb:iframe> tag. The smartsize attribute sizes the frame to the space available in the Canvas area, and the frameborder attribute removes any visual frame around the iFrame. The src attribute specifies login.php, which is loaded in the iFrame area. The iFrame is necessary for the OpenAuth authentication process, which I discuss in the following section.

Authentication with OpenAuth

As shown in Listing 2, the authentication process begins with login.php, which is loaded into the Facebook application's iFrame. After a PHP session is opened, the aolAuthToken session variable is checked. If it already exists, authentication must have already occurred, so the user is redirected to upload.php. Otherwise, the following session variables are created:

  • succUrl - the URL the user is redirected to after successful authentication
  • loginUrl - the URL of the login page; this is where users are redirected when they log out
  • devId - your AOL Developer ID

After the session variables are created, the current aolAuthToken is cleared, and the URL of the OpenAuth login function is created. The login function takes the following parameters:

  • f - the response format of the login function; in this case qs indicates the response parameters will be on the URL query string of the page to which we are redirected
  • succUrl - the page to which the user is redirected after successfully authenticating
  • devId - the AOL Developer ID
  • supportedIdType - a comma-separated list of the supported authentication types; SN=AOL and AIM users, ICQ=ICQ users, OID=OpenID users

The URL created is used as the link for the Login item on the page. When users click Login, as shown earlier in Figure 2, they are presented with the OpenAuth authentication screen, shown earlier in Figure 3. Upon successful authentication, the user is redirected to upload.php.

Another thing to note is the inclusion of the Facebook style sheet, shown in Listing 2. This ensures that the application displayed in the iFrame is displayed with the familiar Facebook look and feel.

Listing 2. Login.php - the application's authentication page
<?php
// *****
// File: login.php 
// Purpose: If the user is not authenticated through the OpenAuth API
//		  - authenticate before files can be uploaded....
//
// Author: Fronckowiak
// *****

	// open PHP session
   	session_start();

	// is this user already authenticated?
   	if($_SESSION['aolAuthToken']) {
		// automatically redirect to the upload page...
   		header( 'Location: '.$_SESSION['succUrl']) ;
    } else { 
		// set session variables
		$_SESSION['succUrl'] = "http://www.idcc.net/facebook/VideoUpload/upload.php";
		$_SESSION['loginUrl'] = 'http://www.idcc.net/facebook/VideoUpload/login.php';
		$_SESSION['devId'] = "***YOUR DEVID HERE***";
		
		// clear authentication token
		$_SESSION['aolAuthToken'] = "";
		
		// assemble OpenAuth login function URL
		$href = 'http://api.screenname.aol.com/auth/login?f=qs&succUrl='.urlencode($_SESSION['succUrl']);
		$href .= '&devId='.urlencode($_SESSION['devId']).'&supportedIdType=SN,ICQ,OID&uiType=mini';
	}
?>
<html>
<head>
	<link href="http://static.ak.facebook.com/css/base.css?12:68276" rel="stylesheet" type="text/css">
</head>	
<body>
	<p/><p><strong>You Must <a href="<?php echo($href); ?>">Login</a> Using Your AOL/AIM ID, ICQ Account or OpenID URL Before You Can Upload A Video.</strong></p>
</body>
</html>
Video Upload Form

After the user has authenticated, the next step is to provide the information necessary to upload a video file. The AOL Video Upload API requires the user to at least specify the actual video file itself, and to provide a title for the video. The video upload form, shown earlier in Figure 4, requests this information, in addition to a brief description, and also gives the user the ability to be notified by e-mail when the video has been uploaded and is ready for viewing.

As shown in Listing 3, upload.php provides the video upload form and processing necessary for validation. The upload form simply collects the necessary valid data and loads the video file to the server hosting the Facebook application. The file is then actually uploaded through the AOL Video API on result.php, which is called as a result of submitting the form.

Before the form is submitted, the JavaScript function validate_upload is called to ensure the required data has been specified. This includes the title, the video file itself, and agreeing to the AOL Video terms and conditions. This agreement is required to use the AOL Video API. If any information is missing, a JavaScript dialog box is displayed; otherwise, the collected data is passed to result.php for processing. It's important to note that the Prototype JavaScript library is included, and used in the validate_upload JavaScript function, to simplify form field handling. (I discuss the Prototype JavaScript library in my AOL Developer Network blog.) Once again, the Facebook style sheet is included to ensure upload.php retains the Facebook look and feel.

Listing 3. Upload.php - collecting the necessary data to upload the video file
<?php
// *****
// File: upload.php 
// Purpose: Collect the pertinent video data, and upload file for 
//		  processing on result.php...
//
// Author: Fronckowiak
// *****

	// open PHP session
  	session_start();
	// do we already have the authentication token?
  	if(!$_SESSION['aolAuthToken']) {
		// no? get it from the URL parameters....
  		$_SESSION['aolAuthToken'] = $_GET["token_a"];
  	}
	// get the OpenAuth username
  	$getinforesults = callgetInfo();
  	parse_str($getinforesults, $info);
	// save the username
  	$_SESSION[ 'user' ] = $info['userData_loginId'];
	// create the logout URL - this calls the OpenAuth logout function - and redirects the user back to logout.php
  	$_SESSION['logoutUrl'] = 'http://api.screenname.aol.com/auth/logout?f=qs&succUrl='.urlencode('http://www.idcc.net/facebook/VideoUpload/logout.php').'&devId='.$_SESSION['devId'].'&a='.urlencode($_SESSION['aolAuthToken']);
?>
<html>

<script>
	<!-- Include the Prototype JavaScript library to simplify form field processing... -->
	<?php require_once('js/prototype.js'); ?>
</script>

<script>
	// *****
	// Function: validate_upload 
	// Purpose: Validate the form fields before sending processing 
//		  to result.php....
	//
	// Author: Fronckowiak
	// *****
	function validate_upload() {
		// has the user agreed to the AOL Video Upload Terms and Conditions?
    	if($('terms').checked) {
			// have they specified a file to upload?
	  		if($('videoFile').value.blank()) {
				// display an error message...
	  	  		alert('You must specify a video file to upload!');
	  		} else {
				// the video title is required!
		  		if($('title').value.blank()) {
					// display an error message...
			 		alert('You must provide a title!');
		   		} else {
					// set the form action
		   			$('videoUpload').action = "result.php";
					// all's well!
		   			return true;
				}
	   		}
		} else {
			// display an error message...
			alert('You must agree to the AOL Video Standards before uploading!');
		}
		// validation failed!
		return false;
	}  
</script>

<head>
	
	<!-- Include the Facebook style sheet... -->
	<link href="http://static.ak.facebook.com/css/base.css?12:68276" rel="stylesheet" type="text/css">

</head>

<body>
	<!-- Display the OpenAuth username and provide a link to logout... -->
	<p/><p><label>Username:</label> <?php echo( $_SESSION['user'] ); ?> - <a href="<?php echo($_SESSION['logoutUrl']); ?>">Click Here To Logout</a></p>

	<form action='' enctype="multipart/form-data" method="post" name="videoUpload" id="videoUpload" onsubmit='return validate_upload();'>
	
	<table>
		<tr>
			<!-- Video Title -->
	    	<td><label>Title:</label></td>
	 	  	<td><input name="title" type="text" size="48" maxlength="256" id="title" /></td>
		</tr>
		<tr>
			<!-- Video Description -->
	  		<td valign="top"><label>Description:</label></td>
		  	<td><textarea name="desc" rows="3" cols="46" id="desc" ></textarea></td>
		</tr>
		<tr>
			<!-- AOL Video Terms and Conditions... -->
	    	<td colspan="2"><div align="center"><input type="checkbox" name="terms" id="terms" />By uploading your video to AOL Video, you agree to the <a href="http://uncutvideo.aol.com/License.html" title="AOL Video Standards" target="_blank">AOL Video Standards</a>.</div></td>
		</tr>
		<tr>
			<!-- Video File Name -->
				<td><label>Video File:</label></td>
				<td><div align="left"><input name="videoFile" type="file" id="videoFile" size="48" /> (100MB Max)</div></td>
	    </tr>
		<tr>
			<!-- Notify By Email Combo Box... -->
			<td colspan="2"><div align="left"><label>Notify By Email When Processing Is Complete:</label>
	    		<select name="notify" id="notify">
	      			<option value="yes">Yes</option>
	      			<option value="no">No</option>
	    		</select></div>
			</td>
		</tr>
		<tr>
			<td colspan="2">
				<div align="center">
					<!-- the submit button -->
	    			<input type="submit" id="submit" value="Submit" />
					<!-- the reset button -->
	    			<input type="reset" name="cancel" id="cancel" value="Cancel" />						
				</div>
			</td>
		</tr>
	</table>
	</form>
</body>
</html>

<?php
// *****
// Function: callgetInfo
// Purpose: Call the OpenAuth getInfo function to retrieve the username of the authenticated user....
//
// Author: Fronckowiak
// *****
function callgetInfo() {
	// assemble the OpenAuth getInfo function URL... 
	$getInfoUrl = 'http://api.screenname.aol.com/auth/getInfo?f=qs';
  	$getInfoUrl .= '&devId='.$_SESSION['devId'].'&a='.urlencode($_SESSION['aolAuthToken']);
  	$getInfoUrl .= '&referrer='.urlencode($_SESSION['succUrl']);

  	// initialize the CURL library....
  	$getInfoRequest = curl_init();
  	curl_setopt( $getInfoRequest, CURLOPT_URL, $getInfoUrl );
  	curl_setopt( $getInfoRequest, CURLOPT_RETURNTRANSFER, true );

	// call the getInfo function...
  	$response = curl_exec($getInfoRequest);

	// check the result...
  	if (curl_errno($getInfoRequest)) {
      	return "";
   	} else {
    	curl_close($getInfoRequest);
		// the response is the authenticated user name...
    	return $response;
   	}
}
?>

There are a few other things happening on upload.php that relate to authentication. This includes building the Logout link and displaying the authenticated username. I will discuss this in more detail later in this article.

Video Upload Process and Results

After the upload form has validated the video data, result.php can perform the actual video upload, as shown in Listing 4. The primary function provided by the AOL Video Upload API is upload. The upload function requires that the file and other required data be posted as a multi-part form. The data array created contains the necessary fields:

  • devId - the AOL Developer ID
  • a - the OpenAuth authentication token
  • referrer - the URL of the referring application
  • f - the format of the response; only XML is supported
  • title - the user-supplied title
  • desc - the user-supplied description
  • share - when set to pub, this makes the video available to the public
  • notifyByMail - the user-supplied flag for e-mail notification
  • locale - the originating location of the video
  • datafile - the actual video file to upload

Because the video file is actually posted to result.php, it is copied from the temporary location to a tmp directory on the site hosting the AOL Video Upload Facebook application. In the process, the file is renamed from its temporary name, $_FILES['videoFile']['tmp_name'], to its original base name, basename($_FILES['videoFile']['name']). When the upload process has been completed, the unlink function is used to remove the temporary file.

The form data is passed to the upload function, and the XML result is captured. The simplexml_load_string function is used to parse the XML; if the status_code attribute is 200, then the video was uploaded without incident, and success is reported to the user. Otherwise, an error message is displayed. A link back to upload.php is also provided for further uploads.

Listing 4. Result.php - processing the AOL Video upload call
<?php
// *****
// File: result.php 
// Purpose: After the user fills out the form on upload.php, 
//		  pass that data to as a multi-part form upload
//		  to AOL Video...
//
// Author: Fronckowiak
// *****

	// open PHP session
  	session_start();
?>
<html>

<head>
	<!-- Include the Facebook style sheet... -->
	<link href="http://static.ak.facebook.com/css/base.css?12:68276" rel="stylesheet" type="text/css">
</head>

<body>
	<!-- Display the OpenAuth username and provide a link to logout... -->
	<p/><p><label>Username: </label><?php echo( $_SESSION['user'] ); ?> - <a href="<?php echo($_SESSION['logoutUrl']); ?>">Click Here To Logout</a></p>

	<?php
		// save posted file in tmp directory - so we can resend it to AOL Video...
		// retrieve the current working directory of the application, and move the file to
		// a temp directory - basename retrieves the actual name of the user uploaded file...
		$userfile = getcwd().'/tmp/'.basename($_FILES['videoFile']['name']);
		move_uploaded_file($_FILES['videoFile']['tmp_name'],$userfile);
		
	 	define(FORMAT, 'xml');

		// define the form data array...
	 	$data = array(
	    	'devId' => $_SESSION['devId'],					// developer ID
	    	'a' => urlencode($_SESSION['aolAuthToken']),			// OpenAuth authentication token
	    	'referrer' => urlencode($_SESSION['succUrl']),			// referrer URL
	    	'f' => FORMAT,									// Only an XML response is supported
	    	'title' => $_POST["title"],						// Video title from upload.php form
	    	'desc' => $_POST["desc"],						// Video description from upload.php form
	    	'catName' => 'Short Movies',						// Video category
	    	'share' => 'pub',								// Make the video public...
	    	'notifyByEmail' => $_POST["notify"],				// Upload email notification flag from upload.php form
	    	'locale' => 'en-US',							// The locale of the video...		
			'datafile' => '@'.$userfile					// Finally the video file itself...
	 		);

	 	// define URL for call - the "devId", "referrer" and "a" parameters must be passed both in the GET 
	    // query parameters and in the POST form data 
	 	
	 	$ch = curl_init('http://upload.uncutvideo.aol.com/api/asset/upload?devId='.$_SESSION['devId']."&referrer=".urlencode($_SESSION['succUrl'])."&a=".$_SESSION['aolAuthToken']."&f=".FORMAT);

	 	curl_setopt($ch, CURLOPT_POST, 1);
	 	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
	 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		// call the upload function
	 	$postResult = curl_exec($ch);

		// remove the temporary file...
		unlink($userfile);
 
		// parse the xml response
		$xmlResponse = simplexml_load_string($postResult);
		
		// check the result....
	 	if ($postResult) {
			// 200 signifies success...
			if($xmlResponse->statusCode == 200) {
				// Report success...
				echo "<p>Your File Was Upload Successfully!</p>";
			} else {
				// Oops - there was an error! Show what it was!
				echo "<p>There Was An Error Uploading Your File - [".$postResult."]</p>";
			}
	 	} else {
			// Ooops - there was a curl error! Show what it was!
			echo "<p>There Was An Error Uploading Your File - [".curl_error($ch)."]</p>";
	 	}
		// close curl
	 	curl_close($ch);
	?>
	
	<!-- Provide a link back to the upload page... -->
	<p><a href="upload.php">Click Here To Upload Another File.</a></p>	
	
</body>

</html>
Processing OpenAuth Logout and User Name Display

Upload.php contains OpenAuth code that allows the user to log out, and also display the user's authenticated username. The Logout link is built in the PHP code at the top of the page, and is a straightforward call to the logout function. The parameters required by the logout function include:

  • succUrl - the page to redirect to after logging out
  • devId - the AOL Developer ID
  • a - the authentication token

Because the authentication token is kept in the aolAuthToken session variable, it must be cleared upon logout. This is done on logout.php, shown in Listing 5. Logout.php simply clears the aolAuthToken session variable and redirects the user to login.php.

Listing 5. Logout.php - processing an OpenAuth logout
<?php
// *****
// File: logout.php 
// Purpose: When a user logs out, clear the authentication session 
//		  token and redirect back to the login page
//
// Author: Fronckowiak
// *****

	// open PHP session
   	session_start();
	// clear session authentication token
   	$_SESSION['aolAuthToken'] = "";
	// automatically redirect to the login page
   	header( 'Location: '.$_SESSION['loginUrl']) ;
?>

Finally, upload.php displays the name of the user as authenticated by the OpenAuth API. This is accomplished by calling the OpenAuth getInfo function. This call is processed buy the PHP callgetInfo function. The resulting response, which is the authenticated username, is returned by the function and displayed on the page.

Conclusion

You should now have a basic understanding of the Facebook application development process. The video upload application created here makes extensive use of the OpenAuth and AOL Video Upload APIs. You should now understand the dependencies of the AOL Video Upload API on OpenAuth for proper authentication. The techniques developed here should provide a basis for any OpenID authentication required by Facebook applications you develop using PHP. Finally, I presented a process for collecting information about a video file to be uploaded to AOL Video, as well as a mechanism for processing the upload, and for reporting the result of the process.

In a future article I will tie the AOL Video Upload application with an existing AOL Facebook application, Video Gifts (to install VideoGifts, go to apps.facebook.com/videogifts, and to register for the content, go to today.aol.com and click "contests"). Video Gifts allows Facebook users to send videos retrieved using the Truveo API to their Facebook friends. Currently, users can search videos available on the AOL Truveo web site. When integrated with the AOL Video Upload Facebook application, Facebook users will be able send their own video creations as gifts!

Resources

If you're interested in further developing Facebook applications, using the OpenAuth API or the AOL Video API, the following resources will be helpful: