diff -r cddc2ba706d6 -r 860ba7141641 ajax.php --- a/ajax.php Sun Mar 23 15:24:06 2008 -0400 +++ b/ajax.php Sun Mar 23 20:24:33 2008 -0400 @@ -9,5 +9,104 @@ * This script is in the public domain. Use it for good, not evil. */ +status('initializing Services_JSON'); +$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE); +// keep track of playlist refresh +$playlist_last_refresh = time(); +/** + * Terminate a request with an error string formatted as JSON. + * @param string Error message + */ + +function json_die($msg) +{ + global $json; + echo $json->encode(array( + 'mode' => 'error', + 'error' => $msg + )); + return true; +} + +function ajax_request_handler($httpd) +{ + global $playlist, $mime_types, $json; + + // Set content type + $httpd->header("Content-type: {$mime_types['js']}"); + + // get PATH_INFO + $pathinfo = @substr(@substr($_SERVER['REQUEST_URI'], 1), @strpos(@substr($_SERVER['REQUEST_URI'], 1), '/')+1); + if ( empty($pathinfo) ) + { + return json_die('No action specified on URI'); + } + + $params = explode('/', $pathinfo); + $action =& $params[0]; + switch ( $action ) + { + case 'stop': + case 'next': + case 'prev': + echo dcop_action('player', 'stop'); + break; + case 'play': + echo dcop_action('player', 'playPause'); + break; + case 'jump': + $tid =& $params[1]; + if ( !preg_match('/^[0-9]+$/', $tid) ) + { + return die_json('Invalid track ID'); + } + $tid = intval($tid); + dcop_action('playlist', "playByIndex $tid"); + $return = array( + 'current_track_length' => $playlist[$tid]['length_int'], + 'current_track_pos' => 0 + ); + echo $json->encode($return); + break; + case 'volume': + $volume =& $params[1]; + if ( !preg_match('/^[0-9]+$/', $volume) ) + { + return die_json('Invalid track ID'); + } + $volume = intval($volume); + dcop_action('player', "setVolume $volume"); + $return = array( + 'volume' => $volume + ); + echo $json->encode($return); + break; + case 'refresh': + global $playlist_last_refresh, $playlist, $playlist_last_md5; + if ( $playlist_last_refresh + 60 < time() ) + { + rebuild_playlist(); + } + $current_track = dcop_action('playlist', 'getActiveIndex'); + $return = array( + 'is_playing' => dcop_action('player', 'isPlaying'), + 'current_track' => $current_track, + 'volume' => dcop_action('player', 'getVolume'), + // include the MD5 of the playlist so that if it changes, the + // client can refresh (otherwise things get madly corrupted) + 'playlist_hash' => $playlist_last_md5 + ); + if ( isset($playlist[$current_track]) ) + { + $return['current_track_length'] = $playlist[$current_track]['length_int']; + $return['current_track_pos'] = dcop_action('player', 'trackCurrentTime'); + } + echo $json->encode($return); + break; + default: + return json_die("Undefined action: $action"); + } +} +