diff --git a/lib/digest.js b/lib/digest.js index 93fb9ae..f3780e9 100644 --- a/lib/digest.js +++ b/lib/digest.js @@ -2,6 +2,13 @@ const DIGEST_TITLE_MAX = 200; const DIGEST_BODY_MAX = 5000; +const DIGEST_IMAGE_MAX = 20; + +function isSafeDigestPath(p) { + if (typeof p !== 'string' || !p.startsWith('/uploads/')) return false; + const name = p.slice('/uploads/'.length); + return name !== '' && !name.includes('/') && !name.includes('..') && /^[\w,.()-]+$/.test(name); +} function ensureDigestTable(pool) { return pool.query(`CREATE TABLE IF NOT EXISTS digests ( @@ -10,13 +17,28 @@ function ensureDigestTable(pool) { body TEXT NOT NULL DEFAULT '', author_id INT REFERENCES users(id) ON DELETE SET NULL, is_pinned BOOLEAN NOT NULL DEFAULT false, + preview_path VARCHAR(255), + post_at TIMESTAMPTZ, + hide_at TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now() )`) - .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS title VARCHAR(200) NOT NULL DEFAULT \'\'')) - .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS body TEXT NOT NULL DEFAULT \'\'')) + .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS title VARCHAR(200) NOT NULL DEFAULT \'\'\')) + .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS body TEXT NOT NULL DEFAULT \'\'\')) .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS author_id INT REFERENCES users(id) ON DELETE SET NULL')) .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN NOT NULL DEFAULT false')) + .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS preview_path VARCHAR(255)')) + .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS post_at TIMESTAMPTZ')) + .then(() => pool.query('ALTER TABLE digests ADD COLUMN IF NOT EXISTS hide_at TIMESTAMPTZ')) + .then(() => pool.query(`CREATE TABLE IF NOT EXISTS digest_images ( + id SERIAL PRIMARY KEY, + digest_id INT NOT NULL REFERENCES digests(id) ON DELETE CASCADE, + path VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL DEFAULT '', + size INT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ DEFAULT now() + )`)) + .then(() => pool.query('CREATE INDEX IF NOT EXISTS idx_digest_images_digest ON digest_images(digest_id)')) .then(() => pool.query('CREATE INDEX IF NOT EXISTS idx_digests_pinned_created ON digests(is_pinned DESC, created_at DESC)')) .then(() => pool.query('CREATE INDEX IF NOT EXISTS idx_digests_created ON digests(created_at DESC)')) .then(() => pool.query("INSERT INTO settings (key, value) VALUES ('digest_enabled', 'true') ON CONFLICT (key) DO NOTHING")); @@ -28,13 +50,19 @@ function validateDigest(body) { const text = typeof body.body === 'string' ? body.body.trim() : ''; if (!text || text.length > DIGEST_BODY_MAX) throw new Error('Неверная длина текста'); const isPinned = body.is_pinned === true; - return { title, text, isPinned }; + const previewPath = body.preview_path == null ? null : String(body.preview_path); + if (previewPath != null && !isSafeDigestPath(previewPath)) throw new Error('Неверный путь превью'); + const postAt = body.post_at == null ? null : String(body.post_at); + const hideAt = body.hide_at == null ? null : String(body.hide_at); + return { title, text, isPinned, previewPath, postAt, hideAt }; } async function listDigests(pool) { const { rows } = await pool.query( - `SELECT d.id, d.title, d.body, d.author_id, d.is_pinned, d.created_at, d.updated_at, - u.name AS author_name, u.username AS author_username + `SELECT d.id, d.title, d.body, d.author_id, d.is_pinned, d.preview_path, d.post_at, d.hide_at, d.created_at, d.updated_at, + u.name AS author_name, u.username AS author_username, + COALESCE((SELECT json_agg(json_build_object('id', di.id, 'path', di.path, 'name', di.name, 'size', di.size) ORDER BY di.id) + FILTER (WHERE di.id IS NOT NULL)) FROM digest_images di WHERE di.digest_id = d.id), '[]'::json) AS images FROM digests d LEFT JOIN users u ON u.id = d.author_id ORDER BY d.is_pinned DESC, d.created_at DESC` @@ -43,34 +71,36 @@ async function listDigests(pool) { } async function createDigest(pool, data, authorId) { - const { title, text, isPinned } = validateDigest(data); + const { title, text, isPinned, previewPath, postAt, hideAt } = validateDigest(data); const { rows } = await pool.query( - `INSERT INTO digests (title, body, author_id, is_pinned) - VALUES ($1, $2, $3, $4) - RETURNING id, title, body, author_id, is_pinned, created_at, updated_at`, - [title, text, authorId, isPinned] + `INSERT INTO digests (title, body, author_id, is_pinned, preview_path, post_at, hide_at) + VALUES ($1, $2, $3, $4, $5, $6, $7) + RETURNING id, title, body, author_id, is_pinned, preview_path, post_at, hide_at, created_at, updated_at`, + [title, text, authorId, isPinned, previewPath, postAt, hideAt] ); return rows[0]; } async function updateDigest(pool, id, data, authorId, isAdmin) { - const { title, text, isPinned } = validateDigest(data); + const { title, text, isPinned, previewPath, postAt, hideAt } = validateDigest(data); const { rows } = await pool.query( - `UPDATE digests SET title = $1, body = $2, is_pinned = $3, updated_at = now() - WHERE id = $4 AND ($5::boolean OR author_id = $6) - RETURNING id, title, body, author_id, is_pinned, created_at, updated_at`, - [title, text, isPinned, id, isAdmin, authorId] + `UPDATE digests SET title = $1, body = $2, is_pinned = $3, preview_path = $4, post_at = $5, hide_at = $6, updated_at = now() + WHERE id = $7 AND ($8::boolean OR author_id = $9) + RETURNING id, title, body, author_id, is_pinned, preview_path, post_at, hide_at, created_at, updated_at`, + [title, text, isPinned, previewPath, postAt, hideAt, id, isAdmin, authorId] ); if (!rows.length) throw { http: 404, message: 'Дайджест не найден или нет прав на редактирование' }; return rows[0]; } -async function deleteDigest(pool, id, authorId, isAdmin) { +async function deleteDigest(pool, id, authorId, isAdmin, unlink) { + const { rows: imgs } = await pool.query('SELECT path FROM digest_images WHERE digest_id = $1', [id]); const { rows } = await pool.query( `DELETE FROM digests WHERE id = $1 AND ($2::boolean OR author_id = $3) RETURNING id`, [id, isAdmin, authorId] ); if (!rows.length) throw { http: 404, message: 'Дайджест не найден или нет прав на удаление' }; + if (typeof unlink === 'function') imgs.forEach(r => unlink(r.path)); return rows[0]; } @@ -84,13 +114,54 @@ async function toggleDigestPin(pool, id, isAdmin) { return rows[0]; } +async function listDigestImages(pool, digestId) { + const { rows } = await pool.query( + 'SELECT id, path, name, size, created_at FROM digest_images WHERE digest_id = $1 ORDER BY id', + [digestId] + ); + return rows; +} + +async function addDigestImage(pool, digestId, path, name, size, authorId, isAdmin) { + const { rows } = await pool.query( + 'SELECT id FROM digests WHERE id = $1 AND ($2::boolean OR author_id = $3)', + [digestId, isAdmin, authorId] + ); + if (!rows.length) throw { http: 404, message: 'Дайджест не найден или нет прав на добавление вложений' }; + const { rows: existing } = await pool.query('SELECT id FROM digest_images WHERE digest_id = $1', [digestId]); + if (existing.length >= DIGEST_IMAGE_MAX) throw { http: 400, message: 'Слишком много вложений в сообщении' }; + if (!isSafeDigestPath(path)) throw { http: 400, message: 'Неверный путь файла' }; + const { rows: ins } = await pool.query( + 'INSERT INTO digest_images (digest_id, path, name, size) VALUES ($1, $2, $3, $4) RETURNING id, path, name, size, created_at', + [digestId, path, name || '', size || 0] + ); + return ins[0]; +} + +async function deleteDigestImage(pool, imageId, authorId, isAdmin, unlink) { + const { rows } = await pool.query( + `SELECT di.id, di.path FROM digest_images di + JOIN digests d ON d.id = di.digest_id + WHERE di.id = $1 AND ($2::boolean OR d.author_id = $3)`, + [imageId, isAdmin, authorId] + ); + if (!rows.length) throw { http: 404, message: 'Вложение не найдено или нет прав на удаление' }; + await pool.query('DELETE FROM digest_images WHERE id = $1', [imageId]); + if (typeof unlink === 'function') unlink(rows[0].path); + return rows[0]; +} + module.exports = { DIGEST_TITLE_MAX, DIGEST_BODY_MAX, + DIGEST_IMAGE_MAX, ensureDigestTable, listDigests, createDigest, updateDigest, deleteDigest, toggleDigestPin, + listDigestImages, + addDigestImage, + deleteDigestImage, };