Created
June 12, 2014 17:35
-
-
Save cjlyth/120939624faefe4b84e7 to your computer and use it in GitHub Desktop.
AngularJS Piwik Service
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
"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