From 2cacb127627c1dbab737bfdea8b59fb75d3c6005 Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 10 Oct 2026 00:24:05 +0300 Subject: [PATCH] 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 --- AGENTS.md | 11 ++ backup-restore.js | 19 +- backup.selftest.js | 14 ++ db/init.sql | 15 ++ db/migration.sql | 24 +++ docker-compose.yml | 4 + photo-ai/app.py | 97 +++++++++ public/admin.js | 1 + public/bookmarks.html | 146 ++++++++++++++ public/groups.html | 4 + public/index.html | 42 ++++ public/js/bookmarks.js | 433 +++++++++++++++++++++++++++++++++++++++++ public/js/groups.js | 6 +- public/js/index.js | 124 +++++++++++- server.js | 223 ++++++++++++++++++++- 15 files changed, 1153 insertions(+), 10 deletions(-) create mode 100644 public/bookmarks.html create mode 100644 public/js/bookmarks.js diff --git a/AGENTS.md b/AGENTS.md index ad206c6..6a6011d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -211,6 +211,15 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **Сохранение порядка**: `persistNoteOrder()` сравнивает порядок id в DOM с `notes[]` (пустая серия — без запроса), шлёт `PUT /api/notes/reorder` и на успехе перестраивает `notes[]` по DOM, на ошибке — `renderNotes()` для отката визуала - **Бэкап**: `user_notes` входит в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, `normalizeRestoreData` (пустые `title`/`tags`/`note` валидируются через `optText`, не `optStr` — тот бросает исключение на пустой строке), `DELETE` перед `DELETE FROM users` и `INSERT` с проверкой пользователя в restore +### 3j. Закладки (`server.js`, `public/bookmarks.html`, `public/js/bookmarks.js`) +- **Таблица `bookmarks`** (`id`, `title`, `url`, `description`, `photo_path`, `image_mode` = `logo` | `cover`, `open_new_tab`, `is_active`, `sort_order`, `created_at`, `updated_at`) — общие закладки-ссылки. Схема в трёх местах: `db/init.sql`, `db/migration.sql` и `ensureBookmarksTable()` в `server.js`, вызывается из `ensureUsersAndFirstAdmin()` +- **Доступ**: страница в общем сайдбаре (`public/admin.js`, base-массив, пункт `bookmarks`), видна админу и тьюторам. `GET /api/bookmarks` под `requireAuth`: админ получает все, тьютор — только `is_active = true`; фильтр `?search=` по `title`/`description`/`url`. Все мутации (`POST`, `PUT`, `PUT /reorder`, `DELETE`, `POST`/`DELETE /photo`) — под `requireAdmin` +- **Картинка**: режим `logo` (квадратная миниатюра через `thumbSrc`) или `cover` (широкая) хранится в `image_mode`. Загрузка — вторым шагом после сохранения записи: `POST /api/bookmarks/:id/photo` (`upload.single('photo')`, `convertPhoto`, путь `/uploads/`), `DELETE /api/bookmarks/:id/photo` чистит через `safeUnlink` +- **Порядок**: `sort_order`, `PUT /api/bookmarks/reorder` `{ ids }` регистрируется **до** `PUT /api/bookmarks/:id`; новая закладка получает `MIN(sort_order) - 1`. Перетаскивание — ручка `.bookmark-drag` (только админ), `persistBookmarkOrder()` в `public/js/bookmarks.js`. При загрузке список группируется по режиму картинки: сначала `image_mode = 'cover'`, затем `logo` (`sortByType()` в `loadBookmarks()`), внутри групп сохраняется `sort_order` +- **Скрытие**: `is_active` переключается через `PUT /api/bookmarks/:id`, карточка получает класс `.bookmark-hidden` и бейдж «Скрыта» +- **Ссылка**: валидируется `parseShareLinkUrl` (только `http(s)`, ≤500). При `open_new_tab` фронтенд ставит `target="_blank"` и `rel="noopener noreferrer"` +- **Бэкап**: `bookmarks` входит в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, нормализуется в `normalizeRestoreData` (путь картинки — через `optUploadPath`), `DELETE`/`INSERT` в restore. `sweepOrphanedUploads` обязан включать `bookmarks.photo_path`, иначе sweep снесёт картинку + --- ### 4. API Patterns @@ -422,6 +431,8 @@ guards against. | `public/feedback.html` | Страница обратной связи (отзывы тьютора) | | `public/notes.html` | Заметки: сетка карточек 4 в ряд, инлайн-стили `.note-*`, модалка редактирования | | `public/js/notes.js` | Заметки: рендер карточек, CRUD, drag-and-drop порядок (`bindDrag`/`persistNoteOrder`) | +| `public/bookmarks.html` | Закладки: сетка карточек (логотип/обложка), поиск, drag-and-drop порядок | +| `public/js/bookmarks.js` | Закладки: CRUD, загрузка картинки, скрытие и порядок карточек | | `public/js/feedback.js` | Логика обратной связи: список, модалка, выбор short_messages, ИИ-очередь | | `scripts/backup.sh` | Host-level backup script (DB dump + storage export) | | `scripts/restore.sh` | Host-level restore script (DB dump + storage import) | diff --git a/backup-restore.js b/backup-restore.js index 7baaef2..8ab3dc4 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -9,13 +9,13 @@ const BACKUP_TABLES = [ 'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments', - 'short_messages', 'feedbacks', + 'short_messages', 'feedbacks', 'bookmarks', ]; const BACKUP_SEQUENCE_TABLES = [ 'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages', - 'chat_attachments', 'short_messages', 'feedbacks', + 'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', ]; function isSupportedBackupVersion(data) { @@ -571,7 +571,20 @@ function normalizeRestoreData(data) { created_at: optTs(x.created_at), updated_at: optTs(x.updated_at), })); - return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks }; + const bookmarks = (data.bookmarks || []).map(x => ({ + id: reqInt(x.id), + title: optText(x.title, 200) || '', + url: optText(x.url, 500) || '', + description: optText(x.description, 500) || '', + photo_path: optUploadPath(x.photo_path, 300), + image_mode: x.image_mode === 'cover' ? 'cover' : 'logo', + open_new_tab: x.open_new_tab !== false, + is_active: x.is_active !== false, + sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0, + created_at: optTs(x.created_at), + updated_at: optTs(x.updated_at), + })); + return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, bookmarks }; } module.exports = { diff --git a/backup.selftest.js b/backup.selftest.js index 4488cad..eacd4c9 100644 --- a/backup.selftest.js +++ b/backup.selftest.js @@ -137,5 +137,19 @@ throws('notifications не массив отклоняется', () => normalize const legacy = normalizeRestoreData({ version: 1, groups: [{ id: 1, name: 'G' }] }); ok('старый архив без новых таблиц восстанавливается', Array.isArray(legacy.audit_log) && legacy.audit_log.length === 0 && legacy.groups.length === 1, Object.keys(legacy)); +ok('bookmarks входят в бэкап и sequences', BACKUP_TABLES.includes('bookmarks') && BACKUP_SEQUENCE_TABLES.includes('bookmarks')); +const bkm = normalizeRestoreData({ + ...base, + bookmarks: [{ id: 1, title: 'T', url: 'https://ex.com', description: 'd', photo_path: '/uploads/1700000000000-abc123.png', image_mode: 'cover', open_new_tab: false, is_active: false, sort_order: 3 }], +}); +ok('bookmarks нормализуются', bkm.bookmarks[0].image_mode === 'cover' && bkm.bookmarks[0].is_active === false && bkm.bookmarks[0].photo_path === '/uploads/1700000000000-abc123.png', bkm.bookmarks[0]); +let bkmBadPath = false; +try { + normalizeRestoreData({ ...base, bookmarks: [{ id: 1, title: 'T', url: 'https://ex.com', photo_path: '/etc/passwd' }] }); +} catch (e) { + bkmBadPath = true; +} +ok('путь картинки закладки вне uploads отклоняется', bkmBadPath); + console.log(failed ? `\n${failed} проверок провалено` : '\nBACKUP SELFTEST OK'); process.exit(failed ? 1 : 0); \ No newline at end of file diff --git a/db/init.sql b/db/init.sql index 364198b..beff15f 100644 --- a/db/init.sql +++ b/db/init.sql @@ -239,6 +239,21 @@ CREATE TABLE IF NOT EXISTS user_notes ( ); CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending'; +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() +); +CREATE INDEX IF NOT EXISTS idx_bookmarks_sort ON bookmarks(sort_order, id); + CREATE TABLE IF NOT EXISTS sessions ( id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/db/migration.sql b/db/migration.sql index 00ffc2f..93c9c77 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -194,6 +194,30 @@ ALTER TABLE user_notes ADD COLUMN IF NOT EXISTS ai_status VARCHAR(20) NOT NULL D CREATE INDEX IF NOT EXISTS idx_user_notes_pending ON user_notes(ai_status, id) WHERE ai_status = 'pending'; INSERT INTO settings (key, value) VALUES ('notes_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING; +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() +); + +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS description TEXT NOT NULL DEFAULT ''; +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS photo_path TEXT; +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS image_mode VARCHAR(10) NOT NULL DEFAULT 'logo'; +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS open_new_tab BOOLEAN NOT NULL DEFAULT true; +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true; +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0; +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ DEFAULT now(); +ALTER TABLE bookmarks ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT now(); +CREATE INDEX IF NOT EXISTS idx_bookmarks_sort ON bookmarks(sort_order, id); + CREATE TABLE IF NOT EXISTS api_keys ( id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/docker-compose.yml b/docker-compose.yml index aec368c..1aa497a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -216,6 +216,10 @@ services: PHOTO_AI_FACE_MODEL: ${PHOTO_AI_FACE_MODEL:-gfpgan} PHOTO_AI_LOAD_ALL: ${PHOTO_AI_LOAD_ALL:-0} PHOTO_AI_JPEG_QUALITY: ${PHOTO_AI_JPEG_QUALITY:-92} + # Выгрузка всех моделей после N секунд простоя (0 = выкл). Сбрасывается при /enhance. + PHOTO_AI_IDLE_UNLOAD_SEC: ${PHOTO_AI_IDLE_UNLOAD_SEC:-0} + # 1 = выгружать неиспользуемые модели сразу после каждого ответа /enhance. + PHOTO_AI_TRIM_AFTER_EACH: ${PHOTO_AI_TRIM_AFTER_EACH:-0} HF_HOME: /root/.cache/huggingface TORCH_HOME: /root/.cache/torch TRANSFORMERS_CACHE: /root/.cache/huggingface diff --git a/photo-ai/app.py b/photo-ai/app.py index c5391e0..fb3aef9 100644 --- a/photo-ai/app.py +++ b/photo-ai/app.py @@ -1,5 +1,6 @@ import asyncio import base64 +import gc import importlib.util import logging import os @@ -42,6 +43,7 @@ MIN_FACE_SIDE = 320 POOL_LIMIT = 2 WARMUP_SIZE = 64 RETRY_AFTER_SEC = 5 +IDLE_POLL_SEC = 5 def env_text(name, default=''): @@ -90,6 +92,10 @@ LOAD_ALL = env_flag('PHOTO_AI_LOAD_ALL', False) WARMUP = env_flag('PHOTO_AI_WARMUP', True) DEFAULT_FACE_MODEL = env_text('PHOTO_AI_FACE_MODEL', 'gfpgan').lower() DEFAULT_JPEG_QUALITY = clamp(env_int('PHOTO_AI_JPEG_QUALITY', 92), 70, 100) +# Секунды простоя без /enhance, после которых выгружаются все модели (0/пусто = выкл). +IDLE_UNLOAD_SEC = env_int('PHOTO_AI_IDLE_UNLOAD_SEC', 0) +# Форс-очистка кэша моделей сразу после каждого успешного ответа /enhance. +TRIM_AFTER_EACH = env_flag('PHOTO_AI_TRIM_AFTER_EACH', False) OUTPUT_FORMATS = { 'jpg': ('jpg', 'image/jpeg', [int(cv2.IMWRITE_JPEG_QUALITY)]), @@ -425,6 +431,22 @@ class ModelPool: self.loading = OrderedDict() self.in_use = {} self.limit = limit + self.last_active = time.monotonic() + self.unloaded_by_idle = False + self.idle_thread = None + + def touch(self): + with self.lock: + self.last_active = time.monotonic() + self.unloaded_by_idle = False + + def idle_for(self): + with self.lock: + return time.monotonic() - self.last_active + + def idle_unloaded(self): + with self.lock: + return self.unloaded_by_idle def get(self, key, label, factory): with self.lock: @@ -484,6 +506,38 @@ class ModelPool: self.entries.clear() self.in_use.clear() + def unload_all(self): + """Полностью выгружает все модели и возвращает память/VRAM системе.""" + with self.lock: + self.entries.clear() + self.in_use.clear() + self.unloaded_by_idle = True + gc.collect() + try: + if state['device'].startswith('cuda'): + torch.cuda.synchronize() + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + except Exception as err: + log.warning('не удалось очистить кэш CUDA: %s', err) + log.info('все модели выгружены, память/VRAM возвращены системе') + + def trim(self): + """Выгружает всё, кроме моделей, которые используются прямо сейчас.""" + with self.lock: + removable = [key for key in list(self.entries) if not self.in_use.get(key)] + for key in removable: + self.entries.pop(key, None) + self.in_use.pop(key, None) + if removable: + gc.collect() + try: + if state['device'].startswith('cuda'): + torch.cuda.empty_cache() + except Exception as err: + log.warning('не удалось очистить кэш CUDA: %s', err) + log.info('выгружаю после запроса: %s', ', '.join(removable)) + def set_tile(self, tile): with self.lock: for entry in self.entries.values(): @@ -501,6 +555,37 @@ class ModelPool: with self.lock: return list(self.loading.values()) + def _idle_watch(self): + if not IDLE_UNLOAD_SEC: + return + while True: + time.sleep(IDLE_POLL_SEC) + if not IDLE_UNLOAD_SEC: + continue + try: + if self.idle_for() < IDLE_UNLOAD_SEC: + continue + if self.idle_unloaded() or not self.contains_any(): + # Уже выгружено или нечего выгружать — просто фиксируем флаг. + with self.lock: + self.unloaded_by_idle = True + continue + self.unload_all() + except Exception as err: + log.warning('idle-выгрузка не удалась: %s', err) + + def contains_any(self): + with self.lock: + return bool(self.entries) + + def start_idle_watch(self): + if not IDLE_UNLOAD_SEC or (self.idle_thread and self.idle_thread.is_alive()): + return + self.idle_thread = threading.Thread(target=self._idle_watch, name='photo-ai-idle-unload', + daemon=True) + self.idle_thread.start() + log.info('idle-выгрузка включена: через %d с простоя', IDLE_UNLOAD_SEC) + pool = ModelPool() @@ -672,6 +757,7 @@ def degrade_to_cpu(warnings): def run_guarded(img, outscale, model_name, face, face_name, strength, warnings): + pool.touch() with INFER_LOCK: start_tile = state['tile'] try: @@ -797,6 +883,7 @@ async def startup(): log.info('устройство: %s (%s), half=%s, tile=%s, веса: %s', state['device'], state['device_name'], state['half'], state['tile'], WEIGHTS_DIR) threading.Thread(target=preload, name='photo-ai-preload', daemon=True).start() + pool.start_idle_watch() @app.get('/health') @@ -817,6 +904,10 @@ def health(): 'loaded': pool.loaded_labels(), 'loading': pool.loading_labels(), 'max_pixels': MAX_PIXELS, + 'idle_unloaded': pool.idle_unloaded(), + 'idle_unload_after_sec': IDLE_UNLOAD_SEC, + 'last_active_ago_sec': round(pool.idle_for()), + 'trim_after_each': TRIM_AFTER_EACH, } @@ -907,6 +998,12 @@ async def enhance(request: Request, if face_mode != 'off' and not faces_found: warnings.append('лица не найдены, фон обработан апскейлом') elapsed_ms = int((time.time() - started) * 1000) + if TRIM_AFTER_EACH: + # Возвращаем VRAM/RAM сразу после обработки, не дожидаясь idle-таймаута. + try: + pool.trim() + except Exception as err: + log.warning('форс-очистка после запроса не удалась: %s', err) if wants_json(request): return { 'ok': True, diff --git a/public/admin.js b/public/admin.js index 40533b0..b4efb8a 100644 --- a/public/admin.js +++ b/public/admin.js @@ -60,6 +60,7 @@ function buildSidebar(active) { { page: 'photos', label: 'Фото', icon: 'Image' }, { page: 'files', label: 'Файлы', icon: 'folder' }, { page: 'links', label: 'Ссылки', icon: 'link' }, + { page: 'bookmarks', label: 'Закладки', icon: 'bookmark' }, { page: 'trash', label: 'Корзина', icon: 'trash-2' }, { page: 'notes', label: 'Заметки', icon: 'sticky-note' }, ]; diff --git a/public/bookmarks.html b/public/bookmarks.html new file mode 100644 index 0000000..893abfe --- /dev/null +++ b/public/bookmarks.html @@ -0,0 +1,146 @@ + + + + + + Закладки — Админ-панель + + + + +
+ +
+
+

Закладки

+

Полезные ссылки для команды

+ +
+
+ +
+
+
+
+ + + +
+ + + + + + + diff --git a/public/groups.html b/public/groups.html index f35d54d..e89306f 100644 --- a/public/groups.html +++ b/public/groups.html @@ -216,6 +216,10 @@ + + diff --git a/public/index.html b/public/index.html index 879ebca..f80950e 100644 --- a/public/index.html +++ b/public/index.html @@ -81,6 +81,33 @@ nav{position:fixed;top:16px;right:16px;display:flex;gap:8px} nav a{color:var(--muted);text-decoration:none;font-size:.8rem;padding:6px 12px;border-radius:8px;transition:color .15s} nav a:hover{color:var(--text)} +.bm-fab{position:fixed;right:24px;bottom:24px;z-index:150;display:flex;-webkit-tap-highlight-color:transparent} +.bm-fab[hidden]{display:none} +.bm-btn{width:52px;height:52px;border-radius:50%;border:1px solid var(--accent);background:var(--accent);color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 10px 24px rgba(37,99,235,.32);transition:opacity .15s} +.bm-btn:hover{opacity:.88} +.bm-btn svg{width:22px;height:22px} +.bm-modal{z-index:160} +.bm-modal-box{background:var(--card);border-radius:16px;padding:20px;width:92%;max-width:760px;max-height:86vh;display:flex;flex-direction:column;gap:14px;overflow:hidden} +.bm-modal-head{display:flex;align-items:center;justify-content:flex-end;gap:8px} +.bm-close{background:none;border:none;color:var(--muted);cursor:pointer;font-size:1rem;line-height:1;padding:4px 8px;border-radius:8px} +.bm-close:hover{color:var(--text);background:var(--bg)} +.bm-modal-body{overflow-y:auto;display:flex;flex-direction:column;gap:22px;padding-right:4px} +.bm-section{display:flex;flex-direction:column} +.bm-covers{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:14px} +.bm-cover-card{display:flex;flex-direction:column;border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;text-decoration:none;color:var(--text);background:var(--card);transition:border-color .15s,box-shadow .15s} +.bm-cover-card:hover{border-color:var(--accent);box-shadow:0 8px 20px rgba(0,0,0,.08)} +.bm-cover-img{width:100%;height:150px;object-fit:cover;display:block;background:var(--bg)} +.bm-cover-body{padding:10px 12px;display:flex;flex-direction:column;gap:3px;min-width:0} +.bm-cover-name{font-size:.9rem;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.bm-host{font-size:.72rem;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.bm-logos{display:flex;flex-wrap:wrap;justify-content:center;gap:16px} +.bm-logo-card{display:flex;flex-direction:column;align-items:center;gap:8px;width:104px;text-decoration:none;color:var(--text)} +.bm-logo-img{width:56px;height:56px;border-radius:12px;object-fit:cover;border:1px solid var(--border);background:var(--bg)} +.bm-logo-ph{width:56px;height:56px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:var(--muted);background:rgba(127,127,127,.12)} +.bm-logo-ph svg{width:22px;height:22px} +.bm-logo-name{font-size:.78rem;text-align:center;line-height:1.3;word-break:break-word} +@media(max-width:760px){.bm-fab{right:16px;bottom:16px}.bm-modal-box{padding:16px;max-height:90vh}} + .modal{position:fixed;inset:0;background:rgba(0,0,0,.7);display:flex;align-items:center;justify-content:center;z-index:100;display:none} .modal.open{display:flex} .modal-box{background:var(--card);border-radius:16px;padding:16px;max-width:400px;width:90%;display:flex;flex-direction:column;gap:12px} @@ -184,6 +211,21 @@ nav a:hover{color:var(--text)}
Готово!
+ + + + diff --git a/public/js/bookmarks.js b/public/js/bookmarks.js new file mode 100644 index 0000000..02ad238 --- /dev/null +++ b/public/js/bookmarks.js @@ -0,0 +1,433 @@ +(async function() { + 'use strict'; + let bookmarks = []; + let editingId = null; + let dragId = null; + let saving = false; + let bookmarkPhotoDeleteFlag = false; + let bookmarkPhotoLimitMb = 50; + let bSearchTimer = null; + + function esc(s) { + return String(s || '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + } + + function fullSrc(p) { + if (!p) return p; + if (/^https?:\/\//i.test(p)) return p; + return API + p; + } + + function hostOf(url) { + try { return new URL(url).host; } catch (e) { return url; } + } + + function sortByType(list) { + const covers = []; + const logos = []; + list.forEach(function (b) { + if (b.image_mode === 'cover') covers.push(b); + else logos.push(b); + }); + return covers.concat(logos); + } + + function bookmarkPhotoHint() { + return `jpg, png, gif, webp, avif, heic и др., до ${bookmarkPhotoLimitMb} МБ · или вставьте из буфера (Ctrl+V)`; + } + + function bookmarkCardHtml(b) { + const admin = isAdmin(); + const hidden = !b.is_active; + const target = b.open_new_tab ? '_blank' : '_self'; + const relAttr = b.open_new_tab ? ' rel="noopener noreferrer"' : ''; + const mode = b.image_mode === 'cover' ? 'cover' : 'logo'; + + let mediaHtml = ''; + if (b.photo_path) { + mediaHtml = mode === 'cover' + ? '' + : ''; + } else if (mode === 'logo') { + mediaHtml = ''; + } + + const body = + '
' + + '
' + + (admin ? '⠿' : '') + + '
' + esc(b.title) + '
' + + (hidden ? 'Скрыта' : '') + + '
' + + (b.description ? '
' + esc(b.description) + '
' : '') + + '
' + + '' + esc(hostOf(b.url)) + '' + + '
' + + '' + + (admin + ? '' + + '' + + '' + : '') + + '
' + + '
' + + '
'; + + const inner = mode === 'cover' + ? mediaHtml + body + : '
' + mediaHtml + body + '
'; + + return '
' + inner + '
'; + } + + function renderBookmarks() { + const el = document.getElementById('bookmarksList'); + if (!el) return; + if (!bookmarks.length) { + el.innerHTML = '
Закладок пока нет.
'; + return; + } + el.innerHTML = bookmarks.map(bookmarkCardHtml).join(''); + renderIcons(); + } + + function openBookmark(id) { + const b = bookmarks.find(function (x) { return x.id === id; }); + if (!b || !b.url) return; + if (b.open_new_tab) window.open(b.url, '_blank', 'noopener,noreferrer'); + else location.href = b.url; + } + + async function persistBookmarkOrder() { + const els = Array.prototype.slice.call(document.querySelectorAll('#bookmarksList .bookmark-card')); + const order = els.map(function (el) { return parseInt(el.dataset.id, 10); }); + if (JSON.stringify(order) === JSON.stringify(bookmarks.map(function (b) { return b.id; }))) return; + let res; + try { + res = await fetch(API + '/api/bookmarks/reorder', { + method: 'PUT', + headers: hdrJson(), + body: JSON.stringify({ ids: order }) + }); + } catch (e) { + showToast('Ошибка сети', true); + renderBookmarks(); + return; + } + if (!res.ok) { + const data = await res.json().catch(function () { return {}; }); + showToast(data.error || 'Не удалось сохранить порядок закладок', true); + renderBookmarks(); + return; + } + bookmarks = order.map(function (id) { + return bookmarks.find(function (b) { return b.id === id; }); + }).filter(Boolean); + showToast('Порядок закладок сохранён'); + } + + function bindDrag() { + const list = document.getElementById('bookmarksList'); + if (!list) return; + list.addEventListener('dragstart', function (e) { + const handle = e.target.closest('.bookmark-drag'); + if (!handle) { e.preventDefault(); return; } + const card = handle.closest('.bookmark-card'); + if (!card) return; + dragId = parseInt(card.dataset.id, 10); + card.classList.add('dragging'); + e.dataTransfer.effectAllowed = 'move'; + e.dataTransfer.setData('text/plain', String(dragId)); + try { e.dataTransfer.setDragImage(card, 24, 24); } catch (err) {} + }); + list.addEventListener('dragover', function (e) { + if (dragId == null) return; + e.preventDefault(); + e.dataTransfer.dropEffect = 'move'; + const target = e.target.closest('.bookmark-card'); + const dragged = list.querySelector('.bookmark-card[data-id="' + dragId + '"]'); + if (!target || !dragged || target === dragged || target.contains(dragged)) return; + const rect = target.getBoundingClientRect(); + list.insertBefore(dragged, e.clientX > rect.left + rect.width / 2 ? target.nextSibling : target); + }); + list.addEventListener('dragend', function (e) { + const card = e.target.closest('.bookmark-card'); + if (card) card.classList.remove('dragging'); + if (dragId != null) persistBookmarkOrder(); + dragId = null; + }); + list.addEventListener('drop', function (e) { e.preventDefault(); }); + } + + function resetBookmarkPhoto(b) { + bookmarkPhotoDeleteFlag = false; + const fileInput = document.getElementById('bookmarkPhotoFile'); + const preview = document.getElementById('bookmarkPhotoPreview'); + const delBtn = document.getElementById('bookmarkPhotoDeleteBtn'); + const note = document.getElementById('bookmarkPhotoNote'); + fileInput.value = ''; + if (b && b.photo_path) { + preview.src = thumbSrc(b.photo_path); + preview.style.display = 'block'; + delBtn.style.display = 'inline-block'; + note.textContent = 'Загрузка новой картинки заменит текущую'; + } else { + preview.removeAttribute('src'); + preview.style.display = 'none'; + delBtn.style.display = 'none'; + note.textContent = bookmarkPhotoHint(); + } + } + + function previewBookmarkPhotoFile() { + const file = document.getElementById('bookmarkPhotoFile').files[0]; + const preview = document.getElementById('bookmarkPhotoPreview'); + const delBtn = document.getElementById('bookmarkPhotoDeleteBtn'); + const note = document.getElementById('bookmarkPhotoNote'); + if (!file) return; + bookmarkPhotoDeleteFlag = false; + preview.src = URL.createObjectURL(file); + preview.style.display = 'block'; + delBtn.style.display = 'none'; + note.textContent = 'Новая картинка будет сохранена после нажатия «Сохранить»'; + } + + function removeBookmarkPhoto() { + const preview = document.getElementById('bookmarkPhotoPreview'); + const delBtn = document.getElementById('bookmarkPhotoDeleteBtn'); + const note = document.getElementById('bookmarkPhotoNote'); + if (!confirm('Удалить картинку закладки?')) return; + bookmarkPhotoDeleteFlag = true; + document.getElementById('bookmarkPhotoFile').value = ''; + preview.removeAttribute('src'); + preview.style.display = 'none'; + delBtn.style.display = 'none'; + note.textContent = 'Картинка будет удалена после нажатия «Сохранить»'; + } + + function pasteBookmarkPhotoFile(e) { + const modal = document.getElementById('bookmarkModal'); + if (!modal || !modal.classList.contains('open')) return; + const items = e.clipboardData && e.clipboardData.items; + if (!items) return; + for (const item of items) { + if (item.type && item.type.startsWith('image/')) { + const file = item.getAsFile(); + if (!file) continue; + e.preventDefault(); + const dt = new DataTransfer(); + dt.items.add(file); + const input = document.getElementById('bookmarkPhotoFile'); + input.files = dt.files; + previewBookmarkPhotoFile(); + return; + } + } + } + + function openBookmarkModal(b) { + editingId = b ? b.id : null; + document.getElementById('bookmarkModalTitle').textContent = b ? 'Редактировать закладку' : 'Новая закладка'; + document.getElementById('bookmarkTitle').value = b ? (b.title || '') : ''; + document.getElementById('bookmarkUrl').value = b ? (b.url || '') : ''; + document.getElementById('bookmarkDescription').value = b ? (b.description || '') : ''; + document.getElementById('bookmarkImageMode').value = b && b.image_mode === 'cover' ? 'cover' : 'logo'; + document.getElementById('bookmarkOpenNewTab').checked = b ? !!b.open_new_tab : true; + resetBookmarkPhoto(b); + document.getElementById('bookmarkModal').classList.add('open'); + renderIcons(); + setTimeout(function () { document.getElementById('bookmarkTitle').focus(); }, 50); + } + + function closeBookmarkModal() { + const m = document.getElementById('bookmarkModal'); + if (m) m.classList.remove('open'); + editingId = null; + } + + async function saveBookmark() { + const title = document.getElementById('bookmarkTitle').value.trim(); + const url = document.getElementById('bookmarkUrl').value.trim(); + const description = document.getElementById('bookmarkDescription').value.trim(); + const image_mode = document.getElementById('bookmarkImageMode').value === 'cover' ? 'cover' : 'logo'; + const open_new_tab = document.getElementById('bookmarkOpenNewTab').checked; + if (!title) { showToast('Введите заголовок', true); return; } + if (!/^https?:\/\//i.test(url)) { showToast('Ссылка должна начинаться с http:// или https://', true); return; } + if (saving) return; + const payload = { title: title, url: url, description: description, image_mode: image_mode, open_new_tab: open_new_tab }; + let res; + saving = true; + try { + if (editingId) { + const cur = bookmarks.find(function (b) { return b.id === editingId; }); + const body = Object.assign({}, payload, { is_active: cur ? !!cur.is_active : true }); + res = await fetch(API + '/api/bookmarks/' + editingId, { method: 'PUT', headers: hdrJson(), body: JSON.stringify(body) }); + } else { + res = await fetch(API + '/api/bookmarks', { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload) }); + } + } catch (e) { + saving = false; + showToast('Ошибка сети', true); + return; + } + saving = false; + const data = await res.json().catch(function () { return {}; }); + if (!res.ok) { + showToast(data.error || 'Ошибка при сохранении', true); + return; + } + const item = data.item || data; + const id = editingId || item.id; + if (!id) { + showToast('Не удалось определить id закладки', true); + closeBookmarkModal(); + loadBookmarks(); + return; + } + if (bookmarkPhotoDeleteFlag) { + await fetch(API + '/api/bookmarks/' + id + '/photo', { method: 'DELETE', headers: hdr() }); + } + const file = document.getElementById('bookmarkPhotoFile').files[0]; + if (file) { + const fd = new FormData(); + fd.append('photo', file); + await fetch(API + '/api/bookmarks/' + id + '/photo', { method: 'POST', headers: hdr(), body: fd }); + } + showToast(editingId ? 'Закладка обновлена' : 'Закладка создана'); + closeBookmarkModal(); + loadBookmarks(); + } + + async function toggleBookmark(id) { + const b = bookmarks.find(function (x) { return x.id === id; }); + if (!b) return; + let res; + try { + res = await fetch(API + '/api/bookmarks/' + id, { + method: 'PUT', + headers: hdrJson(), + body: JSON.stringify({ + title: b.title, + url: b.url, + description: b.description || '', + image_mode: b.image_mode === 'cover' ? 'cover' : 'logo', + open_new_tab: !!b.open_new_tab, + is_active: !b.is_active + }) + }); + } catch (e) { + showToast('Ошибка сети', true); + return; + } + const data = await res.json().catch(function () { return {}; }); + if (!res.ok) { + showToast(data.error || 'Ошибка при сохранении', true); + return; + } + b.is_active = !b.is_active; + renderBookmarks(); + showToast(b.is_active ? 'Закладка показана' : 'Закладка скрыта'); + } + + async function removeBookmark(id) { + if (!confirm('Удалить эту закладку?')) return; + let res; + try { + res = await fetch(API + '/api/bookmarks/' + id, { method: 'DELETE', headers: hdr() }); + } catch (e) { + showToast('Ошибка сети', true); + return; + } + const data = await res.json().catch(function () { return {}; }); + if (!res.ok) { + showToast(data.error || 'Ошибка при удалении', true); + return; + } + bookmarks = bookmarks.filter(function (b) { return b.id !== id; }); + renderBookmarks(); + showToast('Закладка удалена'); + } + + async function loadBookmarks() { + const p = new URLSearchParams(); + const q = document.getElementById('bookmarkSearch').value.trim(); + if (q) p.set('search', q); + let res; + try { + res = await fetch(API + '/api/bookmarks' + (p.toString() ? '?' + p.toString() : ''), { headers: hdr() }); + } catch (e) { + showToast('Ошибка сети при загрузке закладок', true); + return; + } + if (!res.ok) return; + const data = await res.json().catch(function () { return {}; }); + bookmarks = sortByType(data.items || []); + renderBookmarks(); + } + + function bindModal() { + document.getElementById('bookmarkModalClose').addEventListener('click', closeBookmarkModal); + document.getElementById('bookmarkCancel').addEventListener('click', closeBookmarkModal); + document.getElementById('bookmarkSave').addEventListener('click', saveBookmark); + document.getElementById('bookmarkPhotoFile').addEventListener('change', previewBookmarkPhotoFile); + document.getElementById('bookmarkPhotoDeleteBtn').addEventListener('click', removeBookmarkPhoto); + document.getElementById('bookmarkModal').addEventListener('click', function (e) { + if (e.target === e.currentTarget) closeBookmarkModal(); + }); + document.addEventListener('paste', pasteBookmarkPhotoFile); + document.addEventListener('keydown', function (e) { + const m = document.getElementById('bookmarkModal'); + const open = m && m.classList.contains('open'); + if (e.key === 'Escape' && open) closeBookmarkModal(); + }); + } + + function bindPage() { + document.getElementById('bookmarkSearch').addEventListener('input', function () { + clearTimeout(bSearchTimer); + bSearchTimer = setTimeout(loadBookmarks, 300); + }); + document.addEventListener('click', async function (e) { + const actEl = e.target.closest('[data-action]'); + if (actEl) { + const action = actEl.dataset.action; + const id = parseInt(actEl.dataset.id, 10); + if (action === 'edit') { + const b = bookmarks.find(function (x) { return x.id === id; }); + if (b) openBookmarkModal(b); + return; + } + if (action === 'toggle') { await toggleBookmark(id); return; } + if (action === 'delete') { await removeBookmark(id); return; } + return; + } + if (e.target.closest('#bookmarksNewBtn')) { openBookmarkModal(null); return; } + if (e.target.closest('a')) return; + if (e.target.closest('.bookmark-drag')) return; + const card = e.target.closest('.bookmark-card'); + if (card) openBookmark(parseInt(card.dataset.id, 10)); + }); + } + + async function init() { + if (!(await checkAuth())) return; + buildSidebar(document.body.dataset.page); + if (!isAdmin()) { + const nb = document.getElementById('bookmarksNewBtn'); + if (nb) nb.style.display = 'none'; + } + try { + const res = await fetch(API + '/api/public-settings'); + const f = await res.json(); + const n = parseInt(f.upload_file_limit_mb, 10); + if (Number.isFinite(n) && n >= 1) bookmarkPhotoLimitMb = n; + } catch (e) {} + bindModal(); + bindPage(); + if (isAdmin()) bindDrag(); + renderIcons(); + await loadBookmarks(); + } + + init(); +})(); diff --git a/public/js/groups.js b/public/js/groups.js index 6009aff..e69e20d 100644 --- a/public/js/groups.js +++ b/public/js/groups.js @@ -37,7 +37,7 @@ async function loadGroups() { return `
${g.cover_path - ? `` + ? `` : `
📷
`}
@@ -435,10 +435,11 @@ function updateGroupCoverUI(coverPath) { if (!card) return; const g = allGroups.find(x => String(x.id) === String(currentGroupId)); const existing = card.querySelector('.group-cover'); - if (existing && existing.tagName === 'IMG') { existing.src = API + coverPath; return; } + if (existing && existing.tagName === 'IMG') { existing.src = API + coverPath; existing.dataset.img = API + coverPath; return; } const el = document.createElement('img'); el.className = 'group-cover'; el.src = API + coverPath; + el.dataset.img = API + coverPath; el.alt = ''; if (existing) existing.replaceWith(el); else card.insertBefore(el, card.firstChild); @@ -1239,6 +1240,7 @@ document.getElementById('photoHistoryCloseBtn')?.addEventListener('click', () => document.getElementById('photoHistoryModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) e.currentTarget.classList.remove('open'); }); +document.getElementById('imgModal')?.addEventListener('click', e => e.currentTarget.classList.remove('open')); document.getElementById('photoHistoryList')?.addEventListener('click', e => { const rollbackBtn = e.target.closest('[data-job-rollback]'); if (rollbackBtn) { rollbackPhotoJob(parseInt(rollbackBtn.dataset.jobRollback, 10)); return; } diff --git a/public/js/index.js b/public/js/index.js index d776589..498fe53 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -471,4 +471,126 @@ moduleInput.addEventListener('input', () => { }); moduleInput.addEventListener('focus', async () => { if (!moduleInput.value.trim()) renderModuleOptions(await fetchModules('', 50)); -}); \ No newline at end of file +}); + +(async () => { + const fab = document.getElementById('bmFab'); + const btn = document.getElementById('bmBtn'); + const modal = document.getElementById('bmModal'); + const body = document.getElementById('bmModalBody'); + const closeBtn = document.getElementById('bmClose'); + if (!fab || !btn || !modal || !body || !closeBtn) return; + const authToken = sessionStorage.getItem('authToken'); + if (!authToken) return; + let items = []; + try { + const res = await fetch(`${API}/api/bookmarks`, { headers: { 'X-Auth-Token': authToken } }); + if (!res.ok) return; + const data = await res.json(); + items = Array.isArray(data.items) ? data.items : []; + } catch (e) { return; } + if (!items.length) return; + + function fullSrc(p) { + if (!p) return p; + if (/^https?:\/\//i.test(p)) return p; + return API + p; + } + function logoSrc(p) { + if (!p) return p; + if (p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`; + if (p.includes('/api/files/')) return p + (p.includes('?') ? '&' : '?') + 'thumb=1'; + return p; + } + function hostOf(url) { + try { return new URL(url, location.origin).host; } catch (e) { return ''; } + } + function linkFor(b) { + const a = document.createElement('a'); + a.href = b.url; + if (b.open_new_tab) { a.target = '_blank'; a.rel = 'noopener noreferrer'; } + return a; + } + function nameEl(b, cls) { + const n = document.createElement('span'); + n.className = cls; + n.textContent = b.title || b.url; + return n; + } + + const covers = items.filter(b => b.image_mode === 'cover'); + const logos = items.filter(b => b.image_mode !== 'cover'); + + if (covers.length) { + const section = document.createElement('div'); + section.className = 'bm-section'; + const grid = document.createElement('div'); + grid.className = 'bm-covers'; + covers.forEach(b => { + const a = linkFor(b); + a.className = 'bm-cover-card'; + if (b.photo_path) { + const img = document.createElement('img'); + img.className = 'bm-cover-img'; + img.src = fullSrc(b.photo_path); + img.alt = ''; + img.loading = 'lazy'; + a.appendChild(img); + } + const info = document.createElement('div'); + info.className = 'bm-cover-body'; + info.appendChild(nameEl(b, 'bm-cover-name')); + const host = hostOf(b.url); + if (host) { + const h = document.createElement('span'); + h.className = 'bm-host'; + h.textContent = host; + info.appendChild(h); + } + a.appendChild(info); + grid.appendChild(a); + }); + section.append(grid); + body.appendChild(section); + } + + if (logos.length) { + const section = document.createElement('div'); + section.className = 'bm-section'; + const row = document.createElement('div'); + row.className = 'bm-logos'; + logos.forEach(b => { + const a = linkFor(b); + a.className = 'bm-logo-card'; + if (b.photo_path) { + const img = document.createElement('img'); + img.className = 'bm-logo-img'; + img.src = logoSrc(b.photo_path); + img.alt = ''; + img.loading = 'lazy'; + a.appendChild(img); + } else { + const ph = document.createElement('span'); + ph.className = 'bm-logo-ph'; + ph.innerHTML = ''; + a.appendChild(ph); + } + a.appendChild(nameEl(b, 'bm-logo-name')); + row.appendChild(a); + }); + section.append(row); + body.appendChild(section); + } + + fab.hidden = false; + + function setOpen(open) { + modal.classList.toggle('open', open); + modal.setAttribute('aria-hidden', open ? 'false' : 'true'); + btn.setAttribute('aria-expanded', open ? 'true' : 'false'); + } + btn.addEventListener('click', () => setOpen(!modal.classList.contains('open'))); + closeBtn.addEventListener('click', () => setOpen(false)); + modal.addEventListener('click', (e) => { if (e.target === modal) setOpen(false); }); + document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && modal.classList.contains('open')) setOpen(false); }); +})(); \ No newline at end of file diff --git a/server.js b/server.js index 6511988..4350896 100644 --- a/server.js +++ b/server.js @@ -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)',