Skip to content

Instantly share code, notes, and snippets.

@piffie
Last active August 29, 2015 14:14
Show Gist options
  • Save piffie/6d55a2810adc2a495a21 to your computer and use it in GitHub Desktop.
Save piffie/6d55a2810adc2a495a21 to your computer and use it in GitHub Desktop.
Google Analytics Realtime API retrieval
var http = require('http');
var https = require('https');
var uri = require('url');
module['exports'] = function garealtime (hook) {
var auth = hook.params.authorization
run = function() {
var url = "https://www.googleapis.com/analytics/v3/data/realtime?ids="+hook.params.ga+"&metrics=rt%3AactiveUsers&key=" + hook.params.key
options = uri.parse(url)
options.headers = {
"Authorization": auth
}
https.get(options, function(res){
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
hook.debug("recieved results");
data = JSON.parse(body);
var users = -1
if(typeof(data.totalsForAllResults) !== 'undefined'){
users = data.totalsForAllResults['rt:activeUsers'];
}else {
hook.debug(body)
}
hook.debug(users);
//hook.debug('Summe ist:' + sum);
hook.res.end('{"value": ' + users + '}');
});
}).on('error', function (){
hook.res.end('error calling google analytics');
});
};
if(auth == hook.env.pwd) {
var tokenHook = hook.open('http://hook.io/piffie/GoogleRefreshToken?pwd='+auth);
var body = ''
tokenHook.on('data', function(chunk){
body += chunk;
});
tokenHook.on('end', function() {
auth = "Bearer " + JSON.parse(body).token
run();
});
} else {
run();
}
//hook.res.end(JSON.stringify(hook.params, true, 2));
};
module['exports'].schema = {
"key": {
"type": "string"
},
"ga": {
"type": "string"
},
"authorization": {
"type": "string"
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment