Created
November 13, 2013 13:59
-
-
Save mikeyhu/7449552 to your computer and use it in GitHub Desktop.
Dashing-js Job to receive Google Analytics Realtime data using CoffeeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
googleapis = require 'googleapis' | |
email = 'MYDEVELOPERACCOUNT@developer.gserviceaccount.com' | |
scope = ['https://www.google.com/analytics/feeds/'] | |
keyFile = 'MYKEY.pem' | |
previousMetrics = [] | |
maxHistory = 120 | |
current = 0 | |
getDevice = (rows,name)-> (parseInt(row[1],10) for row in rows when row[0]==name)[0] | |
getRealTimeMetrics = ()-> | |
googleapis.discover('analytics','v3').execute (err,client)-> | |
jwt = new googleapis.auth.JWT(email,keyFile,scope) | |
jwt.authorize (err,result)-> | |
console.log "#{moment().format()} : getRealTimeMetrics-authorise : #{err}" if err | |
client.analytics.data.realtime.get({ | |
'ids': 'ga:MY_GA_ID', | |
'metrics': 'ga:activeVisitors', | |
'dimensions':'ga:deviceCategory' | |
}).withAuthClient(jwt).execute (err,results)-> | |
console.log "#{moment().format()} : getRealTimeMetrics-execute : #{err}" if err | |
#Get active visitors | |
activeVisitors = parseInt(results.totalsForAllResults['ga:activeVisitors'],10) | |
previousMetrics.shift() if previousMetrics.length >= maxHistory | |
current = current + 1 | |
previousMetrics.push({x:current, y:activeVisitors}) | |
#Work out % of mobile/tablet | |
mobilePct = (100 / activeVisitors * getDevice(results.rows,'MOBILE')).toFixed(1) | |
tabletPct = (100 / activeVisitors * getDevice(results.rows,'TABLET')).toFixed(1) | |
mobileTabletPct = (100 / activeVisitors * (getDevice(results.rows,'TABLET')+getDevice(results.rows,'MOBILE'))).toFixed(1) | |
send_event('activeVisitors',{points:previousMetrics}) | |
send_event('mobilePct',{value:mobilePct}) | |
send_event('tabletPct',{value:tabletPct}) | |
send_event('mobileTabletPct',{value:mobileTabletPct}) | |
setInterval(getRealTimeMetrics, 60 * 1000) | |
getRealTimeMetrics() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment