|
1 | 1 | 'use strict' |
2 | 2 |
|
3 | 3 | const Alert = require('./alert') |
| 4 | +const crypto = require('crypto') |
| 5 | +const shortHash = (str) => { |
| 6 | + let hash = crypto.createHash('sha512').update(str).digest('hex') |
| 7 | + return hash.substr(parseInt(hash.substr(0, 1), 16), 16) |
| 8 | +} |
4 | 9 |
|
5 | 10 | class Group { |
6 | | - constructor (main) { |
| 11 | + constructor (main, config, prevAlerts) { |
7 | 12 | this.main = main |
| 13 | + this.config = config |
| 14 | + this.alerts = {} |
| 15 | + this.prevAlerts = prevAlerts || [] |
8 | 16 | } |
9 | 17 | name (name) { |
10 | 18 | this.name = name |
| 19 | + this.id = shortHash(name) |
11 | 20 | return this |
12 | 21 | } |
| 22 | + attachAlert (alert) { |
| 23 | + this.alerts[alert.id] = alert |
| 24 | + } |
13 | 25 | alert (id) { |
14 | | - const alert = new Alert(id) |
| 26 | + const alert = new Alert(this.config).setID(id) |
15 | 27 | this.attachAlert(alert) |
| 28 | + return alert |
| 29 | + } |
| 30 | + setAutoClear (v) { |
| 31 | + this.autoClear = v |
| 32 | + } |
| 33 | + process () { |
| 34 | + let alerts = Object.keys(this.alerts).map(k => this.alerts[k]) |
| 35 | + let prevAlerts = this.prevAlerts |
| 36 | + let clearable = prevAlerts.filter(pa => !alerts.filter(a => a.id === pa.id).length) |
| 37 | + let newPrevAlerts = alerts.filter(a => a.type !== 'clear') // don't keep clear events arround |
| 38 | + let sendNotify = alerts.filter(a => { |
| 39 | + if (!prevAlerts.filter(pa => pa.id === a.id).length && a.type !== 'clear') { // new non-clear |
| 40 | + return true |
| 41 | + } |
| 42 | + |
| 43 | + if (prevAlerts.filter(pa => pa.id === a.id).length && a.type === 'clear') { // old clear |
| 44 | + return true |
| 45 | + } |
| 46 | + |
| 47 | + return false |
| 48 | + }) |
| 49 | + if (this.autoClear) { |
| 50 | + sendNotify = sendNotify.concat(clearable.map(a => |
| 51 | + this.alert(a.id).type('clear').title('Cleared alert ' + JSON.stringify(a.title)).body('Alert for group ' + JSON.stringify(this.name) + ' has been cleared') |
| 52 | + )) |
| 53 | + } else { |
| 54 | + newPrevAlerts = newPrevAlerts.concat(clearable) // keep clearable events arround |
| 55 | + } |
| 56 | + |
| 57 | + sendNotify.forEach(alert => { |
| 58 | + this.main.notifies.forEach(notify => { |
| 59 | + notify.notify(alert) |
| 60 | + }) |
| 61 | + }) |
| 62 | + |
| 63 | + return newPrevAlerts |
16 | 64 | } |
17 | 65 | } |
18 | 66 |
|
|
0 commit comments