2010-09-06, 15:01
Hello all, I'm kinda new to this forum but I have been using XBMC for a few weeks now. I have started on a dedicated XBMC Jsonrpc class for php, but I can't figure out why it does not work 100%. My problem is that 9 out of 10 times my connection times out and in the log it says just:
"14:50:50 T:140333434550032 M:3258880000 NOTICE: WebServer: POST | /jsonrpc"
When it works I get a reponse after < 1 second and when it fails it loads for ~10 seconds.
Here is my code:
"14:50:50 T:140333434550032 M:3258880000 NOTICE: WebServer: POST | /jsonrpc"
When it works I get a reponse after < 1 second and when it fails it loads for ~10 seconds.
Here is my code:
PHP Code:
class xbmcRPC {
public function getMovie( $ids = array( ), $params = array( ) )
{
if ( !is_array( $ids ) ) $ids = array( $ids );
$movies = $this->request("VideoLibrary.GetMovies", $params);
if(!empty($ids)) // Get movies in $ids
{
$return = array();
foreach($movies["result"]["movies"] AS $movie)
if(in_array($movie["id"], $ids))
$return = movie;
if(count($return)>0)
return $return;
else
return array("error" => "Movie not found");
} // Get all movies
else
return $movies["result"]["movies"];
}
protected function request( $method, $params = array( ) )
{
$this->id++;
$data = array("jsonrpc" => "2.0","method" => $method, "id" => $this->id);
if(count($params) > 0)
$data["params"] = $params;
$data = json_encode( $data );
$opts = array( 'http' => array('user_agent' => $_SERVER['HTTP_USER_AGENT'] ,'timeout' => '5','ignore_errors' => true,'method' => 'POST','content' => $data,'header' => 'Content-type: application/json'."\r\n"));
if ( $this->username && $this->password )
$opts['http']['header'] .= sprintf( "Authorization: Basic %s\r\n", base64_encode( $this->username.':'.$this->password ) );
$stream = stream_context_create( $opts );
if ( $fp = fopen( $this->url, 'r', false, $stream ) ) {
$response = '';
while( $row = fgets( $fp ) ) {
$response.= trim( $row )."\n";
}
}
$stream_meta = stream_get_meta_data( $fp );
fclose( $fp );
if(!$fp)
throw new xbmcRPCException( 'Unable to establish a connection to '. $this->url);
else if( $stream_meta['timed_out'] )
throw new xbmcRPCException( "Timed out connecting to " . $this->url);
else if( substr( $stream_meta['wrapper_data'][0], 9, 3 ) == "401" )
throw new xbmcRPCException( "Invalid username/password.");
return json_decode( $response, true );
}
public function __construct($url = 'http://localhost:8080', $username = "xbmc", $password = null)
{
$this->url = $url;
$this->username = $username;
$this->password = $password;
ini_set ('user_agent', $_SERVER['HTTP_USER_AGENT']);
}
}
class xbmcRPCException extends Exception {
public function __construct( $message = null, $code = 0, Exception $previous = null )
{
parent::__construct( $message, $code );
}
}