mirror of
https://github.com/traberph/short.git
synced 2026-11-22 22:55:12 +00:00
v2: rewrite on Hono + SQLite with user namespaces
Replaces the Next.js/Prisma/next-auth app with a single-container Hono server, SQLite via Drizzle, OIDC login against Authentik and a React/Vite admin UI that talks to a JSON API. - users get /<username>/<code>, admins (Authentik group) get root codes, pinning and full access - link pages with link and Markdown text blocks, themes, avatars - editable 302 redirects, random or custom codes - personal API tokens, CSRF-protected cookie sessions - privacy-friendly stats: daily-rotating visitor salt, 90-day click retention with daily totals kept - QR codes as PNG/SVG - tests for permissions, auth, redirects and stats; CI runs them before publishing images See REQUIREMENTS.md for the full requirement list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
import { createHash, randomBytes, randomInt } from "node:crypto";
|
||||
|
||||
export function sha256(value: string): string {
|
||||
return createHash("sha256").update(value).digest("hex");
|
||||
}
|
||||
|
||||
export function randomToken(bytes = 32): string {
|
||||
return randomBytes(bytes).toString("base64url");
|
||||
}
|
||||
|
||||
// No 0/O/1/l/I to keep generated codes readable.
|
||||
const CODE_ALPHABET = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
||||
|
||||
export function randomCode(length = 5): string {
|
||||
let code = "";
|
||||
for (let i = 0; i < length; i++) code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
|
||||
return code;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export class HttpError extends Error {
|
||||
constructor(
|
||||
readonly status: 400 | 401 | 403 | 404 | 409 | 413 | 415,
|
||||
message: string,
|
||||
readonly issues?: Record<string, string[]>,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export const notFound = () => new HttpError(404, "Not found");
|
||||
export const forbidden = () => new HttpError(403, "Forbidden");
|
||||
@@ -0,0 +1,51 @@
|
||||
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomToken } from "./crypto.js";
|
||||
import { HttpError } from "./errors.js";
|
||||
|
||||
const MAX_AVATAR_BYTES = 2 * 1024 * 1024;
|
||||
const NAME_PATTERN = /^[A-Za-z0-9_-]+\.(png|jpg|webp)$/;
|
||||
|
||||
export const CONTENT_TYPES = { png: "image/png", jpg: "image/jpeg", webp: "image/webp" } as const;
|
||||
type Ext = keyof typeof CONTENT_TYPES;
|
||||
|
||||
// Detects the image type from its first bytes instead of trusting the upload's content type.
|
||||
function sniff(bytes: Uint8Array): Ext | null {
|
||||
const ascii = (start: number, end: number) => String.fromCharCode(...bytes.subarray(start, end));
|
||||
if (bytes[0] === 0x89 && ascii(1, 4) === "PNG") return "png";
|
||||
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpg";
|
||||
if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "webp";
|
||||
return null;
|
||||
}
|
||||
|
||||
const mediaDir = (dataDir: string) => path.join(dataDir, "media");
|
||||
|
||||
export async function saveAvatar(dataDir: string, file: File): Promise<string> {
|
||||
if (file.size > MAX_AVATAR_BYTES) throw new HttpError(413, "Image must be smaller than 2 MB");
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const ext = sniff(bytes);
|
||||
if (!ext) throw new HttpError(415, "Only PNG, JPEG and WebP images are allowed");
|
||||
const name = `${randomToken(16)}.${ext}`;
|
||||
mkdirSync(mediaDir(dataDir), { recursive: true });
|
||||
writeFileSync(path.join(mediaDir(dataDir), name), bytes);
|
||||
return name;
|
||||
}
|
||||
|
||||
export function readMedia(dataDir: string, name: string): { bytes: Buffer; type: string } | null {
|
||||
const match = name.match(NAME_PATTERN);
|
||||
if (!match) return null;
|
||||
try {
|
||||
return { bytes: readFileSync(path.join(mediaDir(dataDir), name)), type: CONTENT_TYPES[match[1] as Ext] };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function removeMedia(dataDir: string, name: string): void {
|
||||
if (!NAME_PATTERN.test(name)) return;
|
||||
try {
|
||||
unlinkSync(path.join(mediaDir(dataDir), name));
|
||||
} catch {
|
||||
// Already gone.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import { and, asc, eq, inArray, sql } from "drizzle-orm";
|
||||
import type { Block, Conflict, PageDetail, PageSummary } from "../../shared/api-types.js";
|
||||
import {
|
||||
DEFAULT_THEME,
|
||||
RESERVED_CODES,
|
||||
type CreateBlockInput,
|
||||
type CreatePageInput,
|
||||
type Theme,
|
||||
type UpdatePageInput,
|
||||
} from "../../shared/validation.js";
|
||||
import type { Db } from "../db/index.js";
|
||||
import { blocks, dailyStats, pages, settings, users } from "../db/schema.js";
|
||||
import { randomCode } from "./crypto.js";
|
||||
import { forbidden, HttpError, notFound } from "./errors.js";
|
||||
import { canLinkTo, canManagePage, canWriteNamespace, type Actor } from "./permissions.js";
|
||||
|
||||
type PageRow = typeof pages.$inferSelect;
|
||||
|
||||
const PINNED_KEY = "pinned_page_id";
|
||||
|
||||
export function pagePath(page: { namespace: string; code: string }): string {
|
||||
return page.namespace ? `/${page.namespace}/${page.code}` : `/${page.code}`;
|
||||
}
|
||||
|
||||
export function avatarUrl(avatar: string | null): string | null {
|
||||
return avatar ? `/~/media/${avatar}` : null;
|
||||
}
|
||||
|
||||
export function getPinnedPageId(db: Db): number | null {
|
||||
const row = db.select().from(settings).where(eq(settings.key, PINNED_KEY)).get();
|
||||
return row ? Number(row.value) : null;
|
||||
}
|
||||
|
||||
export function findByPath(db: Db, namespace: string, code: string): PageRow | undefined {
|
||||
return db
|
||||
.select()
|
||||
.from(pages)
|
||||
.where(and(eq(pages.namespace, namespace), eq(pages.code, code)))
|
||||
.get();
|
||||
}
|
||||
|
||||
function isUsername(db: Db, name: string): boolean {
|
||||
return !!db
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(sql`lower(${users.username}) = lower(${name})`)
|
||||
.get();
|
||||
}
|
||||
|
||||
function codeTaken(db: Db, namespace: string, code: string): boolean {
|
||||
if (findByPath(db, namespace, code)) return true;
|
||||
return namespace === "" && (RESERVED_CODES.has(code.toLowerCase()) || isUsername(db, code));
|
||||
}
|
||||
|
||||
function resolveNamespace(db: Db, actor: Actor, requested: string | undefined): string {
|
||||
const namespace = requested ?? actor.username;
|
||||
if (!canWriteNamespace(actor, namespace)) throw forbidden();
|
||||
if (namespace !== "" && !db.select().from(users).where(eq(users.username, namespace)).get()) {
|
||||
throw new HttpError(400, "Unknown namespace", { namespace: ["No user with this name"] });
|
||||
}
|
||||
return namespace;
|
||||
}
|
||||
|
||||
function loadManagedPage(db: Db, actor: Actor, id: number): PageRow {
|
||||
const page = db.select().from(pages).where(eq(pages.id, id)).get();
|
||||
// Pages outside the actor's reach are reported as missing, so ids can't be probed.
|
||||
if (!page || !canManagePage(actor, page)) throw notFound();
|
||||
return page;
|
||||
}
|
||||
|
||||
export function createPage(db: Db, actor: Actor, input: CreatePageInput): PageSummary {
|
||||
const namespace = resolveNamespace(db, actor, input.namespace);
|
||||
|
||||
let code = input.code;
|
||||
if (code) {
|
||||
if (codeTaken(db, namespace, code)) {
|
||||
throw new HttpError(409, "Shortcode is not available", { code: ["Already in use or reserved"] });
|
||||
}
|
||||
} else {
|
||||
for (let attempt = 0; attempt < 20 && !code; attempt++) {
|
||||
const candidate = randomCode();
|
||||
if (!codeTaken(db, namespace, candidate)) code = candidate;
|
||||
}
|
||||
if (!code) throw new HttpError(409, "Could not generate a free shortcode");
|
||||
}
|
||||
|
||||
const row = db
|
||||
.insert(pages)
|
||||
.values({
|
||||
namespace,
|
||||
code,
|
||||
kind: input.kind,
|
||||
dest: input.kind === "redirect" ? input.dest : null,
|
||||
title: input.kind === "linkpage" ? input.title : null,
|
||||
theme: input.kind === "linkpage" ? DEFAULT_THEME : null,
|
||||
createdBy: actor.id,
|
||||
})
|
||||
.returning()
|
||||
.get();
|
||||
return toSummary(row, 0, false);
|
||||
}
|
||||
|
||||
export function updatePage(db: Db, actor: Actor, id: number, input: UpdatePageInput): PageDetail {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
if (input.dest !== undefined && page.kind !== "redirect") throw new HttpError(400, "Only redirects have a destination");
|
||||
if ((input.title !== undefined || input.theme !== undefined) && page.kind !== "linkpage") {
|
||||
throw new HttpError(400, "Only link pages have a title and theme");
|
||||
}
|
||||
db.update(pages)
|
||||
.set({ ...input, updatedAt: new Date() })
|
||||
.where(eq(pages.id, id))
|
||||
.run();
|
||||
return getPageDetail(db, actor, id);
|
||||
}
|
||||
|
||||
export function setAvatar(db: Db, actor: Actor, id: number, avatar: string | null): string | null {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
if (page.kind !== "linkpage") throw new HttpError(400, "Only link pages have an avatar");
|
||||
db.update(pages).set({ avatar, updatedAt: new Date() }).where(eq(pages.id, id)).run();
|
||||
return page.avatar;
|
||||
}
|
||||
|
||||
// Returns the removed page's avatar file, if any, so the caller can delete it from disk.
|
||||
export function deletePage(db: Db, actor: Actor, id: number): string | null {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
db.transaction((tx) => {
|
||||
// Blocks, clicks and stats go with the page via ON DELETE CASCADE.
|
||||
tx.delete(pages).where(eq(pages.id, id)).run();
|
||||
tx.delete(settings)
|
||||
.where(and(eq(settings.key, PINNED_KEY), eq(settings.value, String(id))))
|
||||
.run();
|
||||
});
|
||||
return page.avatar;
|
||||
}
|
||||
|
||||
function totalClicks(db: Db, pageIds: number[]): Map<number, number> {
|
||||
if (pageIds.length === 0) return new Map();
|
||||
const rows = db
|
||||
.select({ pageId: dailyStats.pageId, total: sql<number>`sum(${dailyStats.clicks})` })
|
||||
.from(dailyStats)
|
||||
.where(inArray(dailyStats.pageId, pageIds))
|
||||
.groupBy(dailyStats.pageId)
|
||||
.all();
|
||||
return new Map(rows.map((r) => [r.pageId, r.total]));
|
||||
}
|
||||
|
||||
function toSummary(row: PageRow, clicks: number, pinned: boolean): PageSummary {
|
||||
return {
|
||||
id: row.id,
|
||||
namespace: row.namespace,
|
||||
code: row.code,
|
||||
path: pagePath(row),
|
||||
kind: row.kind,
|
||||
dest: row.dest,
|
||||
title: row.title,
|
||||
totalClicks: clicks,
|
||||
pinned,
|
||||
};
|
||||
}
|
||||
|
||||
export function listPages(db: Db, actor: Actor): PageSummary[] {
|
||||
const query = db.select().from(pages);
|
||||
const rows = (actor.isAdmin ? query : query.where(eq(pages.namespace, actor.username)))
|
||||
.orderBy(asc(pages.namespace), asc(pages.code))
|
||||
.all();
|
||||
const counts = totalClicks(
|
||||
db,
|
||||
rows.map((r) => r.id),
|
||||
);
|
||||
const pinned = getPinnedPageId(db);
|
||||
return rows.map((r) => toSummary(r, counts.get(r.id) ?? 0, r.id === pinned));
|
||||
}
|
||||
|
||||
export function getBlocks(db: Db, pageId: number): Block[] {
|
||||
const rows = db.select().from(blocks).where(eq(blocks.pageId, pageId)).orderBy(asc(blocks.position)).all();
|
||||
const targetIds = rows.flatMap((b) => (b.targetId ? [b.targetId] : []));
|
||||
const targets = targetIds.length
|
||||
? new Map(
|
||||
db
|
||||
.select()
|
||||
.from(pages)
|
||||
.where(inArray(pages.id, targetIds))
|
||||
.all()
|
||||
.map((t) => [t.id, t]),
|
||||
)
|
||||
: new Map<number, PageRow>();
|
||||
|
||||
return rows.map((b) => {
|
||||
const target = b.targetId ? targets.get(b.targetId) : undefined;
|
||||
return {
|
||||
id: b.id,
|
||||
position: b.position,
|
||||
kind: b.kind,
|
||||
label: b.label,
|
||||
markdown: b.markdown,
|
||||
target: target ? { id: target.id, path: pagePath(target), dest: target.dest } : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function getPageDetail(db: Db, actor: Actor, id: number): PageDetail {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
const clicks = totalClicks(db, [id]).get(id) ?? 0;
|
||||
return {
|
||||
...toSummary(page, clicks, getPinnedPageId(db) === id),
|
||||
theme: (page.theme as Theme | null) ?? DEFAULT_THEME,
|
||||
avatarUrl: avatarUrl(page.avatar),
|
||||
blocks: page.kind === "linkpage" ? getBlocks(db, id) : [],
|
||||
};
|
||||
}
|
||||
|
||||
export function assertCanManage(db: Db, actor: Actor, id: number): void {
|
||||
loadManagedPage(db, actor, id);
|
||||
}
|
||||
|
||||
function loadLinkPage(db: Db, actor: Actor, id: number): PageRow {
|
||||
const page = loadManagedPage(db, actor, id);
|
||||
if (page.kind !== "linkpage") throw new HttpError(400, "Blocks can only be added to link pages");
|
||||
return page;
|
||||
}
|
||||
|
||||
export function addBlock(db: Db, actor: Actor, pageId: number, input: CreateBlockInput): Block[] {
|
||||
const page = loadLinkPage(db, actor, pageId);
|
||||
let targetId: number | null = null;
|
||||
if (input.kind === "link") {
|
||||
const target = db.select().from(pages).where(eq(pages.id, input.targetId)).get();
|
||||
if (!target || !canLinkTo(actor, page, target)) {
|
||||
throw new HttpError(400, "Invalid link target", { targetId: ["Pick one of your redirect links"] });
|
||||
}
|
||||
targetId = target.id;
|
||||
}
|
||||
const max = db
|
||||
.select({ max: sql<number | null>`max(${blocks.position})` })
|
||||
.from(blocks)
|
||||
.where(eq(blocks.pageId, pageId))
|
||||
.get();
|
||||
db.insert(blocks)
|
||||
.values({
|
||||
pageId,
|
||||
position: (max?.max ?? -1) + 1,
|
||||
kind: input.kind,
|
||||
label: input.kind === "link" ? input.label : null,
|
||||
markdown: input.kind === "text" ? input.markdown : null,
|
||||
targetId,
|
||||
})
|
||||
.run();
|
||||
return getBlocks(db, pageId);
|
||||
}
|
||||
|
||||
function loadManagedBlock(db: Db, actor: Actor, blockId: number) {
|
||||
const block = db.select().from(blocks).where(eq(blocks.id, blockId)).get();
|
||||
if (!block) throw notFound();
|
||||
loadManagedPage(db, actor, block.pageId);
|
||||
return block;
|
||||
}
|
||||
|
||||
export function updateBlock(
|
||||
db: Db,
|
||||
actor: Actor,
|
||||
blockId: number,
|
||||
input: { label?: string; markdown?: string },
|
||||
): Block[] {
|
||||
const block = loadManagedBlock(db, actor, blockId);
|
||||
if (block.kind === "link" && input.markdown !== undefined) throw new HttpError(400, "Link blocks have no text");
|
||||
if (block.kind === "text" && input.label !== undefined) throw new HttpError(400, "Text blocks have no label");
|
||||
db.update(blocks).set(input).where(eq(blocks.id, blockId)).run();
|
||||
return getBlocks(db, block.pageId);
|
||||
}
|
||||
|
||||
export function deleteBlock(db: Db, actor: Actor, blockId: number): Block[] {
|
||||
const block = loadManagedBlock(db, actor, blockId);
|
||||
db.delete(blocks).where(eq(blocks.id, blockId)).run();
|
||||
return getBlocks(db, block.pageId);
|
||||
}
|
||||
|
||||
export function reorderBlocks(db: Db, actor: Actor, pageId: number, ids: number[]): Block[] {
|
||||
loadLinkPage(db, actor, pageId);
|
||||
const current = db.select({ id: blocks.id }).from(blocks).where(eq(blocks.pageId, pageId)).all();
|
||||
const currentIds = new Set(current.map((b) => b.id));
|
||||
if (ids.length !== currentIds.size || new Set(ids).size !== ids.length || !ids.every((id) => currentIds.has(id))) {
|
||||
throw new HttpError(400, "ids must list every block of the page exactly once");
|
||||
}
|
||||
db.transaction((tx) => {
|
||||
ids.forEach((id, position) => tx.update(blocks).set({ position }).where(eq(blocks.id, id)).run());
|
||||
});
|
||||
return getBlocks(db, pageId);
|
||||
}
|
||||
|
||||
export function pinPage(db: Db, actor: Actor, pageId: number | null): void {
|
||||
if (!actor.isAdmin) throw forbidden();
|
||||
if (pageId === null) {
|
||||
db.delete(settings).where(eq(settings.key, PINNED_KEY)).run();
|
||||
return;
|
||||
}
|
||||
if (!db.select().from(pages).where(eq(pages.id, pageId)).get()) throw notFound();
|
||||
db.insert(settings)
|
||||
.values({ key: PINNED_KEY, value: String(pageId) })
|
||||
.onConflictDoUpdate({ target: settings.key, set: { value: String(pageId) } })
|
||||
.run();
|
||||
}
|
||||
|
||||
// Users whose name is also used as a root code (possible when the user logs in after the code was created).
|
||||
export function listConflicts(db: Db): Conflict[] {
|
||||
return db
|
||||
.select({ username: users.username, pageId: pages.id })
|
||||
.from(users)
|
||||
.innerJoin(pages, and(eq(pages.namespace, ""), sql`lower(${pages.code}) = lower(${users.username})`))
|
||||
.all();
|
||||
}
|
||||
|
||||
export function listUsernames(db: Db): string[] {
|
||||
return db
|
||||
.select({ username: users.username })
|
||||
.from(users)
|
||||
.orderBy(asc(users.username))
|
||||
.all()
|
||||
.map((u) => u.username);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// All authorization rules in one place. Ownership follows the namespace:
|
||||
// a user owns everything under /<username>/, root ("") belongs to admins.
|
||||
|
||||
export interface Actor {
|
||||
id: number;
|
||||
username: string;
|
||||
isAdmin: boolean;
|
||||
}
|
||||
|
||||
interface Namespaced {
|
||||
namespace: string;
|
||||
}
|
||||
|
||||
export function canWriteNamespace(actor: Actor, namespace: string): boolean {
|
||||
return actor.isAdmin || namespace === actor.username;
|
||||
}
|
||||
|
||||
export function canManagePage(actor: Actor, page: Namespaced): boolean {
|
||||
return canWriteNamespace(actor, page.namespace);
|
||||
}
|
||||
|
||||
// A link page may only contain buttons for links in its own namespace, unless an admin builds it.
|
||||
export function canLinkTo(actor: Actor, page: Namespaced, target: Namespaced & { kind: string }): boolean {
|
||||
if (target.kind !== "redirect") return false;
|
||||
return actor.isAdmin || target.namespace === page.namespace;
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { and, desc, eq, gte, lt, sql } from "drizzle-orm";
|
||||
import type { PageStats } from "../../shared/api-types.js";
|
||||
import type { Db, Tx } from "../db/index.js";
|
||||
import { clicks, dailyStats, settings } from "../db/schema.js";
|
||||
import { randomToken, sha256 } from "./crypto.js";
|
||||
|
||||
// Calendar day (YYYY-MM-DD) in the configured timezone.
|
||||
export function dayOf(date: Date, timezone: string): string {
|
||||
return new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: timezone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function addDays(day: string, delta: number): string {
|
||||
const d = new Date(`${day}T12:00:00Z`);
|
||||
d.setUTCDate(d.getUTCDate() + delta);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
// The visitor salt is random, stored only for the current day and replaced on the next one,
|
||||
// so visitor hashes can't be linked across days or reversed after the fact.
|
||||
function dailySalt(db: Db | Tx, day: string): string {
|
||||
const row = db.select().from(settings).where(eq(settings.key, "visitor_salt")).get();
|
||||
if (row) {
|
||||
const stored = JSON.parse(row.value) as { day: string; salt: string };
|
||||
if (stored.day === day) return stored.salt;
|
||||
}
|
||||
const salt = randomToken();
|
||||
const value = JSON.stringify({ day, salt });
|
||||
db.insert(settings)
|
||||
.values({ key: "visitor_salt", value })
|
||||
.onConflictDoUpdate({ target: settings.key, set: { value } })
|
||||
.run();
|
||||
return salt;
|
||||
}
|
||||
|
||||
// Normalizes an IP so that the last part is dropped (IPv4 /24, IPv6 /48) before hashing.
|
||||
export function anonymizeIp(ip: string): string {
|
||||
const v4 = ip.match(/^(?:::ffff:)?(\d+)\.(\d+)\.(\d+)\.\d+$/);
|
||||
if (v4) return `${v4[1]}.${v4[2]}.${v4[3]}.0`;
|
||||
if (ip.includes(":")) return ip.split(":").slice(0, 3).join(":") + "::";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function recordClick(
|
||||
db: Db,
|
||||
timezone: string,
|
||||
pageId: number,
|
||||
ip: string,
|
||||
userAgent: string,
|
||||
now = new Date(),
|
||||
): void {
|
||||
const day = dayOf(now, timezone);
|
||||
db.transaction((tx) => {
|
||||
const visitor = sha256(`${dailySalt(tx, day)}|${anonymizeIp(ip)}|${userAgent}`);
|
||||
const seen = tx
|
||||
.select({ id: clicks.id })
|
||||
.from(clicks)
|
||||
.where(and(eq(clicks.pageId, pageId), eq(clicks.day, day), eq(clicks.visitor, visitor)))
|
||||
.limit(1)
|
||||
.get();
|
||||
tx.insert(clicks).values({ pageId, at: now, day, visitor }).run();
|
||||
tx.insert(dailyStats)
|
||||
.values({ pageId, day, clicks: 1, uniques: seen ? 0 : 1, lastAt: now })
|
||||
.onConflictDoUpdate({
|
||||
target: [dailyStats.pageId, dailyStats.day],
|
||||
set: {
|
||||
clicks: sql`${dailyStats.clicks} + 1`,
|
||||
uniques: sql`${dailyStats.uniques} + ${seen ? 0 : 1}`,
|
||||
lastAt: now,
|
||||
},
|
||||
})
|
||||
.run();
|
||||
});
|
||||
}
|
||||
|
||||
export function getStats(db: Db, timezone: string, pageId: number, days: number, now = new Date()): PageStats {
|
||||
const today = dayOf(now, timezone);
|
||||
const from = addDays(today, -(days - 1));
|
||||
|
||||
const rows = db
|
||||
.select()
|
||||
.from(dailyStats)
|
||||
.where(and(eq(dailyStats.pageId, pageId), gte(dailyStats.day, from)))
|
||||
.all();
|
||||
const byDay = new Map(rows.map((r) => [r.day, r]));
|
||||
|
||||
const series = [];
|
||||
for (let i = 0; i < days; i++) {
|
||||
const day = addDays(from, i);
|
||||
const row = byDay.get(day);
|
||||
series.push({ day, clicks: row?.clicks ?? 0, uniques: row?.uniques ?? 0 });
|
||||
}
|
||||
|
||||
const totals = db
|
||||
.select({ total: sql<number>`coalesce(sum(${dailyStats.clicks}), 0)` })
|
||||
.from(dailyStats)
|
||||
.where(eq(dailyStats.pageId, pageId))
|
||||
.get();
|
||||
const last = db
|
||||
.select({ lastAt: dailyStats.lastAt })
|
||||
.from(dailyStats)
|
||||
.where(eq(dailyStats.pageId, pageId))
|
||||
.orderBy(desc(dailyStats.day))
|
||||
.limit(1)
|
||||
.get();
|
||||
const todayRow = byDay.get(today);
|
||||
|
||||
return {
|
||||
total: totals?.total ?? 0,
|
||||
today: todayRow?.clicks ?? 0,
|
||||
uniquesToday: todayRow?.uniques ?? 0,
|
||||
lastVisit: last?.lastAt.toISOString() ?? null,
|
||||
series,
|
||||
};
|
||||
}
|
||||
|
||||
export function resetStats(db: Db, pageId: number): void {
|
||||
db.transaction((tx) => {
|
||||
tx.delete(clicks).where(eq(clicks.pageId, pageId)).run();
|
||||
tx.delete(dailyStats).where(eq(dailyStats.pageId, pageId)).run();
|
||||
});
|
||||
}
|
||||
|
||||
// Deletes individual clicks older than the retention period. Daily totals are kept.
|
||||
export function pruneClicks(db: Db, retentionDays: number, now = new Date()): number {
|
||||
const cutoff = new Date(now.getTime() - retentionDays * 24 * 60 * 60 * 1000);
|
||||
return db.delete(clicks).where(lt(clicks.at, cutoff)).run().changes;
|
||||
}
|
||||
Reference in New Issue
Block a user