78 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-06-22 20:41:12 +08:00
import { FeedFilter, FilterType } from "./feed"
import { RSSItem } from "./item"
export const enum ItemAction {
2021-08-21 14:49:56 -07:00
Read = "r",
Star = "s",
2020-06-22 20:41:12 +08:00
Hide = "h",
2020-07-09 17:59:25 +08:00
Notify = "n",
2020-06-22 20:41:12 +08:00
}
export type RuleActions = {
[type in ItemAction]: boolean
}
2020-06-24 16:32:06 +08:00
export namespace RuleActions {
export function toKeys(actions: RuleActions): string[] {
return Object.entries(actions).map(([t, f]) => `${t}-${f}`)
}
export function fromKeys(strs: string[]): RuleActions {
const fromKey = (str: string): [ItemAction, boolean] => {
let [t, f] = str.split("-") as [ItemAction, string]
if (f) return [t, f === "true"]
else return [t, true]
}
return Object.fromEntries(strs.map(fromKey)) as RuleActions
}
}
2020-06-22 20:41:12 +08:00
type ActionTransformType = {
[type in ItemAction]: (i: RSSItem, f: boolean) => void
}
const actionTransform: ActionTransformType = {
[ItemAction.Read]: (i, f) => {
2020-08-31 15:59:39 +08:00
i.hasRead = f
2020-06-22 20:41:12 +08:00
},
[ItemAction.Star]: (i, f) => {
2020-08-31 15:59:39 +08:00
i.starred = f
2020-06-22 20:41:12 +08:00
},
[ItemAction.Hide]: (i, f) => {
2020-08-31 15:59:39 +08:00
i.hidden = f
2020-07-09 17:59:25 +08:00
},
[ItemAction.Notify]: (i, f) => {
2020-08-31 15:59:39 +08:00
i.notify = f
2020-07-09 17:59:25 +08:00
},
2020-06-22 20:41:12 +08:00
}
export class SourceRule {
filter: FeedFilter
match: boolean
actions: RuleActions
2021-08-21 14:49:56 -07:00
constructor(
regex: string,
actions: string[],
filter: FilterType,
match: boolean
) {
2020-08-24 20:51:36 +08:00
this.filter = new FeedFilter(filter, regex)
2020-06-22 20:41:12 +08:00
this.match = match
2020-06-24 16:32:06 +08:00
this.actions = RuleActions.fromKeys(actions)
2020-06-22 20:41:12 +08:00
}
static apply(rule: SourceRule, item: RSSItem) {
let result = FeedFilter.testItem(rule.filter, item)
if (result === rule.match) {
for (let [action, flag] of Object.entries(rule.actions)) {
actionTransform[action](item, flag)
}
}
}
static applyAll(rules: SourceRule[], item: RSSItem) {
for (let rule of rules) {
this.apply(rule, item)
}
}
2021-08-21 14:49:56 -07:00
}