| 1 | // This file is part of HFS - Copyright 2021, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt |
| 2 | |
| 3 | import { defineConfig } from './config' |
| 4 | import { KvStorage } from '@rejetto/kvstorage' |
| 5 | import { Middleware } from 'koa' |
| 6 | import { CFG, isLocalHost, MINUTE } from './misc' |
| 7 | import { onProcessExit } from './first' |
| 8 | |
| 9 | const trackIps = defineConfig(CFG.track_ips, true) |
| 10 | export const ips = new KvStorage({ |
| 11 | defaultPutDelay: MINUTE, |
| 12 | maxPutDelay: 10 * MINUTE, |
| 13 | maxPutDelayCreate: 0, |
| 14 | }) |
| 15 | onProcessExit(() => ips.close()) |
| 16 | |
| 17 | export const trackIpsMw: Middleware = async (ctx, next) => { |
| 18 | if (ips.isOpen() && !isLocalHost(ctx)) |
| 19 | ips.put(ctx.ip, { ts: new Date, country: ctx.state.connection.country }) |
| 20 | await next() |
| 21 | } |
| 22 | |
| 23 | trackIps.sub(v => { |
| 24 | if (v) |
| 25 | ips.open('ips.kv') |
| 26 | else |
| 27 | ips.close() |
| 28 | }) |