Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AjaxHelper.ts « AjaxHelper « src « vue « CoreHome « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a3965760b896bd17d8b888844f0f1bd40fdef089 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*!
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

import jqXHR = JQuery.jqXHR;
import MatomoUrl from '../MatomoUrl/MatomoUrl';
import Matomo from '../Matomo/Matomo';

interface AjaxOptions {
  withTokenInUrl?: boolean;
  postParams?: QueryParameters;
}

window.globalAjaxQueue = [] as unknown as GlobalAjaxQueue;
window.globalAjaxQueue.active = 0;

window.globalAjaxQueue.clean = function globalAjaxQueueClean() {
  for (let i = this.length; i >= 0; i -= 1) {
    if (!this[i] || this[i]!.readyState === 4) {
      this.splice(i, 1);
    }
  }
};

window.globalAjaxQueue.push = function globalAjaxQueuePush(...args: (XMLHttpRequest|null)[]) {
  this.active += args.length;

  // cleanup ajax queue
  this.clean();

  // call original array push
  return Array.prototype.push.call(this, ...args);
};

window.globalAjaxQueue.abort = function globalAjaxQueueAbort() {
  // abort all queued requests if possible
  this.forEach((x) => x && x.abort && x.abort());

  // remove all elements from array
  this.splice(0, this.length);

  this.active = 0;
};

type AnyFunction = (...params:any[]) => any; // eslint-disable-line

/**
 * error callback to use by default
 */
function defaultErrorCallback(deferred: XMLHttpRequest, status: string): void {
  // do not display error message if request was aborted
  if (status === 'abort') {
    return;
  }

  if (typeof Piwik_Popover === 'undefined') {
    console.log(`Request failed: ${deferred.responseText}`); // mostly for tests
    return;
  }

  const loadingError = $('#loadingError');
  if (Piwik_Popover.isOpen() && deferred && deferred.status === 500) {
    if (deferred && deferred.status === 500) {
      $(document.body).html(piwikHelper.escape(deferred.responseText));
    }
  } else {
    loadingError.show();
  }
}

/**
 * Global ajax helper to handle requests within Matomo
 */
export default class AjaxHelper<T = any> { // eslint-disable-line
  /**
   * Format of response
   */
  format = 'json';

  /**
   * A timeout for the request which will override any global timeout
   */
  timeout: number|null = null;

  /**
   * Callback function to be executed on success
   */
  callback: AnyFunction|null = null;

  /**
   * Use this.callback if an error is returned
   */
  useRegularCallbackInCaseOfError = false;

  /**
   * Callback function to be executed on error
   *
   * @deprecated use the jquery promise API
   */
  errorCallback: AnyFunction;

  withToken = false;

  /**
   * Callback function to be executed on complete (after error or success)
   *
   * @deprecated use the jquery promise API
   */
  completeCallback?: AnyFunction;

  /**
   * Params to be passed as GET params
   * @see ajaxHelper.mixinDefaultGetParams
   */
  getParams: QueryParameters = {};

  /**
   * Base URL used in the AJAX request. Can be set by setUrl.
   *
   * It is set to '?' rather than 'index.php?' to increase chances that it works
   * including for users who have an automatic 301 redirection from index.php? to ?
   * POST values are missing when there is such 301 redirection. So by by-passing
   * this 301 redirection, we avoid this issue.
   *
   * @see ajaxHelper.setUrl
   */
  getUrl = '?';

  /**
   * Params to be passed as GET params
   * @see ajaxHelper.mixinDefaultPostParams
   */
  postParams: QueryParameters = {};

  /**
   * Element to be displayed while loading
   */
  loadingElement: HTMLElement|null|JQuery|JQLite|string = null;

  /**
   * Element to be displayed on error
   */
  errorElement: HTMLElement|JQuery|JQLite|string = '#ajaxError';

  /**
   * Handle for current request
   */
  requestHandle: JQuery.jqXHR|null = null;

  defaultParams = ['idSite', 'period', 'date', 'segment'];

  // helper method entry point
  static fetch<R = any>(params: QueryParameters, options: AjaxOptions = {}): Promise<R> { // eslint-disable-line
    const helper = new AjaxHelper<R>();
    if (options.withTokenInUrl) {
      helper.withTokenInUrl();
    }
    helper.setFormat('json');
    helper.addParams({ module: 'API', format: 'json', ...params }, 'get');
    if (options.postParams) {
      helper.addParams(options.postParams, 'post');
    }
    return helper.send();
  }

  constructor() {
    this.errorCallback = defaultErrorCallback;
  }

  /**
   * Adds params to the request.
   * If params are given more then once, the latest given value is used for the request
   *
   * @param  initialParams
   * @param  type  type of given parameters (POST or GET)
   * @return {void}
   */
  addParams(initialParams: QueryParameters|string, type: string): void {
    const params: QueryParameters = typeof initialParams === 'string'
      ? window.broadcast.getValuesFromUrl(initialParams) : initialParams;

    const arrayParams = ['compareSegments', 'comparePeriods', 'compareDates'];
    Object.keys(params).forEach((key) => {
      const value = params[key];
      if (arrayParams.indexOf(key) !== -1
        && !value
      ) {
        return;
      }

      if (type.toLowerCase() === 'get') {
        this.getParams[key] = value;
      } else if (type.toLowerCase() === 'post') {
        this.postParams[key] = value;
      }
    });
  }

  withTokenInUrl(): void {
    this.withToken = true;
  }

  /**
   * Sets the base URL to use in the AJAX request.
   */
  setUrl(url: string): void {
    this.addParams(broadcast.getValuesFromUrl(url), 'GET');
  }

  /**
   * Gets this helper instance ready to send a bulk request. Each argument to this
   * function is a single request to use.
   */
  setBulkRequests(...urls: Array<string|QueryParameters>): void {
    const urlsProcessed = urls.map((u) => (typeof u === 'string' ? u : $.param(u)));

    this.addParams({
      module: 'API',
      method: 'API.getBulkRequest',
      urls: urlsProcessed,
      format: 'json',
    }, 'post');
  }

  /**
   * Set a timeout (in milliseconds) for the request. This will override any global timeout.
   *
   * @param timeout  Timeout in milliseconds
   */
  setTimeout(timeout: number): void {
    this.timeout = timeout;
  }

  /**
   * Sets the callback called after the request finishes
   *
   * @param callback  Callback function
   * @deprecated use the jquery promise API
   */
  setCallback(callback: AnyFunction): void {
    this.callback = callback;
  }

  /**
   * Set that the callback passed to setCallback() should be used if an application error (i.e. an
   * Exception in PHP) is returned.
   */
  useCallbackInCaseOfError(): void {
    this.useRegularCallbackInCaseOfError = true;
  }

  /**
   * Set callback to redirect on success handler
   * &update=1(+x) will be appended to the current url
   *
   * @param [params] to modify in redirect url
   * @return {void}
   */
  redirectOnSuccess(params: QueryParameters): void {
    this.setCallback(() => {
      piwikHelper.redirect(params);
    });
  }

  /**
   * Sets the callback called in case of an error within the request
   *
   * @deprecated use the jquery promise API
   */
  setErrorCallback(callback: AnyFunction): void {
    this.errorCallback = callback;
  }

  /**
   * Sets the complete callback which is called after an error or success callback.
   *
   * @deprecated use the jquery promise API
   */
  setCompleteCallback(callback: AnyFunction): void {
    this.completeCallback = callback;
  }

  /**
   * Sets the response format for the request
   *
   * @param format  response format (e.g. json, html, ...)
   */
  setFormat(format: string): void {
    this.format = format;
  }

  /**
   * Set the div element to show while request is loading
   *
   * @param [element]  selector for the loading element
   */
  setLoadingElement(element: string|HTMLElement|JQuery): void {
    this.loadingElement = element || '#ajaxLoadingDiv';
  }

  /**
   * Set the div element to show on error
   *
   * @param element  selector for the error element
   */
  setErrorElement(element: HTMLElement|JQuery|string): void {
    if (!element) {
      return;
    }
    this.errorElement = element;
  }

  /**
   * Detect whether are allowed to use the given default parameter or not
   */
  private useGETDefaultParameter(parameter: string): boolean {
    if (parameter && this.defaultParams) {
      for (let i = 0; i < this.defaultParams.length; i += 1) {
        if (this.defaultParams[i] === parameter) {
          return true;
        }
      }
    }

    return false;
  }

  /**
   * Removes a default parameter that is usually send automatically along the request.
   *
   * @param parameter  A name such as "period", "date", "segment".
   */
  removeDefaultParameter(parameter: string): void {
    if (parameter && this.defaultParams) {
      for (let i = 0; i < this.defaultParams.length; i += 1) {
        if (this.defaultParams[i] === parameter) {
          this.defaultParams.splice(i, 1);
        }
      }
    }
  }

  /**
   * Send the request
   */
  send(): AbortablePromise<T> {
    if ($(this.errorElement).length) {
      $(this.errorElement).hide();
    }

    if (this.loadingElement) {
      $(this.loadingElement).fadeIn();
    }

    this.requestHandle = this.buildAjaxCall();
    window.globalAjaxQueue.push(this.requestHandle);

    const result: AbortablePromise<T> = new Promise<T>((resolve, reject) => {
      this.requestHandle!.then(resolve).fail((xhr: jqXHR) => {
        if (xhr.statusText !== 'abort') {
          console.log(`Warning: the ${$.param(this.getParams)} request failed!`);

          reject(xhr);
        }
      });
    }) as AbortablePromise<T>;

    result.abort = () => {
      if (this.requestHandle) {
        this.requestHandle.abort();
      }
    };

    return result;
  }

  /**
   * Aborts the current request if it is (still) running
   */
  abort(): void {
    if (this.requestHandle && typeof this.requestHandle.abort === 'function') {
      this.requestHandle.abort();
      this.requestHandle = null;
    }
  }

  /**
   * Builds and sends the ajax requests
   */
  private buildAjaxCall(): JQuery.jqXHR {
    const self = this;
    const parameters = this.mixinDefaultGetParams(this.getParams);

    let url = this.getUrl;
    if (url[url.length - 1] !== '?') {
      url += '&';
    }

    // we took care of encoding &segment properly already, so we don't use $.param for it ($.param
    // URL encodes the values)
    if (parameters.segment) {
      url = `${url}segment=${parameters.segment}&`;
      delete parameters.segment;
    }
    if (parameters.date) {
      url = `${url}date=${decodeURIComponent(parameters.date.toString())}&`;
      delete parameters.date;
    }
    url += $.param(parameters);
    const ajaxCall = {
      type: 'POST',
      async: true,
      url,
      dataType: this.format || 'json',
      complete: this.completeCallback,
      error: function errorCallback(...args: any[]) { // eslint-disable-line
        window.globalAjaxQueue.active -= 1;

        if (self.errorCallback) {
          self.errorCallback.apply(this, args);
        }
      },
      success: (response: any, status: string, request: jqXHR) => { // eslint-disable-line
        if (this.loadingElement) {
          $(this.loadingElement).hide();
        }

        if (response && response.result === 'error' && !this.useRegularCallbackInCaseOfError) {
          let placeAt = null;
          let type: string|null = 'toast';
          if ($(this.errorElement).length && response.message) {
            $(this.errorElement).show();
            placeAt = this.errorElement;
            type = null;
          }

          if (response.message) {
            const UI = window['require']('piwik/UI'); // eslint-disable-line
            const notification = new UI.Notification();
            notification.show(response.message, {
              placeat: placeAt,
              context: 'error',
              type,
              id: 'ajaxHelper',
            });
            notification.scrollToNotification();
          }
        } else if (this.callback) {
          this.callback(response, status, request);
        }

        window.globalAjaxQueue.active -= 1;
        if (Matomo.ajaxRequestFinished) {
          Matomo.ajaxRequestFinished();
        }
      },
      data: this.mixinDefaultPostParams(this.postParams),
      timeout: this.timeout !== null ? this.timeout : undefined,
    };

    return $.ajax(ajaxCall);
  }

  private isRequestToApiMethod() {
    return (this.getParams && this.getParams.module === 'API' && this.getParams.method)
      || (this.postParams && this.postParams.module === 'API' && this.postParams.method);
  }

  isWidgetizedRequest(): boolean {
    return (broadcast.getValueFromUrl('module') === 'Widgetize');
  }

  private getDefaultPostParams() {
    if (this.withToken || this.isRequestToApiMethod() || Matomo.shouldPropagateTokenAuth) {
      return {
        token_auth: Matomo.token_auth,
        // When viewing a widgetized report there won't be any session that can be used, so don't
        // force session usage
        force_api_session: broadcast.isWidgetizeRequestWithoutSession() ? 0 : 1,
      };
    }

    return {};
  }

  /**
   * Mixin the default parameters to send as POST
   *
   * @param params   parameter object
   */
  private mixinDefaultPostParams(params: QueryParameters): QueryParameters {
    const defaultParams = this.getDefaultPostParams();

    const mergedParams = {
      ...defaultParams,
      ...params,
    };

    return mergedParams;
  }

  /**
   * Mixin the default parameters to send as GET
   *
   * @param   params   parameter object
   */
  private mixinDefaultGetParams(originalParams: QueryParameters): QueryParameters {
    const segment = MatomoUrl.getSearchParam('segment');

    const defaultParams: Record<string, string> = {
      idSite: Matomo.idSite ? Matomo.idSite.toString() : broadcast.getValueFromUrl('idSite'),
      period: Matomo.period || broadcast.getValueFromUrl('period'),
      segment,
    };

    const params = originalParams;

    // never append token_auth to url
    if (params.token_auth) {
      params.token_auth = null;
      delete params.token_auth;
    }

    Object.keys(defaultParams).forEach((key) => {
      if (this.useGETDefaultParameter(key)
        && !params[key]
        && !this.postParams[key]
        && defaultParams[key]
      ) {
        params[key] = defaultParams[key];
      }
    });

    // handle default date & period if not already set
    if (this.useGETDefaultParameter('date') && !params.date && !this.postParams.date) {
      params.date = Matomo.currentDateString;
    }

    return params;
  }
}