Jump to content
XboxLeaders
Sign in to follow this  
cave

Show Online Presence (modified api.php)

Recommended Posts

So with the api.php off Jason's GitHub i added a few lines in there to get the online status (Online Playing COD:.......) 

 

 

Here is how it shows in the results.

{
"status": "success",
"version": "2.0",
"data": {
"gamertag": "Stallion83",
"is_cheater": false,
"is_gold": true,
"url": "http://live.xbox.com/en-US/Profile?gamertag=stallion83",
"presence": "Online playing Dead Space™ 2 - DE - Idle",
"avatars": {
"small": "http://avatar.xboxlive.com/avatar/stallion83/avatarpic-s.png",
"large": "http://avatar.xboxlive.com/avatar/stallion83/avatarpic-l.png",
"body": "http://avatar.xboxlive.com/avatar/stallion83/avatar-body.png"
},

 

 

The code I added.

$presence = explode('<div class="presence">', file_get_contents('http://live.xbox.com/en-US/Profile?gamertag='.rawurlencode($this->gamertag)));
$presence = explode('</div>', $presence[1]);
$data['presence'] = trim($presence[0]);

 

 

Here is the fill api.php file with this code added to it.

<?php

class XboxAPI {

    public $version = '2.0';       // API Version
    public $format = 'json';       // Format to return data
    public $cache_path = '/tmp/';  // Relative directory to store cache files
    public $ttl = 3600;            // Time To Live for cache files, in seconds
    public $gamertag;              // The gamertag
    public $error;                 // Error code
    public $runtime;
    public $errors = array(
        600 => 'The gamertag supplied is not valid.',
        601 => 'The gamertag supplied does not exist.'
    );

    public function __construct() {
        $this->runtime = microtime(true);
    }

    protected function read_cache($key) {
        if (!file_exists($this->cache_path . $key) || filesize($this->cache_path . $key) == 0) {
            return false;
        } else {
            $file = fopen($this->cache_path . $key, 'r');
            $data = json_decode(fread($file, filesize($this->cache_path . $key)), true);
            if ($data['cached'] <= (time() - $this->ttl)) {
                return false;
            } else {
                return $data['data'];
            }
            fclose($file);
        }

        return false;
    }

    protected function save_cache($key, $data, $ttl = 3600) {
        if (file_exists($this->cache_path . $key)) {
            $file = fopen($this->cache_path . $key, 'r+');
            $data = fread($file, filesize($this->cache_path . $key));
            if ($data['timestamp'] <= (time() - $this->ttl)) {
                $data['data'] = $data;
                $data['timestamp'] = time();
                fwrite($file, json_encode($data));
            }
            fclose($file);
        }

        return false;
    }

    protected function find($haystack, $start, $finish) {
        $s = explode($start, $haystack);
        $s = explode($finish, $s[1]);

        return $s[0];
    }

    protected function find_tid($string) {
        $tid = parse_url($string);
        $tid = explode('&', html_entity_decode($tid['query']));
        $tid = explode('=', $tid['0']);
        return $tid['1'];
    }

    protected function http() {
        $gamertag = str_replace("%20", " ", $this->gamertag);

        // Validity check. Saves resources on invalid gamertags.
        if (!preg_match('/^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/', $gamertag)) {
            $this->error = 600;
            return false;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://gamercard.xbox.com/en-US/' . $gamertag . '.card');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)');

        $result = curl_exec($ch);

        curl_close($ch);

        // Make sure the gamertag exists on Xbox
        if (strpos($result, 'http://image.xboxlive.com//global/t.FFFE07D1/tile/0/20000') !== false) {
            $this->error = 601;
            return false;
        }

        return $result;
    }

    public function output_headers() {
        header('Content-type: application/' . $this->format);
    }

    public function output_payload($data) {
        $payload = array(
            'status' => 'success',
            'version' => $this->version,
            'data' => $data,
            'runtime' => round(microtime(true) - $this->runtime, 3)
        );

        switch ($this->format) {
            case 'json':
                $payload = output_pretty_json($payload);
                break;
            case 'xml':
                $payload = output_pretty_xml($payload);
                break;
            case 'php':
                $payload = output_pretty_php($payload);
                break;
            case 'csv':
                $payload = output_pretty_csv($payload);
                break;
        }

        return $payload;
    }

    public function output_error($code) {
        $payload = array(
            'status' => 'error',
            'version' => $this->version,
            'error' => array(
                'code' => $code,
                'message' => $this->errors[$code]
            ),
            'runtime' => round(microtime(true) - $this->runtime, 3)
        );

        switch ($this->format) {
            case 'json':
                $payload = output_pretty_json($payload);
                break;
            case 'xml':
                $payload = output_pretty_xml($payload);
                break;
            case 'php':
                $payload = output_pretty_php($payload);
                break;
            case 'csv':
                $payload = output_pretty_csv($payload);
                break;
        }

        return $payload;
    }

    public function fetch() {
        $key = 'cache_' . md5($this->gamertag);
        $cached = $this->read_cache($key);
        if ($cached) {
            $result = $cached;
        } else {
            $result = $this->http();
        }

        if ($result) {
            // A few regex's
            preg_match('~<div class="XbcGamercard (.*?)">~si', $result, $status);
            preg_match_all('~<div class="Star (.*?)">~si', $result, $reputation);

            /** Preparation * */
            if (strpos($status[1], 'Male') !== false) {
                $prep['gender'] = 'male';
            } else if (strpos($status[1], 'Female') !== false) {
                $prep['gender'] = 'female';
            } else {
                $prep['gender'] = 'unknown';
            }

            $prep['reputation'] = 0;
            foreach ($reputation[1] as $k => $v) {
                $starvalue = array(
                    'Empty' => 0, 'Quarter' => 1, 'Half' => 2,
                    'ThreeQuarter' => 3, 'Full' => 4
                );
                $prep['reputation'] = $prep['reputation'] + $starvalue[$v];
            }
            /** END Preparation * */
            $data = array();

            $data['gamertag'] = trim($this->find($result, '<title>', '</title>'));
            $data['is_cheater'] = (strpos($status[1], 'Cheater') !== false) ? true : false;
            $data['is_gold'] = (strpos($status[1], 'Gold') !== false) ? true : false;
            $data['url'] = 'http://live.xbox.com/en-US/Profile?gamertag=' . rawurlencode($this->gamertag);
            $presence = explode('<div class="presence">', file_get_contents('http://live.xbox.com/en-US/Profile?gamertag=' . rawurlencode($this->gamertag)));
            $presence = explode('</div>', $presence[1]);
            $data['presence'] = trim($presence[0]);
            $data['avatars']['small'] = 'http://avatar.xboxlive.com/avatar/' . rawurlencode($this->gamertag) . '/avatarpic-s.png';
            $data['avatars']['large'] = 'http://avatar.xboxlive.com/avatar/' . rawurlencode($this->gamertag) . '/avatarpic-l.png';
            $data['avatars']['body'] = 'http://avatar.xboxlive.com/avatar/' . rawurlencode($this->gamertag) . '/avatar-body.png';
            $data['launch_team']['xboxlive'] = (strpos($result, 'Xbc360Launch') !== false) ? true : false;
            $data['launch_team']['nxe'] = (strpos($result, 'XbcNXELaunch') !== false) ? true : false;
            $data['launch_team']['kinect'] = (strpos($result, 'XbcKinectLaunch') !== false) ? true : false;
            $data['gamerscore'] = trim($this->find($result, '<div id="Gamerscore">', '</div>'));
            $data['reputation'] = $prep['reputation'];
            $data['gender'] = $prep['gender'];
            $data['motto'] = trim($this->find($result, '<div id="Motto">', '</div>'));
            $data['name'] = trim($this->find($result, '<div id="Name">', '</div>'));
            $data['location'] = trim($this->find($result, '<div id="Location">', '</div>'));
            $data['bio'] = trim($this->find($result, '<div id="Bio">', '</div>'));

            if (strpos($result, '<ol id="PlayedGames" class="NoGames">') !== false) {
                $data['recent_games'] = array();
            } else {
                $games_html = $this->find($result, '<ol id="PlayedGames" >', '</ol');
                preg_match_all('~<li >(.*?)</li>~si', $games_html, $games);

                $i = 0;
                foreach ($games[1] as $game) {
                    preg_match('~<a href="(.*?)">~si', $game, $url);
                    $g['tid'] = $this->find_tid($url[1]);
                    $g['url'] = 'http://marketplace.xbox.com/Title/' . $g['tid'] . '/';
                    $g['img'] = $this->find($game, '<img src="', '" alt="');
                    $g['title'] = $this->find($game, '<span class="Title">', '</span>');
                    $g['last_played'] = $this->find($game, '<span class="LastPlayed">', '</span>');
                    $g['gamerscore']['earned'] = $this->find($game, '<span class="EarnedGamerscore">', '</span>');
                    $g['gamerscore']['possible'] = $this->find($game, '<span class="AvailableGamerscore">', '</span>');
                    $g['achievements']['earned'] = $this->find($game, '<span class="EarnedAchievements">', '</span>');
                    $g['achievements']['possible'] = $this->find($game, '<span class="AvailableAchievements">', '</span>');
                    $g['percent_completed'] = $this->find($game, '<span class="PercentageComplete">', '</span>');
                    $g['completed'] = ($g['percent_completed'] == '100%') ? true : false;
                    $g['boxart']['large'] = 'http://tiles.xbox.com/consoleAssets/' . strtoupper(dechex($g['tid'])) . '/en-US/largeboxart.jpg';
                    $g['boxart']['small'] = 'http://tiles.xbox.com/consoleAssets/' . strtoupper(dechex($g['tid'])) . '/en-US/smallboxart.jpg';

                    $data['recent_games'][$i] = $g;
                    ++$i;
                }
            }

            $this->save_cache($key, $data, $this->ttl);

            return $this->output_payload($data);
        } else {
            // We've failed, master.
            return $this->output_error($this->errors[$this->error]);
        }
    }

}

function output_pretty_json($data) {
    header('Content-type: text/json');
    echo json_encode($data);
}

function output_pretty_xml($data) {
    echo $data;
}

function output_pretty_php($data) {
    echo print_r($data);
}

function output_pretty_csv($data) {
    echo $data;
}

 

 

 

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...