PageRenderTime 49ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/stats/plugins/CoreHome/angularjs/common/services/piwik-api.js

https://bitbucket.org/webstar1987923/mycampaignsio
JavaScript | 347 lines | 224 code | 65 blank | 58 comment | 54 complexity | 55d3d402732084ab29c493b5f12b425b MD5 | raw file
Possible License(s): BSD-3-Clause, MPL-2.0-no-copyleft-exception, GPL-3.0, GPL-2.0, WTFPL, BSD-2-Clause, LGPL-2.1, Apache-2.0, MIT, AGPL-3.0
  1. /*!
  2. * Piwik - free/libre analytics platform
  3. *
  4. * @link http://piwik.org
  5. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  6. */
  7. // see https://github.com/piwik/piwik/issues/5094 used to detect an ad blocker
  8. var hasBlockedContent = false;
  9. (function () {
  10. angular.module('piwikApp.service').factory('piwikApi', piwikApiService);
  11. piwikApiService.$inject = ['$http', '$q', '$rootScope', 'piwik', '$window'];
  12. function piwikApiService ($http, $q, $rootScope, piwik, $window) {
  13. var url = 'index.php';
  14. var format = 'json';
  15. var getParams = {};
  16. var postParams = {};
  17. var allRequests = [];
  18. /**
  19. * Adds params to the request.
  20. * If params are given more then once, the latest given value is used for the request
  21. *
  22. * @param {object} params
  23. * @return {void}
  24. */
  25. function addParams (params) {
  26. if (typeof params == 'string') {
  27. params = piwik.broadcast.getValuesFromUrl(params);
  28. }
  29. for (var key in params) {
  30. getParams[key] = params[key];
  31. }
  32. }
  33. function withTokenInUrl()
  34. {
  35. postParams['token_auth'] = piwik.token_auth;
  36. }
  37. function isRequestToApiMethod() {
  38. return getParams && getParams['module'] === 'API' && getParams['method'];
  39. }
  40. function isWidgetizedRequest() {
  41. return (broadcast.getValueFromUrl('module') == 'Widgetize');
  42. }
  43. function reset () {
  44. getParams = {};
  45. postParams = {};
  46. }
  47. function isErrorResponse(response) {
  48. return response && angular.isObject(response) && response.result == 'error';
  49. }
  50. function createResponseErrorNotification(response, options) {
  51. if (response.message
  52. && options.createErrorNotification
  53. ) {
  54. var UI = require('piwik/UI');
  55. var notification = new UI.Notification();
  56. notification.show(response.message, {
  57. context: 'error',
  58. type: 'toast',
  59. id: 'ajaxHelper',
  60. placeat: options.placeat
  61. });
  62. setTimeout(function () {
  63. // give some time for angular to render it
  64. notification.scrollToNotification();
  65. }, 100);
  66. }
  67. }
  68. /**
  69. * Send the request
  70. * @return $promise
  71. */
  72. function send (options) {
  73. if (!options) {
  74. options = {};
  75. }
  76. if (options.createErrorNotification === undefined) {
  77. options.createErrorNotification = true;
  78. }
  79. function onSuccess(response)
  80. {
  81. response = response.data;
  82. if (!angular.isDefined(response) || response === null) {
  83. return $q.reject(null);
  84. } else if (isErrorResponse(response)) {
  85. createResponseErrorNotification(response, options);
  86. return $q.reject(response.message || null);
  87. } else {
  88. return response;
  89. }
  90. }
  91. function onError(response)
  92. {
  93. var message = 'Something went wrong';
  94. if (response && (response.status === 0 || response.status === -1)) {
  95. message = 'Request was possibly aborted';
  96. }
  97. return $q.reject(message);
  98. }
  99. var deferred = $q.defer(),
  100. requestPromise = deferred.promise;
  101. var headers = {
  102. 'Content-Type': 'application/x-www-form-urlencoded',
  103. // ie 8,9,10 caches ajax requests, prevent this
  104. 'cache-control': 'no-cache'
  105. };
  106. var requestFormat = format;
  107. if (getParams.format && getParams.format.toLowerCase() !== 'json' && getParams.format.toLowerCase() !== 'json2') {
  108. requestFormat = getParams.format;
  109. }
  110. var ajaxCall = {
  111. method: 'POST',
  112. url: url,
  113. responseType: requestFormat,
  114. params: _mixinDefaultGetParams(getParams),
  115. data: $.param(getPostParams(postParams)),
  116. timeout: requestPromise,
  117. headers: headers
  118. };
  119. var promise = $http(ajaxCall).then(onSuccess, onError);
  120. // we can't modify requestPromise directly and add an abort method since for some reason it gets
  121. // removed after then/finally/catch is called.
  122. var addAbortMethod = function (to, deferred) {
  123. return {
  124. then: function () {
  125. return addAbortMethod(to.then.apply(to, arguments), deferred);
  126. },
  127. 'finally': function () {
  128. return addAbortMethod(to.finally.apply(to, arguments), deferred);
  129. },
  130. 'catch': function () {
  131. return addAbortMethod(to.catch.apply(to, arguments), deferred);
  132. },
  133. abort: function () {
  134. deferred.resolve();
  135. return this;
  136. }
  137. };
  138. };
  139. var request = addAbortMethod(promise, deferred);
  140. allRequests.push(request);
  141. return request.finally(function() {
  142. var index = allRequests.indexOf(request);
  143. if (index !== -1) {
  144. allRequests.splice(index, 1);
  145. }
  146. });
  147. }
  148. /**
  149. * Get the parameters to send as POST
  150. *
  151. * @param {object} params parameter object
  152. * @return {object}
  153. * @private
  154. */
  155. function getPostParams (params) {
  156. if (isRequestToApiMethod() || isWidgetizedRequest()) {
  157. params.token_auth = piwik.token_auth;
  158. }
  159. return params;
  160. }
  161. /**
  162. * Mixin the default parameters to send as GET
  163. *
  164. * @param {object} getParamsToMixin parameter object
  165. * @return {object}
  166. * @private
  167. */
  168. function _mixinDefaultGetParams (getParamsToMixin) {
  169. var segment = piwik.broadcast.getValueFromHash('segment', $window.location.href.split('#')[1]);
  170. // we have to decode the value manually because broadcast will not decode anything itself. if we don't,
  171. // angular will encode it again before sending the value in an HTTP request.
  172. segment = decodeURIComponent(segment);
  173. var defaultParams = {
  174. idSite: piwik.idSite || piwik.broadcast.getValueFromUrl('idSite'),
  175. period: piwik.period || piwik.broadcast.getValueFromUrl('period'),
  176. segment: segment
  177. };
  178. // never append token_auth to url
  179. if (getParamsToMixin.token_auth) {
  180. getParamsToMixin.token_auth = null;
  181. delete getParamsToMixin.token_auth;
  182. }
  183. for (var key in defaultParams) {
  184. if (!(key in getParamsToMixin) && !(key in postParams) && defaultParams[key]) {
  185. getParamsToMixin[key] = defaultParams[key];
  186. }
  187. }
  188. // handle default date & period if not already set
  189. if (!getParamsToMixin.date && !postParams.date) {
  190. getParamsToMixin.date = piwik.currentDateString || piwik.broadcast.getValueFromUrl('date');
  191. if (getParamsToMixin.period == 'range' && piwik.currentDateString) {
  192. getParamsToMixin.date = piwik.startDateString + ',' + getParamsToMixin.date;
  193. }
  194. }
  195. return getParamsToMixin;
  196. }
  197. function abortAll() {
  198. reset();
  199. allRequests.forEach(function (request) {
  200. request.abort();
  201. });
  202. allRequests = [];
  203. }
  204. function abort () {
  205. abortAll();
  206. }
  207. /**
  208. * Perform a reading API request.
  209. * @param getParams
  210. */
  211. function fetch (getParams, options) {
  212. getParams.module = getParams.module || 'API';
  213. if (!getParams.format) {
  214. getParams.format = 'JSON2';
  215. }
  216. addParams(getParams);
  217. var promise = send(options);
  218. reset();
  219. return promise;
  220. }
  221. function post(getParams, _postParams_, options) {
  222. if (_postParams_) {
  223. if (postParams && postParams.token_auth && !_postParams_.token_auth) {
  224. _postParams_.token_auth = postParams.token_auth;
  225. }
  226. postParams = _postParams_;
  227. }
  228. return fetch(getParams, options);
  229. }
  230. function addPostParams(_postParams_) {
  231. if (_postParams_) {
  232. angular.merge(postParams, _postParams_);
  233. }
  234. }
  235. /**
  236. * Convenience method that will perform a bulk request using Piwik's API.getBulkRequest method.
  237. * Bulk requests allow you to execute multiple Piwik requests with one HTTP request.
  238. *
  239. * @param {object[]} requests
  240. * @param {object} options
  241. * @return {HttpPromise} a promise that is resolved when the request finishes. The argument passed
  242. * to the .then(...) callback will be an array with one element per request
  243. * made.
  244. */
  245. function bulkFetch(requests, options) {
  246. var bulkApiRequestParams = {
  247. urls: requests.map(function (requestObj) { return '?' + $.param(requestObj); })
  248. };
  249. var deferred = $q.defer(),
  250. requestPromise = post({method: "API.getBulkRequest"}, bulkApiRequestParams, options).then(function (response) {
  251. if (!(response instanceof Array)) {
  252. response = [response];
  253. }
  254. // check for errors
  255. for (var i = 0; i != response.length; ++i) {
  256. var specificResponse = response[i];
  257. if (isErrorResponse(specificResponse)) {
  258. deferred.reject(specificResponse.message || null);
  259. createResponseErrorNotification(specificResponse, options || {});
  260. return;
  261. }
  262. }
  263. deferred.resolve(response);
  264. }).catch(function () {
  265. deferred.reject.apply(deferred, arguments);
  266. });
  267. return deferred.promise;
  268. }
  269. return {
  270. withTokenInUrl: withTokenInUrl,
  271. bulkFetch: bulkFetch,
  272. post: post,
  273. fetch: fetch,
  274. addPostParams: addPostParams,
  275. /**
  276. * @deprecated
  277. */
  278. abort: abort,
  279. abortAll: abortAll
  280. };
  281. }
  282. })();