refactor: make each visit timestamped separately so we can filter them out properly

This commit is contained in:
dusk 2025-01-16 14:11:59 +03:00
parent 8bc6d13650
commit 78d7752f81
Signed by: dusk
SSH Key Fingerprint: SHA256:Abmvag+juovVufZTxyWY8KcVgrznxvBjQpJesv071Aw
2 changed files with 14 additions and 7 deletions

View File

@ -8,7 +8,7 @@ import { get, writable } from "svelte/store";
const visitCountFile = `${env.WEBSITE_DATA_DIR}/visitcount`
const visitCount = writable(parseInt(existsSync(visitCountFile) ? readFileSync(visitCountFile).toString() : '0'))
type Visitor = { count: number, since: number }
type Visitor = { visits: number[] }
const lastVisitors = writable<Map<string, Visitor>>(new Map())
const VISITOR_EXPIRY_SECONDS = 60 * 60 * 1
@ -47,8 +47,15 @@ const _addLastVisitor = (visitors: Map<string, Visitor>, request: Request, cooki
// filter out old entries
visitors = new Map(
visitors.entries().filter(
([_, value]) =>
{ return currentTime - value.since < 1000 * VISITOR_EXPIRY_SECONDS }
([_, visitor]) =>
{ return currentTime - visitor.visits[0] < 1000 * VISITOR_EXPIRY_SECONDS }
).map(
([id, visitor]) => {
visitor.visits = visitor.visits.filter((since) => {
return currentTime - since < 1000 * VISITOR_EXPIRY_SECONDS
})
return [id, visitor]
}
)
)
// check whether the request is from a bot or not (this doesnt need to be accurate we just want to filter out honest bots)
@ -63,9 +70,9 @@ const _addLastVisitor = (visitors: Map<string, Visitor>, request: Request, cooki
console.log(`new client visitor id ${visitorId}`)
}
// update the entry
let visitorEntry = visitors.get(visitorId) || {count: 0, since: 0}
visitorEntry.count += 1
visitorEntry.since = currentTime
let visitorEntry = visitors.get(visitorId) || {visits: []}
// put new visit in the front
visitorEntry.visits = [currentTime].concat(visitorEntry.visits)
visitors.set(visitorId, visitorEntry);
return visitors
}

View File

@ -43,7 +43,7 @@
$: title = getTitle(data.route);
$: recentVisitCount = data.lastVisitors.values().reduce(
(total, visitor) => { return total + visitor.count; }, 0
(total, visitor) => { return total + visitor.visits.length; }, 0
)
const svgSquiggles = [[2], [3], [2], [3], [1]];