aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/controllers/app-state.js
blob: 9533fd4581ebe1c1e0f34f36fdb57a2c2868fb58 (plain) (blame)
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
const ObservableStore = require('obs-store')
const extend = require('xtend')

class AppStateController {
  /**
   * @constructor
   * @param opts
   */
  constructor (opts = {}) {
    const {initState, onInactiveTimeout, preferencesStore} = opts
    const {preferences} = preferencesStore.getState()

    this.onInactiveTimeout = onInactiveTimeout || (() => {})
    this.store = new ObservableStore(extend({
      timeoutMinutes: 0,
    }, initState))
    this.timer = null

    preferencesStore.subscribe(state => {
      this._setInactiveTimeout(state.preferences.autoLogoutTimeLimit)
    })

    this._setInactiveTimeout(preferences.autoLogoutTimeLimit)
  }

  /**
   * Sets the last active time to the current time
   * @return {void}
   */
  setLastActiveTime () {
    this._resetTimer()
  }

  /**
   * Sets the inactive timeout for the app
   * @param {number} timeoutMinutes the inactive timeout in minutes
   * @return {void}
   * @private
   */
  _setInactiveTimeout (timeoutMinutes) {
    this.store.putState({
      timeoutMinutes,
    })

    this._resetTimer()
  }

  /**
   * Resets the internal inactive timer
   *
   * If the {@code timeoutMinutes} state is falsy (i.e., zero) then a new
   * timer will not be created.
   *
   * @return {void}
   * @private
   */
  _resetTimer () {
    const {timeoutMinutes} = this.store.getState()

    if (this.timer) {
      clearTimeout(this.timer)
    }

    if (!timeoutMinutes) {
      return
    }

    this.timer = setTimeout(() => this.onInactiveTimeout(), timeoutMinutes * 60 * 1000)
  }
}

module.exports = AppStateController