ora/src/background/index.js

70 lines
2.2 KiB
JavaScript
Raw Normal View History

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'
2021-11-23 01:45:19 +01:00
import { getSettingsWithDefaults, 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
})
2021-11-23 01:45:19 +01:00
.map(({ url, audible, mutedInfo }) => {
2020-09-19 02:05:33 +02:00
const { host } = new URL(url)
2021-11-23 01:45:19 +01:00
return { host, audio: audible && !mutedInfo.muted }
2020-09-19 02:05:33 +02:00
})
2021-11-23 01:45:19 +01:00
.filter((x) => x.host)
2020-09-18 21:00:59 +02:00
2021-11-23 01:45:19 +01:00
if (active.length === 0) return
const settings = await getSettingsWithDefaults()
let idle = false
if (settings.idleTimeout > 0) {
idle = dayjs(settings.lastActivity).add(settings.idleTimeout, 'minutes').isBefore(dayjs())
}
const inserted = active
.filter((tab) => !idle || tab.audio)
.map((tab) => {
return insertLog({
timestamp: normalizeTimestamp(new Date()),
host: tab.host,
seconds: (frequency / 1000) | 0,
})
2020-09-19 02:05:33 +02:00
})
2021-11-23 01:45:19 +01:00
await Promise.all(inserted)
} catch (e) {
console.error(e)
}
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
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
})