add bookmarks section and fix group cover lightbox

- add bookmarks table, API, admin page and public launcher
- persist bookmarks in backup/restore and orphan sweep
- fix group cover lightbox via shared image modal
- add optional idle unload and trim-after-each to photo-ai
- document bookmarks in AGENTS.md
This commit is contained in:
dev
2026-10-10 00:24:05 +03:00
parent ec47659ec6
commit 2cacb12762
15 changed files with 1153 additions and 10 deletions
+219 -4
View File
@@ -1536,7 +1536,7 @@ async function removeEntryFiles(entryId) {
async function sweepOrphanedUploads() {
const dir = UPLOADS_DIR;
try { fs.mkdirSync(dir, { recursive: true }); } catch {}
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }] = await Promise.all([
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }] = await Promise.all([
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
pool.query('SELECT path AS p FROM project_files'),
pool.query('SELECT photo_path AS p FROM group_photos'),
@@ -1551,9 +1551,10 @@ async function sweepOrphanedUploads() {
pool.query('SELECT photo_original_path AS p FROM entries WHERE photo_original_path IS NOT NULL'),
pool.query('SELECT before_path AS p FROM photo_jobs WHERE before_path IS NOT NULL'),
pool.query('SELECT path AS p FROM chat_attachments'),
pool.query('SELECT photo_path AS p FROM bookmarks WHERE photo_path IS NOT NULL'),
]);
const refs = new Set();
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles].forEach(r => {
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos].forEach(r => {
const key = storage.keyFromPath(r.p);
if (key) refs.add(key);
});
@@ -1812,6 +1813,27 @@ async function ensureUserNotesTable() {
await pool.query("INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING");
}
async function ensureBookmarksTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS bookmarks (
id SERIAL PRIMARY KEY,
title VARCHAR(200) NOT NULL,
url VARCHAR(500) NOT NULL,
description TEXT NOT NULL DEFAULT '',
photo_path TEXT,
image_mode VARCHAR(10) NOT NULL DEFAULT 'logo',
open_new_tab BOOLEAN NOT NULL DEFAULT true,
is_active BOOLEAN NOT NULL DEFAULT true,
sort_order INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query("ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS image_mode VARCHAR(10) NOT NULL DEFAULT 'logo'");
await pool.query('ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS open_new_tab BOOLEAN NOT NULL DEFAULT true');
await pool.query('ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true');
await pool.query('ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0');
await pool.query('CREATE INDEX IF NOT EXISTS idx_bookmarks_sort ON bookmarks(sort_order, id)');
}
async function ensureApiKeysTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
id SERIAL PRIMARY KEY,
@@ -1851,6 +1873,7 @@ async function ensureUsersAndFirstAdmin() {
await ensureUserTables();
await ensureApiKeysTable();
await ensureUserNotesTable();
await ensureBookmarksTable();
await ensureFirstAdmin();
}
@@ -3502,6 +3525,189 @@ app.delete('/api/notes/:id', requireAuth, async (req, res) => {
}
});
// --- Bookmarks (закладки: admin + tutors) ---
const BOOKMARK_TITLE_MAX = 200;
const BOOKMARK_DESC_MAX = 500;
function bookmarkImageMode(v) {
return v === 'cover' ? 'cover' : 'logo';
}
function bookmarkUrl(v) {
const s = parseShareLinkUrl(v);
if (!s) throw new Error('Ссылка обязательна');
return s;
}
app.get('/api/bookmarks', requireAuth, async (req, res) => {
try {
const admin = req.user.role === 'admin';
const search = typeof req.query.search === 'string' ? req.query.search.trim() : '';
const params = [];
let where = 'WHERE 1 = 1';
if (!admin) where += ' AND is_active = true';
if (search) {
const ph = `$${params.push(`%${search}%`)}`;
where += ` AND (title ILIKE ${ph} OR description ILIKE ${ph} OR url ILIKE ${ph})`;
}
const { rows } = await pool.query(
`SELECT id, title, url, description, photo_path, image_mode, open_new_tab, is_active, sort_order, created_at, updated_at
FROM bookmarks ${where}
ORDER BY sort_order ASC, id ASC`,
params
);
res.json({ items: rows });
} catch (e) {
console.error('bookmarks list:', e);
res.status(500).json({ error: 'Не удалось получить закладки' });
}
});
app.post('/api/bookmarks', requireAdmin, async (req, res) => {
try {
const title = reqStr(req.body?.title, BOOKMARK_TITLE_MAX);
const url = bookmarkUrl(req.body?.url);
const description = optText(req.body?.description, BOOKMARK_DESC_MAX);
const image_mode = bookmarkImageMode(req.body?.image_mode);
const open_new_tab = req.body?.open_new_tab !== false;
const { rows } = await pool.query(
`INSERT INTO bookmarks (title, url, description, image_mode, open_new_tab, sort_order)
VALUES ($1, $2, $3, $4, $5, COALESCE((SELECT MIN(sort_order) FROM bookmarks), 1) - 1)
RETURNING id, title, url, description, photo_path, image_mode, open_new_tab, is_active, sort_order, created_at, updated_at`,
[title, url, description, image_mode, open_new_tab]
);
await logAudit(req, 'bookmark.create', { id: rows[0].id, url });
res.json({ item: rows[0] });
} catch (e) {
if (e.message === 'Invalid string' || e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
if (e.message === 'Ссылка обязательна' || e.message === 'Ссылка слишком длинная (макс. 500 символов)' || e.message === 'Некорректная ссылка' || e.message === 'Ссылка должна начинаться с http:// или https://') {
return res.status(400).json({ error: e.message });
}
console.error('bookmarks create:', e);
res.status(500).json({ error: 'Не удалось создать закладку' });
}
});
app.put('/api/bookmarks/reorder', requireAdmin, async (req, res) => {
try {
const raw = Array.isArray(req.body?.ids) ? req.body.ids : null;
if (!raw || raw.some(id => !Number.isInteger(Number(id)))) {
return res.status(400).json({ error: 'Некорректный порядок закладок' });
}
const ids = raw.map(id => Number(id));
if (ids.some(id => id < 1)) return res.status(400).json({ error: 'Некорректный порядок закладок' });
if (new Set(ids).size !== ids.length) {
return res.status(400).json({ error: 'Порядок закладок содержит дубликаты' });
}
const client = await pool.connect();
try {
await client.query('BEGIN');
for (let i = 0; i < ids.length; i++) {
const { rowCount } = await client.query('UPDATE bookmarks SET sort_order = $1 WHERE id = $2', [i + 1, ids[i]]);
if (!rowCount) throw { http: 404, message: 'Закладка не найдена' };
}
await client.query('COMMIT');
await logAudit(req, 'bookmark.reorder', { order: ids });
res.json({ ok: true });
} catch (e) {
await client.query('ROLLBACK');
if (e.http) return res.status(e.http).json({ error: e.message });
throw e;
} finally {
client.release();
}
} catch (e) {
console.error('bookmarks reorder:', e);
res.status(500).json({ error: 'Не удалось сохранить порядок закладок' });
}
});
app.put('/api/bookmarks/:id', requireAdmin, async (req, res) => {
try {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
const title = reqStr(req.body?.title, BOOKMARK_TITLE_MAX);
const url = bookmarkUrl(req.body?.url);
const description = optText(req.body?.description, BOOKMARK_DESC_MAX);
const image_mode = bookmarkImageMode(req.body?.image_mode);
const open_new_tab = req.body?.open_new_tab !== false;
const is_active = req.body?.is_active !== false;
const { rows } = await pool.query(
`UPDATE bookmarks SET title=$1, url=$2, description=$3, image_mode=$4, open_new_tab=$5, is_active=$6, updated_at=now()
WHERE id=$7
RETURNING id, title, url, description, photo_path, image_mode, open_new_tab, is_active, sort_order, created_at, updated_at`,
[title, url, description, image_mode, open_new_tab, is_active, id]
);
if (!rows.length) return res.status(404).json({ error: 'Not found' });
await logAudit(req, 'bookmark.update', { id, url });
res.json({ item: rows[0] });
} catch (e) {
if (e.message === 'Invalid string' || e.message === 'Invalid string length') return res.status(400).json({ error: 'Неверная длина поля' });
if (e.message === 'Ссылка обязательна' || e.message === 'Ссылка слишком длинная (макс. 500 символов)' || e.message === 'Некорректная ссылка' || e.message === 'Ссылка должна начинаться с http:// или https://') {
return res.status(400).json({ error: e.message });
}
console.error('bookmarks update:', e);
res.status(500).json({ error: 'Не удалось обновить закладку' });
}
});
app.delete('/api/bookmarks/:id', requireAdmin, async (req, res) => {
try {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
const { rows } = await pool.query('DELETE FROM bookmarks WHERE id = $1 RETURNING photo_path', [id]);
if (!rows.length) return res.status(404).json({ error: 'Not found' });
if (rows[0].photo_path) safeUnlink(rows[0].photo_path);
await logAudit(req, 'bookmark.delete', { id });
res.json({ ok: true });
} catch (e) {
console.error('bookmarks delete:', e);
res.status(500).json({ error: 'Не удалось удалить закладку' });
}
});
const bookmarkPhotoUpload = upload.single('photo');
app.post('/api/bookmarks/:id/photo', requireAdmin, (req, res) => {
bookmarkPhotoUpload(req, res, async (err) => {
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
if (err.message === 'Only images') return res.status(400).json({ error: 'Картинка: допустимы только изображения (jpg, png, gif, webp, bmp, avif, ico, heic, heif, jfif)' });
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла (*.html, *.js, *.svg и т.п. запрещены)' });
return res.status(400).json({ error: 'Недопустимый файл' });
}
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
try {
const bm = await pool.query('SELECT photo_path FROM bookmarks WHERE id = $1', [req.params.id]);
if (!bm.rows.length) {
removeUpload(req.file);
return res.status(404).json({ error: 'Не найдено' });
}
await convertPhoto(req.file);
const oldPath = bm.rows[0].photo_path;
const { rows } = await pool.query(
'UPDATE bookmarks SET photo_path = $1, updated_at = now() WHERE id = $2 RETURNING id, title, url, description, photo_path, image_mode, open_new_tab, is_active, sort_order',
[`/uploads/${req.file.filename}`, req.params.id]
);
if (oldPath) safeUnlink(oldPath);
await logAudit(req, 'bookmark.photo.create', { id: req.params.id, photo_path: rows[0].photo_path });
res.json(rows[0]);
} catch (e) {
removeUpload(req.file);
console.error('POST /api/bookmarks/:id/photo:', e);
res.status(500).json({ error: e.message });
}
});
});
app.delete('/api/bookmarks/:id/photo', requireAdmin, async (req, res) => {
const { rows } = await pool.query('SELECT id, photo_path FROM bookmarks WHERE id = $1', [req.params.id]);
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
if (rows[0].photo_path) safeUnlink(rows[0].photo_path);
await pool.query('UPDATE bookmarks SET photo_path = NULL, updated_at = now() WHERE id = $1', [req.params.id]);
await logAudit(req, 'bookmark.photo.delete', { id: req.params.id, photo_path: rows[0].photo_path });
res.json({ ok: true });
});
app.put('/api/feedbacks/:id', requireAuth, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
@@ -4443,7 +4649,7 @@ function sweepBackupStorage() {
async function buildBackupArchive() {
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
try {
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un] = await Promise.all([
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm] = await Promise.all([
pool.query('SELECT * FROM groups ORDER BY id'),
pool.query('SELECT * FROM students ORDER BY id'),
pool.query('SELECT * FROM entries ORDER BY id'),
@@ -4471,6 +4677,7 @@ async function buildBackupArchive() {
pool.query('SELECT * FROM feedbacks ORDER BY id'),
pool.query('SELECT * FROM user_settings ORDER BY user_id, key'),
pool.query('SELECT * FROM user_notes ORDER BY id'),
pool.query('SELECT * FROM bookmarks ORDER BY id'),
]);
const settings = {};
st.rows.forEach(r => { settings[r.key] = r.value; });
@@ -4487,8 +4694,9 @@ async function buildBackupArchive() {
notification_reads: nr.rowCount, banned_ips: bi.rowCount,
chat_threads: ct.rowCount, chat_messages: cm.rowCount, chat_attachments: ca.rowCount,
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.rowCount,
bookmarks: bm.rowCount,
},
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows,
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows,
};
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
const files = await storage.downloadAll(path.join(staging, 'uploads'));
@@ -4670,6 +4878,7 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
await client.query('DELETE FROM audit_log');
await client.query('DELETE FROM user_settings');
await client.query('DELETE FROM user_notes');
await client.query('DELETE FROM bookmarks');
await client.query('DELETE FROM users');
await client.query('DELETE FROM branches');
for (const x of ndata.branches) {
@@ -4700,6 +4909,12 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
[x.id, x.user_id, x.title, x.note, x.tags, x.color, x.sort_order, x.ai_status || 'none', x.created_at || null, x.updated_at || null]
);
}
for (const x of (ndata.bookmarks || [])) {
await client.query(
'INSERT INTO bookmarks (id, title, url, description, photo_path, image_mode, open_new_tab, is_active, sort_order, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)',
[x.id, x.title, x.url, x.description, x.photo_path || null, x.image_mode === 'cover' ? 'cover' : 'logo', x.open_new_tab !== false, x.is_active !== false, x.sort_order, x.created_at || null, x.updated_at || null]
);
}
for (const x of ndata.user_branches) {
await client.query(
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',