DrivecastAPI 1.0 PHP Class

From DriveCast Wiki

Jump to: navigation, search
 <?php
 # DrivecastAPI 1.0 PHP Class works with the Drivecast API 1.0
 # Filename: DrivecastAPI.php
 # Authors: 
 # Luca Restagno
 # Giorgio Bernardi
 # Url: http://wiki.drivecast.eu/index.php/DrivecastAPI_1.0_PHP_Library
 
 #######################################################################
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.
 #
 # This program is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # ERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 # GNU General Public License for more details. 
 #######################################################################
 
 class DrivecastAPI
 {
  public $error;
  public $statuscode;
  public $statusdesc;
  public $result;
  
  private $debug = false;
  
  private $AuthCode;
  private $APIkey;
  private $APIurl = 'https://drivecast.eu/api/1.0/';
 
  function __construct ($user="", $password=""){
    /*if(empty($user) || empty($password)){
      $this->Error(1);
      return;
    }*/
    $this->AuthCode = base64_encode($user.":".$password);
  }
  
  public function setAuthCode($authCode=""){
    if($authCode!="")
      $this->AuthCode = $authCode;
  }
  
  public function setAPIkey($APIkey=""){
    $this->APIkey = $APIkey;
  }
 
 
 /******************** User Methods *****************************/
 
 /***************************************
 ** handleRequest() method
 **
 ** returns true or false
 **
 ** Description: user method to send requests to the Drivecast Server API
 **
 ** Parameters:
 ** $resource // the type of resource requested, in a RESTful format
 ** "feed"
 ** "feed/<DEVICE_NAME>"
 ** "feed/<DEVICE_NAME>/<SERIAL>"
 ** "playlist"
 ** "playlist/<PLAYLIST_NAME>"
 ** "library"
 ** "library/<UID>"
 ** "recording"
 ** "recording/<UID>"
 ** "podcast"
 ** "podcast/<UID>"
 ** "thumbnail"
 ** "thumbnail/<UID>"
 **
 ** $method // action to perform
 ** "read"
 ** "create"
 ** "delete"
 ** "modify"
 **
 ** $postData (optional) // the object needed to perform "create" and "modify" actions
 ** required to perform "create" and "modify" actions
 ******************************************/
  public function handleRequest($resource='', $method='', $postData='', $xml='', $debug=''){
    if(!$this->AuthCode){
      $this->Error(11);
      return false;
    }
    if ( !function_exists('json_decode') ){
      $this->Error(11);
      return false;
    }
    if(empty($method)){
      $this->Error(5);
      return false;
    }
    if($debug==true){
      // debug mode ON
      $this->debug = true;
    }
    
    if(substr($resource,0,1)=="/"){
      $resource = substr($resource,1,strlen($resource));
    }
      $resourceArray = split("/",$resource);
      $base = $resourceArray[0];
      $restParam = '';
      if($resourceArray[1])
        $restParam = rawurlencode($resourceArray[1]);
      $url = $this->APIurl.$base."/".$restParam;
      $url .= "?apikey=".$this->APIkey;
      
      // add the format parameter, if set
      if($xml){
        $url .= "&fmt=xml";
        $fmt = "xml";
      }
 
      if($xml){
        $this->result = "";
        $this->result = $this->sendRequest($resource, $url, $method, $fmt, $postData);
      }
      else{
        if(strpos($resource,'thumbnail')===false){
          // every request minus "thumbnail"
          $res = $this->json2array($this->sendRequest($resource, $url, $method, $fmt, $postData));
          $variables = get_object_vars($res);
          $keys = array_keys($variables);
          $this->statuscode = $variables[$keys[0]];
          $this->statusdesc = $variables[$keys[1]];
  
          unset($res->statuscode);
          unset($res->statusdesc);
  
          $this->result = $res;
          
          // an error occurred
          if($this->statuscode != "200" && $this->statuscode != "302" ){
            return false;
          }
        }
        else{
          // $this->result contains the image datas
          $this->result = $this->sendRequest($resource, $url, $method, $fmt, $postData);
          if(substr($this->result,0,1)=="{"){
            // an error occurred on the "thumbnail" request
            $res = $this->json2array($this->result);
            $variables = get_object_vars($res);
            $keys = array_keys($variables);
            $this->statuscode = $variables[$keys[0]];
            $this->statusdesc = $variables[$keys[1]];
            $this->result = "";
            return false;
          }
        }
      }
 
      return true;
 
  }
 
 /******************** End User Methods *****************************/
 
 /******************** Internal functions *********************************/
 
  public function sendRequest($resource='', $url='', $userMethod='', $fmt='', $postData=''){
      // return the correct HTTP method
      $resource = split("/",$resource);
      $method = $this->getHttpMethod($userMethod,$resource[0]);
      $session = curl_init($url);
 
      $str  = array(
        "User-Agent : ".$_SERVER['HTTP_USER_AGENT']." DriveCast apikey=".$this->APIkey,
        "Accept-Language: en-us,en;q=0.5",
        "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
        "Keep-Alive: 300",
        "Connection: keep-alive",
        "Authorization: Basic ".$this->AuthCode.""
    );
    
      curl_setopt($session, CURLOPT_HEADER, 1);
      curl_setopt($session, CURLOPT_VERBOSE, 1);
      curl_setopt($session, CURLOPT_TIMEOUT, 5000);
      curl_setopt($session, CURLOPT_HEADER, false);
      curl_setopt($session, CURLOPT_HTTPHEADER, $str);
      curl_setopt($session, CURLOPT_CUSTOMREQUEST, $method);
      curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
      //curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
 
      curl_setopt ($session, CURLOPT_POST, 1);
      curl_setopt ($session, CURLOPT_POSTFIELDS, json_encode($postData));

      if($resource[0]=='thumbnail'){
        $output = $this->curl_redir_exec($session);
      }
      else{
        // Make the call
        $output = curl_exec($session);
      }
        
      
      //$Headers = curl_getinfo($session);
      //if($Headers['http_code'] == 302 || $Headers['http_code'] == 301){
      /*else if($Headers['http_code'] == 404){
        if($resource == 'playlist'){
        $this->Error(7);
        return;
        }
      }*/
      // The web service returns XML. Set the Content-Type appropriately
      /*if($fmt=='xml')
        header("Content-Type: text/xml");*/
 
      curl_close($session);
      if($this->debug)
        print("Debug ::: API response: ".$output."
"); return $output; } function curl_redir_exec($ch){ static $curl_loops = 0; static $curl_max_loops = 20; if ($curl_loops++ >= $curl_max_loops) { $curl_loops = 0; return FALSE; } curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); list($header, $data) = explode("\n\n", $data, 2); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($http_code == 301 || $http_code == 302) { $matches = array(); preg_match('/Location:(.*?)\n/', $header, $matches); $url = @parse_url(trim(array_pop($matches))); if (!$url) { //could not process the url to redirect to $curl_loops = 0; return $data; } $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)); if (!$url['scheme']) $url['scheme'] = $last_url['scheme']; if (!$url['host']) $url['host'] = $last_url['host']; if (!$url['path']) $url['path'] = $last_url['path']; $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:''); curl_setopt($ch, CURLOPT_URL, $new_url); //echo 'Redirecting to'.$new_url; return $this->curl_redir_exec($ch); } else { curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $data = curl_exec($ch); $curl_loops=0; return $data; } } // Function that decodes the JSON response, returns an array function json2array($jsonObj){ if ( !function_exists('json_decode') ){ $this->Error(11); return false; } return json_decode($jsonObj); } // Function that converts the human typed actions into HTTP Request Methods protected function getHttpMethod($userMethod, $resource){ switch (strtolower($userMethod)) { case "read": return "GET"; break; case "create": return "POST"; break; case "delete": return "DELETE"; break; case "modify": return "PUT"; break; default: $this->Error(3); return false; break; } } //Function to be called if error occurs private function Error($Error){ //List of Errors $e[1] = 'Username and/or password not set'; $e[2] = 'No resource specified'; $e[3] = 'Invalid method'; $e[4] = 'Invalid username/password'; $e[5] = 'No method specified'; $e[6] = 'Invalid format'; $e[7] = 'Playlist does not exist'; $e[8] = 'You must specify a playlist name'; $e[9] = 'You must specify a playlist UID'; $e[10] = 'You must specify some metadata'; $e[11] = 'Your server does not support the json_decode() function. Look for a json PHP lib compatible with your PHP version.'; //Display Error if(array_key_exists($Error, $e)){ $this->error = $e[$Error]; } else{ $this->error = 'Invalid Error Code'; } }//End Error() } class LibraryItem { // this variabiles must be public to allow json_encode to see them public $author; public $title; public $description; function __construct ($author="",$title="",$description="") { $this->author = $author; $this->title = $title; $this->description = $description; } } class Recording { // this variabiles must be public to allow json_encode to see them public $radioID; public $timezone_used; public $from_time; public $to_time; public $repeat; public $rectype; public $keep; public $title; function __construct ($radioID="",$timezone_used="",$from_time="",$to_time="",$repeat="",$rectype="",$keep="",$title="") { $this->radioID = $radioID; $this->timezone_used = $timezone_used; $this->from_time = $from_time; $this->to_time = $to_time; $this->repeat = $repeat; $this->rectype= $rectype; $this->keep = $keep; $this->title = $title; } } class Podcast { // this variabiles must be public to allow json_encode to see them public $podcast_url; public $podcast_title; public $podcast_description; function __construct ($podcast_url="",$podcast_title="",$podcast_description="") { $this->podcast_url = $podcast_url; $this->podcast_title = $podcast_title; $this->podcast_description = $podcast_description; } }  ?>
Personal tools