forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-time.ts
More file actions
53 lines (43 loc) · 1.34 KB
/
run-time.ts
File metadata and controls
53 lines (43 loc) · 1.34 KB
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
import { onRuntimeMessage, sendMsg2Runtime } from "@api/chrome/runtime"
class RunTimeTracker {
private start: number = Date.now()
private url: string
// Real host, including builtin hosts
private host: string | undefined
constructor(url: string) {
this.url = url
this.start = Date.now()
}
init(): void {
this.fetchSite()
onRuntimeMessage<void, void>(async req => {
if (req.code === 'siteRunChange') {
this.fetchSite()
return { code: 'success' }
}
return { code: 'ignore' }
})
setInterval(() => this.collect(), 1000)
}
private fetchSite() {
sendMsg2Runtime('cs.getRunSites', this.url)
.then((site: timer.site.SiteKey) => this.host = site?.host)
// Extension reloaded, so terminate
.catch(() => this.host = undefined)
}
private collect() {
const now = Date.now()
const lastTime = this.start
const event: timer.core.Event = {
start: lastTime,
end: now,
url: this.url,
ignoreTabCheck: false,
host: this.host,
}
sendMsg2Runtime('cs.trackRunTime', event)
.then(() => this.start = now)
.catch(() => { })
}
}
export default RunTimeTracker