forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.ts
More file actions
29 lines (26 loc) · 1.16 KB
/
runtime.ts
File metadata and controls
29 lines (26 loc) · 1.16 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
import itemService from "@service/item-service"
import whitelistHolder from "@service/whitelist/holder"
import FIFOCache from '@util/fifo-cache'
import { formatTimeYMD, getStartOfDay, MILL_PER_DAY } from "@util/time"
function splitRunTime(start: number, end: number): Record<string, number> {
const res: Record<string, number> = {}
while (start < end) {
const startOfNextDay = getStartOfDay(start) + MILL_PER_DAY
const newStart = Math.min(end, startOfNextDay)
const runTime = newStart - start
runTime && (res[formatTimeYMD(start)] = runTime)
start = newStart
}
return res
}
const RUN_TIME_END_CACHE = new FIFOCache<number>(500)
export async function handleTrackRunTimeEvent(event: timer.core.Event): Promise<void> {
const { start, end, url, host } = event || {}
if (!host || !start || !end) return
if (whitelistHolder.contains(host, url)) return
const realStart = Math.max(RUN_TIME_END_CACHE.get(host) ?? 0, start)
const byDate = splitRunTime(realStart, end)
if (!Object.keys(byDate).length) return
await itemService.addRunTime(host, byDate)
RUN_TIME_END_CACHE.set(host, Math.max(end, realStart))
}