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:
@@ -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()` для отката визуала
|
- **Сохранение порядка**: `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
|
- **Бэкап**: `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/<name>`), `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
|
### 4. API Patterns
|
||||||
@@ -422,6 +431,8 @@ guards against.
|
|||||||
| `public/feedback.html` | Страница обратной связи (отзывы тьютора) |
|
| `public/feedback.html` | Страница обратной связи (отзывы тьютора) |
|
||||||
| `public/notes.html` | Заметки: сетка карточек 4 в ряд, инлайн-стили `.note-*`, модалка редактирования |
|
| `public/notes.html` | Заметки: сетка карточек 4 в ряд, инлайн-стили `.note-*`, модалка редактирования |
|
||||||
| `public/js/notes.js` | Заметки: рендер карточек, CRUD, drag-and-drop порядок (`bindDrag`/`persistNoteOrder`) |
|
| `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, ИИ-очередь |
|
| `public/js/feedback.js` | Логика обратной связи: список, модалка, выбор short_messages, ИИ-очередь |
|
||||||
| `scripts/backup.sh` | Host-level backup script (DB dump + storage export) |
|
| `scripts/backup.sh` | Host-level backup script (DB dump + storage export) |
|
||||||
| `scripts/restore.sh` | Host-level restore script (DB dump + storage import) |
|
| `scripts/restore.sh` | Host-level restore script (DB dump + storage import) |
|
||||||
|
|||||||
+16
-3
@@ -9,13 +9,13 @@ const BACKUP_TABLES = [
|
|||||||
'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs',
|
'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs',
|
||||||
'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications',
|
'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications',
|
||||||
'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments',
|
'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments',
|
||||||
'short_messages', 'feedbacks',
|
'short_messages', 'feedbacks', 'bookmarks',
|
||||||
];
|
];
|
||||||
const BACKUP_SEQUENCE_TABLES = [
|
const BACKUP_SEQUENCE_TABLES = [
|
||||||
'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos',
|
'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos',
|
||||||
'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports',
|
'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports',
|
||||||
'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages',
|
'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages',
|
||||||
'chat_attachments', 'short_messages', 'feedbacks',
|
'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks',
|
||||||
];
|
];
|
||||||
|
|
||||||
function isSupportedBackupVersion(data) {
|
function isSupportedBackupVersion(data) {
|
||||||
@@ -571,7 +571,20 @@ function normalizeRestoreData(data) {
|
|||||||
created_at: optTs(x.created_at),
|
created_at: optTs(x.created_at),
|
||||||
updated_at: optTs(x.updated_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 = {
|
module.exports = {
|
||||||
|
|||||||
@@ -137,5 +137,19 @@ throws('notifications не массив отклоняется', () => normalize
|
|||||||
const legacy = normalizeRestoreData({ version: 1, groups: [{ id: 1, name: 'G' }] });
|
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('старый архив без новых таблиц восстанавливается', 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');
|
console.log(failed ? `\n${failed} проверок провалено` : '\nBACKUP SELFTEST OK');
|
||||||
process.exit(failed ? 1 : 0);
|
process.exit(failed ? 1 : 0);
|
||||||
+15
@@ -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 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 (
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
|||||||
@@ -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';
|
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;
|
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 (
|
CREATE TABLE IF NOT EXISTS api_keys (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
|||||||
@@ -216,6 +216,10 @@ services:
|
|||||||
PHOTO_AI_FACE_MODEL: ${PHOTO_AI_FACE_MODEL:-gfpgan}
|
PHOTO_AI_FACE_MODEL: ${PHOTO_AI_FACE_MODEL:-gfpgan}
|
||||||
PHOTO_AI_LOAD_ALL: ${PHOTO_AI_LOAD_ALL:-0}
|
PHOTO_AI_LOAD_ALL: ${PHOTO_AI_LOAD_ALL:-0}
|
||||||
PHOTO_AI_JPEG_QUALITY: ${PHOTO_AI_JPEG_QUALITY:-92}
|
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
|
HF_HOME: /root/.cache/huggingface
|
||||||
TORCH_HOME: /root/.cache/torch
|
TORCH_HOME: /root/.cache/torch
|
||||||
TRANSFORMERS_CACHE: /root/.cache/huggingface
|
TRANSFORMERS_CACHE: /root/.cache/huggingface
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import base64
|
import base64
|
||||||
|
import gc
|
||||||
import importlib.util
|
import importlib.util
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
@@ -42,6 +43,7 @@ MIN_FACE_SIDE = 320
|
|||||||
POOL_LIMIT = 2
|
POOL_LIMIT = 2
|
||||||
WARMUP_SIZE = 64
|
WARMUP_SIZE = 64
|
||||||
RETRY_AFTER_SEC = 5
|
RETRY_AFTER_SEC = 5
|
||||||
|
IDLE_POLL_SEC = 5
|
||||||
|
|
||||||
|
|
||||||
def env_text(name, default=''):
|
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)
|
WARMUP = env_flag('PHOTO_AI_WARMUP', True)
|
||||||
DEFAULT_FACE_MODEL = env_text('PHOTO_AI_FACE_MODEL', 'gfpgan').lower()
|
DEFAULT_FACE_MODEL = env_text('PHOTO_AI_FACE_MODEL', 'gfpgan').lower()
|
||||||
DEFAULT_JPEG_QUALITY = clamp(env_int('PHOTO_AI_JPEG_QUALITY', 92), 70, 100)
|
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 = {
|
OUTPUT_FORMATS = {
|
||||||
'jpg': ('jpg', 'image/jpeg', [int(cv2.IMWRITE_JPEG_QUALITY)]),
|
'jpg': ('jpg', 'image/jpeg', [int(cv2.IMWRITE_JPEG_QUALITY)]),
|
||||||
@@ -425,6 +431,22 @@ class ModelPool:
|
|||||||
self.loading = OrderedDict()
|
self.loading = OrderedDict()
|
||||||
self.in_use = {}
|
self.in_use = {}
|
||||||
self.limit = limit
|
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):
|
def get(self, key, label, factory):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
@@ -484,6 +506,38 @@ class ModelPool:
|
|||||||
self.entries.clear()
|
self.entries.clear()
|
||||||
self.in_use.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):
|
def set_tile(self, tile):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
for entry in self.entries.values():
|
for entry in self.entries.values():
|
||||||
@@ -501,6 +555,37 @@ class ModelPool:
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
return list(self.loading.values())
|
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()
|
pool = ModelPool()
|
||||||
|
|
||||||
@@ -672,6 +757,7 @@ def degrade_to_cpu(warnings):
|
|||||||
|
|
||||||
|
|
||||||
def run_guarded(img, outscale, model_name, face, face_name, strength, warnings):
|
def run_guarded(img, outscale, model_name, face, face_name, strength, warnings):
|
||||||
|
pool.touch()
|
||||||
with INFER_LOCK:
|
with INFER_LOCK:
|
||||||
start_tile = state['tile']
|
start_tile = state['tile']
|
||||||
try:
|
try:
|
||||||
@@ -797,6 +883,7 @@ async def startup():
|
|||||||
log.info('устройство: %s (%s), half=%s, tile=%s, веса: %s',
|
log.info('устройство: %s (%s), half=%s, tile=%s, веса: %s',
|
||||||
state['device'], state['device_name'], state['half'], state['tile'], WEIGHTS_DIR)
|
state['device'], state['device_name'], state['half'], state['tile'], WEIGHTS_DIR)
|
||||||
threading.Thread(target=preload, name='photo-ai-preload', daemon=True).start()
|
threading.Thread(target=preload, name='photo-ai-preload', daemon=True).start()
|
||||||
|
pool.start_idle_watch()
|
||||||
|
|
||||||
|
|
||||||
@app.get('/health')
|
@app.get('/health')
|
||||||
@@ -817,6 +904,10 @@ def health():
|
|||||||
'loaded': pool.loaded_labels(),
|
'loaded': pool.loaded_labels(),
|
||||||
'loading': pool.loading_labels(),
|
'loading': pool.loading_labels(),
|
||||||
'max_pixels': MAX_PIXELS,
|
'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:
|
if face_mode != 'off' and not faces_found:
|
||||||
warnings.append('лица не найдены, фон обработан апскейлом')
|
warnings.append('лица не найдены, фон обработан апскейлом')
|
||||||
elapsed_ms = int((time.time() - started) * 1000)
|
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):
|
if wants_json(request):
|
||||||
return {
|
return {
|
||||||
'ok': True,
|
'ok': True,
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ function buildSidebar(active) {
|
|||||||
{ page: 'photos', label: 'Фото', icon: 'Image' },
|
{ page: 'photos', label: 'Фото', icon: 'Image' },
|
||||||
{ page: 'files', label: 'Файлы', icon: 'folder' },
|
{ page: 'files', label: 'Файлы', icon: 'folder' },
|
||||||
{ page: 'links', label: 'Ссылки', icon: 'link' },
|
{ page: 'links', label: 'Ссылки', icon: 'link' },
|
||||||
|
{ page: 'bookmarks', label: 'Закладки', icon: 'bookmark' },
|
||||||
{ page: 'trash', label: 'Корзина', icon: 'trash-2' },
|
{ page: 'trash', label: 'Корзина', icon: 'trash-2' },
|
||||||
{ page: 'notes', label: 'Заметки', icon: 'sticky-note' },
|
{ page: 'notes', label: 'Заметки', icon: 'sticky-note' },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Закладки — Админ-панель</title>
|
||||||
|
<link rel="stylesheet" href="admin.css">
|
||||||
|
<style>
|
||||||
|
.bookmarks-list { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-top: 8px; align-items: stretch; }
|
||||||
|
@media (max-width: 1200px) { .bookmarks-list { grid-template-columns: repeat(3, 1fr); } }
|
||||||
|
@media (max-width: 900px) { .bookmarks-list { grid-template-columns: repeat(2, 1fr); } }
|
||||||
|
@media (max-width: 640px) { .bookmarks-list { grid-template-columns: 1fr; } }
|
||||||
|
.bookmark-card {
|
||||||
|
position: relative;
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
min-width: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: box-shadow .15s, transform .15s, opacity .15s;
|
||||||
|
}
|
||||||
|
.bookmark-card:hover { box-shadow: 0 8px 20px rgba(0,0,0,.08); }
|
||||||
|
.bookmark-card.dragging { opacity: .4; border-style: dashed; }
|
||||||
|
.bookmark-card.bookmark-hidden { opacity: .55; }
|
||||||
|
.bookmark-main { display: flex; gap: 12px; align-items: stretch; flex: 1; min-width: 0; }
|
||||||
|
.bookmark-body { display: flex; flex-direction: column; gap: 8px; min-width: 0; flex: 1; }
|
||||||
|
.bookmark-cover { width: 100%; height: 130px; object-fit: cover; border-radius: 10px; border: 1px solid var(--border); display: block; background: var(--bg); }
|
||||||
|
.bookmark-logo { width: 48px; height: 48px; border-radius: 10px; object-fit: cover; flex: none; border: 1px solid var(--border); background: var(--bg); }
|
||||||
|
.bookmark-logo-ph { width: 48px; height: 48px; border-radius: 10px; flex: none; display: inline-flex; align-items: center; justify-content: center; color: var(--muted); background: rgba(127,127,127,.12); }
|
||||||
|
.bookmark-logo-ph svg { width: 20px; height: 20px; }
|
||||||
|
.bookmark-title-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
|
||||||
|
.bookmark-title { font-weight: 600; font-size: .95rem; word-break: break-word; min-width: 0; }
|
||||||
|
.bookmark-badge { padding: 1px 8px; border-radius: 999px; font-size: .68rem; font-weight: 600; background: rgba(239,68,68,.12); color: #ef4444; }
|
||||||
|
.bookmark-desc { font-size: .85rem; color: var(--muted); line-height: 1.5; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||||
|
.bookmark-drag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
flex: none;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: .85rem;
|
||||||
|
cursor: grab;
|
||||||
|
border-radius: 6px;
|
||||||
|
transition: color .15s, background .15s;
|
||||||
|
}
|
||||||
|
.bookmark-drag:hover { color: var(--text); background: rgba(127,127,127,.15); }
|
||||||
|
.bookmark-drag:active { cursor: grabbing; }
|
||||||
|
.bookmark-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; border-top: 1px solid var(--border); padding-top: 10px; margin-top: auto; }
|
||||||
|
.bookmark-host { font-size: .75rem; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
|
||||||
|
.bookmark-actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||||
|
.bookmark-actions .btn-link { padding: 5px 10px; font-size: .75rem; }
|
||||||
|
.bookmark-actions .btn-link.danger { color: #ef4444; border-color: rgba(239,68,68,.35); }
|
||||||
|
.bookmark-actions .btn-link.danger:hover { border-color: #ef4444; }
|
||||||
|
.bookmark-link { display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg); color: var(--accent); text-decoration: none; transition: border-color .15s; }
|
||||||
|
.bookmark-link:hover { border-color: var(--accent); }
|
||||||
|
.bookmark-link svg { width: 14px; height: 14px; }
|
||||||
|
.bookmark-empty { text-align: center; color: var(--muted); padding: 32px 16px; font-size: .9rem; border: 1px dashed var(--border); border-radius: 12px; }
|
||||||
|
.bookmark-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||||
|
.bookmark-modal-head h3 { margin: 0; font-size: 1.05rem; }
|
||||||
|
.bookmark-check { display: flex; align-items: center; gap: 8px; font-size: .88rem; font-weight: 400; color: var(--text); cursor: pointer; }
|
||||||
|
.bookmark-photo-controls { display: flex; flex-direction: column; gap: 10px; align-items: flex-start; width: 100%; }
|
||||||
|
.bookmark-photo-preview { width: 100%; max-height: 180px; object-fit: contain; border: 1px solid var(--border); border-radius: 10px; background: var(--bg); }
|
||||||
|
.bookmark-photo-actions { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.bookmark-photo-pick { text-align: center; cursor: pointer; margin: 0; }
|
||||||
|
.bookmark-photo-actions .btn-link.danger { color: #ef4444; border-color: rgba(239,68,68,.35); }
|
||||||
|
.bookmark-photo-actions .btn-link.danger:hover { border-color: #ef4444; }
|
||||||
|
#bookmarkModal .hint { font-size: .78rem; color: var(--muted); line-height: 1.5; display: block; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body data-page="bookmarks">
|
||||||
|
<div class="layout">
|
||||||
|
<div class="sidebar" id="sidebar"></div>
|
||||||
|
<div class="main">
|
||||||
|
<div class="page-head">
|
||||||
|
<h2>Закладки</h2>
|
||||||
|
<p class="page-sub">Полезные ссылки для команды</p>
|
||||||
|
<button type="button" class="btn-primary" id="bookmarksNewBtn"><i data-lucide="plus"></i> Новая закладка</button>
|
||||||
|
</div>
|
||||||
|
<div class="actions-row" style="margin-bottom:16px">
|
||||||
|
<input type="text" id="bookmarkSearch" class="search-input" placeholder="Поиск по названию..." style="flex:1;min-width:200px;max-width:340px;padding:10px 14px;font-size:.9rem">
|
||||||
|
</div>
|
||||||
|
<div id="bookmarksList" class="bookmarks-list"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-overlay" id="bookmarkModal">
|
||||||
|
<div class="edit-modal" style="max-width:560px">
|
||||||
|
<div class="bookmark-modal-head">
|
||||||
|
<h3 id="bookmarkModalTitle">Новая закладка</h3>
|
||||||
|
<button type="button" class="icon-btn" id="bookmarkModalClose"><i data-lucide="x"></i></button>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Заголовок <span style="color:#ef4444">*</span></label>
|
||||||
|
<input id="bookmarkTitle" class="settings-input" maxlength="200" placeholder="Название закладки">
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Ссылка (URL) <span style="color:#ef4444">*</span></label>
|
||||||
|
<input id="bookmarkUrl" class="settings-input" maxlength="500" placeholder="https://example.com" autocomplete="off">
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Краткое описание</label>
|
||||||
|
<textarea id="bookmarkDescription" class="settings-input" rows="3" maxlength="500" placeholder="Необязательно"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Картинка</label>
|
||||||
|
<div class="bookmark-photo-controls">
|
||||||
|
<img id="bookmarkPhotoPreview" class="bookmark-photo-preview" alt="" style="display:none">
|
||||||
|
<div class="bookmark-photo-actions">
|
||||||
|
<label class="btn-primary ghost bookmark-photo-pick" for="bookmarkPhotoFile">Выбрать файл</label>
|
||||||
|
<input type="file" id="bookmarkPhotoFile" accept="image/*" style="display:none">
|
||||||
|
<button type="button" id="bookmarkPhotoDeleteBtn" class="btn-link danger" style="display:none">Удалить</button>
|
||||||
|
</div>
|
||||||
|
<span id="bookmarkPhotoNote" class="hint"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label>Режим картинки</label>
|
||||||
|
<select id="bookmarkImageMode" class="settings-input">
|
||||||
|
<option value="logo">Логотип (иконка)</option>
|
||||||
|
<option value="cover">Обложка</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="settings-field">
|
||||||
|
<label class="bookmark-check"><input type="checkbox" id="bookmarkOpenNewTab" checked> Открывать в новой вкладке</label>
|
||||||
|
</div>
|
||||||
|
<div class="card-foot">
|
||||||
|
<button type="button" class="btn-primary ghost" id="bookmarkCancel">Отмена</button>
|
||||||
|
<button type="button" class="btn-primary" id="bookmarkSave">Сохранить</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<script src="vendor/lucide.min.js"></script>
|
||||||
|
<script src="js/datetime.js"></script>
|
||||||
|
<script src="admin.js"></script>
|
||||||
|
<script src="js/bookmarks.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -216,6 +216,10 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-overlay" id="imgModal">
|
||||||
|
<img id="imgModalSrc">
|
||||||
|
</div>
|
||||||
|
|
||||||
<script src="vendor/lucide.min.js"></script>
|
<script src="vendor/lucide.min.js"></script>
|
||||||
<script src="js/datetime.js"></script>
|
<script src="js/datetime.js"></script>
|
||||||
<script src="admin.js"></script>
|
<script src="admin.js"></script>
|
||||||
|
|||||||
@@ -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{color:var(--muted);text-decoration:none;font-size:.8rem;padding:6px 12px;border-radius:8px;transition:color .15s}
|
||||||
nav a:hover{color:var(--text)}
|
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{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.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}
|
.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)}
|
|||||||
|
|
||||||
<div class="toast" id="toast">Готово!</div>
|
<div class="toast" id="toast">Готово!</div>
|
||||||
|
|
||||||
|
<div class="bm-fab" id="bmFab" hidden>
|
||||||
|
<button type="button" class="bm-btn" id="bmBtn" aria-label="Закладки" title="Закладки" aria-expanded="false">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal bm-modal" id="bmModal" aria-hidden="true">
|
||||||
|
<div class="bm-modal-box" role="dialog" aria-modal="true">
|
||||||
|
<div class="bm-modal-head">
|
||||||
|
<button type="button" class="bm-close" id="bmClose" aria-label="Закрыть">✕</button>
|
||||||
|
</div>
|
||||||
|
<div class="bm-modal-body" id="bmModalBody"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<script src="js/datetime.js"></script>
|
<script src="js/datetime.js"></script>
|
||||||
<script src="js/index.js"></script>
|
<script src="js/index.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -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, '"').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'
|
||||||
|
? '<img class="bookmark-cover" src="' + esc(fullSrc(b.photo_path)) + '" alt="">'
|
||||||
|
: '<img class="bookmark-logo" src="' + esc(thumbSrc(b.photo_path)) + '" alt="">';
|
||||||
|
} else if (mode === 'logo') {
|
||||||
|
mediaHtml = '<span class="bookmark-logo-ph"><i data-lucide="bookmark"></i></span>';
|
||||||
|
}
|
||||||
|
|
||||||
|
const body =
|
||||||
|
'<div class="bookmark-body">' +
|
||||||
|
'<div class="bookmark-title-row">' +
|
||||||
|
(admin ? '<span class="bookmark-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>' : '') +
|
||||||
|
'<div class="bookmark-title">' + esc(b.title) + '</div>' +
|
||||||
|
(hidden ? '<span class="bookmark-badge">Скрыта</span>' : '') +
|
||||||
|
'</div>' +
|
||||||
|
(b.description ? '<div class="bookmark-desc">' + esc(b.description) + '</div>' : '') +
|
||||||
|
'<div class="bookmark-foot">' +
|
||||||
|
'<span class="bookmark-host" title="' + esc(b.url) + '">' + esc(hostOf(b.url)) + '</span>' +
|
||||||
|
'<div class="bookmark-actions">' +
|
||||||
|
'<a class="bookmark-link" href="' + esc(b.url) + '" target="' + target + '"' + relAttr + ' title="Открыть ссылку"><i data-lucide="external-link"></i></a>' +
|
||||||
|
(admin
|
||||||
|
? '<button type="button" class="btn-link" data-action="edit" data-id="' + b.id + '">Изменить</button>' +
|
||||||
|
'<button type="button" class="btn-link" data-action="toggle" data-id="' + b.id + '">' + (b.is_active ? 'Скрыть' : 'Показать') + '</button>' +
|
||||||
|
'<button type="button" class="btn-link danger" data-action="delete" data-id="' + b.id + '">Удалить</button>'
|
||||||
|
: '') +
|
||||||
|
'</div>' +
|
||||||
|
'</div>' +
|
||||||
|
'</div>';
|
||||||
|
|
||||||
|
const inner = mode === 'cover'
|
||||||
|
? mediaHtml + body
|
||||||
|
: '<div class="bookmark-main">' + mediaHtml + body + '</div>';
|
||||||
|
|
||||||
|
return '<div class="bookmark-card' + (hidden ? ' bookmark-hidden' : '') + '" data-id="' + b.id + '">' + inner + '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBookmarks() {
|
||||||
|
const el = document.getElementById('bookmarksList');
|
||||||
|
if (!el) return;
|
||||||
|
if (!bookmarks.length) {
|
||||||
|
el.innerHTML = '<div class="bookmark-empty">Закладок пока нет.</div>';
|
||||||
|
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();
|
||||||
|
})();
|
||||||
+4
-2
@@ -37,7 +37,7 @@ async function loadGroups() {
|
|||||||
return `
|
return `
|
||||||
<div class="group-card" data-group-id="${g.id}">
|
<div class="group-card" data-group-id="${g.id}">
|
||||||
${g.cover_path
|
${g.cover_path
|
||||||
? `<img class="group-cover" src="${thumbSrc(g.cover_path)}" loading="lazy" decoding="async" alt="">`
|
? `<img class="group-cover" src="${thumbSrc(g.cover_path)}" data-img="${API}${g.cover_path}" loading="lazy" decoding="async" alt="">`
|
||||||
: `<div class="group-cover empty-cover">📷</div>`}
|
: `<div class="group-cover empty-cover">📷</div>`}
|
||||||
<div class="group-head">
|
<div class="group-head">
|
||||||
<input class="name-input" id="name-${g.id}" value="${esc(g.name)}">
|
<input class="name-input" id="name-${g.id}" value="${esc(g.name)}">
|
||||||
@@ -435,10 +435,11 @@ function updateGroupCoverUI(coverPath) {
|
|||||||
if (!card) return;
|
if (!card) return;
|
||||||
const g = allGroups.find(x => String(x.id) === String(currentGroupId));
|
const g = allGroups.find(x => String(x.id) === String(currentGroupId));
|
||||||
const existing = card.querySelector('.group-cover');
|
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');
|
const el = document.createElement('img');
|
||||||
el.className = 'group-cover';
|
el.className = 'group-cover';
|
||||||
el.src = API + coverPath;
|
el.src = API + coverPath;
|
||||||
|
el.dataset.img = API + coverPath;
|
||||||
el.alt = '';
|
el.alt = '';
|
||||||
if (existing) existing.replaceWith(el);
|
if (existing) existing.replaceWith(el);
|
||||||
else card.insertBefore(el, card.firstChild);
|
else card.insertBefore(el, card.firstChild);
|
||||||
@@ -1239,6 +1240,7 @@ document.getElementById('photoHistoryCloseBtn')?.addEventListener('click', () =>
|
|||||||
document.getElementById('photoHistoryModal')?.addEventListener('click', e => {
|
document.getElementById('photoHistoryModal')?.addEventListener('click', e => {
|
||||||
if (e.target === e.currentTarget) e.currentTarget.classList.remove('open');
|
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 => {
|
document.getElementById('photoHistoryList')?.addEventListener('click', e => {
|
||||||
const rollbackBtn = e.target.closest('[data-job-rollback]');
|
const rollbackBtn = e.target.closest('[data-job-rollback]');
|
||||||
if (rollbackBtn) { rollbackPhotoJob(parseInt(rollbackBtn.dataset.jobRollback, 10)); return; }
|
if (rollbackBtn) { rollbackPhotoJob(parseInt(rollbackBtn.dataset.jobRollback, 10)); return; }
|
||||||
|
|||||||
@@ -472,3 +472,125 @@ moduleInput.addEventListener('input', () => {
|
|||||||
moduleInput.addEventListener('focus', async () => {
|
moduleInput.addEventListener('focus', async () => {
|
||||||
if (!moduleInput.value.trim()) renderModuleOptions(await fetchModules('', 50));
|
if (!moduleInput.value.trim()) renderModuleOptions(await fetchModules('', 50));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
(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 = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>';
|
||||||
|
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); });
|
||||||
|
})();
|
||||||
@@ -1536,7 +1536,7 @@ async function removeEntryFiles(entryId) {
|
|||||||
async function sweepOrphanedUploads() {
|
async function sweepOrphanedUploads() {
|
||||||
const dir = UPLOADS_DIR;
|
const dir = UPLOADS_DIR;
|
||||||
try { fs.mkdirSync(dir, { recursive: true }); } catch {}
|
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 photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
|
||||||
pool.query('SELECT path AS p FROM project_files'),
|
pool.query('SELECT path AS p FROM project_files'),
|
||||||
pool.query('SELECT photo_path AS p FROM group_photos'),
|
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 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 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 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();
|
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);
|
const key = storage.keyFromPath(r.p);
|
||||||
if (key) refs.add(key);
|
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");
|
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() {
|
async function ensureApiKeysTable() {
|
||||||
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
|
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
@@ -1851,6 +1873,7 @@ async function ensureUsersAndFirstAdmin() {
|
|||||||
await ensureUserTables();
|
await ensureUserTables();
|
||||||
await ensureApiKeysTable();
|
await ensureApiKeysTable();
|
||||||
await ensureUserNotesTable();
|
await ensureUserNotesTable();
|
||||||
|
await ensureBookmarksTable();
|
||||||
await ensureFirstAdmin();
|
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) => {
|
app.put('/api/feedbacks/:id', requireAuth, async (req, res) => {
|
||||||
const id = parseInt(req.params.id, 10);
|
const id = parseInt(req.params.id, 10);
|
||||||
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
|
||||||
@@ -4443,7 +4649,7 @@ function sweepBackupStorage() {
|
|||||||
async function buildBackupArchive() {
|
async function buildBackupArchive() {
|
||||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||||
try {
|
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 groups ORDER BY id'),
|
||||||
pool.query('SELECT * FROM students ORDER BY id'),
|
pool.query('SELECT * FROM students ORDER BY id'),
|
||||||
pool.query('SELECT * FROM entries 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 feedbacks ORDER BY id'),
|
||||||
pool.query('SELECT * FROM user_settings ORDER BY user_id, key'),
|
pool.query('SELECT * FROM user_settings ORDER BY user_id, key'),
|
||||||
pool.query('SELECT * FROM user_notes ORDER BY id'),
|
pool.query('SELECT * FROM user_notes ORDER BY id'),
|
||||||
|
pool.query('SELECT * FROM bookmarks ORDER BY id'),
|
||||||
]);
|
]);
|
||||||
const settings = {};
|
const settings = {};
|
||||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
st.rows.forEach(r => { settings[r.key] = r.value; });
|
||||||
@@ -4487,8 +4694,9 @@ async function buildBackupArchive() {
|
|||||||
notification_reads: nr.rowCount, banned_ips: bi.rowCount,
|
notification_reads: nr.rowCount, banned_ips: bi.rowCount,
|
||||||
chat_threads: ct.rowCount, chat_messages: cm.rowCount, chat_attachments: ca.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,
|
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));
|
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
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 audit_log');
|
||||||
await client.query('DELETE FROM user_settings');
|
await client.query('DELETE FROM user_settings');
|
||||||
await client.query('DELETE FROM user_notes');
|
await client.query('DELETE FROM user_notes');
|
||||||
|
await client.query('DELETE FROM bookmarks');
|
||||||
await client.query('DELETE FROM users');
|
await client.query('DELETE FROM users');
|
||||||
await client.query('DELETE FROM branches');
|
await client.query('DELETE FROM branches');
|
||||||
for (const x of ndata.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]
|
[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) {
|
for (const x of ndata.user_branches) {
|
||||||
await client.query(
|
await client.query(
|
||||||
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',
|
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',
|
||||||
|
|||||||
Reference in New Issue
Block a user