-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathvisit-processor.ts
More file actions
72 lines (62 loc) · 2.27 KB
/
visit-processor.ts
File metadata and controls
72 lines (62 loc) · 2.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { sendMsg2Runtime } from "@api/chrome/runtime"
import NormalTracker from "@cs/tracker/normal"
import { DELAY_MILL } from "@util/limit"
import { MILL_PER_SECOND } from "@util/time"
import { type ModalContext, type Processor } from "../common"
class VisitProcessor implements Processor {
private context: ModalContext
private focusTime: number = 0
private rules: timer.limit.Rule[] = []
private tracker: NormalTracker | undefined
private delayCount: number = 0
constructor(context: ModalContext) {
this.context = context
}
async handleMsg(code: timer.mq.ReqCode): 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" }
}
hasLimited(rule: timer.limit.Rule): boolean {
const { visitTime } = rule || {}
if (!visitTime) return false
return visitTime * MILL_PER_SECOND + this.delayCount * DELAY_MILL < this.focusTime
}
async handleTracker(data: timer.core.Event) {
const diff = (data?.end ?? 0) - (data?.start ?? 0)
this.focusTime += diff
this.rules?.forEach?.(rule => {
if (!this.hasLimited(rule)) return
const { id, cond, allowDelay } = rule
this.context.modal.addReason({
id,
cond,
type: "VISIT",
allowDelay,
delayCount: this.delayCount,
getVisitTime: () => this.focusTime,
})
})
}
async initRules() {
this.rules = await sendMsg2Runtime("cs.getRelatedRules", this.context.url) ?? []
this.context.modal.removeReasonsByType("VISIT")
}
async init(): Promise<void> {
this.tracker = new NormalTracker({
onReport: data => this.handleTracker(data),
})
this.tracker.init()
this.initRules()
this.context.modal.addDelayHandler(() => this.processMore5Minutes())
}
private processMore5Minutes() {
this.delayCount = (this.delayCount ?? 0) + 1
this.context.modal.removeReasonsByType("VISIT")
}
}
export default VisitProcessor