forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile-tracker.ts
More file actions
59 lines (51 loc) · 1.55 KB
/
file-tracker.ts
File metadata and controls
59 lines (51 loc) · 1.55 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
import { getTab, onTabActivated } from '@api/chrome/tab'
import optionHolder from '@service/components/option-holder'
import { extractFileHost } from '@util/pattern'
import { handleTrackTimeEvent } from './normal'
type Context = {
host: string
tab: ChromeTab
// Start timestamp of this tick
start: number
}
async function convertContext(tabId: number): Promise<Context | null> {
const tab = await getTab(tabId)
if (!tab) return null
const { active, url } = tab
if (!active || !url) return null
const fileHost = extractFileHost(url)
if (!fileHost) return null
return {
host: fileHost, tab,
start: Date.now(),
}
}
/**
* Local file tracker for firefox
*/
class FileTracker {
private enabled = false
private current: Context | null = null
init() {
optionHolder.get().then(v => this.enabled = v.countLocalFiles)
optionHolder.addChangeListener(v => this.enabled = v.countLocalFiles)
onTabActivated(async tabId => {
this.tick()
this.current = await convertContext(tabId)
})
// NOTE: if migrate to MV3, this line won't work expectedly
setInterval(() => this.tick(), 1000)
}
private tick() {
if (!this.current) return
const { host, tab, start } = this.current
const end = Date.now()
this.enabled && handleTrackTimeEvent({
host, start, end,
url: tab.url ?? '',
ignoreTabCheck: false,
}, tab)
this.current.start = end
}
}
export default FileTracker