ora/src/shared/lib.js

65 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-09-20 18:37:02 +02:00
import { groupBy, orderBy, sum } from 'lodash'
2020-09-19 01:16:43 +02:00
import dj from 'dayjs'
2020-09-18 21:00:59 +02:00
2020-09-20 22:24:57 +02:00
import { Limits, Logs } from './db.js'
2020-09-18 21:00:59 +02:00
export async function data({ start, end }) {
const logs = await getLogsBetweenDates({ start, end })
return groupBy(logs, 'host')
}
2020-09-20 17:43:39 +02:00
export async function getLogsBetweenDates({ start, end, host }) {
const where = {
2020-09-18 21:00:59 +02:00
$and: [{ timestamp: { $gt: start } }, { timestamp: { $lt: end } }],
2020-09-20 17:43:39 +02:00
}
if (host) where.host = host
return await Logs.find(where)
2020-09-18 21:00:59 +02:00
}
export function countInGroup(grouped) {
const counted = Object.entries(grouped).map(([key, data]) => {
2020-09-19 01:16:43 +02:00
const total = data.reduce((acc, cur) => acc + cur.seconds, 0)
const human = dj.duration(total, 'seconds').humanize()
2020-09-18 21:00:59 +02:00
return {
host: key,
total,
human,
}
})
return orderBy(counted, 'total', 'desc')
}
2020-09-20 17:28:09 +02:00
export function longPress(node, fn) {
let timeout
node.addEventListener('mousedown', () => (timeout = setTimeout(fn, 500)), false)
node.addEventListener('mouseup', () => clearTimeout(timeout), false)
}
2020-09-20 18:37:02 +02:00
export function getUsageForRules(host, rules) {
return rules.map(async ({ every, limit }) => {
const limitAsSeconds = dj.duration(...limit).asSeconds()
const everyAsSeconds = dj.duration(...every).asSeconds()
const logs = await getLogsBetweenDates({
start: dj().subtract(everyAsSeconds, 's').toDate(),
end: new Date(),
host,
})
// Calculate usage in percentage 0-100
const consumed = sum(logs.map((log) => log.seconds))
return (consumed / limitAsSeconds) * 100
})
}
2020-09-20 22:24:57 +02:00
export async function getUsageForHost(host) {
const limit = await Limits.findOne({ host })
return await Promise.all(getUsageForRules(host, limit.rules))
}
export function percentagesToBool(percentages) {
const blocked = percentages.map((p) => p >= 100).includes(true)
console.log(percentages, blocked)
return blocked
}