initial commit for better sessions app
[qcg-portal.git] / better_sessions / static / better_sessions / better_sessions.js
1 "use strict";
2
3 var psnc = psnc || {};
4
5 psnc.BetterSession = function (options) {
6     $.extend(this, this.defaults, options);
7
8     // account for network delays and rendering time
9     this.warnAfter -= 5;
10     this.expireAfter -= 5;
11
12     this.postponeWarn = _.debounce(this.warn, this.warnAfter * 1000);
13     this.postponeExpire = _.debounce(this.expire, this.expireAfter * 1000);
14
15     $(this.warnSel).find('button').on('click', $.proxy(this.ping, this));
16
17     // update session whenever user loaded sth with ajax...
18     $(document).ajaxComplete($.proxy(this.update, this, true));
19     // ...or in another window
20     $(window).on('storage', $.proxy(this.update, this));
21
22     this.update(true);
23
24     return this;
25 };
26
27 psnc.BetterSession.prototype = {
28     defaults: {
29         expired: false,
30         warnAfter: 3300,
31         expireAfter: 3600,
32         key: 'lastActivity',
33         pingUrl: '/session/ping/',
34         warnSel: '#better-sessions-warn',
35         expireSel: '#better-sessions-expire',
36         timerSel: '#better-sessions-timer'
37     },
38
39     update: _.throttle(function (local) {
40         if (this.expired) return;
41
42         $(this.warnSel).hide();
43         clearInterval(this.timer);
44
45         // postpone expire message and warning
46         this.postponeWarn();
47         this.postponeExpire();
48
49         // update timestamp only if it is local event
50         if (local === true)
51             localStorage.setItem(this.key, new Date());
52     }, 1000),
53
54     ping: function () {
55         var self = this;
56         $.post(this.pingUrl, {}, function(response) {
57             // session is implicitly extended after every ajax request
58             if (response.status === 'expired')
59                 self.expire();
60         }, 'json');
61     },
62
63     warn: function () {
64         this.timer = setInterval($.proxy(this.updateTimer, this), 1000);
65         this.updateTimer();
66         $(this.warnSel).show();
67     },
68
69     expire: function () {
70         this.expired = true;
71
72         $(this.warnSel).hide();
73         $(this.expireSel).show();
74         clearInterval(this.timer);
75     },
76
77     updateTimer: function() {
78         var remaining = Date.parse(localStorage.getItem(this.key)) - new Date() + (this.expireAfter * 1000);
79         $(this.timerSel).text((humanizeDuration(remaining, {language: 'pl', round: true}) || 'chwilÄ™'))
80     }
81 };