forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisit-processor.ts
More file actions
55 lines (46 loc) · 1.76 KB
/
visit-processor.ts
File metadata and controls
55 lines (46 loc) · 1.76 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
import TrackerClient from "@src/background/timer/client"
import { ModalContext, Processor } from "./common"
import { sendMsg2Runtime } from "@api/chrome/runtime"
class VisitProcessor implements Processor {
private context: ModalContext
private focusTime: number = 0
private rules: timer.limit.Rule[]
private tracker: TrackerClient
constructor(context: ModalContext) {
this.context = context
}
async handleMsg(code: timer.mq.ReqCode, _data: any): Promise<timer.mq.Response> {
if (code === "limitChanged") {
this.initRules()
return { code: "success" }
} else if (code === "askVisitTime") {
return { code: "success", data: this.focusTime }
}
return { code: "ignore" }
}
async handleTracker(data: timer.stat.Event) {
const diff = (data?.end ?? 0) - (data?.start ?? 0)
this.focusTime += diff
this.rules?.forEach?.(({ visitTime, cond, allowDelay }) => {
if (!visitTime) return
if (visitTime * 1000 < this.focusTime) {
this.context.modal.addReason({ cond, type: "VISIT", allowDelay })
}
})
}
async initRules() {
this.rules = await sendMsg2Runtime("cs.getRelatedRules", this.context.url)
this.context.modal.removeReasonsByType("VISIT")
}
async init(): Promise<void> {
this.tracker = new TrackerClient(data => this.handleTracker(data))
this.tracker.init()
this.initRules()
this.context.modal.addDelayHandler(() => this.processMore5Minutes())
}
private processMore5Minutes() {
this.focusTime = Math.max(0, this.focusTime - 5 * 60 * 1000)
this.context.modal.removeReasonsByType("VISIT")
}
}
export default VisitProcessor