-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathmessage-adaptor.ts
More file actions
66 lines (57 loc) · 2.81 KB
/
message-adaptor.ts
File metadata and controls
66 lines (57 loc) · 2.81 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
import { sendMsg2Runtime } from "@api/chrome/runtime"
import { hasDailyLimited, hasWeeklyLimited, matches } from "@util/limit"
import { type LimitReason, type ModalContext, type Processor } from "../common"
const cvtItem2AddReason = (item: timer.limit.Item): LimitReason[] => {
const { cond, allowDelay, id, delayCount, weeklyDelayCount } = item
const reasons2Add: LimitReason[] = []
hasDailyLimited(item) && reasons2Add.push({ type: "DAILY", cond, allowDelay, id, delayCount })
hasWeeklyLimited(item) && reasons2Add.push({ type: 'WEEKLY', cond, allowDelay, id, delayCount: weeklyDelayCount })
return reasons2Add
}
const cvtItem2RemoveReason = (item: timer.limit.Item): LimitReason[] => {
const { cond, allowDelay, id, delayCount, weeklyDelayCount } = item
const reasons2Remove: LimitReason[] = []
!hasDailyLimited(item) && reasons2Remove.push({ type: 'DAILY', cond, allowDelay, id, delayCount })
!hasWeeklyLimited(item) && reasons2Remove.push({ type: 'WEEKLY', cond, allowDelay, id, delayCount: weeklyDelayCount })
return reasons2Remove
}
class MessageAdaptor implements Processor {
private context: ModalContext
constructor(context: ModalContext) {
this.context = context
}
handleMsg(code: timer.mq.ReqCode, data: unknown): timer.mq.Response | Promise<timer.mq.Response> {
let items = data as timer.limit.Item[]
if (code === "limitTimeMeet") {
if (!items?.length) {
return { code: "fail" }
}
items.filter(item => matches(item?.cond, this.context.url))
.flatMap(cvtItem2AddReason)
.forEach(reason => reason && this.context.modal.addReason(reason))
return { code: "success" }
} else if (code === "limitChanged") {
this.context.modal.removeReasonsByType("DAILY", "WEEKLY")
items?.flatMap(cvtItem2AddReason)
?.forEach(reason => reason && this.context.modal.addReason(reason))
return { code: "success" }
} else if (code === "limitWaking") {
const reasons2Remove = items?.flatMap(cvtItem2RemoveReason)
reasons2Remove?.length && this.context.modal.removeReason(...reasons2Remove)
return { code: "success" }
}
return { code: "ignore" }
}
async init(): Promise<void> {
this.initRules?.()
this.context.modal?.addDelayHandler(() => this.initRules())
}
async initRules(): Promise<void> {
this.context.modal?.removeReasonsByType?.('DAILY', 'WEEKLY')
const limitedRules = await sendMsg2Runtime<string, timer.limit.Item[]>('cs.getLimitedRules', this.context.url)
limitedRules
?.flatMap?.(cvtItem2AddReason)
?.forEach(reason => this.context.modal.addReason(reason))
}
}
export default MessageAdaptor