-
Notifications
You must be signed in to change notification settings - Fork 2
/
Watcher.js
46 lines (37 loc) · 1.42 KB
/
Watcher.js
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
const EventEmitter = require('events')
const connect_isa = require('./lib/connect-isa')
module.exports = class Watcher extends EventEmitter {
constructor() {
super()
this.interval = null
}
watch(ISA_ADDR, { token, course_reg_url }, { watched_courses, polling_interval }) {
if (this.interval != null)
return
this.interval = setInterval(async () => {
try {
const courses = await connect_isa.fetch_courses(ISA_ADDR, token, course_reg_url)
const now_available_courses = watched_courses.map(id => courses[id])
.filter(d => !!d)
.filter(d => d.isAvailable)
.filter(d => watched_courses.includes(d.id))
if (now_available_courses.length > 0) {
this.emit('available-course', now_available_courses)
let unwatch = id => {
let ind = watched_courses.indexOf(id)
if (ind > -1)
watched_courses.splice(ind, 1)
}
now_available_courses.map(d => d.id).forEach(i => unwatch(i))
}
this.emit('checked')
} catch(e) {
this.emit('error', e)
}
}, polling_interval)
}
stop() {
clearInterval(this.interval)
this.interval = null
}
}