social sharing count

Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: social sharing count
PostPosted: Wed Sep 19, 2012 10:18 am 
User avatar
Obliterated

Current Scorched3D Rank: Unranked



Joined: Wed Jun 14, 2006 11:18 pm
Posts: 1493
Location: United Kingdom
the current system is unreliable. we're using this http://sharedcount.com/. it's cool, but it's failing a bit. the count keeps changing or vanishing.

ive put some code together so that we dont need to rely on third-party servers:

Code:
<?php

function api_request($api_uri, $request_method, $content_type, $content) {
    $options = array(
        'http' => array(
            'method'  => $request_method,
            'header'  => $content_type . '\r\n',
            'content' => $content,
            'timeout' => 1
        )
    );

    $context = stream_context_create($options);
    //add a bit of error trapping
    if ($response = file_get_contents($api_uri, false, $context)) {;
        return $response;
    }
    else {
        return false;
    }
    //var_dump($http_response_header);
}



function get_counts() {
   
    $url = 'http://www.scorched3d.co.uk/';
    $total_count = 0;
    $failed = 0;
   
    //google +1's
    $api_uri = 'https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ';
    $request_method = 'POST';
    $content_type = 'Content-Type: application/json';
    $request_array[] = array(
        'apiVersion' => 'v1',
        'id' => 'p',
        'jsonrpc' => '2.0',
        'key' => 'p',
        'method' => 'pos.plusones.get',
        'params' => array(
            'nolog' => 'true',
            'id' => $url,
            'source' => 'widget',
            'container' => $url,
            'userId' => '@viewer',
            'groupId' => '@self'
        )
    );
    $content = json_encode($request_array);
    //love that php test on assignment stuff or whatever they call it
    if ($response = api_request($api_uri, $request_method, $content_type, $content)) {
        $response_json = json_decode($response, true);
        $google = $response_json[0]['result']['metadata']['globalCounts']['count'];
        $total_count = $total_count + $google;
    }
    else {
        $failed = $failed + 1;
    }
   
    //facebook
    $api_uri = 'https://api.facebook.com/method/fql.query';
    $request_method = 'POST';
    $content_type = 'Content-Type: application/json';
    $content = http_build_query(array('query' => 'select total_count from link_stat where url="'.$url.'"')).'&format=json';
    if ($response = api_request($api_uri, $request_method, $content_type, $content)) {
        $response_json = json_decode($response, true);
        $facebook = $response_json[0]['total_count'];
        $total_count = $total_count + $facebook;
    }
    else {
        $failed = $failed + 1;
    }
   
   
    //stumbleupon - using GET, bit inconsistent, but no one will know
    $api_uri = 'http://www.stumbleupon.com/services/1.01/badge.getinfo?url='.$url;
    $request_method = 'GET';
    $content_type = 'Content-type: application/octet-stream';
    $content = '';
    if ($response = api_request($api_uri, $request_method, $content_type, $content)) {
        $response_json = json_decode($response, true);
        $stumbleupon = $response_json['result']['views'];
        $total_count = $total_count + $stumbleupon;
    }
    else {
        $failed = $failed + 1;
    }
   
    //twitter
    $api_uri = 'http://cdn.api.twitter.com/1/urls/count.json?url='.$url;
    $request_method = 'GET';
    $content_type = 'Content-type: application/octet-stream';
    $content = '';
    if ($response = api_request($api_uri, $request_method, $content_type, $content)) {
        $response_json = json_decode($response, true);
        $twitter = $response_json['count'];
        $total_count = $total_count + $twitter;
    }
    else {
        $failed = $failed + 1;
    }
    if ($failed) {
        return false;
    }
    else {
        return $total_count;
    }
}

//a bit of caching code - we dont want to query the api's with every hit
$cache_count = 'cache/cache_count.txt';
$cache_time = 30;

if (file_exists($cache_count) && time() - $cache_time < filemtime($cache_count)) {
        //read from cache
        echo file_get_contents($cache_count) . ',' . filemtime($cache_count);
}
else {
    if ($total_count = get_counts()) {
        //write new
        file_put_contents($cache_count, $total_count);
        echo $total_count . ',' . filemtime($cache_count);
    }
    else {
        //one or more requests failed.  let's add the last cache time so we can check client-side
        echo file_get_contents($cache_count) . ',' . filemtime($cache_count);
    }
}

?>


seems to work. twitter's and google's api's are undocumented and could fail at any time if they alter them. i thought id include the cache time and add it to the page somewhere secret so we can keep an eye on it client-side.

we'll just xhr the above php page, and the numbers should be faster and a bit more reliable:

Code:
<script>
var xhr = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
    xhr = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
    try {
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch (e) {
        xhr = false;
    }
}
@else
    xhr = false;
@end @*/
if (!xhr && typeof XMLHttpRequest!='undefined') {
    try {
        xhr = new XMLHttpRequest();
    }
    catch (e) {
        xhr = false;
    }
}

function getDoc(counts) {
    if (xhr) {
        xhr.open('GET', counts, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                var response = xhr.responseText;
                console.log(response.split(',')[0]);
            }     
        }
    xhr.send(null)
    }
}

getDoc('/dev/counts.php');
</script>


i'll clear the caching system with the boss and see about getting that live. anyone who speaks the language in the mean time, feel free to offer thoughts on better ways to do this. thanks


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Powered by phpBB © phpBB Group