var version = '1.1',
update_url = 'http://adriankenny.com/assets/file/analytics/version.txt',
download_url = 'http://analyticswidget.com/download/';
// Function: load()
// Called by HTML body element's onload event when the widget is ready to start
function load()
{
if (window.widget)
{
KeyChainAccess.setAppName('Analytics');
var email = widget.preferenceForKey(keyWithIdentifier('email')),
gaid = JSON.parse(widget.preferenceForKey(keyWithIdentifier('gaid'))),
gaid_list = JSON.parse(widget.preferenceForKey(keyWithIdentifier('gaid-list'))),
site_name = widget.preferenceForKey(keyWithIdentifier('site-name')),
password = KeyChainAccess.loadPassword(email),
today = widget.preferenceForKey(keyWithIdentifier('visits-today')),
yesterday = widget.preferenceForKey(keyWithIdentifier('visits-yesterday')),
this_week = widget.preferenceForKey(keyWithIdentifier('visits-this-week')),
this_month = widget.preferenceForKey(keyWithIdentifier('visits-this-month')),
this_year = widget.preferenceForKey(keyWithIdentifier('visits-this-year'));
if (email && email.length > 0) {
$('#email').val(email);
}
if (email && email.length > 0)
{
$('#password').val(password);
}
if (today.length > 0)
{
$('#site-name').text(gaid.name),
$('#visits-today').text(today),
$('#visits-yesterday').text(yesterday),
$('#visits-this-week').text(this_week),
$('#visits-this-month').text(this_month),
$('#visits-this-year').text(this_year);
}
$.each(gaid_list, function(name, value) {
if (gaid.id === value)
{
$('#google-account-profiles').append('');
}
else
{
$('#google-account-profiles').append('');
}
});
checkWidgetVersion();
checkIfWeShouldEnableOrDisableDoneButton();
}
}
function remove()
{
// Stop any timers to prevent CPU usage and remove any preferences as needed.
if (window.widget) {
widget.setPreferenceForKey(null, keyWithIdentifier('email'));
widget.setPreferenceForKey(null, keyWithIdentifier('gaid'));
widget.setPreferenceForKey(null, keyWithIdentifier('gaid-list'));
widget.setPreferenceForKey(null, keyWithIdentifier('site-name'));
widget.setPreferenceForKey(null, keyWithIdentifier('visits-today'));
widget.setPreferenceForKey(null, keyWithIdentifier('visits-yesterday'));
widget.setPreferenceForKey(null, keyWithIdentifier('visits-this-week'));
widget.setPreferenceForKey(null, keyWithIdentifier('visits-this-month'));
widget.setPreferenceForKey(null, keyWithIdentifier('visits-this-year'));
widget.setPreferenceForKey(null, keyWithIdentifier('successful-login'));
}
}
function hide()
{
// Stop any timers to prevent CPU usage.
saveWidgetSettings();
}
function show()
{
// Restart any timers that were stopped on hide.
checkWidgetVersion();
}
function sync(){
// Sync stuff here..
}
// Function: showBack(event)
// Called when the info button is clicked to show the back of the widget
//
// event: onClick event from the info button
function showBack(event)
{
var front = document.getElementById('front');
var back = document.getElementById('back');
if (window.widget) {
widget.prepareForTransition('ToBack');
}
front.style.display = 'none';
back.style.display = 'block';
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
}
// Function: showFront(event)
// Called when the done button is clicked from the back of the widget
//
// event: onClick event from the done button
function showFront(event)
{
var front = document.getElementById('front');
var back = document.getElementById('back');
if (window.widget) {
widget.prepareForTransition('ToFront');
}
front.style.display='block';
back.style.display='none';
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
}
if (window.widget) {
widget.onremove = remove;
widget.onhide = hide;
widget.onshow = show;
widget.onsync = sync;
}
// Get profles
function getAccountProfiles() {
// Disable some ui.
$('#google-account-login').attr('disabled', true).addClass('disabled');
// Clear previous data
$('#visits-today, #visits-yesterday, #visits-this-week, #visits-this-month, #visits-this-year').text('');
// If we run this a second time we should clear the previous set of options.
$('#google-account-profiles option').remove();
var filename = 'responses/accounts-' + widget.identifier + '.json',
email = encodeURIComponent( $('#email').val() ),
password = encodeURIComponent( $('#password').val() ),
accountsfeed = new String(),
cmd = 'curl "https://www.google.com/analytics/feeds/accounts/default?prettyprint=false&alt=json" -s --header "Authorization: GoogleLogin $(curl https://www.google.com/accounts/ClientLogin -s -d Email=' + email + ' -d Passwd=' + password + ' -d accountType=GOOGLE -d source=curl-accountFeed-v1 -d service=analytics | awk /Auth=.*/)" > ' + filename,
command = widget.system(cmd, endHandler);
$('#notice').text('Fetching accounts…').fadeIn('fast');
function endHandler(command)
{
$.ajax({
type: 'GET',
url: filename,
dataType: 'json',
success: function(data) {
for (var i = 0; i < data.feed.entry.length; i++) {
$('#google-account-profiles').append('');
$('#google-account-profiles, #google-account-done, #google-account-login').attr('disabled', false).removeClass('disabled');
$('#notice').fadeOut('fast');
}
widget.setPreferenceForKey('1', keyWithIdentifier('successful-login'));
},
error: function() {
widget.setPreferenceForKey('0', keyWithIdentifier('successful-login'));
$('#google-account-login').attr('disabled', false).removeClass('disabled');
$('#notice').text('Fetching failed.').delay(2000).fadeOut('fast');
},
complete: function() {
checkIfWeShouldEnableOrDisableDoneButton();
}
});
}
}
// Get total visits for each timeframe.
function getData() {
var successful_login = widget.preferenceForKey(keyWithIdentifier('successful-login'));
if (successful_login == '1')
{
$('#refresh').addClass('disabled');
// Clear previous data
$('#site-name, #visits-today, #visits-yesterday, #visits-this-week, #visits-this-month, #visits-this-year').text('');
// I'm getting total visits for each timeframe. This seems hugely inefficient. Got to refactor this at some point.
getTotalVisitsForTimePeriod(
'visits-today',
Date.today().toString('yyyy-MM-dd'),
Date.today().toString('yyyy-MM-dd')
);
getTotalVisitsForTimePeriod(
'visits-yesterday',
Date.today().add(-1).days().toString('yyyy-MM-dd'),
Date.today().add(-1).days().toString('yyyy-MM-dd')
);
getTotalVisitsForTimePeriod(
'visits-this-week',
Date.today().addWeeks(-1).toString('yyyy-MM-dd'),
Date.today().toString('yyyy-MM-dd')
);
getTotalVisitsForTimePeriod(
'visits-this-month',
Date.today().moveToFirstDayOfMonth().toString('yyyy-MM-dd'),
Date.today().toString('yyyy-MM-dd')
);
getTotalVisitsForTimePeriod(
'visits-this-year',
Date.today().set({ month: 0, day: 1 }).toString('yyyy-MM-dd'),
Date.today().toString('yyyy-MM-dd')
);
$('#visits-today, #visits-yesterday, #visits-this-week, #visits-this-month, #visits-this-year').each(function() {
var id = $(this).attr('id');
$.ajax({
type: 'GET',
url: 'responses/analyze-' + id + '-' + widget.identifier + '.json',
dataType: 'json',
success: function(data) {
// Send metrics to front.
$('#' + id).html(addCommas(data.feed.dxp$aggregates.dxp$metric[0].value));
// Enable refresh button on front.
$('#refresh').removeClass('disabled');
}
});
});
$('#site-name').text( $('#google-account-profiles :selected').text() );
showFront();
}
}
// Get total visits during specified time frame.
function getTotalVisitsForTimePeriod(timeframe, start, end) {
if (window.widget) {
var filename = 'responses/analyze-' + timeframe + '-' + widget.identifier + '.json',
email = encodeURIComponent( $('#email').val() ),
gaid = $('#google-account-profiles :selected').val(),
password = encodeURIComponent( $('#password').val() ),
cmd = 'curl "https://www.google.com/analytics/feeds/data?start-date=' + start + '&end-date=' + end + '&dimensions=ga:date&metrics=ga:uniquePageviews&ids=ga:' + gaid + '&prettyprint=false&alt=json&max-results=0" -s --header "Authorization: GoogleLogin $(curl https://www.google.com/accounts/ClientLogin -s -d Email=' + email + ' -d Passwd=' + password + ' -d accountType=GOOGLE -d source=curl-accountFeed-v1 -d service=analytics | awk /Auth=.*/)" --header "GData-Version: 2" > ' + filename;
widget.system(cmd, null);
}
}
function getTotalUniqueVisitsForTimePeriod(timeframe, start, end) {
if (window.widget) {
var filename = 'responses/analyze-' + timeframe + '-' + widget.identifier + '.json',
email = encodeURIComponent( $('#email').val() ),
gaid = $('#google-account-profiles :selected').val(),
password = encodeURIComponent( $('#password').val() ),
cmd = 'curl "https://www.google.com/analytics/feeds/data?start-date=' + start + '&end-date=' + end + '&dimensions=ga:date&metrics=ga:visits&ids=ga:' + gaid + '&prettyprint=false&alt=json&max-results=0" -s --header "Authorization: GoogleLogin $(curl https://www.google.com/accounts/ClientLogin -s -d Email=' + email + ' -d Passwd=' + password + ' -d accountType=GOOGLE -d source=curl-accountFeed-v1 -d service=analytics | awk /Auth=.*/)" --header "GData-Version: 2" > ' + filename;
widget.system(cmd, null);
}
}
// Save [email, password, and google profile id, visits].
function saveWidgetSettings() {
var email = $('#email').val(),
gaid = new Object(),
gaid_list = new Object(),
password = $('#password').val(),
today = $('#visits-today').text(),
yesterday = $('#visits-yesterday').text(),
this_week = $('#visits-this-week').text(),
this_month = $('#visits-this-month').text(),
this_year = $('#visits-this-year').text();
gaid['id'] = $('#google-account-profiles :selected').val();
gaid['name'] = $('#google-account-profiles :selected').text();
$('#google-account-profiles option').each(function() {
var $this = $(this), name = $this.text(), val = $this.val()
gaid_list[name] = val;
});
gaid = JSON.stringify(gaid);
gaid_list = JSON.stringify(gaid_list);
if (window.widget) {
// Save email and gaid
widget.setPreferenceForKey(email, keyWithIdentifier('email'));
widget.setPreferenceForKey(gaid, keyWithIdentifier('gaid'));
widget.setPreferenceForKey(gaid_list, keyWithIdentifier('gaid-list'));
// Save the metrics to prefs.
widget.setPreferenceForKey(today, keyWithIdentifier('visits-today'));
widget.setPreferenceForKey(yesterday, keyWithIdentifier('visits-yesterday'));
widget.setPreferenceForKey(this_week, keyWithIdentifier('visits-this-week'));
widget.setPreferenceForKey(this_month, keyWithIdentifier('visits-this-month'));
widget.setPreferenceForKey(this_year, keyWithIdentifier('visits-this-year'));
if (password.length > 0) KeyChainAccess.savePassword(email, password);
}
}
// Helper function to format numbers with commas.
function addCommas(number)
{
number += '';
x = number.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var regex = /(\d+)(\d{3})/;
while (regex.test(x1)) {
x1 = x1.replace(regex, '$1' + ',' + '$2');
}
return x1 + x2;
}
// Helper function to save settings with a unique identifier key (so we can have multiple instaces of this widget).
function keyWithIdentifier(key) {
return widget.identifier + '-' + key;
}
function checkIfWeShouldEnableOrDisableDoneButton() {
if ( widget.preferenceForKey(keyWithIdentifier('successful-login')) == '1' )
{
$('#google-account-done').attr('disabled', false).removeClass('disabled');
$('#refresh').removeClass('disabled');
}
else
{
$('#google-account-done').attr('disabled', true).addClass('disabled');
$('#refresh').addClass('disabled');
}
}
function checkWidgetVersion() {
$.get(update_url, function(latest) {
if ( version < latest ) $('#new-version').show();
});
}
function openSite (url) {
if (window.widget) {
widget.openURL(url); return false;
}
return true;
}