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
63 lines (54 loc) · 1.98 KB
/
Copy pathvisit-processor.ts
File metadata and controls
63 lines (54 loc) · 1.98 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
import { trySendMsg2Runtime } from '@api/sw/common'
import NormalTracker from "@cs/tracker/normal"
import { MILL_PER_MINUTE, MILL_PER_SECOND } from "@util/time"
import type { ModalContext, Processor } from '../types'
class VisitProcessor implements Processor {
private focusTime: number = 0
private rules: tt4b.limit.Rule[] = []
tracker: NormalTracker
private delayCount: number = 0
constructor(private readonly context: ModalContext, private readonly delayDuration: number) {
this.tracker = new NormalTracker({
onReport: data => this.handleTracker(data),
})
}
onLimitChanged(): void {
this.initRules()
}
private hasLimited(rule: tt4b.limit.Rule): boolean {
const { visitTime } = rule
if (!visitTime) return false
const afterDelayed = visitTime * MILL_PER_SECOND + this.delayCount * this.delayDuration * MILL_PER_MINUTE
return afterDelayed < this.focusTime
}
private async handleTracker({ start, end }: tt4b.core.Event) {
const diff = end - start
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,
})
})
}
private async initRules() {
this.rules = await trySendMsg2Runtime("limit.list", { effective: true, url: this.context.url }) ?? []
this.context.modal.removeReasonsByType("VISIT")
}
async init(): Promise<void> {
this.tracker.init()
this.initRules()
this.context.modal.addDelayHandler(() => this.processDelay())
}
private processDelay() {
this.delayCount++
this.context.modal.removeReasonsByType("VISIT")
}
}
export default VisitProcessor