-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathrun-time.ts
More file actions
56 lines (47 loc) · 1.45 KB
/
run-time.ts
File metadata and controls
56 lines (47 loc) · 1.45 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
54
55
56
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 async collect() {
const now = Date.now()
const lastTime = this.start
try {
if (this.host) {
const event: timer.core.Event = {
start: lastTime,
end: now,
url: this.url,
ignoreTabCheck: false,
host: this.host,
}
await sendMsg2Runtime('cs.trackRunTime', event)
}
this.start = now
} catch {
}
}
}
export default RunTimeTracker