-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathlimit-processor.ts
More file actions
71 lines (66 loc) · 2.77 KB
/
limit-processor.ts
File metadata and controls
71 lines (66 loc) · 2.77 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
/**
* Copyright (c) 2022-present Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { createTabAfterCurrent, getRightOf, listTabs, resetTabUrl, sendMsg2Tab } from "@api/chrome/tab"
import { LIMIT_ROUTE } from "@app/router/constants"
import { getAppPageUrl } from "@util/constant/url"
import MessageDispatcher from "./message-dispatcher"
import { matches } from "@util/limit"
import limitService from "@service/limit-service"
import { isBrowserUrl } from "@util/pattern"
function processLimitWaking(rules: timer.limit.Item[], tab: ChromeTab) {
const { url } = tab
const anyMatch = rules.map(rule => matches(rule, url)).reduce((a, b) => a || b, false)
if (!anyMatch) {
return
}
sendMsg2Tab(tab.id, 'limitWaking', rules)
.then(() => console.log(`Waked tab[id=${tab.id}]`))
.catch(err => console.error(`Failed to wake with limit rule: rules=${JSON.stringify(rules)}, msg=${err.msg}`))
}
async function processOpenPage(limittedUrl: string, sender: ChromeMessageSender) {
const originTab = sender?.tab
if (!originTab) return
const realUrl = getAppPageUrl(true, LIMIT_ROUTE, { url: encodeURI(limittedUrl) })
const baseUrl = getAppPageUrl(true, LIMIT_ROUTE)
const rightTab = await getRightOf(originTab)
const rightUrl = rightTab?.url
if (rightUrl && isBrowserUrl(rightUrl) && rightUrl.includes(baseUrl)) {
// Reset url
await resetTabUrl(rightTab.id, realUrl)
} else {
await createTabAfterCurrent(realUrl, sender?.tab)
}
}
export default function init(dispatcher: MessageDispatcher) {
dispatcher
.register<string>('openLimitPage', processOpenPage)
.register<timer.limit.Item[]>(
'limitWaking',
async data => {
const rules = data || []
const tabs = await listTabs({ status: 'complete' })
tabs.forEach(tab => processLimitWaking(rules, tab))
}
)
// More minutes
.register<string>('cs.moreMinutes', async url => {
const rules = await limitService.moreMinutes(url)
const tabs = await listTabs({ status: 'complete' })
tabs.forEach(tab => processLimitWaking(rules, tab))
})
// Judge any tag hit the time limit per visit
.register<timer.limit.Item, boolean>("askHitVisit", async item => {
let tabs = await listTabs()
tabs = tabs?.filter(({ url }) => matches(item, url))
const { visitTime = 0 } = item || {}
for (const { id } of tabs) {
const tabFocus = await sendMsg2Tab(id, "askVisitTime", undefined)
if (tabFocus && tabFocus > visitTime * 1000) return true
}
return false
})
}