Skip to content

Instantly share code, notes, and snippets.

@cjlyth
Created June 12, 2014 17:35
Show Gist options
  • Save cjlyth/120939624faefe4b84e7 to your computer and use it in GitHub Desktop.
Save cjlyth/120939624faefe4b84e7 to your computer and use it in GitHub Desktop.
AngularJS Piwik Service
"use strict";
angular.module("MyApp.services"/*, []*/)
.constant('piwikUrl', 'http://0.0.0.0/piwik')
.constant('piwikAuthToken', '0a0a00a0aa0a00000a00aaa0000a0a0')
.constant('piwikSiteUrl', 'http://myapp.mydomain.com')
.constant('piwikSiteName', 'MyApp')
.service('piwik', ['$q', '$http', 'piwikUrl', 'piwikAuthToken', 'piwikSiteUrl', 'piwikSiteName',
function($q, $http, piwikUrl, piwikAuthToken, piwikSiteUrl, piwikSiteName) {
function fetchSiteIds (){
var deferred = $q.defer();
$http({
method: 'POST',
url: piwikUrl + '/index.php',
responseType: 'json',
params: {
module: 'API',
format: 'JSON',
method: 'SitesManager.getSitesIdFromSiteUrl',
url: piwikSiteUrl,
token_auth: piwikAuthToken
}
}).
success(function(data, status, headers, config) {
deferred.resolve(data.map(function(o){return o.idsite;}));
}).
error(function(data, status, headers, config) {
deferred.reject('Error fetching Piwik Site IDs: ' + status);
});
return deferred.promise;
}
function createSite (){
var deferred = $q.defer();
$http({
method: 'POST',
url: piwikUrl + '/index.php',
responseType: 'json',
params: {
token_auth: piwikAuthToken,
module: 'API',
format: 'JSON',
method: 'SitesManager.addSite',
siteName: piwikSiteName,
urls: [piwikSiteUrl]
}
}).
success(function(data, status, headers, config) {
deferred.resolve([data.value]);
}).
error(function(data, status, headers, config) {
deferred.reject('Error adding Piwik Site: ' + status);
});
return deferred.promise;
}
function getSiteId() {
return fetchSiteIds()
.then(function(siteIds){
if (siteIds.length === 0) {
return createSite();
} else {
return siteIds;
}
});
}
return {
fetchSiteIds: fetchSiteIds,
createSite: createSite,
getSiteId: getSiteId
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment