2020-09-17 14:27:08 +02:00
|
|
|
import browser from 'webextension-polyfill'
|
2020-10-11 23:46:06 +02:00
|
|
|
import dayjs from 'dayjs'
|
2020-09-17 14:27:08 +02:00
|
|
|
|
2020-09-18 21:00:59 +02:00
|
|
|
import { dashboard } from '../shared/utils'
|
2021-11-22 01:36:18 +01:00
|
|
|
import { insertLog, normalizeTimestamp, DB } from '../shared/db'
|
2020-09-20 22:24:57 +02:00
|
|
|
import { getUsageForHost, percentagesToBool } from '../shared/lib'
|
2020-09-17 14:27:08 +02:00
|
|
|
|
2020-09-18 21:00:59 +02:00
|
|
|
browser.browserAction.onClicked.addListener(() => browser.tabs.create({ url: dashboard, active: true }))
|
2020-09-17 14:27:08 +02:00
|
|
|
|
2020-09-19 02:05:33 +02:00
|
|
|
const frequency = 1000
|
2020-09-17 14:27:08 +02:00
|
|
|
|
2020-10-11 23:46:06 +02:00
|
|
|
async function log() {
|
2020-09-19 02:05:33 +02:00
|
|
|
try {
|
|
|
|
const tabs = await browser.tabs.query({})
|
|
|
|
const windows = await browser.windows.getAll()
|
|
|
|
const active = tabs
|
|
|
|
.filter((tab) => {
|
|
|
|
const window = windows.find((window) => window.id === tab.windowId)
|
|
|
|
return tab.active && window.focused
|
|
|
|
})
|
|
|
|
.map(({ id, title, url }) => {
|
|
|
|
const { host } = new URL(url)
|
|
|
|
return { id, title, host }
|
|
|
|
})
|
2020-09-18 21:00:59 +02:00
|
|
|
|
2020-09-19 02:05:33 +02:00
|
|
|
await Promise.all(
|
|
|
|
active.map(({ host }) => {
|
|
|
|
if (host)
|
|
|
|
return insertLog({
|
|
|
|
timestamp: normalizeTimestamp(new Date()),
|
|
|
|
host,
|
|
|
|
seconds: (frequency / 1000) | 0,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
)
|
|
|
|
} catch {}
|
2020-09-17 14:27:08 +02:00
|
|
|
}
|
|
|
|
|
2020-10-11 23:46:06 +02:00
|
|
|
async function deleteOldLogs() {
|
|
|
|
const { retention } = await browser.storage.local.get()
|
|
|
|
const maxAge = dayjs().startOf('day').subtract(retention, 'days').toDate()
|
|
|
|
const toDelete = await DB.logs.where('timestamp').below(maxAge).toArray()
|
|
|
|
const ids = toDelete.map((log) => log.id)
|
|
|
|
await DB.logs.bulkDelete(ids)
|
|
|
|
}
|
|
|
|
|
|
|
|
setInterval(deleteOldLogs, 5 * 60 * 1000) // Delete old logs every 5 minutes
|
|
|
|
setInterval(log, frequency)
|
2020-09-20 22:24:57 +02:00
|
|
|
|
2020-10-08 20:03:09 +02:00
|
|
|
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
2021-11-22 20:07:06 +01:00
|
|
|
switch (message.type) {
|
|
|
|
case 'check':
|
|
|
|
return getUsageForHost(message.host).then((percentages) => percentagesToBool(percentages))
|
|
|
|
case 'report':
|
|
|
|
DB.settings.put({ key: 'lastActivity', value: new Date() })
|
|
|
|
break
|
|
|
|
}
|
2020-09-20 22:24:57 +02:00
|
|
|
})
|