Tuesday 18 October 2016

Installation of Drop Box API on Codigniter

As with the YouTube API the first step in getting this sucker setup is getting a developer key by visiting https://www.dropbox.com/developers/apps. There you will setup your new application and they will give you an 'App Key' and 'App Secret'. Put these values into a config file so that we can reference them later. Now download the API files from my github repository and place them into your application folder.

  1. My trusty oauth_helper.php file belongs in the helpers directory
  2. dropbox.php is the API file and belongs in the libraries directory

Once they are in place we need to authenticate the API with your dropbox account. We do this using OAuth so you will need to create a controller and add the following methods.

public function request_dropbox()
{
   $params['key'] = $this->config->item('dropbox_key');
   $params['secret'] = $this->config->item('dropbox_secret');
       
   $this->load->library('dropbox', $params);
   $data = $this->dropbox->get_request_token(site_url("welcome/access_dropbox"));
   $this->session->set_userdata('token_secret', $data['token_secret']);
   redirect($data['redirect']);
}
    
public function access_dropbox()
{
   $params['key'] = $this->config->item('dropbox_key');
   $params['secret'] = $this->config->item('dropbox_secret');
       
   $this->load->library('dropbox', $params);
       
   $oauth = $this->dropbox->get_access_token($this->session->userdata('token_secret'));
       
   $this->_store_in_db($oauth['oauth_token']);
   $this->_store_in_db($oauth['oauth_token_secret']);
}

Now a few lines there need some explanation. In request_dropbox my get_request_token call should have a URL to the access_dropbox method right below. Basically we want the dropbox site to redirect there once the request step is finished. On the next line we store the token secret because we will need that in the access_dropbox method later. Finally we redirect to the provided redirect (this will take the user to the dropbox site).

In the access_dropbox method not too much is different. Make the get_access_token call and pass in the token secret. You should get back an array with an 'oauth_token' value and an 'oauth_token_secret' value. You should store those with your user as they are what you will use to make authenticated request on that users behalf.

Provided those went well we can begin actually fiddling with the API (it should be noted that most calls from the API will return PHP objects as a response). Here is an example of how to load the API with all of the data we have generated.

$params['key'] = $this->config->item('dropbox_key');    
$params['secret'] = $this->config->item('dropbox_secret');
$params['access'] = array('oauth_token'=>urlencode($this->_get_from_db()),
                          'oauth_token_secret'=>urlencode($this->_get_from_db()));
       
$this->load->library('dropbox', $params);

Note that the access parameter is an array with keys 'oauth_token' and 'oauth_token_secret' and that the value of each of these keys is urlencoded. Make sure you mimic this same layout otherwise you risk running into issues with your authenication. Finally load the library with the parameters.

Once the library is successfully loaded you can now make some calls. There are several to choose from the simplest is 'account', so calling:

$this->dropbox->account();

Should return a php object with various account data in it. Most of the methods return a php object there are only two that do not.

$this->dropbox->thumbnail($destination, $path, $size='small', $format='JPEG', $root='dropbox')
$this->dropbox->get($destination, $path, $root='dropbox')

The reason these don't return an object is because they actually write a file to the $destination path. The only time these will return anything useful is if an error has occurred.

Another useful method is the add method which will add a file to your dropbox.

$this->dropbox->add($dbpath, $filepath, $root='dropbox');

Here $dbpath is the path within your dropbox (including file name) where the file will go, and $filepath is the path to the file on your server. Unless you know what the $root parameter is for I would just leave it alone.

To finish things off here is the list of the remaining methods. Most are simply for manipulating files in your dropbox folder a few are for getting information on files in your dropbox.


$this->dropbox->metadata($path, $root='dropbox');
$this->dropbox->link($path)
$this->dropbox->copy($from, $to, $root='dropbox');
$this->dropbox->create_folder($path, $root='dropbox');
$this->dropbox->delete($path, $root='dropbox');
$this->dropbox->move($from, $to, $root='dropbox');

That's it every one of those should be decently documented in the code. I should point out that I am not doing anything specatular with CodeIgniter so the library should work with 2.0 and the old 1.7.2. I hope you guys enjoy, it was a lot of fun writing it. Let me know in the comments or post on the github repo if you have any problems.

Installation of YouTube API in Codigniter

 This will let you connect to youtube and make requests without having to load any Zend GData libraries. It is written exclusively for CodeIgniter.

To use the library you must first pass in some parameters. The apikey is the apikey provided to you once you register with youtube to use the API (I put mine in a config file). Next you want to include the oauth consumer key that you setup when you setup oauth with google. The secret is the consumer secret google provides you if you are using HMAC-SHA1 signing or the file path to your .pem file if you are using RSA-SHA1 signing (again I put these in a config file for easy access/changes). You must then specify the signing algorithm you use to make your oauth signatures. Finally you have to specify the access token and token secret if your user has already authorized your site to connect to youtube on their behalf.

If any of this seems over your head please consult the oauth docs on youtube for further clarification. You can find those here. It should also be noted that this library only does OAuth authentication it does not support AuthSub feel free to add this if you would like though.

This library does require the oauth_helper I wrote for CodeIgniter I will link to the file at the bottom of the page but if you wish to further understand what it does visit the CodeIgniter Wiki here. Also I wrote a library to handle all of the OAuth interactions that is also available on the Wiki here. (I will provide a link to this at the bottom of this post too.)


$params['apikey'] = $this->config->item('youtube_api_key');
$params['oauth']['key'] = $this->config->item('google_consumer_key');
$params['oauth']['secret'] = $this->config->item('google_consumer_secret');
$params['oauth']['algorithm'] = 'RSA-SHA1';
$params['oauth']['access_token'] = array('oauth_token'=>urlencode($token));
$this->load->library('youtube', $params);

That's it you now have a youtube API instance and can make calls. The following methods are available please consult the documentation for usage etc.

Here is a list of methods that are available right out of the box, no authentication needed.

$this->youtube->getVideoEntry($videoId);
$this->youtube->getRelatedVideoFeed($videoId, $params = array());
$this->youtube->getVideoResponseFeed($videoId, $params = array());
$this->youtube->getKeywordVideoFeed(array $keywords, $params = array());
$this->youtube->getVideoCommentFeed($videoId, $params = array());
$this->youtube->getTopRatedVideoFeed($params = array());
$this->youtube->getMostViewedVideoFeed($params = array());
$this->youtube->getRecentlyFeaturedVideoFeed($params = array());
$this->youtube->getWatchOnMobileVideoFeed($params = array());

The list of methods below requires an authenticated user before they can be used.

$this->youtube->getUserPlaylistFeed($user = 'default', $params = array());
$this->youtube->getPlaylistFeed($playlistid, $params = array());
$this->youtube->getSubscriptionFeed($user = 'default', $params = array());
$this->youtube->getContactFeed($user = 'default', $params = array());
$this->youtube->getUserUploads($user = 'default', $params = array());
$this->youtube->getUserFavorites($user = 'default', $params = array());
$this->youtube->getUserProfile($user = 'default');
$this->youtube->getUserActivity($user = 'default');
$this->youtube->getInboxFeedForCurrentUser();

Finally these methods all require some type of data to be specified whether that be XML meta data, a comment or a boolean value.

$this->youtube->directUpload($path, $contenttype, $metadata, $user = 'default');
$this->youtube->getFormUploadToken($metadata);
$this->youtube->addComment($videoId, $comment, $commentId = false);
$this->youtube->addVideoResponse($videoId, $responseId);
$this->youtube->addNumericRating($videoId, $rating);
$this->youtube->addLikeDislike($videoId, $like);


All methods where the user is defined as 'default', or are getting data from the current user, and the form upload token method, all require oauth authentication or they wont work. The methods that let you define the user may work without authentication but will only show data that the specified user has made public. The form upload token method requires xml meta data to be passed in as well. You can see what this should look like here. All API request return XML and it is your job to parse it and get what you want from it.  

I should note that I haven't tested all of the methods defined in this library so I cannot say with 100% certainty that they all work, but from the ones I have tested I can make a pretty good assumption that they do. Also I used RSA-SHA1 signing for my OAuth requests I just couldn't get HMAC to work properly I found an issue with my signing method for HMAC and fixed it but I cannot guarantee that it works properly either. If you have an issue post it in the comments and give me your HTTP header information for both your request and the response. There is a DEBUG constant flag you can set that will output this information to your error logs. I am also going to post a more technical brief of this on the CodeIgniter wiki which I will link to here.


There seems to be some confusion about how all this stuff fits together so let me clarify the steps. Please Please Please read all the documentation before leaving a comment.
  1. Download the linked files and put them in the correct CI directories. You need all 3 of them. Two go in the application/libraries folder and one goes in the application/helpers folder.
  2. Read the documentation on OAuth. Having a basic understanding of how it works is key. Make sure you read the oauth_helper and google_oauth wiki pages. Both contain vital information about generating the necessary keys and how to use those files. Read the oauth_helper wiki first. It has links on generating some keys and how to use them. Don't worry too much about understanding how oauth_helper works it is more for internal purposes but you do need to checkout the links in its wiki. Read the google_oauth wiki next as it provides more working examples of what you need to do to get oauth up and running and get the necessary access token.
  3. Make your controller to get a request and access token. Samples are provided on the google_oauth wiki page. If you have read the documentation up to this point then it shouldn't be too difficult to figure out what to do. Just use the google_oauth wiki controller examples for reference.
  4. Test your controller methods out and make sure you are getting an access token and there are no hiccups in the 3 step process. You can get an access token as many times as you need so don't worry if you messed something up and need to get a new one.
  5. Read the youtube api wiki page and check out the official youtube api documentation which can be found here
  6. Make your controller to access the youtube api. You will pass in the access token you got from the previous steps as well as an API key you get from google. Make sure you read up on all of the methods the api provides. It is by no means a complete API library there are a number of missing features which may get added in the future but my hope is that you can figure out how to add the things you need by reading the official youtube api documentation and looking at how I implemented things in the api library. Really what it boils down to is HTTP header manipulation.
  7. Finally put everything together. The process should be pretty seamless with the user only having to leave your site for a split second to approve the request token. Also note that you can do this via a local server so even if you setup everything to your sites domain if you are running a dev instance locally everything should still work.

Installation of Google Maps using Codeigniter

I modified to fit with Codeigniter were the data access and XML generation.  And in both of these cases it was more about reworking the code structure to fit into the MVC format that Codeigniter utilizes.  First we will look at the data access.
I created a model called MapData to hold my database query.
1<?php
2 
3class MapData extends CI_Model {
4   function __construct() {
5      parent::__construct();
6      $this->load->database();
7   }
8 
9   function getmappoints() {
10      $sql "SELECT * FROM markers WHERE 1";
11      $query $this->db->query($sql);
12      if ($query->num_rows() > 0) {
13         return $query;
14      }
15   }
16}
Yes I know that I do not thoroughly test if there was a failure with the database connection, left it out for brevity.  But as you can see it is just a simple database look up that returns the results object.  Now on to the controller.
The controller is all the other XML creation occurs.  To generate the XML I created a function calledsendXML that will generate the XML and echo it to the page when requested.
1public function sendXML() {
2   $dom new DOMDocument("1.0");
3   $node $dom->createElement("markers");
4   $parnode $dom->appendChild($node);
5   $this->load->model('MapData');
6   $mapdata new MapData();
7 
8   foreach $mapdata->getmappoints()->result() as $row ) {
9      $node $dom->createElement("marker");
10      $newnode $parnode->appendChild($node);
11      $newnode->setAttribute("name"$row->name);
12      $newnode->setAttribute("address"$row->address);
13      $newnode->setAttribute("lat"$row->lat);
14      $newnode->setAttribute("lng"$row->lng);
15      $newnode->setAttribute("type"$row->type);
16   }
17   header("Content-type: text/xml");
18   echo $dom->saveXML();
19}
Once again this code is very straight forward and it almost exactly as you will find in the tutorial code.  Now to render the map I simply created a view and pasted all the tutorial code went into the view verbatim, with the exception of the of the URL for the XML.  Then I called the view form the index function in the controller like so.
1public function index() {
2   $this->load->view('googlemap_mapview.php');
3}
The XML is passed via the Codeigniter controller instead directly from a php file.  And so my entry for URL in the javascript was  a Codeigniter styled URL as such.
1// Change this depending on the name of your PHP file
2downloadUrl("/codeigniter_test/index.php/googlemaptest/sendXML/",function(data) {
And that wraps it up.  I hope this was useful and interesting and I will post more about the project that I am working on later.

Installation of Drop Box API on Codigniter

As with the YouTube API the first step in getting this sucker setup is getting a developer key by visiting  https://www.dropbox.com/develop...