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
46 lines (39 loc) · 1.27 KB
/
Copy pathrun-time.ts
File metadata and controls
46 lines (39 loc) · 1.27 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
import { trySendMsg2Runtime } from '@api/sw/common'
import { extractHostname } from '@util/pattern'
import Dispatcher from '../dispatcher'
class RunTimeTracker {
private start: number = Date.now()
// Real host, including builtin hosts
private host: string | undefined
constructor(private readonly url: string) {
}
init(dispatcher: Dispatcher): void {
this.fetchSite()
dispatcher.register('siteRunChange', () => void this.fetchSite())
setInterval(() => this.collect(), 1000)
}
private async fetchSite() {
const { host } = extractHostname(this.url)
if (!host) return
const enabled = await trySendMsg2Runtime('site.runEnabled', host)
this.host = enabled ? host : undefined
}
private async collect() {
const now = Date.now()
const lastTime = this.start
try {
if (this.host) {
const event: tt4b.core.Event = {
start: lastTime,
end: now,
ignoreTabCheck: false,
host: this.host,
}
await trySendMsg2Runtime('track.runTime', event)
}
this.start = now
} catch {
}
}
}
export default RunTimeTracker