aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/notice-controller.js
blob: 00c87c6709e5f8003d7ce356554578677a86a5bc (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const EventEmitter = require('events').EventEmitter
const hardCodedNotices = require('../../development/notices.json')

module.exports = class NoticeController extends EventEmitter {

  constructor (opts) {
    super()
    this.configManager = opts.configManager
    this.noticePoller = null
  }

  getState () {
    var lastUnreadNotice = this.getLatestUnreadNotice()

    return {
      lastUnreadNotice: lastUnreadNotice,
      noActiveNotices: !lastUnreadNotice,
    }
  }

  getNoticesList () {
    var data = this.configManager.getData()
    if ('noticesList' in data) {
      return data.noticesList
    } else {
      return []
    }
  }

  setNoticesList (list) {
    var data = this.configManager.getData()
    data.noticesList = list
    this.configManager.setData(data)
    return Promise.resolve(true)
  }

  markNoticeRead (notice, cb) {
    cb = cb || function (err) { if (err) throw err }
    try {
      var notices = this.getNoticesList()
      var id = notice.id
      notices[id].read = true
      this.setNoticesList(notices)
      const latestNotice = this.getLatestUnreadNotice()
      cb(null, latestNotice)
    } catch (err) {
      cb(err)
    }
  }

  updateNoticesList () {
    return this._retrieveNoticeData().then((newNotices) => {
      var oldNotices = this.getNoticesList()
      var combinedNotices = this._mergeNotices(oldNotices, newNotices)
      return Promise.resolve(this.setNoticesList(combinedNotices))
    })
  }

  getLatestUnreadNotice () {
    var notices = this.getNoticesList()
    var filteredNotices = notices.filter((notice) => {
      return notice.read === false
    })
    return filteredNotices[filteredNotices.length - 1]
  }

  startPolling () {
    if (this.noticePoller) {
      clearInterval(this.noticePoller)
    }
    this.noticePoller = setInterval(() => {
      this.noticeController.updateNoticesList()
    }, 300000)
  }

  _mergeNotices (oldNotices, newNotices) {
    var noticeMap = this._mapNoticeIds(oldNotices)
    newNotices.forEach((notice) => {
      if (noticeMap.indexOf(notice.id) === -1) {
        oldNotices.push(notice)
      }
    })
    return oldNotices
  }

  _mapNoticeIds (notices) {
    return notices.map((notice) => notice.id)
  }

  _retrieveNoticeData () {
    // Placeholder for the API.
    return Promise.resolve(hardCodedNotices)
  }


}