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

live.js « javascripts « Live « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7ef5807d58de9ac035850a0125780cde12fd6450 (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
/*!
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

/**
 * jQueryUI widget for Live visitors widget
 */

(function ($) {
    $.widget('piwik.liveWidget', {

        /**
         * Default settings for widgetPreview
         */
        options:{
            // Maximum numbers of rows to display in widget
            maxRows: 10,
            // minimal time in microseconds to wait between updates
            interval: 3000,
            // maximum time to wait between requests
            maxInterval: 300000,
            // url params to use for data request
            dataUrlParams: null,
            // callback triggered on a successful update (content of widget changed)
            onUpdate: null,
            // speed for fade animation
            fadeInSpeed: 'slow'
        },

        /**
         * current updateInterval used
         */
        currentInterval: null,

        /**
         * identifies if content has updated (eg new visits/views)
         */
        updated: false,

        /**
         * window timeout interval
         */
        updateInterval: null,

        /**
         * identifies if the liveWidget ist started or not
         */
        isStarted: true,

        /**
         * Update the widget
         *
         * @return void
         */
        _update: function () {

            this.updated = false;

            var that = this;

            var ajaxRequest = new ajaxHelper();
            ajaxRequest.addParams(this.options.dataUrlParams, 'GET');
            ajaxRequest.setFormat('html');
            ajaxRequest.setCallback(function (r) {
                if (that.options.replaceContent) {
                    $(that.element).html(r);
                    if (that.options.fadeInSpeed) {
                        $(that.element).effect("highlight", {}, that.options.fadeInSpeed);
                    }
                } else {
                    that._parseResponse(r);
                }

                that.options.interval = parseInt(that.options.interval, 10);

                // add default interval to last interval if not updated or reset to default if so
                if (!that.updated) {
                    that.currentInterval += that.options.interval;
                } else {
                    that.currentInterval = that.options.interval;
                    if (that.options.onUpdate) that.options.onUpdate();
                }

                // check new interval doesn't reach the defined maximum
                if (that.options.maxInterval < that.currentInterval) {
                    that.currentInterval = that.options.maxInterval;
                }

                if (that.isStarted) {
                    window.clearTimeout(that.updateInterval);
                    if (that.element.length && $.contains(document, that.element[0])) {
                        that.updateInterval = window.setTimeout(function() { that._update() }, that.currentInterval);
                    }
                }
            });
            ajaxRequest.send();
        },

        /**
         * Parses the given response and updates the widget if newer content is available
         *
         * @return void
         */
        _parseResponse: function (data) {
            if (!data || !data.length) {
                this.updated = false;
                return;
            }

            var items = $('li.visit', $(data));
            for (var i = items.length; i--;) {
                this._parseItem(items[i]);
            }

            this._initTooltips();
        },

        /**
         * Initializes the icon tooltips
         */
        _initTooltips: function() {
            $('li.visit').tooltip({
                items: '.visitorLogIconWithDetails',
                track: true,
                show: false,
                hide: false,
                content: function() {
                    return $('<ul>').html($('ul', $(this)).html());
                },
                tooltipClass: 'small'
            });
        },

        /**
         * Parses the given item and updates or adds an entry to the list
         *
         * @param item to parse
         * @return void
         */
        _parseItem: function (item) {
            var visitId = $(item).attr('id');
            if ($('#' + visitId, this.element).length) {
                if ($('#' + visitId, this.element).html() != $(item).html()) {
                    this.updated = true;
                }
                $('#' + visitId, this.element).remove();
                $(this.element).prepend(item);
            } else {
                this.updated = true;
                $(item).hide();
                $(this.element).prepend(item);
                $(item).fadeIn(this.options.fadeInSpeed);
            }
            // remove rows if there are more than the maximum
            $('li.visit:gt(' + (this.options.maxRows - 1) + ')', this.element).remove();
        },

        /**
         * Constructor
         *
         * @return void
         */
        _create: function () {

            if (!this.options.dataUrlParams) {
                console && console.error('liveWidget error: dataUrlParams needs to be defined in settings.');
                return;
            }

            this.currentInterval = parseInt(this.options.interval, 10);

            if (0 === $(this.element).parents('.widget').length) {
                window.CoreHome.Matomo.postEvent('hidePeriodSelector');
            }

            var self = this;

            window.setTimeout(function() { self._initTooltips(); }, 250);

            this.updateInterval = window.setTimeout(function() { self._update(); }, this.currentInterval);
        },

        /**
         * Stops requests if widget is destroyed
         */
        _destroy: function () {
            this.stop();
        },

        /**
         * Triggers an update for the widget
         *
         * @return void
         */
        update: function () {
            this._update();
        },

        /**
         * Starts the automatic update cycle
         *
         * @return void
         */
        start: function () {
            this.isStarted = true;
            this.currentInterval = 0;
            this._update();
        },

        /**
         * Stops the automatic update cycle
         *
         * @return void
         */
        stop: function () {
            this.isStarted = false;
            window.clearTimeout(this.updateInterval);
        },

        /**
         * Return true in case widget is started.
         * @returns {boolean}
         */
        started: function() {
            return this.isStarted;
        },

        /**
         * Set the interval for refresh
         *
         * @param {int} interval  new interval for refresh
         * @return void
         */
        setInterval: function (interval) {
            this.currentInterval = interval;
        }
    });
})(jQuery);

$(function() {
    var refreshWidget = function (element, refreshAfterXSecs) {
        // if the widget has been removed from the DOM, abort
        if (!element.length || !$.contains(document, element[0])) {
            return;
        }

        function scheduleAnotherRequest()
        {
            setTimeout(function () { refreshWidget(element, refreshAfterXSecs); }, refreshAfterXSecs * 1000);
        }

        if (Visibility.hidden()) {
            scheduleAnotherRequest();
            return;
        }

        var lastMinutes = $(element).attr('data-last-minutes') || 3,
          translations = JSON.parse($(element).attr('data-translations'));

        var ajaxRequest = new ajaxHelper();
        ajaxRequest.addParams({
            module: 'API',
            method: 'Live.getCounters',
            format: 'json',
            lastMinutes: lastMinutes
        }, 'get');
        ajaxRequest.setFormat('json');
        ajaxRequest.setCallback(function (data) {
            data = data[0];

            // set text and tooltip of visitors count metric
            var visitors = data['visitors'];
            if (visitors == 1) {
                var visitorsCountMessage = translations['one_visitor'];
            }
            else {
                var visitorsCountMessage = sprintf(translations['visitors'], visitors);
            }
            $('.simple-realtime-visitor-counter', element)
              .attr('title', visitorsCountMessage)
              .find('div').text(visitors);

            // set text of individual metrics spans
            var metrics = $('.simple-realtime-metric', element);

            var visitsText = data['visits'] == 1
              ? translations['one_visit'] : sprintf(translations['visits'], data['visits']);
            $(metrics[0]).text(visitsText);

            var actionsText = data['actions'] == 1
              ? translations['one_action'] : sprintf(translations['actions'], data['actions']);
            $(metrics[1]).text(actionsText);

            var lastMinutesText = lastMinutes == 1
              ? translations['one_minute'] : sprintf(translations['minutes'], lastMinutes);
            $(metrics[2]).text(lastMinutesText);

            scheduleAnotherRequest();
        });
        ajaxRequest.send();
    };

    var exports = require("piwik/Live");
    exports.initSimpleRealtimeVisitorWidget = function () {
        $('.simple-realtime-visitor-widget').each(function() {
            var $this = $(this),
              refreshAfterXSecs = $this.attr('data-refreshAfterXSecs');
            if ($this.attr('data-inited')) {
                return;
            }

            $this.attr('data-inited', 1);

            setTimeout(function() { refreshWidget($this, refreshAfterXSecs ); }, refreshAfterXSecs * 1000);
        });
    };
});

function onClickPause() {
    $('#pauseImage').hide();
    $('#playImage').show();
    return $('#visitsLive').liveWidget('stop');
}
function onClickPlay() {
    $('#playImage').hide();
    $('#pauseImage').show();
    return $('#visitsLive').liveWidget('start');
}

(function () {
    if (!Visibility.isSupported()) {
        return;
    }

    var isStoppedByBlur = false;

    function isStarted()
    {
        return $('#visitsLive').liveWidget('started');
    }

    function onTabBlur() {
        if (isStarted()) {
            isStoppedByBlur = true;
            onClickPause();
        }
    }

    function onTabFocus() {
        if (isStoppedByBlur && !isStarted()) {
            isStoppedByBlur = false;
            onClickPlay();
        }
    }

    Visibility.change(function (event, state) {
        if (Visibility.hidden()) {
            onTabBlur();
        } else {
            onTabFocus();
        }
    });
})();