db.ts
TypeScript · 137 рядків
1// База коментарів порталу: SQLite (node:sqlite) у portal/data/comments.db — поза git, окремо на кожному порталі.
2// Користувачі (вхід, реєстрація з підтвердженням), сесії, коментарі з прив'язкою до коміту й файлу,
3// журнал дій над коментарем. Номер C-NN — для людей і тексту, UUID — технічний.
4import { mkdirSync } from 'node:fs'
5import { join } from 'node:path'
6import { DatabaseSync } from 'node:sqlite'
7import { randomUUID } from 'node:crypto'
8
9export const DATA_DIR = process.env.PORTAL_DATA ?? join(import.meta.dirname, '..', '..', 'data')
10
11export type Role = 'admin' | 'user' | 'bot'
12export interface User { id: number; name: string; role: Role; approved: boolean; created_at: string }
13export type State = 'open' | 'closed'
14export interface LogEntry { at: string; by: string; action: 'create' | 'close' | 'reopen' | 'anchor' | 'edit'; text?: string; commit?: string }
15export interface Comment {
16 id: string; num: number; ref: string
17 path: string; commit: string; blob: string; dirty: boolean
18 quote: string; prefix: string; suffix: string; heading: string
19 text: string; author: string; created_at: string
20 state: State; answer: string; answer_where: string; answer_commit: string; closed_by: string; closed_at: string
21 log: LogEntry[]
22}
23
24let db: DatabaseSync | null = null
25export const now = () => new Date().toISOString()
26
27export function open(): DatabaseSync {
28 if (db) return db
29 mkdirSync(DATA_DIR, { recursive: true })
30 db = new DatabaseSync(join(DATA_DIR, 'comments.db'))
31 db.exec(`PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;
32 CREATE TABLE IF NOT EXISTS users (
33 id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE COLLATE NOCASE, pass TEXT NOT NULL DEFAULT '', token TEXT,
34 role TEXT NOT NULL DEFAULT 'user', approved INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL);
35 CREATE TABLE IF NOT EXISTS sessions (
36 token TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires TEXT NOT NULL);
37 CREATE TABLE IF NOT EXISTS comments (
38 id TEXT PRIMARY KEY, num INTEGER NOT NULL UNIQUE,
39 path TEXT NOT NULL, "commit" TEXT NOT NULL, blob TEXT NOT NULL, dirty INTEGER NOT NULL DEFAULT 0,
40 quote TEXT NOT NULL, prefix TEXT NOT NULL DEFAULT '', suffix TEXT NOT NULL DEFAULT '', heading TEXT NOT NULL DEFAULT '',
41 text TEXT NOT NULL, author_id INTEGER NOT NULL REFERENCES users(id), created_at TEXT NOT NULL,
42 state TEXT NOT NULL DEFAULT 'open', answer TEXT NOT NULL DEFAULT '', answer_where TEXT NOT NULL DEFAULT '',
43 answer_commit TEXT NOT NULL DEFAULT '', closed_by INTEGER REFERENCES users(id), closed_at TEXT NOT NULL DEFAULT '',
44 log TEXT NOT NULL DEFAULT '[]');
45 CREATE INDEX IF NOT EXISTS comments_path ON comments(path);`)
46 return db
47}
48
49const toUser = (r: any): User => ({ id: Number(r.id), name: String(r.name), role: r.role as Role, approved: !!r.approved, created_at: String(r.created_at) })
50
51export const users = {
52 byName: (name: string) => { const r = open().prepare('SELECT * FROM users WHERE name = ?').get(name); return r ? { ...toUser(r), pass: String(r.pass) } : null },
53 byId: (id: number) => { const r = open().prepare('SELECT * FROM users WHERE id = ?').get(id); return r ? toUser(r) : null },
54 byToken: (hash: string) => { const r = open().prepare('SELECT * FROM users WHERE token = ? AND approved = 1').get(hash); return r ? toUser(r) : null },
55 all: () => open().prepare('SELECT * FROM users ORDER BY approved, created_at').all().map(toUser),
56 create: (name: string, pass: string, role: Role = 'user', approved = false) =>
57 Number(open().prepare('INSERT INTO users (name, pass, role, approved, created_at) VALUES (?, ?, ?, ?, ?)').run(name, pass, role, approved ? 1 : 0, now()).lastInsertRowid),
58 set: (id: number, f: { approved?: boolean; role?: Role; token?: string | null; pass?: string }) => {
59 const d = open()
60 if (f.approved !== undefined) d.prepare('UPDATE users SET approved = ? WHERE id = ?').run(f.approved ? 1 : 0, id)
61 if (f.role) d.prepare('UPDATE users SET role = ? WHERE id = ?').run(f.role, id)
62 if (f.token !== undefined) d.prepare('UPDATE users SET token = ? WHERE id = ?').run(f.token, id)
63 if (f.pass) d.prepare('UPDATE users SET pass = ? WHERE id = ?').run(f.pass, id)
64 },
65 remove: (id: number) => open().prepare('DELETE FROM users WHERE id = ? AND id NOT IN (SELECT author_id FROM comments)').run(id).changes > 0,
66 admins: () => Number(open().prepare("SELECT count(*) n FROM users WHERE role = 'admin' AND approved = 1").get()!.n),
67}
68
69export const sessions = {
70 create: (token: string, userId: number, days: number) =>
71 open().prepare('INSERT INTO sessions (token, user_id, expires) VALUES (?, ?, ?)').run(token, userId, new Date(Date.now() + days * 864e5).toISOString()),
72 user: (token: string) => {
73 const r = open().prepare('SELECT user_id FROM sessions WHERE token = ? AND expires > ?').get(token, now())
74 return r ? users.byId(Number(r.user_id)) : null
75 },
76 drop: (token: string) => open().prepare('DELETE FROM sessions WHERE token = ?').run(token),
77}
78
79const SELECT = `SELECT c.*, a.name author, b.name closer FROM comments c JOIN users a ON a.id = c.author_id LEFT JOIN users b ON b.id = c.closed_by`
80const toComment = (r: any): Comment => ({
81 id: String(r.id), num: Number(r.num), ref: `C-${r.num}`, path: String(r.path), commit: String(r.commit), blob: String(r.blob), dirty: !!r.dirty,
82 quote: String(r.quote), prefix: String(r.prefix), suffix: String(r.suffix), heading: String(r.heading),
83 text: String(r.text), author: String(r.author), created_at: String(r.created_at),
84 state: r.state as State, answer: String(r.answer), answer_where: String(r.answer_where), answer_commit: String(r.answer_commit),
85 closed_by: r.closer ? String(r.closer) : '', closed_at: String(r.closed_at), log: JSON.parse(String(r.log)),
86})
87
88export interface NewComment { path: string; commit: string; blob: string; dirty: boolean; quote: string; prefix: string; suffix: string; heading: string; text: string }
89
90export const comments = {
91 list: (f: { path?: string; state?: State; author?: string } = {}) => {
92 const where: string[] = [], args: (string | number)[] = []
93 if (f.path) { where.push('c.path = ?'); args.push(f.path) }
94 if (f.state) { where.push('c.state = ?'); args.push(f.state) }
95 if (f.author) { where.push('a.name = ?'); args.push(f.author) }
96 return open().prepare(`${SELECT}${where.length ? ' WHERE ' + where.join(' AND ') : ''} ORDER BY c.num`).all(...args).map(toComment)
97 },
98 get: (key: string) => {
99 const m = /^C-(\d+)$/i.exec(key)
100 const r = m ? open().prepare(`${SELECT} WHERE c.num = ?`).get(Number(m[1])) : open().prepare(`${SELECT} WHERE c.id = ?`).get(key)
101 return r ? toComment(r) : null
102 },
103 nums: () => new Set(open().prepare('SELECT num FROM comments').all().map(r => Number(r.num))),
104 create: (c: NewComment, author: User) => {
105 const d = open()
106 const id = randomUUID()
107 const num = Number(d.prepare('SELECT coalesce(max(num), 0) + 1 n FROM comments').get()!.n)
108 const log: LogEntry[] = [{ at: now(), by: author.name, action: 'create' }]
109 d.prepare(`INSERT INTO comments (id, num, path, "commit", blob, dirty, quote, prefix, suffix, heading, text, author_id, created_at, log)
110 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, num, c.path, c.commit, c.blob, c.dirty ? 1 : 0, c.quote, c.prefix, c.suffix, c.heading, c.text, author.id, now(), JSON.stringify(log))
111 return comments.get(id)!
112 },
113 close: (c: Comment, by: User, a: { answer: string; where: string; commit: string }) => {
114 const log = [...c.log, { at: now(), by: by.name, action: 'close' as const, text: a.answer, commit: a.commit }]
115 open().prepare(`UPDATE comments SET state = 'closed', answer = ?, answer_where = ?, answer_commit = ?, closed_by = ?, closed_at = ?, log = ? WHERE id = ?`)
116 .run(a.answer, a.where, a.commit, by.id, now(), JSON.stringify(log), c.id)
117 return comments.get(c.id)!
118 },
119 reopen: (c: Comment, by: User, text: string) => {
120 const log = [...c.log, { at: now(), by: by.name, action: 'reopen' as const, text }]
121 open().prepare(`UPDATE comments SET state = 'open', closed_by = NULL, closed_at = '', log = ? WHERE id = ?`).run(JSON.stringify(log), c.id)
122 return comments.get(c.id)!
123 },
124 /** Переприв'язати відкритий коментар до нової версії тексту. */
125 anchor: (c: Comment, by: User, a: { commit: string; blob: string; quote: string; prefix: string; suffix: string; heading: string }) => {
126 const log = [...c.log, { at: now(), by: by.name, action: 'anchor' as const, commit: a.commit }]
127 open().prepare(`UPDATE comments SET "commit" = ?, blob = ?, dirty = 0, quote = ?, prefix = ?, suffix = ?, heading = ?, log = ? WHERE id = ?`)
128 .run(a.commit, a.blob, a.quote, a.prefix, a.suffix, a.heading, JSON.stringify(log), c.id)
129 return comments.get(c.id)!
130 },
131 edit: (c: Comment, by: User, text: string) => {
132 const log = [...c.log, { at: now(), by: by.name, action: 'edit' as const, text: c.text }]
133 open().prepare('UPDATE comments SET text = ?, log = ? WHERE id = ?').run(text, JSON.stringify(log), c.id)
134 return comments.get(c.id)!
135 },
136}
137