Guest User

Untitled

a guest
Jun 13th, 2011
885
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 23.43 KB | None | 0 0
  1. <?php
  2. if(PHP_SAPI != 'cli') die('This script can only be accessed through the command line.');
  3. $config = array(
  4.  
  5.  
  6.  
  7.  
  8. /********* CONFIGURATION *********/
  9.  
  10.  
  11. // Transmission RPC connection details
  12. 'host' => 'http://localhost:9881/transmission/rpc',
  13. 'user' => '',
  14. 'password' => '',
  15.  
  16. // ratio shaping upload speed limits
  17. // the default config means: if ratio is >1, then limit upload to 100KB/s, if ratio >1.5, limit to 50KB/s etc
  18. // use 0 as speed value for no limit
  19. 'ratioshape' => array(
  20.     1.0 => 100,
  21.     1.5 => 50,
  22.     2.0 => 10,
  23. ),
  24.  
  25. // what ratio is denominated against (default is amount uploaded / amount to download)
  26. 'ratioStat' => 'sizeWhenDone', // can be sizeWhenDone, totalSize or downloadedEver
  27.  
  28.  
  29.  
  30. /*********  *********/
  31.  
  32.  
  33.  
  34.  
  35. );
  36. // sort ratio levels for convenience later on
  37. krsort($config['ratioshape'], SORT_NUMERIC);
  38. $configRatioStat = $config['ratioStat'];
  39.  
  40. // TODO: PHP version check thingy
  41.  
  42. try {
  43.     // grab list of torrents in transmission
  44.     $transmission = new TransmissionRPC($config['host'], $config['user'], $config['password']);
  45.     $torrents = $transmission->get(array(), array('id', 'status', 'bandwidthPriority', 'peer-limit', 'uploadLimit', 'uploadLimited', 'uploadedEver', $configRatioStat));
  46.    
  47.    
  48.     // no torrents = leave
  49.     if(empty($torrents->arguments->torrents)) exit;
  50.    
  51.     // traverse list of torrents
  52.     foreach($torrents->arguments->torrents as &$torrent) {
  53.         if($torrent->status != 4) continue; // only consider active, non-seeding, torrents
  54.        
  55.         if(!isset($torrent->uploadLimited)) $torrent->uploadLimited = false;
  56.         if(!isset($torrent->uploadedEver)) $torrent->uploadedEver = 0;
  57.        
  58.         if(@$torrent->$configRatioStat > 0) { // we cannot divide by 0, ever
  59.             $ratio = $torrent->uploadedEver / $torrent->$configRatioStat;
  60.             foreach($config['ratioshape'] as $level => $action) {
  61.                 if($ratio > $level) { // hit a ratio threadhold level
  62.                    
  63.                     // perform action
  64.                     if($action) {
  65.                         if(!$torrent->uploadLimited || $torrent->uploadLimit > $action)
  66.                             $transmission->set($torrent->id, array('uploadLimited' => true, 'uploadLimit' => $action));
  67.                     }
  68.                     elseif($torrent->uploadLimited) // action=0 -> no limit
  69.                         $transmission->set($torrent->id, array('uploadLimited' => false));
  70.                    
  71.                     break;
  72.                 }
  73.             }
  74.         }
  75.     }
  76.    
  77. } catch(Exception $ex) {
  78.     echo "Exception ".$ex->getMessage()." occurred.\n";
  79. }
  80. unset($transmission);
  81.  
  82.  
  83.  
  84.  
  85. /**
  86.  * Transmission bittorrent client/daemon RPC communication class
  87.  * Copyright (C) 2010 Johan Adriaans <[email protected]>,
  88.  *                    Bryce Chidester <[email protected]>
  89.  *
  90.  * This program is free software: you can redistribute it and/or modify
  91.  * it under the terms of the GNU General Public License as published by
  92.  * the Free Software Foundation, either version 3 of the License, or
  93.  * (at your option) any later version.
  94.  *
  95.  * This program is distributed in the hope that it will be useful,
  96.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  97.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  98.  * GNU General Public License for more details.
  99.  *
  100.  * You should have received a copy of the GNU General Public License
  101.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  102.  */
  103.  
  104. /**
  105.  * PHP version specific information
  106.  * version_compare() (PHP 4 >= 4.1.0, PHP 5)
  107.  * ctype_digit() (PHP 4 >= 4.0.4, PHP 5)
  108.  * stream_context_create (PHP 4 >= 4.3.0, PHP 5)
  109.  * PHP Class support (PHP 5) (PHP 4 might work, untested)
  110.  */
  111.  
  112. /**
  113.  * A friendly little version check...
  114.  */
  115. if ( version_compare( PHP_VERSION, TransmissionRPC::MIN_PHPVER, '<' ) )
  116.   die( "The TransmissionRPC class requires PHP version {TransmissionRPC::TRANSMISSIONRPC_MIN_PHPVER} or above." . PHP_EOL );
  117.  
  118. /**
  119.  * Transmission bittorrent client/daemon RPC communication class
  120.  *
  121.  * Usage example:
  122.  * <code>
  123.  *   $rpc = new TransmissionRPC($rpc_url);
  124.  *   $result = $rpc->add_file( $url_or_path_to_torrent, $target_folder );
  125.  * </code>
  126.  *
  127.  */
  128. class TransmissionRPC
  129. {
  130.   /**
  131.    * User agent used in all http communication
  132.    */
  133.   const HTTP_UA = 'TransmissionRPC for PHP/0.3';
  134.  
  135.   /**
  136.    * Minimum PHP version required
  137.    */
  138.   const MIN_PHPVER = '5.0.0';
  139.  
  140.   /**
  141.    * The URL to the bittorent client you want to communicate with
  142.    * the port (default: 9091) can be set in you Tranmission preferences
  143.    * @var string
  144.    */
  145.   public $url = '';
  146.  
  147.   /**
  148.    * If your Transmission RPC requires authentication, supply username here
  149.    * @var string
  150.    */
  151.   public $username = '';
  152.  
  153.   /**
  154.    * If your Transmission RPC requires authentication, supply password here
  155.    * @var string
  156.    */
  157.   public $password = '';
  158.  
  159.   /**
  160.    * Return results as an array, or an object (default)
  161.    * @var bool
  162.    */
  163.   public $return_as_array = false;
  164.  
  165.   /**
  166.    * Print debugging information, default is off
  167.    * @var bool
  168.    */
  169.   public $debug = false;
  170.  
  171.   /**
  172.    * Transmission uses a session id to prevent CSRF attacks
  173.    * @var string
  174.    */
  175.   protected $session_id = '';
  176.  
  177.   /**
  178.    * Default values for stream context
  179.    * @var array
  180.    */
  181.   private $default_context_opts = array( 'http' => array(
  182.                                            'user_agent'  => self::HTTP_UA,
  183.                                            //  'timeout' => '5',    // Don't want to be too slow
  184.                                            'ignore_errors' => true, // Leave the error parsing/handling to the code
  185.                                          )
  186.                                        );
  187.  
  188.   /**
  189.    * Start one or more torrents
  190.    *
  191.    * @param int|array ids A list of transmission torrent ids
  192.    */
  193.   public function start ( $ids )
  194.   {
  195.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  196.     $request = array( "ids" => $ids );
  197.     return $this->request( "torrent-start", $request );
  198.   }
  199.  
  200.   /**
  201.    * Stop one or more torrents
  202.    *
  203.    * @param int|array ids A list of transmission torrent ids
  204.    */
  205.   public function stop ( $ids )
  206.   {
  207.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  208.     $request = array( "ids" => $ids );
  209.     return $this->request( "torrent-stop", $request );
  210.   }
  211.  
  212.   /**
  213.    * Reannounce one or more torrents
  214.    *
  215.    * @param int|array ids A list of transmission torrent ids
  216.    */
  217.   public function reannounce ( $ids )
  218.   {
  219.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  220.     $request = array( "ids" => $ids );
  221.     return $this->request( "torrent-reannounce", $request );
  222.   }
  223.  
  224.   /**
  225.    * Verify one or more torrents
  226.    *
  227.    * @param int|array ids A list of transmission torrent ids
  228.    */
  229.   public function verify ( $ids )
  230.   {
  231.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  232.     $request = array( "ids" => $ids );
  233.     return $this->request( "torrent-verify", $request );
  234.   }
  235.  
  236.   /**
  237.    * Get information on torrents in transmission, if the ids parameter is
  238.    * empty all torrents will be returned. The fields array can be used to return certain
  239.    * fields. Default fields are: "id", "name", "status", "doneDate", "haveValid", "totalSize".
  240.    * See https://trac.transmissionbt.com/browser/trunk/doc/rpc-spec.txt for available fields
  241.    *
  242.    * @param array fields An array of return fields
  243.    * @param int|array ids A list of transmission torrent ids
  244.    */
  245.   public function get ( $ids = array(), $fields = array() )
  246.   {
  247.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  248.     if ( count( $fields ) == 0 ) $fields = array( "id", "name", "status", "doneDate", "haveValid", "totalSize" );   // Defaults
  249.     $request = array(
  250.       "fields" => $fields,
  251.       "ids" => $ids
  252.     );
  253.     return $this->request( "torrent-get", $request );
  254.   }
  255.  
  256.   /**
  257.    * Set properties on one or more torrents, available fields are:
  258.    *   "bandwidthPriority"   | number     this torrent's bandwidth tr_priority_t
  259.    *   "downloadLimit"       | number     maximum download speed (in K/s)
  260.    *   "downloadLimited"     | boolean    true if "downloadLimit" is honored
  261.    *   "files-wanted"        | array      indices of file(s) to download
  262.    *   "files-unwanted"      | array      indices of file(s) to not download
  263.    *   "honorsSessionLimits" | boolean    true if session upload limits are honored
  264.    *   "ids"                 | array      torrent list, as described in 3.1
  265.    *   "location"            | string     new location of the torrent's content
  266.    *   "peer-limit"          | number     maximum number of peers
  267.    *   "priority-high"       | array      indices of high-priority file(s)
  268.    *   "priority-low"        | array      indices of low-priority file(s)
  269.    *   "priority-normal"     | array      indices of normal-priority file(s)
  270.    *   "seedRatioLimit"      | double     session seeding ratio
  271.    *   "seedRatioMode"       | number     which ratio to use.  See tr_ratiolimit
  272.    *   "uploadLimit"         | number     maximum upload speed (in K/s)
  273.    *   "uploadLimited"       | boolean    true if "uploadLimit" is honored
  274.    * See https://trac.transmissionbt.com/browser/trunk/doc/rpc-spec.txt for more information
  275.    *
  276.    * @param array arguments An associative array of arguments to set
  277.    * @param int|array ids A list of transmission torrent ids
  278.    */  
  279.   public function set ( $ids = array(), $arguments = array() )
  280.   {
  281.     // See https://trac.transmissionbt.com/browser/trunk/doc/rpc-spec.txt for available fields
  282.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  283.     if ( !isset( $arguments['ids'] ) ) $arguments['ids'] = $ids;    // Any $ids given in $arguments overrides the method parameter
  284.     return $this->request( "torrent-set", $arguments );
  285.   }
  286.  
  287.   /**
  288.    * Add a new torrent
  289.    *
  290.    * Available extra options:
  291.    *  key                  | value type & description
  292.    *  ---------------------+-------------------------------------------------
  293.    *  "download-dir"       | string      path to download the torrent to
  294.    *  "filename"           | string      filename or URL of the .torrent file
  295.    *  "metainfo"           | string      base64-encoded .torrent content
  296.    *  "paused"             | boolean     if true, don't start the torrent
  297.    *  "peer-limit"         | number      maximum number of peers
  298.    *  "bandwidthPriority"  | number      torrent's bandwidth tr_priority_t
  299.    *  "files-wanted"       | array       indices of file(s) to download
  300.    *  "files-unwanted"     | array       indices of file(s) to not download
  301.    *  "priority-high"      | array       indices of high-priority file(s)
  302.    *  "priority-low"       | array       indices of low-priority file(s)
  303.    *  "priority-normal"    | array       indices of normal-priority file(s)
  304.    *  
  305.    *   Either "filename" OR "metainfo" MUST be included.
  306.    *     All other arguments are optional.  
  307.    *
  308.    * @param torrent_location The URL or path to the torrent file
  309.    * @param save_path Folder to save torrent in
  310.    * @param extra options Optional extra torrent options
  311.    */
  312.   public function add_file( $torrent_location, $save_path = '', $extra_options = array() )
  313.   {
  314.     $extra_options['download-dir'] = $save_path;
  315.     $extra_options['filename'] = $torrent_location;
  316.    
  317.     return $this->request( "torrent-add", $extra_options );
  318.   }
  319.  
  320.   /**
  321.    * Add a torrent using the raw torrent data
  322.    *
  323.    * @param torrent_metainfo The raw, unencoded contents (metainfo) of a torrent
  324.    * @param save_path Folder to save torrent in
  325.    * @param extra options Optional extra torrent options
  326.    */
  327.   public function add_metainfo( $torrent_metainfo, $save_path = '', $extra_options = array() )
  328.   {
  329.     $extra_options['download-dir'] = $save_path;
  330.     $extra_options['metainfo'] = base64_encode( $torrent_metainfo );
  331.    
  332.     return $this->request( "torrent-add", $extra_options );
  333.   }
  334.  
  335.   /* Add a new torrent using a file path or a URL (For backwards compatibility)
  336.    * @param torrent_location The URL or path to the torrent file
  337.    * @param save_path Folder to save torrent in
  338.    * @param extra options Optional extra torrent options
  339.    */
  340.   public function add( $torrent_location, $save_path = '', $extra_options = array() )
  341.   {
  342.     return $this->add_file( $torrent_location, $save_path, $extra_options );
  343.   }
  344.  
  345.   /**
  346.    * Remove torrent from transmission
  347.    *
  348.    * @param bool delete_local_data Also remove local data?
  349.    * @param int|array ids A list of transmission torrent ids
  350.    */
  351.   public function remove ( $ids, $delete_local_data = false )
  352.   {
  353.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  354.     $request = array(
  355.       "ids" => $ids,
  356.       "delete-local-data" => $delete_local_data
  357.     );
  358.     return $this->request( "torrent-remove", $request );
  359.   }
  360.  
  361.   /**
  362.    * Move local storage location
  363.    *
  364.    * @param int|array ids A list of transmission torrent ids
  365.    * @param string target_location The new storage location
  366.    * @param string move_existing_data Move existing data or scan new location for available data
  367.    */
  368.   public function move ( $ids, $target_location, $move_existing_data = true )
  369.   {
  370.     if ( !is_array( $ids ) ) $ids = array( $ids );  // Convert $ids to an array if only a single id was passed
  371.     $request = array(
  372.       "ids" => $ids,
  373.       "location" => $target_location,
  374.       "move" => $move_existing_data
  375.     );
  376.     return $this->request( "torrent-set-location", $request );  
  377.   }
  378.  
  379.  
  380.  
  381.   /**
  382.    * Here be dragons (Internal methods)
  383.    */
  384.  
  385.  
  386.  
  387.   /**
  388.    * Clean up the request array. Removes any empty fields from the request
  389.    *
  390.    * @param array array The request associative array to clean
  391.    * @returns array The cleaned array
  392.    */  
  393.   protected function cleanRequestData ( $array )
  394.   {
  395.     if ( !is_array( $array ) || count( $array ) == 0 ) return null; // Nothing to clean
  396.     foreach ( $array as $index => $value )
  397.     {
  398.       if( is_array( $array[$index] ) ) $array[$index] = $this->cleanRequestData( $array[$index] );  // Recursion
  399.       if ( empty( $value ) ) unset( $array[$index] );   // Remove empty members
  400.     }
  401.     return $array;
  402.   }
  403.  
  404.   /**
  405.    * Clean up the result object. Replaces all minus(-) characters in the object properties with underscores
  406.    * and converts any object with any all-digit property names to an array.
  407.    *
  408.    * @param object The request result to clean
  409.    * @returns array The cleaned object
  410.    */  
  411.   protected function cleanResultObject ( $object )
  412.   {
  413.     // Prepare and cast object to array
  414.     $return_as_array = false;
  415.     $array = $object;
  416.     if ( !is_array( $array ) ) $array = (array) $array;
  417.     foreach ( $array as $index => $value )
  418.     {
  419.       if( is_array( $array[$index] ) || is_object( $array[$index] ) )
  420.       {
  421.         $array[$index] = $this->cleanResultObject( $array[$index] );    // Recursion
  422.       }
  423.       if ( strstr( $index, '-' ) )
  424.       {
  425.         $valid_index = str_replace( '-', '_', $index );
  426.         $array[$valid_index] = $array[$index];
  427.         unset( $array[$index] );
  428.         $index = $valid_index;
  429.       }
  430.       // Might be an array, check index for digits, if so, an array should be returned
  431.       if ( ctype_digit( (string) $index ) ) { $return_as_array = true; }
  432.       if ( empty( $value ) ) unset( $array[$index] );
  433.     }
  434.     // Return array cast to object
  435.     return $return_as_array ? $array : (object) $array;
  436.   }
  437.  
  438.   /**
  439.    * The request handler method handles all requests to the Transmission client
  440.    *
  441.    * @param string method The request method to use
  442.    * @param array arguments The request arguments
  443.    * @returns array The request result
  444.    */
  445.   protected function request( $method, $arguments, $in_recur=false )
  446.   {
  447.     // Check the parameters
  448.     if ( !is_scalar( $method ) )
  449.       throw new TransmissionRPCException( 'Method name has no scalar value', TransmissionRPCException::E_INVALIDARG );
  450.     if ( !is_array( $arguments ) )
  451.       throw new TransmissionRPCException( 'Arguments must be given as array', TransmissionRPCException::E_INVALIDARG );
  452.    
  453.     $arguments = $this->cleanRequestData( $arguments ); // Sanitize input
  454.    
  455.     // Grab the X-Transmission-Session-Id if we don't have it already
  456.     if( !$this->session_id )
  457.       if( !$this->GetSessionID() )
  458.         throw new TransmissionRPCException( 'Unable to acquire X-Transmission-Session-Id', TransmissionRPCException::E_SESSIONID );
  459.    
  460.     // Build (and encode) request array
  461.     $data = array(
  462.       "method" => $method,
  463.       "arguments" => $arguments
  464.     );
  465.     $data = json_encode( $data );
  466.    
  467.     // performs the HTTP POST
  468.     $contextopts = $this->default_context_opts; // Start with the defaults
  469.     $contextopts['http']['method'] = 'POST';
  470.     $contextopts['http']['header'] = 'Content-type: application/json'."\r\n".
  471.                                      'X-Transmission-Session-Id: '.$this->session_id."\r\n";
  472.     $contextopts['http']['content'] = $data;
  473.    
  474.     // Setup authentication (if provided)
  475.     if ( $this->username && $this->password )
  476.       $contextopts['http']['header'] .= sprintf( "Authorization: Basic %s\r\n", base64_encode( $this->username.':'.$this->password ) );
  477.    
  478.     if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: request( method=$method, ...):: Stream context created with options:" .
  479.                             PHP_EOL . print_r( $contextopts, true );
  480.    
  481.     $context  = stream_context_create( $contextopts );  // Create the context for this request
  482.     if ( $fp = @fopen( $this->url, 'r', false, $context ) ) {   // Open a filepointer to the data, and use fgets to get the result
  483.       $response = '';
  484.       while( $row = fgets( $fp ) ) {
  485.         $response.= trim( $row )."\n";
  486.       }
  487.       if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: request( method=$method, ...):: POST Result: ".
  488.                               PHP_EOL . print_r( $response, true );
  489.     } else
  490.       throw new TransmissionRPCException( 'Unable to connect to '.$this->url, TransmissionRPCException::E_CONNECTION );
  491.    
  492.     // Check the response (headers etc)
  493.     $stream_meta = stream_get_meta_data( $fp );
  494.     fclose( $fp );
  495.     if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: request( method={$method}, ...):: Stream meta info: ".
  496.                             PHP_EOL . print_r( $stream_meta, true );
  497.     if( $stream_meta['timed_out'] )
  498.       throw new TransmissionRPCException( "Timed out connecting to {$this->url}", TransmissionRPCException::E_CONNECTION );
  499.     if( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "401" )
  500.       throw new TransmissionRPCException( "Invalid username/password.", TransmissionRPCException::E_AUTHENTICATION );
  501.     elseif( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "409" ) {
  502.       if( $in_recur )
  503.         throw new TransmissionRPCException( "Invalid X-Transmission-Session-Id. Please try again after calling GetSessionID().", TransmissionRPCException::E_SESSIONID );
  504.       else {
  505.         $this->GetSessionID();
  506.         return $this->request( $method, $arguments, true );
  507.       }
  508.     }
  509.    
  510.     return $this->return_as_array ? json_decode( $response, true ) : $this->cleanResultObject( json_decode( $response ) );  // Return the sanitized result
  511.   }
  512.  
  513.   /**
  514.    * Performs an empty GET on the Transmission RPC to get the X-Transmission-Session-Id
  515.    * and store it in $this->session_id
  516.    *
  517.    * @return string
  518.    */
  519.   public function GetSessionID()
  520.   {
  521.     if( !$this->url )
  522.       throw new TransmissionRPCException( "Class must be initialized before GetSessionID() can be called.", TransmissionRPCException::E_INVALIDARG );
  523.    
  524.     // Setup the context
  525.     $contextopts = $this->default_context_opts; // Start with the defaults
  526.    
  527.     // Make sure it's blank/empty (reset)
  528.     $this->session_id = null;
  529.    
  530.     // Setup authentication (if provided)
  531.     if ( $this->username && $this->password )
  532.       $contextopts['http']['header'] = sprintf( "Authorization: Basic %s\r\n", base64_encode( $this->username.':'.$this->password ) );
  533.    
  534.     if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream context created with options:".
  535.                             PHP_EOL . print_r( $contextopts, true );
  536.    
  537.     $context  = stream_context_create( $contextopts );  // Create the context for this request
  538.     if ( ! $fp = @fopen( $this->url, 'r', false, $context ) )   // Open a filepointer to the data, and use fgets to get the result
  539.       throw new TransmissionRPCException( 'Unable to connect to '.$this->url, TransmissionRPCException::E_CONNECTION );
  540.    
  541.     // Check the response (headers etc)
  542.     $stream_meta = stream_get_meta_data( $fp );
  543.     fclose( $fp );
  544.     if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Stream meta info: ".
  545.                             PHP_EOL . print_r( $stream_meta, true );
  546.     if( $stream_meta['timed_out'] )
  547.       throw new TransmissionRPCException( "Timed out connecting to {$this->url}", TransmissionRPCException::E_CONNECTION );
  548.     if( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "401" )
  549.       throw new TransmissionRPCException( "Invalid username/password.", TransmissionRPCException::E_AUTHENTICATION );
  550.     elseif( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "409" )  // This is what we're hoping to find
  551.     {
  552.       // Loop through the returned headers and extract the X-Transmission-Session-Id
  553.       foreach( $stream_meta['wrapper_data'] as $header )
  554.       {
  555.         if( strpos( $header, 'X-Transmission-Session-Id: ' ) === 0 )
  556.         {
  557.           if( $this->debug ) echo "TRANSMISSIONRPC_DEBUG:: GetSessionID():: Session-Id header: ".
  558.                                   PHP_EOL . print_r( $header, true );
  559.           $this->session_id = trim( substr( $header, 27 ) );
  560.           break;
  561.         }
  562.       }
  563.       if( ! $this->session_id ) {   // Didn't find a session_id
  564.         throw new TransmissionRPCException( "Unable to retrieve X-Transmission-Session-Id", TransmissionRPCException::E_SESSIONID );
  565.       }
  566.     } else {
  567.       throw new TransmissionRPCException( "Unexpected response from Transmission RPC: ".$stream_meta['wrapper_data'][0] );
  568.     }
  569.     return $this->session_id;
  570.   }
  571.  
  572.   /**
  573.    * Takes the connection parameters
  574.    *
  575.    * TODO: Sanitize username, password, and URL
  576.    *
  577.    * @param string $url
  578.    * @param string $username
  579.    * @param string $password
  580.    */
  581.   public function __construct( $url = 'http://localhost:9091/transmission/rpc', $username = null, $password = null, $return_as_array = false )
  582.   {
  583.     // server URL
  584.     $this->url = $url;
  585.    
  586.     // Username & password
  587.     $this->username = $username;
  588.     $this->password = $password;
  589.    
  590.     // Return As Array
  591.     $this->return_as_array = $return_as_array;
  592.    
  593.     // Reset X-Transmission-Session-Id so we (re)fetch one
  594.     $this->session_id = null;
  595.   }
  596. }
  597.  
  598. /**
  599.  * This is the type of exception the TransmissionRPC class will throw
  600.  */
  601. class TransmissionRPCException extends Exception
  602. {
  603.   /**
  604.    * Exception: Invalid arguments
  605.    */
  606.   const E_INVALIDARG = -1;
  607.  
  608.   /**
  609.    * Exception: Invalid Session-Id
  610.    */
  611.   const E_SESSIONID = -2;
  612.  
  613.   /**
  614.    * Exception: Error while connecting
  615.    */
  616.   const E_CONNECTION = -3;
  617.  
  618.   /**
  619.    * Exception: Error 401 returned, unauthorized
  620.    */
  621.   const E_AUTHENTICATION = -4;
  622.  
  623.   /**
  624.    * Exception constructor
  625.    */
  626.   public function __construct( $message = null, $code = 0, Exception $previous = null )
  627.   {
  628.     parent::__construct( $message, $code, $previous );
  629.   }
  630. }
Add Comment
Please, Sign In to add comment