groups: AI enhance for gallery photos (photo_jobs.group_photo_id, before/after compare modal)

This commit is contained in:
dev
2026-10-09 13:52:02 +03:00
parent df9c67b047
commit ec47659ec6
12 changed files with 1499 additions and 74 deletions
+2 -2
View File
@@ -26,8 +26,8 @@ RUN set -e; \
wget -qO- --timeout=15 http://mirrors.edge.kernel.org/alpine/$V/main/x86_64/APKINDEX.tar.gz >/dev/null && echo "http probe: ok" || echo "http probe: fail"; \ wget -qO- --timeout=15 http://mirrors.edge.kernel.org/alpine/$V/main/x86_64/APKINDEX.tar.gz >/dev/null && echo "http probe: ok" || echo "http probe: fail"; \
exit 1; \ exit 1; \
fi && \ fi && \
openssl req -x509 -nodes -newkey rsa:2048 -days 3650 \ openssl req -x509 -nodes -newkey rsa:2048 -days 3650 \
-keyout certs/key.pem -out certs/cert.pem \ -keyout certs/key.pem -out certs/cert.pem \
-subj "/CN=whatido.local" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" -subj "/CN=whatido.local" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:192.168.88.100,IP:192.168.88.101,IP:192.168.88.102,IP:192.168.88.103,IP:192.168.88.104,IP:192.168.88.105,IP:192.168.88.106,IP:192.168.88.107,IP:192.168.88.108,IP:192.168.88.109,IP:192.168.88.110,IP:192.168.88.111,IP:192.168.88.112,IP:192.168.88.113,IP:192.168.88.114,IP:192.168.88.115,IP:192.168.88.116,IP:192.168.88.117,IP:192.168.88.118,IP:192.168.88.119,IP:192.168.88.120,IP:192.168.88.121,IP:192.168.88.122,IP:192.168.88.123,IP:192.168.88.124,IP:192.168.88.125,IP:192.168.88.126,IP:192.168.88.127,IP:192.168.88.128,IP:192.168.88.129,IP:192.168.88.130,IP:192.168.88.131,IP:192.168.88.132,IP:192.168.88.133,IP:192.168.88.134,IP:192.168.88.135,IP:192.168.88.136,IP:192.168.88.137,IP:192.168.88.138,IP:192.168.88.139,IP:192.168.88.140,IP:192.168.88.141,IP:192.168.88.142,IP:192.168.88.143,IP:192.168.88.144,IP:192.168.88.145,IP:192.168.88.146,IP:192.168.88.147,IP:192.168.88.148,IP:192.168.88.149,IP:192.168.88.150,IP:192.168.88.151,IP:192.168.88.152,IP:192.168.88.153,IP:192.168.88.154,IP:192.168.88.155,IP:192.168.88.156,IP:192.168.88.157,IP:192.168.88.158,IP:192.168.88.159,IP:192.168.88.160,IP:192.168.88.161,IP:192.168.88.162,IP:192.168.88.163,IP:192.168.88.164,IP:192.168.88.165,IP:192.168.88.166,IP:192.168.88.167,IP:192.168.88.168,IP:192.168.88.169,IP:192.168.88.170,IP:192.168.88.171,IP:192.168.88.172,IP:192.168.88.173,IP:192.168.88.174,IP:192.168.88.175,IP:192.168.88.176,IP:192.168.88.177,IP:192.168.88.178,IP:192.168.88.179,IP:192.168.88.180,IP:192.168.88.181,IP:192.168.88.182,IP:192.168.88.183,IP:192.168.88.184,IP:192.168.88.185,IP:192.168.88.186,IP:192.168.88.187,IP:192.168.88.188,IP:192.168.88.189,IP:192.168.88.190,IP:192.168.88.191,IP:192.168.88.192,IP:192.168.88.193,IP:192.168.88.194,IP:192.168.88.195,IP:192.168.88.196,IP:192.168.88.197,IP:192.168.88.198,IP:192.168.88.199,IP:192.168.88.200"
EXPOSE 3003 3443 EXPOSE 3003 3443
CMD ["node", "server.js"] CMD ["node", "server.js"]
+3 -1
View File
@@ -384,6 +384,7 @@ function normalizeRestoreData(data) {
id: reqInt(x.id), id: reqInt(x.id),
group_id: reqInt(x.group_id), group_id: reqInt(x.group_id),
photo_path: reqUploadPath(x.photo_path, 255), photo_path: reqUploadPath(x.photo_path, 255),
photo_original_path: optUploadPath(x.photo_original_path, 255),
caption: optStr(x.caption, 10000), caption: optStr(x.caption, 10000),
taken_at: optDate(x.taken_at), taken_at: optDate(x.taken_at),
sort_order: optInt(x.sort_order, -2147483648, 2147483647), sort_order: optInt(x.sort_order, -2147483648, 2147483647),
@@ -471,7 +472,8 @@ function normalizeRestoreData(data) {
const PHOTO_JOB_STATUSES = new Set(['pending', 'processing', 'done', 'error', 'rejected']); const PHOTO_JOB_STATUSES = new Set(['pending', 'processing', 'done', 'error', 'rejected']);
const photo_jobs = (data.photo_jobs || []).map(x => ({ const photo_jobs = (data.photo_jobs || []).map(x => ({
id: reqInt(x.id), id: reqInt(x.id),
entry_id: reqInt(x.entry_id), entry_id: optInt(x.entry_id, 1, 2147483647),
group_photo_id: optInt(x.group_photo_id, 1, 2147483647),
action: (x.action && PHOTO_JOB_ACTIONS.has(x.action)) ? x.action : 'ai', action: (x.action && PHOTO_JOB_ACTIONS.has(x.action)) ? x.action : 'ai',
params: optJsonText(x.params, 20000), params: optJsonText(x.params, 20000),
before_path: optPhotoRefPath(x.before_path, 255), before_path: optPhotoRefPath(x.before_path, 255),
+4 -1
View File
@@ -169,6 +169,7 @@ CREATE TABLE IF NOT EXISTS group_photos (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
photo_path VARCHAR(255) NOT NULL, photo_path VARCHAR(255) NOT NULL,
photo_original_path VARCHAR(255),
caption TEXT, caption TEXT,
taken_at DATE, taken_at DATE,
sort_order INT DEFAULT 0, sort_order INT DEFAULT 0,
@@ -303,7 +304,8 @@ CREATE INDEX IF NOT EXISTS idx_lesson_report_versions_report ON lesson_report_ve
CREATE TABLE IF NOT EXISTS photo_jobs ( CREATE TABLE IF NOT EXISTS photo_jobs (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
entry_id INT NOT NULL REFERENCES entries(id) ON DELETE CASCADE, entry_id INT REFERENCES entries(id) ON DELETE CASCADE,
group_photo_id INT REFERENCES group_photos(id) ON DELETE CASCADE,
action VARCHAR(20) NOT NULL DEFAULT 'ai', action VARCHAR(20) NOT NULL DEFAULT 'ai',
params JSONB, params JSONB,
before_path VARCHAR(255), before_path VARCHAR(255),
@@ -318,6 +320,7 @@ CREATE TABLE IF NOT EXISTS photo_jobs (
CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending'; CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id); CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id);
CREATE INDEX IF NOT EXISTS idx_photo_jobs_group_photo_id ON photo_jobs(group_photo_id);
INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true') INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true')
ON CONFLICT (key) DO NOTHING; ON CONFLICT (key) DO NOTHING;
+5 -1
View File
@@ -220,12 +220,14 @@ CREATE TABLE IF NOT EXISTS group_photos (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
photo_path VARCHAR(255) NOT NULL, photo_path VARCHAR(255) NOT NULL,
photo_original_path VARCHAR(255),
caption TEXT, caption TEXT,
taken_at DATE, taken_at DATE,
created_at TIMESTAMPTZ DEFAULT now() created_at TIMESTAMPTZ DEFAULT now()
); );
ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS sort_order INT DEFAULT 0; ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS sort_order INT DEFAULT 0;
ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255);
CREATE INDEX IF NOT EXISTS idx_group_photos_group_id ON group_photos(group_id); CREATE INDEX IF NOT EXISTS idx_group_photos_group_id ON group_photos(group_id);
@@ -253,7 +255,8 @@ FOR EACH ROW EXECUTE FUNCTION notify_entries_changed();
CREATE TABLE IF NOT EXISTS photo_jobs ( CREATE TABLE IF NOT EXISTS photo_jobs (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
entry_id INT NOT NULL REFERENCES entries(id) ON DELETE CASCADE, entry_id INT REFERENCES entries(id) ON DELETE CASCADE,
group_photo_id INT REFERENCES group_photos(id) ON DELETE CASCADE,
action VARCHAR(20) NOT NULL DEFAULT 'ai', action VARCHAR(20) NOT NULL DEFAULT 'ai',
params JSONB, params JSONB,
before_path VARCHAR(255), before_path VARCHAR(255),
@@ -268,6 +271,7 @@ CREATE TABLE IF NOT EXISTS photo_jobs (
CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending'; CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending';
CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id); CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id);
CREATE INDEX IF NOT EXISTS idx_photo_jobs_group_photo_id ON photo_jobs(group_photo_id);
INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true') INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true')
ON CONFLICT (key) DO NOTHING; ON CONFLICT (key) DO NOTHING;
+89
View File
@@ -0,0 +1,89 @@
# Script: install-whatido-cert.ps1
# Назначение: скачивает самоподписанный сертификат WhatIDo и импортирует его в
# локальное хранилище "Доверенные корневые центры сертификации" (LocalMachine\Root).
# После перезапуска браузера (или повторного подключения) предупреждение о
# самоподписанном сертификате исчезает.
#
# Запуск (от имени администратора):
# .\install-whatido-cert.ps1
#
# Или удаленно / по URL:
# .\install-whatido-cert.ps1 -Url 'http://192.168.88.100:3003/certs/cert.pem'
param(
[ValidateSet('LocalMachine', 'CurrentUser', IgnoresCase = $false)]
[string] $StoreLocation = 'LocalMachine',
[string] $CertUrl = 'http://127.0.0.1:3003/certs/cert.pem'
)
# Путь, куда временно сохранится сертификат
$TempCert = [System.IO.Path]::GetTempFileName() + '.cer'
trap {
if (Test-Path $TempCert) { Remove-Item -Force $TempCert -ErrorAction SilentlyContinue }
}
# --- 1. Скачиваем сертификат ---
Write-Host "Скачивание сертификата из: $CertUrl" -ForegroundColor Cyan
try {
$bytes = Invoke-WebRequest -Uri $CertUrl -UseBasicParsing -TimeoutSec 30 -ErrorAction Stop
$bytes.Content | Out-File -FilePath $TempCert -Encoding Byte -Force
Write-Host "Сертификат сохранён во временный файл: $TempCert" -ForegroundColor Green
}
catch {
Write-Error "Не удалось скачать сертификат: $_"
exit 1
}
# --- 2. Проверяем, что файл — это X.509 сертификат ---
$certContent = [System.IO.File]::ReadAllBytes($TempCert)
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certContent)
Write-Host "Сертификат: $($cert.Subject)" -ForegroundColor Yellow
Write-Host "Выдан: $($cert.Issuer)" -ForegroundColor Yellow
Write-Host "Срок действия: от $($cert.NotBefore) до $($cert.NotAfter)" -ForegroundColor Yellow
Write-Host "Кол-во IP в SAN: $($cert.Extensions | Where-Object { $_.Oid.FriendlyName -eq 'Subject Alternative Name' } | ForEach-Object { $_.Format($true) -split ',' } | Measure-Object). IP-адресов в сертификате" -ForegroundColor Yellow
if ($cert.Subject -notmatch 'whatido') {
Write-Warning "Тема сертификата '$($cert.Subject)' отличается от ожидаемой ('CN=whatido.local')."
$continue = Read-Host "Продолжить установку? (y/n)"
if ($continue -ne 'y' -and $continue -ne 'Y') { exit 0 }
}
# --- 3. Проверяем, есть ли уже такой сертификат в хранилище ---
$storePath = "Cert:\$StoreLocation\Root"
if (!(Test-Path $storePath)) {
Write-Error "Хранилище не найдено: $storePath"
exit 1
}
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store('Root', $StoreLocation)
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$existing = $store.Certificates | Where-Object {
$_.Thumbprint -eq $cert.Thumbprint -or $_.Thumbprint -eq $cert.Thumbprint.ToUpperInvariant()
}
if ($existing) {
Write-Host "Сертификат уже установлен в хранилище $storePath" -ForegroundColor Green
$store.Close()
exit 0
}
# --- 4. Импортируем в хранилище корневых сертификатов ---
Write-Host "Импортируем сертификат в: $storePath" -ForegroundColor Cyan
$store.Add($cert)
Write-Host "Успешно: сертификат добавлен в хранилище 'Доверенные корневые центры сертификации' ($StoreLocation)" -ForegroundColor Green
# --- 5. Показываем итоговое содержимое (для подтверждения) ---
Write-Host "Теперь в хранилище:" -ForegroundColor Cyan
$store.Certificates | Where-Object { $_.NotAfter -gt (Get-Date) -and $_.Subject -match 'whatido' } |
Select-Object -First 5 Subject, NotAfter, Thumbprint | Format-Table -AutoSize
$store.Close()
# --- 6. Очистка ---
Remove-Item -Force $TempCert -ErrorAction SilentlyContinue
Write-Host "Временный файл удалён." -ForegroundColor Gray
+81
View File
@@ -5,6 +5,33 @@
<meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="viewport" content="width=device-width,initial-scale=1">
<title>Группы — Админ-панель</title> <title>Группы — Админ-панель</title>
<link rel="stylesheet" href="admin.css"> <link rel="stylesheet" href="admin.css">
<style>
.enhance-modal{max-width:1100px;width:94vw}
.enhance-body{display:flex;gap:16px;align-items:stretch;margin-top:4px}
.enhance-compare{position:relative;flex:1 1 auto;min-width:0;border-radius:10px;overflow:hidden;background:var(--bg);border:1px solid var(--border);user-select:none;touch-action:none;cursor:ew-resize}
.enhance-compare.zoomed{cursor:grab}
.enhance-compare.panning{cursor:grabbing}
.enhance-stage{transform-origin:0 0;will-change:transform}
.enhance-stage>img,.enhance-stage>canvas{display:block;width:100%;height:100%}
.enhance-stage>img{height:auto}
.enhance-top{position:absolute;inset:0;overflow:hidden}
.enhance-top .enhance-stage{position:absolute;inset:0}
.enhance-divider{position:absolute;top:0;bottom:0;left:50%;width:32px;transform:translateX(-50%);pointer-events:auto;cursor:ew-resize}
.enhance-divider::before{content:'';position:absolute;top:0;bottom:0;left:50%;width:2px;transform:translateX(-50%);background:#fff;box-shadow:0 0 6px rgba(0,0,0,.6);pointer-events:none}
.enhance-handle{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:44px;height:44px;border-radius:50%;background:rgba(17,17,17,.8);color:#fff;display:flex;align-items:center;justify-content:center;font-size:18px;pointer-events:none;box-shadow:0 4px 10px rgba(0,0,0,.25)}
.enhance-badge{position:absolute;top:10px;padding:4px 10px;border-radius:6px;background:rgba(17,17,17,.7);color:#fff;font-size:.78rem;pointer-events:none}
.enhance-badge.left{left:10px}
.enhance-badge.right{right:10px}
.enhance-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(17,17,17,.55);color:#fff;font-size:.95rem;gap:8px;display:none}
.enhance-loading::after{content:'';width:16px;height:16px;border:2px solid rgba(255,255,255,.6);border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.enhance-sliders{flex:0 0 240px;display:flex;flex-direction:column;gap:14px}
.enhance-sliders .settings-field input[type=range]{width:100%}
.enhance-foot{justify-content:flex-end;gap:8px;margin-top:14px;flex-wrap:wrap}
.enhance-ai-mode{width:auto;min-width:200px;padding:9px 12px;font-size:.85rem}
.enhance-ai-hint{font-size:.75rem;color:var(--muted);max-width:340px}
@media (max-width:800px){.enhance-body{flex-direction:column}.enhance-sliders{flex:1 1 auto;display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr))}}
</style>
</head> </head>
<body data-page="groups"> <body data-page="groups">
<div class="layout"> <div class="layout">
@@ -135,6 +162,60 @@
</div> </div>
</div> </div>
<div class="modal-overlay" id="enhanceModal">
<div class="edit-modal enhance-modal">
<h3>Улучшение фотографии</h3>
<div class="enhance-body">
<div class="enhance-compare" id="enhanceCompare">
<div class="enhance-stage" id="enhanceStage">
<img id="enhanceOrig" alt="Оригинал">
</div>
<div class="enhance-top" id="enhanceTop" style="clip-path:inset(0 0 0 50%)">
<div class="enhance-stage" id="enhanceInner">
<canvas id="enhanceCanvas"></canvas>
</div>
</div>
<div class="enhance-divider" id="enhanceDivider"><div class="enhance-handle">⇔</div></div>
<div class="enhance-badge left">Оригинал</div>
<div class="enhance-badge right">Результат</div>
<div class="enhance-loading" id="enhanceLoading">Загрузка...</div>
</div>
<div class="enhance-sliders">
<div class="settings-field"><label>Яркость <span id="enhanceBrightnessVal">100%</span></label><input type="range" id="enhanceBrightness" min="50" max="150" value="100"></div>
<div class="settings-field"><label>Контраст <span id="enhanceContrastVal">100%</span></label><input type="range" id="enhanceContrast" min="50" max="150" value="100"></div>
<div class="settings-field"><label>Насыщенность <span id="enhanceSaturateVal">100%</span></label><input type="range" id="enhanceSaturate" min="0" max="200" value="100"></div>
<div class="settings-field"><label>Шумодав <span id="enhanceDenoiseVal">0%</span></label><input type="range" id="enhanceDenoise" min="0" max="100" value="0"></div>
<div class="settings-field"><label>Резкость <span id="enhanceSharpVal">0%</span></label><input type="range" id="enhanceSharp" min="0" max="100" value="0"></div>
</div>
</div>
<div class="card-foot enhance-foot">
<button type="button" class="btn-primary ghost" id="enhanceHistoryBtn" title="История изменений фотографии">🕘 История</button>
<button type="button" class="btn-primary ghost" id="enhanceRestoreBtn" style="display:none" title="Вернуть исходную фотографию">↩ Вернуть оригинал</button>
<select id="enhanceAiMode" class="settings-input enhance-ai-mode" style="display:none" title="Режим ИИ-обработки фото">
<option value="x2">Универсально (x2)</option>
<option value="x4">Быстро (x4)</option>
<option value="faces">Лица (GFPGAN)</option>
<option value="facesbg">Лица + фон</option>
</select>
<span class="enhance-ai-hint" id="enhanceAiHint" style="display:none"></span>
<button type="button" class="btn-primary ghost" id="enhanceAiBtn" style="display:none" title="ИИ-восстановление (Real-ESRGAN)">🤖 ИИ</button>
<button type="button" class="btn-primary ghost" id="enhanceAutoBtn" title="Подобрать настройки автоматически">✨ Авто</button>
<button type="button" class="btn-primary ghost" id="enhanceCancelBtn">Оставить как есть</button>
<button type="button" class="btn-primary" id="enhanceSaveBtn">Применить</button>
</div>
</div>
</div>
<div class="modal-overlay" id="photoHistoryModal">
<div class="edit-modal enhance-modal">
<h3 id="photoHistoryTitle">История изменений фотографии</h3>
<div id="photoHistoryList" style="display:flex;flex-direction:column;gap:12px;max-height:60vh;overflow:auto"></div>
<div class="card-foot enhance-foot">
<button type="button" class="btn-primary ghost" id="photoHistoryCloseBtn">Закрыть</button>
</div>
</div>
</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>
+4
View File
@@ -19,6 +19,10 @@ const ACTION_LABELS = {
'group.photo.reorder': 'Изменён порядок фото группы', 'group.photo.reorder': 'Изменён порядок фото группы',
'group.photo.set_cover': 'Обновлена обложка группы', 'group.photo.set_cover': 'Обновлена обложка группы',
'group.photo.delete': 'Удалено фото группы', 'group.photo.delete': 'Удалено фото группы',
'group.photo.enhance': 'Улучшено фото группы',
'group.photo.enhance-ai.queue': 'Постановка ИИ-обработки фото группы',
'group.photo.apply': 'Применён результат ИИ для фото группы',
'group.photo.reject': 'Отклонён результат ИИ для фото группы',
'branch.create': 'Создан филиал', 'branch.create': 'Создан филиал',
'branch.update': 'Изменён филиал', 'branch.update': 'Изменён филиал',
'branch.delete': 'Удалён филиал', 'branch.delete': 'Удалён филиал',
+703 -1
View File
@@ -177,6 +177,7 @@ function photoHTML(p) {
<div class="p-actions"> <div class="p-actions">
<button class="p-cover${isCover ? ' active' : ''}" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" title="${isCover ? 'Текущая обложка' : 'Сделать обложкой'}" ${isCover ? 'disabled' : ''}>🖼️</button> <button class="p-cover${isCover ? ' active' : ''}" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" title="${isCover ? 'Текущая обложка' : 'Сделать обложкой'}" ${isCover ? 'disabled' : ''}>🖼️</button>
<button class="p-edit" data-edit-photo="${p.id}" title="Редактировать">✎</button> <button class="p-edit" data-edit-photo="${p.id}" title="Редактировать">✎</button>
<button class="p-enhance" data-enhance-photo="${p.id}" title="Улучшить фото">✨</button>
<button class="p-del" data-del-photo="${p.id}" title="Удалить">&times;</button> <button class="p-del" data-del-photo="${p.id}" title="Удалить">&times;</button>
</div> </div>
</div> </div>
@@ -523,6 +524,8 @@ document.getElementById('photoGrid').addEventListener('click', async e => {
} }
const ed = e.target.closest('[data-edit-photo]'); const ed = e.target.closest('[data-edit-photo]');
if (ed) { openEditPhoto(parseInt(ed.dataset.editPhoto, 10)); return; } if (ed) { openEditPhoto(parseInt(ed.dataset.editPhoto, 10)); return; }
const en = e.target.closest('[data-enhance-photo]');
if (en) { openEnhance(parseInt(en.dataset.enhancePhoto, 10)); return; }
const dl = e.target.closest('[data-del-photo]'); const dl = e.target.closest('[data-del-photo]');
if (dl) { deletePhoto(parseInt(dl.dataset.delPhoto, 10)); } if (dl) { deletePhoto(parseInt(dl.dataset.delPhoto, 10)); }
}); });
@@ -548,4 +551,703 @@ async function populateNewGroupBranch() {
await populateNewGroupBranch(); await populateNewGroupBranch();
loadGroups(); loadGroups();
} }
})(); })();
let enhancePhotoId = null;
let enhanceAiJobId = null;
let enhanceAiResultPath = null;
let enhanceSourceImg = null;
let photoAiEnabled = false;
let photoAiFaceMode = 'off';
let photoAiFaceModel = 'gfpgan';
let photoAiDevice = '';
let photoAiConfigLoaded = false;
let enhanceSaving = false;
let enhanceTimer = null;
let enhanceClipPos = 50;
let enhanceZoom = 1;
let enhancePanX = 0;
let enhancePanY = 0;
async function loadPhotoAiConfig() {
if (photoAiConfigLoaded) return;
try {
const res = await fetch(API + '/api/public-settings', { headers: hdr() });
if (res.ok) {
const s = await res.json();
photoAiEnabled = s.photo_ai_enabled === 'true';
if (['off', 'face', 'all'].includes(s.photo_ai_face_mode)) photoAiFaceMode = s.photo_ai_face_mode;
if (['gfpgan', 'codeformer'].includes(s.photo_ai_face_model)) photoAiFaceModel = s.photo_ai_face_model;
}
} catch (e) { photoAiEnabled = false; }
photoAiConfigLoaded = true;
const sel = document.getElementById('enhanceAiMode');
if (sel) sel.value = defaultPhotoAiModeKey();
loadPhotoAiDevice();
}
async function loadPhotoAiDevice() {
if (!isAdmin()) return;
try {
const r = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() });
if (!r.ok) return;
const h = await r.json();
if (h && h.device) photoAiDevice = String(h.device);
updateAiHint();
} catch (e) {}
}
const PHOTO_AI_MODES = {
x2: { model: 'x2plus', face: 'off', face_model: null, title: 'Универсально (x2)' },
x4: { model: 'general-x4v3', face: 'off', face_model: null, title: 'Быстро (x4)' },
faces: { model: 'x2plus', face: 'face', face_model: null, title: 'Лица (восстановление)' },
facesbg: { model: 'x2plus', face: 'all', face_model: null, title: 'Лица + фон' },
};
function photoAiMode() {
const sel = document.getElementById('enhanceAiMode');
const key = sel && PHOTO_AI_MODES[sel.value] ? sel.value : 'x2';
const m = { ...PHOTO_AI_MODES[key] };
m.face_model = m.face === 'off' ? null : photoAiFaceModel;
return m;
}
function defaultPhotoAiModeKey() {
if (photoAiFaceMode === 'all') return 'facesbg';
if (photoAiFaceMode === 'face') return 'faces';
return 'x2';
}
function updateAiHint() {
const hint = document.getElementById('enhanceAiHint');
if (!hint) return;
const cpu = photoAiDevice.startsWith('cpu');
hint.textContent = cpu ? 'Фото-ИИ считает на CPU — лицевые режимы могут занять несколько минут' : '';
hint.style.display = photoAiEnabled && cpu ? '' : 'none';
}
function showEnhanceResult(show) {
const top = document.getElementById('enhanceTop');
const loading = document.getElementById('enhanceLoading');
if (top) top.style.display = show ? '' : 'none';
if (loading) loading.style.display = show ? 'none' : '';
}
function setEnhanceLoadingText(text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
el.textContent = text;
}
function medianFilterPass(ctx, w, h) {
const data = ctx.getImageData(0, 0, w, h);
const src = data.data;
const out = new Uint8ClampedArray(src);
const row = w * 4;
const win = new Array(9);
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const i = y * row + x * 4;
for (let ch = 0; ch < 3; ch++) {
win[0] = src[i - row - 4 + ch]; win[1] = src[i - row + ch]; win[2] = src[i - row + 4 + ch];
win[3] = src[i - 4 + ch]; win[4] = src[i + ch]; win[5] = src[i + 4 + ch];
win[6] = src[i + row - 4 + ch]; win[7] = src[i + row + ch]; win[8] = src[i + row + 4 + ch];
win.sort((a, b) => a - b);
out[i + ch] = win[4];
}
}
}
data.data.set(out);
ctx.putImageData(data, 0, 0);
}
function sharpenPass(ctx, w, h, sharp) {
const data = ctx.getImageData(0, 0, w, h);
const src = data.data;
const out = new Uint8ClampedArray(src);
const row = w * 4;
const a = (sharp / 100) * 1.5;
for (let y = 1; y < h - 1; y++) {
for (let x = 1; x < w - 1; x++) {
const i = y * row + x * 4;
for (let ch = 0; ch < 3; ch++) {
const v = (1 + 4 * a) * src[i + ch]
- a * src[i - 4 + ch] - a * src[i + 4 + ch]
- a * src[i - row + ch] - a * src[i + row + ch];
out[i + ch] = v;
}
}
}
data.data.set(out);
ctx.putImageData(data, 0, 0);
}
function drawEnhanced(ctx, img, w, h) {
const b = document.getElementById('enhanceBrightness').value;
const c = document.getElementById('enhanceContrast').value;
const s = document.getElementById('enhanceSaturate').value;
const dn = parseInt(document.getElementById('enhanceDenoise').value, 10);
const sp = parseInt(document.getElementById('enhanceSharp').value, 10);
ctx.filter = `brightness(${b}%) contrast(${c}%) saturate(${s}%)`;
ctx.drawImage(img, 0, 0, w, h);
ctx.filter = 'none';
if (dn > 0) {
medianFilterPass(ctx, w, h);
if (dn > 70) medianFilterPass(ctx, w, h);
}
if (sp > 0) sharpenPass(ctx, w, h, sp);
}
function renderEnhancePreview() {
if (!enhanceSourceImg) return;
const img = enhanceSourceImg;
const scale = Math.min(1, 1600 / img.naturalWidth);
const w = Math.max(1, Math.round(img.naturalWidth * scale));
const h = Math.max(1, Math.round(img.naturalHeight * scale));
const canvas = document.getElementById('enhanceCanvas');
if (!canvas) return;
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
drawEnhanced(ctx, img, w, h);
showEnhanceResult(true);
}
function scheduleEnhancePreview() {
document.getElementById('enhanceBrightnessVal').textContent = document.getElementById('enhanceBrightness').value + '%';
document.getElementById('enhanceContrastVal').textContent = document.getElementById('enhanceContrast').value + '%';
document.getElementById('enhanceSaturateVal').textContent = document.getElementById('enhanceSaturate').value + '%';
document.getElementById('enhanceDenoiseVal').textContent = document.getElementById('enhanceDenoise').value + '%';
document.getElementById('enhanceSharpVal').textContent = document.getElementById('enhanceSharp').value + '%';
if (enhanceTimer) clearTimeout(enhanceTimer);
enhanceTimer = setTimeout(renderEnhancePreview, 120);
}
function enhanceParams() {
return {
brightness: parseInt(document.getElementById('enhanceBrightness').value, 10),
contrast: parseInt(document.getElementById('enhanceContrast').value, 10),
saturate: parseInt(document.getElementById('enhanceSaturate').value, 10),
denoise: parseInt(document.getElementById('enhanceDenoise').value, 10),
sharp: parseInt(document.getElementById('enhanceSharp').value, 10),
};
}
function isDefaultEnhanceParams() {
const p = enhanceParams();
return p.brightness === 100 && p.contrast === 100 && p.saturate === 100 && p.denoise === 0 && p.sharp === 0;
}
function setEnhanceClip(p) {
enhanceClipPos = Math.min(100, Math.max(0, p));
const top = document.getElementById('enhanceTop');
const divider = document.getElementById('enhanceDivider');
if (top) top.style.clipPath = `inset(0 0 0 ${enhanceClipPos}%)`;
if (divider) divider.style.left = enhanceClipPos + '%';
}
function applyEnhanceTransform() {
const t = `translate(${enhancePanX}px, ${enhancePanY}px) scale(${enhanceZoom})`;
const stage = document.getElementById('enhanceStage');
const inner = document.getElementById('enhanceInner');
if (stage) stage.style.transform = t;
if (inner) inner.style.transform = t;
const area = document.getElementById('enhanceCompare');
if (area) {
area.classList.toggle('zoomed', enhanceZoom > 1);
if (enhanceZoom <= 1) area.classList.remove('panning');
}
}
function clampEnhancePan() {
const area = document.getElementById('enhanceCompare');
if (!area) return;
const rect = area.getBoundingClientRect();
const minX = rect.width * (1 - enhanceZoom);
const minY = rect.height * (1 - enhanceZoom);
enhancePanX = Math.min(0, Math.max(minX, enhancePanX));
enhancePanY = Math.min(0, Math.max(minY, enhancePanY));
}
function resetEnhanceZoom() {
enhanceZoom = 1;
enhancePanX = 0;
enhancePanY = 0;
applyEnhanceTransform();
}
(function initEnhanceDrag() {
const area = document.getElementById('enhanceCompare');
if (!area) return;
let dragging = false;
let dividerDrag = false;
let lastX = 0;
let lastY = 0;
const move = ev => {
const rect = area.getBoundingClientRect();
setEnhanceClip(((ev.clientX - rect.left) / rect.width) * 100);
};
area.addEventListener('pointerdown', ev => {
dividerDrag = !!ev.target.closest('#enhanceDivider');
dragging = true;
lastX = ev.clientX;
lastY = ev.clientY;
area.setPointerCapture(ev.pointerId);
if (!dividerDrag && enhanceZoom === 1) move(ev);
});
area.addEventListener('pointermove', ev => {
if (!dragging) return;
if (dividerDrag || enhanceZoom === 1) {
move(ev);
} else {
area.classList.add('panning');
enhancePanX += ev.clientX - lastX;
enhancePanY += ev.clientY - lastY;
lastX = ev.clientX;
lastY = ev.clientY;
clampEnhancePan();
applyEnhanceTransform();
}
});
const end = () => {
dragging = false;
area.classList.remove('panning');
};
area.addEventListener('pointerup', end);
area.addEventListener('pointercancel', end);
area.addEventListener('wheel', ev => {
ev.preventDefault();
const rect = area.getBoundingClientRect();
const cx = ev.clientX - rect.left;
const cy = ev.clientY - rect.top;
const prev = enhanceZoom;
const next = Math.min(5, Math.max(1, enhanceZoom * (ev.deltaY < 0 ? 1.15 : 1 / 1.15)));
if (next === prev) return;
enhanceZoom = next;
enhancePanX = cx - (cx - enhancePanX) * (next / prev);
enhancePanY = cy - (cy - enhancePanY) * (next / prev);
clampEnhancePan();
applyEnhanceTransform();
}, { passive: false });
area.addEventListener('dblclick', resetEnhanceZoom);
})();
function estimateNoise(img) {
const aw = 160;
const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth));
const ac = document.createElement('canvas');
ac.width = aw;
ac.height = ah;
const actx = ac.getContext('2d');
actx.drawImage(img, 0, 0, aw, ah);
const d = actx.getImageData(0, 0, aw, ah).data;
let sum = 0;
let n = 0;
for (let y = 0; y < ah - 1; y++) {
for (let x = 0; x < aw - 1; x++) {
const i = (y * aw + x) * 4;
const l = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
const lr = 0.299 * d[i + 4] + 0.587 * d[i + 5] + 0.114 * d[i + 6];
const lb = 0.299 * d[i + aw * 4] + 0.587 * d[i + aw * 4 + 1] + 0.114 * d[i + aw * 4 + 2];
sum += Math.abs(l - lr) + Math.abs(l - lb);
n += 2;
}
}
return n ? sum / n : 0;
}
function autoEnhance() {
if (!enhanceSourceImg) return;
const img = enhanceSourceImg;
const aw = 160;
const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth));
const ac = document.createElement('canvas');
ac.width = aw;
ac.height = ah;
const actx = ac.getContext('2d');
actx.drawImage(img, 0, 0, aw, ah);
const d = actx.getImageData(0, 0, aw, ah).data;
const hist = new Array(256).fill(0);
let total = 0;
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] < 16) continue;
hist[Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2])]++;
total++;
}
const pct = p => {
let acc = 0;
const target = total * p;
for (let v = 0; v < 256; v++) {
acc += hist[v];
if (acc >= target) return v;
}
return 255;
};
let lo = pct(0.005);
let hi = pct(0.995);
if (hi - lo < 30) {
lo = Math.max(0, lo - 15);
hi = Math.min(255, hi + 15);
}
const contrast = Math.round(Math.min(150, Math.max(100, 25500 / (hi - lo))));
const brightness = Math.round(Math.min(120, Math.max(85, 12800 / Math.max(1, (lo + hi) / 2))));
const noise = estimateNoise(img);
let denoise = 0;
let sharp = 30;
if (noise > 6) {
denoise = Math.min(50, Math.round(noise * 6));
sharp = 15;
}
const saturate = 106;
document.getElementById('enhanceBrightness').value = brightness;
document.getElementById('enhanceContrast').value = contrast;
document.getElementById('enhanceSaturate').value = saturate;
document.getElementById('enhanceDenoise').value = denoise;
document.getElementById('enhanceSharp').value = sharp;
scheduleEnhancePreview();
}
const PHOTO_JOB_ACTION_LABELS = { ai: 'ИИ-обработка', ai_face: 'ИИ-обработка (лица)', enhance: 'Улучшение', restore: 'Возврат оригинала', rollback: 'Откат' };
const PHOTO_JOB_STATUS_LABELS = { pending: 'В очереди', processing: 'Обрабатывается', done: 'Готово', error: 'Ошибка', rejected: 'Отклонено' };
function photoJobThumb(p) {
if (!p) return '';
if (p.startsWith('/uploads/.originals/')) return `${API}${p}`;
return `${API}/uploads/thumb/${p.split('/').pop()}`;
}
async function loadPhotoHistory() {
if (!enhancePhotoId || !currentGroupId) return;
const list = document.getElementById('photoHistoryList');
if (!list) return;
list.innerHTML = '<div style="color:var(--muted);font-size:.85rem">Загрузка...</div>';
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs`, { headers: hdr() });
if (!res.ok) throw new Error('Ошибка загрузки истории');
const rows = await res.json();
if (!rows.length) {
list.innerHTML = '<div style="color:var(--muted);font-size:.85rem">Изменений фотографии пока не было.</div>';
return;
}
list.innerHTML = rows.map(r => {
const before = r.before_path ? `<img class="photo-thumb" loading="lazy" src="${esc(photoJobThumb(r.before_path))}" alt="было">` : '<span style="color:var(--muted)">—</span>';
const after = r.after_path ? `<img class="photo-thumb" loading="lazy" src="${esc(photoJobThumb(r.after_path))}" alt="стало">` : '<span style="color:var(--muted)">—</span>';
const canApply = r.status === 'done' && r.applied === false && (r.action === 'ai' || r.action === 'ai_face') && !!r.after_path;
const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback' && !canApply;
const err = r.error ? `<div style="color:#ef4444;font-size:.75rem;margin-top:4px">${esc(r.error)}</div>` : '';
const time = r.finished_at || r.created_at;
return `<div style="display:flex;gap:10px;align-items:center;border:1px solid var(--border);border-radius:10px;padding:10px">
<div style="display:flex;flex-direction:column;gap:4px;text-align:center">
${before}
<span style="font-size:.65rem;color:var(--muted)">было</span>
</div>
<div style="color:var(--muted)">→</div>
<div style="display:flex;flex-direction:column;gap:4px;text-align:center">
${after}
<span style="font-size:.65rem;color:var(--muted)">стало</span>
</div>
<div style="flex:1;min-width:0">
<div style="font-size:.85rem">${esc(PHOTO_JOB_ACTION_LABELS[r.action] || r.action)}
<span style="color:var(--muted);font-size:.75rem;margin-left:6px">${esc(PHOTO_JOB_STATUS_LABELS[r.status] || r.status)} · ${esc(fmtFull(time))}</span>
</div>
${err}
</div>
${canRollback ? `<button type="button" class="btn-primary ghost" style="white-space:nowrap" data-job-rollback="${r.id}">↩ Откатить</button>` : ''}
${canApply ? `<button type="button" class="btn-primary" style="white-space:nowrap" data-job-apply="${r.id}">✓ Применить</button>` : ''}
</div>`;
}).join('');
} catch (e) {
list.innerHTML = `<div style="color:#ef4444;font-size:.85rem">${esc(e.message)}</div>`;
}
}
function openPhotoHistory() {
if (!enhancePhotoId) return;
document.getElementById('photoHistoryTitle').textContent = `История изменений фотографии — фото #${enhancePhotoId}`;
document.getElementById('photoHistoryModal').classList.add('open');
loadPhotoHistory();
}
async function refreshEnhanceFromPath(mp) {
document.getElementById('enhanceOrig').src = `${API}${mp}`;
showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...');
await new Promise(resolve => {
const img = new Image();
img.onload = () => { enhanceSourceImg = img; renderEnhancePreview(); resolve(); };
img.onerror = () => { setEnhanceLoadingText('Не удалось загрузить фото'); resolve(); };
img.src = `${API}${mp}`;
});
}
async function rollbackPhotoJob(jobId) {
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
if (!confirm('Откатить фотографию к сохранённой версии? Текущая версия сохранится в истории.')) return;
enhanceSaving = true;
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/rollback`, { method: 'POST', headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка отката');
showToast('Фотография откатана');
document.getElementById('photoHistoryModal').classList.remove('open');
await refreshEnhanceFromPath(data.photo_path);
await loadGroupPhotos();
loadGroups();
} catch (e) {
alert(e.message);
} finally {
enhanceSaving = false;
}
}
async function applyPhotoJob(jobId) {
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
if (!confirm('Применить обработанную фотографию? Текущая версия сохранится в истории.')) return;
enhanceSaving = true;
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/apply`, { method: 'POST', headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка применения');
showToast('Фотография обновлена');
document.getElementById('photoHistoryModal').classList.remove('open');
await refreshEnhanceFromPath(data.photo_path);
await loadGroupPhotos();
loadGroups();
} catch (e) {
alert(e.message);
} finally {
enhanceSaving = false;
}
}
async function saveEnhance() {
if (!enhancePhotoId || !currentGroupId || !enhanceSourceImg || enhanceSaving) return;
if (enhanceAiResultPath && isDefaultEnhanceParams()) return applyAiResult();
const btn = document.getElementById('enhanceSaveBtn');
enhanceSaving = true;
if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; }
const groupId = currentGroupId;
const photoId = enhancePhotoId;
try {
const img = enhanceSourceImg;
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d');
drawEnhanced(ctx, img, canvas.width, canvas.height);
const blob = await new Promise((resolve, reject) => canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/jpeg', 0.92));
const fd = new FormData();
fd.append('photo', blob, 'enhanced.jpg');
const res = await fetch(`${API}/api/groups/${groupId}/photos/${photoId}/enhance`, { method: 'PUT', headers: hdr(), body: fd });
if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка сохранения'); }
enhanceSaving = false;
showToast('Фото улучшено и сохранено');
closeEnhance();
await loadGroupPhotos();
loadGroups();
} catch (e) {
enhanceSaving = false;
alert(e.message);
} finally {
if (btn) { btn.disabled = false; btn.textContent = 'Применить'; }
}
}
function openEnhance(id) {
const p = photos.find(x => x.id === id);
if (!p) return;
enhancePhotoId = id;
enhanceAiJobId = null;
enhanceAiResultPath = null;
enhanceSourceImg = null;
enhanceSaving = false;
resetEnhanceZoom();
setEnhanceClip(50);
const modal = document.getElementById('enhanceModal');
if (!modal) return;
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
document.getElementById('enhance' + k).value = 100;
document.getElementById('enhance' + k + 'Val').textContent = '100%';
});
document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%';
document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
const orig = document.getElementById('enhanceOrig');
if (orig) orig.src = API + p.photo_path;
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = true;
loadPhotoAiConfig().then(() => {
const show = photoAiEnabled ? '' : 'none';
if (btnAi) btnAi.style.display = show;
const modeSel = document.getElementById('enhanceAiMode');
if (modeSel) modeSel.style.display = show;
updateAiHint();
});
showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...');
const img = new Image();
img.onload = () => {
enhanceSourceImg = img;
renderEnhancePreview();
if (saveBtn) saveBtn.disabled = false;
};
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить фото');
img.src = API + p.photo_path;
modal.classList.add('open');
}
function closeEnhance() {
cleanupAiPreview();
const modal = document.getElementById('enhanceModal');
if (modal) modal.classList.remove('open');
const history = document.getElementById('photoHistoryModal');
if (history) history.classList.remove('open');
enhancePhotoId = null;
enhanceAiJobId = null;
enhanceAiResultPath = null;
enhanceSourceImg = null;
enhanceSaving = false;
resetEnhanceZoom();
if (enhanceTimer) { clearTimeout(enhanceTimer); enhanceTimer = null; }
}
async function runPhotoAi() {
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
const mode = photoAiMode();
const faceNote = mode.face === 'off'
? 'Может занять до минуты на CPU.'
: `Восстановление лиц (${mode.face_model}), на CPU может занять несколько минут.`;
if (!confirm(`ИИ-обработка фото: ${mode.title}. ${faceNote} Продолжить?`)) return;
const btnAi = document.getElementById('enhanceAiBtn');
const saveBtn = document.getElementById('enhanceSaveBtn');
enhanceSaving = true;
if (btnAi) { btnAi.disabled = true; btnAi.textContent = '⏳ ИИ...'; }
if (saveBtn) saveBtn.disabled = true;
showEnhanceResult(false);
setEnhanceLoadingText(mode.face === 'off'
? 'ИИ обрабатывает фото... (может занять до минуты)'
: 'ИИ обрабатывает фото и восстанавливает лица...');
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai`, {
method: 'POST', headers: hdrJson(), body: JSON.stringify({ model: mode.model, face: mode.face, face_model: mode.face_model }),
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка постановки задания'); }
const data = await res.json();
enhanceAiJobId = data.jobId;
pollAiResult();
} catch (err) {
enhanceSaving = false;
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
if (saveBtn) saveBtn.disabled = (enhanceAiJobId == null);
showEnhanceResult(true);
alert(err.message);
}
}
async function pollAiResult() {
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId) return;
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai/${enhanceAiJobId}`, { headers: hdr() });
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка статуса'); }
const data = await res.json();
if (data.status === 'done' && data.photo_path) {
enhanceSaving = false;
enhanceAiResultPath = data.photo_path;
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = false;
const img = new Image();
img.onload = () => {
enhanceSourceImg = img;
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
document.getElementById('enhance' + k).value = 100;
document.getElementById('enhance' + k + 'Val').textContent = '100%';
});
document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%';
document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
renderEnhancePreview();
};
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить результат ИИ');
img.src = API + data.photo_path;
showToast('ИИ результат готов');
return;
}
if (data.status === 'error') {
enhanceSaving = false;
alert(data.error || 'Ошибка обработки');
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
showEnhanceResult(true);
return;
}
setTimeout(pollAiResult, 2000);
} catch (err) {
enhanceSaving = false;
alert(err.message);
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
showEnhanceResult(true);
}
}
async function applyAiResult() {
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId || enhanceSaving) return;
enhanceSaving = true;
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Применение...'; }
const jobId = enhanceAiJobId;
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/apply`, {
method: 'POST', headers: hdrJson(),
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка применения'); }
enhanceAiJobId = null;
enhanceAiResultPath = null;
closeEnhance();
await loadGroupPhotos();
loadGroups();
} catch (err) {
alert(err.message);
enhanceSaving = false;
if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Применить'; }
}
}
function cleanupAiPreview() {
if (!enhancePhotoId || !currentGroupId || !enhanceAiJobId) return;
fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${enhanceAiJobId}/reject`, {
method: 'POST', headers: hdr(),
}).catch(() => {});
}
document.getElementById('enhanceCancelBtn')?.addEventListener('click', () => { closeEnhance(); });
document.getElementById('enhanceAiBtn')?.addEventListener('click', runPhotoAi);
document.getElementById('enhanceSaveBtn')?.addEventListener('click', saveEnhance);
document.getElementById('enhanceAutoBtn')?.addEventListener('click', autoEnhance);
document.getElementById('enhanceHistoryBtn')?.addEventListener('click', openPhotoHistory);
document.getElementById('enhanceModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeEnhance(); });
document.getElementById('photoHistoryCloseBtn')?.addEventListener('click', () => {
const m = document.getElementById('photoHistoryModal');
if (m) m.classList.remove('open');
});
document.getElementById('photoHistoryModal')?.addEventListener('click', e => {
if (e.target === e.currentTarget) 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; }
const applyBtn = e.target.closest('[data-job-apply]');
if (applyBtn) applyPhotoJob(parseInt(applyBtn.dataset.jobApply, 10));
});
['enhanceBrightness', 'enhanceContrast', 'enhanceSaturate', 'enhanceDenoise', 'enhanceSharp'].forEach(id => {
document.getElementById(id)?.addEventListener('input', scheduleEnhancePreview);
});
loadPhotoAiConfig();
+113 -4
View File
@@ -224,6 +224,43 @@ function render() {
renderIcons(); renderIcons();
} }
function photoCellHtml(r, side) {
const rejected = r.status === 'rejected';
if (side === 'before') {
if (!r.before_path) {
const title = rejected
? 'Копия «Было» не создавалась: результат отклонён и не применялся'
: 'Копия «Было» не создавалась для этого задания';
return `<span class="photo-na" title="${esc(title)}">нет «было»</span>`;
}
return `<img class="photo-thumb" loading="lazy" src="${esc(thumbUrl(r.before_path))}" alt="было" title="Копия «Было» до обработки" data-fallback="нет файла" data-fallback-title="Файл копии «Было» не найден">`;
}
if (!r.after_path) {
const title = rejected ? 'Задание отклонено до создания результата' : 'Файл результата не создавался';
return `<span class="photo-na" title="${esc(title)}">нет «стало»</span>`;
}
if (rejected) {
return '<span class="photo-na" title="Результат отклонён — файл удалён">удалён</span>';
}
return `<img class="photo-thumb" loading="lazy" src="${esc(thumbUrl(r.after_path))}" alt="стало" title="Результат обработки" data-fallback="нет файла" data-fallback-title="Файл результата не найден">`;
}
function photoThumbFail(img) {
if (!img.isConnected) return;
const span = document.createElement('span');
span.className = 'photo-na';
span.textContent = img.dataset.fallback || 'нет файла';
span.title = img.dataset.fallbackTitle || '';
img.replaceWith(span);
}
function bindPhotoThumbs(root) {
root.querySelectorAll('img.photo-thumb[data-fallback]').forEach(img => {
if (img.complete && !img.naturalWidth) { photoThumbFail(img); return; }
img.addEventListener('error', () => photoThumbFail(img), { once: true });
});
}
function renderPhoto() { function renderPhoto() {
if (!photoState) return; if (!photoState) return;
const w = photoState.worker || {}; const w = photoState.worker || {};
@@ -254,8 +291,8 @@ function renderPhoto() {
if (!photoTotal) { tbody.innerHTML = ''; empty.style.display = 'block'; renderPager(pager, photoPage, maxPage, p => { photoPage = p; loadPhoto(); }); return; } if (!photoTotal) { tbody.innerHTML = ''; empty.style.display = 'block'; renderPager(pager, photoPage, maxPage, p => { photoPage = p; loadPhoto(); }); return; }
empty.style.display = 'none'; empty.style.display = 'none';
tbody.innerHTML = rows.map(r => { tbody.innerHTML = rows.map(r => {
const before = r.before_path ? `<img class="photo-thumb" loading="lazy" src="${esc(thumbUrl(r.before_path))}" alt="было">` : '<span style="color:var(--muted)">—</span>'; const before = photoCellHtml(r, 'before');
const after = r.after_path ? `<img class="photo-thumb" loading="lazy" src="${esc(thumbUrl(r.after_path))}" alt="стало">` : '<span style="color:var(--muted)">—</span>'; const after = photoCellHtml(r, 'after');
const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback'; const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback';
const badge = `<span class="ai-badge ${PHOTO_STATUS_BADGE[r.status] || ''}">${esc(PHOTO_STATUS_LABELS[r.status] || r.status)}</span>`; const badge = `<span class="ai-badge ${PHOTO_STATUS_BADGE[r.status] || ''}">${esc(PHOTO_STATUS_LABELS[r.status] || r.status)}</span>`;
return `<tr> return `<tr>
@@ -272,6 +309,7 @@ function renderPhoto() {
</td> </td>
</tr>`; </tr>`;
}).join(''); }).join('');
bindPhotoThumbs(tbody);
renderPager(pager, photoPage, maxPage, p => { photoPage = p; loadPhoto(); }); renderPager(pager, photoPage, maxPage, p => { photoPage = p; loadPhoto(); });
renderIcons(); renderIcons();
} }
@@ -344,16 +382,87 @@ function renderPhotoJobMeta(r) {
: '<span class="hint">Метаданные обработки недоступны</span>'; : '<span class="hint">Метаданные обработки недоступны</span>';
} }
function photoJobImgOk(img) {
return !!(img.getAttribute('src') && img.complete && img.naturalWidth > 0);
}
function imgSettled(img) {
if (!img.getAttribute('src') || img.complete) return Promise.resolve();
return new Promise(resolve => {
img.addEventListener('load', resolve, { once: true });
img.addEventListener('error', resolve, { once: true });
});
}
function photoJobMissingNotes(r, beforeOk, afterOk) {
const notes = [];
if (!beforeOk) {
notes.push(r.status === 'rejected'
? 'Копия «Было» не создавалась: результат отклонён и не применялся'
: 'Копия «Было» не создавалась для этого задания');
}
if (!afterOk) {
notes.push(r.status === 'rejected'
? 'Файл «Стало» удалён после отклонения результата'
: 'Файл «Стало» не найден');
}
return notes;
}
function updatePhotoJobLayers(r, beforeOk, afterOk) {
const beforeImg = document.getElementById('photoJobBefore');
const top = document.getElementById('photoJobTop');
const divider = document.getElementById('photoJobDivider');
const empty = document.getElementById('photoJobEmpty');
const note = document.getElementById('photoJobNote');
const badgeBefore = document.getElementById('photoJobBadgeBefore');
const badgeAfter = document.getElementById('photoJobBadgeAfter');
const both = beforeOk && afterOk;
const anyOk = beforeOk || afterOk;
top.style.display = both ? '' : 'none';
divider.style.display = both ? '' : 'none';
badgeBefore.style.display = beforeOk ? '' : 'none';
badgeAfter.style.display = afterOk ? '' : 'none';
beforeImg.style.display = anyOk ? '' : 'none';
setPhotoJobClip(both ? 50 : 100);
const notes = photoJobMissingNotes(r, beforeOk, afterOk);
empty.textContent = notes.join(' · ');
empty.style.display = anyOk ? 'none' : 'flex';
note.textContent = notes.join(' · ');
note.style.display = anyOk && notes.length ? '' : 'none';
}
async function loadPhotoJobImages(r) {
const beforeImg = document.getElementById('photoJobBefore');
const afterImg = document.getElementById('photoJobAfter');
if (r.before_path) beforeImg.src = thumbUrl(r.before_path);
else beforeImg.removeAttribute('src');
const afterSrc = r.after_path && r.status !== 'rejected' ? `${API}${r.after_path}` : '';
if (afterSrc) afterImg.src = afterSrc;
else afterImg.removeAttribute('src');
await Promise.all([imgSettled(beforeImg), imgSettled(afterImg)]);
if (photoJobRow !== r) return;
const beforeOk = photoJobImgOk(beforeImg);
const afterOk = photoJobImgOk(afterImg);
if (!beforeOk && afterOk) {
beforeImg.src = thumbUrl(r.after_path);
await imgSettled(beforeImg);
if (photoJobRow !== r) return;
}
updatePhotoJobLayers(r, beforeOk, afterOk);
}
function openPhotoJob(r) { function openPhotoJob(r) {
photoJobRow = r; photoJobRow = r;
document.getElementById('photoJobTitle').textContent = `Обработка фото — запись #${r.entry_id} ${r.student_name || ''}`; document.getElementById('photoJobTitle').textContent = `Обработка фото — запись #${r.entry_id} ${r.student_name || ''}`;
document.getElementById('photoJobBefore').src = thumbUrl(r.before_path); document.getElementById('photoJobNote').style.display = 'none';
document.getElementById('photoJobAfter').src = r.after_path ? `${API}${r.after_path}` : ''; document.getElementById('photoJobEmpty').style.display = 'none';
document.getElementById('photoJobRollbackBtn').style.display = (r.before_path && r.action !== 'rollback') ? '' : 'none'; document.getElementById('photoJobRollbackBtn').style.display = (r.before_path && r.action !== 'rollback') ? '' : 'none';
renderPhotoJobMeta(r); renderPhotoJobMeta(r);
loadPhotoJobMeta().then(() => { if (photoJobRow === r) renderPhotoJobMeta(r); }); loadPhotoJobMeta().then(() => { if (photoJobRow === r) renderPhotoJobMeta(r); });
setPhotoJobClip(50); setPhotoJobClip(50);
document.getElementById('photoJobModal').classList.add('open'); document.getElementById('photoJobModal').classList.add('open');
loadPhotoJobImages(r);
} }
async function loadPhoto() { async function loadPhoto() {
+9 -3
View File
@@ -19,6 +19,10 @@
.enhance-badge.left { left: 10px; } .enhance-badge.left { left: 10px; }
.enhance-badge.right { right: 10px; } .enhance-badge.right { right: 10px; }
.photo-thumb { width: 56px; height: 56px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border); display: block; } .photo-thumb { width: 56px; height: 56px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border); display: block; }
.photo-na { display: flex; align-items: center; justify-content: center; width: 56px; height: 56px; padding: 0 4px; box-sizing: border-box; border: 1px dashed var(--border); border-radius: 6px; background: var(--bg); color: var(--muted); font-size: .6rem; line-height: 1.15; text-align: center; overflow: hidden; }
#photoJobModal .edit-modal { width: min(1100px, 94vw); max-width: none; max-height: 94vh; overflow-y: auto; }
#photoJobCompare { min-height: 220px; }
.enhance-empty { position: absolute; inset: 0; display: none; align-items: center; justify-content: center; padding: 24px; text-align: center; color: var(--muted); font-size: .85rem; background: var(--bg); }
</style> </style>
</head> </head>
<body data-page="worker"> <body data-page="worker">
@@ -163,7 +167,7 @@
</div> </div>
</div> </div>
<div class="modal-overlay" id="photoJobModal"> <div class="modal-overlay" id="photoJobModal">
<div class="edit-modal" style="max-width:900px"> <div class="edit-modal">
<h3 id="photoJobTitle">Обработка фотографии</h3> <h3 id="photoJobTitle">Обработка фотографии</h3>
<div class="enhance-compare" id="photoJobCompare"> <div class="enhance-compare" id="photoJobCompare">
<div class="enhance-stage"> <div class="enhance-stage">
@@ -175,9 +179,11 @@
</div> </div>
</div> </div>
<div class="enhance-divider" id="photoJobDivider"><div class="enhance-handle">⇔</div></div> <div class="enhance-divider" id="photoJobDivider"><div class="enhance-handle">⇔</div></div>
<div class="enhance-badge left">Было</div> <div class="enhance-badge left" id="photoJobBadgeBefore">Было</div>
<div class="enhance-badge right">Стало</div> <div class="enhance-badge right" id="photoJobBadgeAfter">Стало</div>
<div class="enhance-empty" id="photoJobEmpty"></div>
</div> </div>
<div class="hint" id="photoJobNote" style="display:none"></div>
<div class="data-stats" id="photoJobMeta" style="margin-top:12px"></div> <div class="data-stats" id="photoJobMeta" style="margin-top:12px"></div>
<div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:14px"> <div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:14px">
<button type="button" class="btn-primary ghost" id="photoJobCloseBtn">Закрыть</button> <button type="button" class="btn-primary ghost" id="photoJobCloseBtn">Закрыть</button>
+437 -30
View File
@@ -352,7 +352,15 @@ async function pushNotification({ type, title, body, link, target, branchId, lev
} }
} }
async function notifyEntry(entryId, { type, title, body, link, target, level }) { async function notifyEntry(entryIdOrJob, { type, title, body, link, target, level }) {
if (entryIdOrJob && typeof entryIdOrJob === 'object' && !Array.isArray(entryIdOrJob)) {
const job = entryIdOrJob;
if (job.group_photo_id) {
return notifyGroupPhoto(job.group_photo_id, { type, title, body, link, target, level });
}
return notifyEntry(job.entry_id, { type, title, body, link, target, level });
}
const entryId = entryIdOrJob;
const id = parseInt(entryId, 10); const id = parseInt(entryId, 10);
if (!Number.isInteger(id) || id < 1) return null; if (!Number.isInteger(id) || id < 1) return null;
const { rows } = await pool.query( const { rows } = await pool.query(
@@ -376,6 +384,30 @@ async function notifyEntry(entryId, { type, title, body, link, target, level })
}); });
} }
async function notifyGroupPhoto(groupPhotoId, { type, title, body, link, target, level }) {
const id = parseInt(groupPhotoId, 10);
if (!Number.isInteger(id) || id < 1) return null;
const { rows } = await pool.query(
`SELECT gp.id, gp.group_id, g.name AS group_name, g.branch_id
FROM group_photos gp LEFT JOIN groups g ON g.id = gp.group_id WHERE gp.id = $1`,
[id]
);
if (!rows.length) return null;
const ctx = rows[0];
const fill = s => String(s === null || s === undefined ? '' : s)
.replace(/\{student\}/g, '')
.replace(/\{group\}/g, ctx.group_name || '—');
return pushNotification({
type,
level,
title: fill(title),
body: fill(body),
link: link || 'groups.html',
target: Object.assign({ group_photo_id: ctx.id, group_id: ctx.group_id, group_name: ctx.group_name }, target || {}),
branchId: ctx.branch_id,
});
}
async function notifyEntryCreated(entryId) { async function notifyEntryCreated(entryId) {
return notifyEntry(entryId, { return notifyEntry(entryId, {
type: 'entry.new', type: 'entry.new',
@@ -796,6 +828,15 @@ app.get('/uploads/*', async (req, res) => {
app.use('/vendor', express.static(path.join(__dirname, 'public', 'vendor'), { maxAge: '30d' })); app.use('/vendor', express.static(path.join(__dirname, 'public', 'vendor'), { maxAge: '30d' }));
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
app.get('/certs/cert.pem', (req, res) => {
const certPath = path.join(__dirname, 'certs', 'cert.pem');
if (fs.existsSync(certPath)) {
res.download(certPath, 'cert.pem');
} else {
res.status(404).send('Certificate not found');
}
});
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
function formatBytes(bytes) { function formatBytes(bytes) {
@@ -1495,10 +1536,11 @@ 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: 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 }] = 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'),
pool.query('SELECT photo_original_path AS p FROM group_photos WHERE photo_original_path IS NOT NULL'),
pool.query('SELECT photo_path AS p FROM entry_photos'), pool.query('SELECT photo_path AS p FROM entry_photos'),
pool.query(`SELECT after_path AS p FROM photo_jobs WHERE status = 'done' AND applied = false AND after_path IS NOT NULL`), pool.query(`SELECT after_path AS p FROM photo_jobs WHERE status = 'done' AND applied = false AND after_path IS NOT NULL`),
pool.query('SELECT photo_path AS p FROM modules WHERE photo_path IS NOT NULL'), pool.query('SELECT photo_path AS p FROM modules WHERE photo_path IS NOT NULL'),
@@ -1511,7 +1553,7 @@ async function sweepOrphanedUploads() {
pool.query('SELECT path AS p FROM chat_attachments'), pool.query('SELECT path AS p FROM chat_attachments'),
]); ]);
const refs = new Set(); const refs = new Set();
[...photos, ...files, ...gphotos, ...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].forEach(r => {
const key = storage.keyFromPath(r.p); const key = storage.keyFromPath(r.p);
if (key) refs.add(key); if (key) refs.add(key);
}); });
@@ -1653,6 +1695,7 @@ async function ensureLessonReportsTable() {
async function ensurePhotoOriginalColumn() { async function ensurePhotoOriginalColumn() {
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255)`); await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255)`);
await pool.query(`ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255)`);
} }
async function ensureEntryAiColumns() { async function ensureEntryAiColumns() {
@@ -1689,7 +1732,8 @@ async function ensureEntryAiColumns() {
async function ensurePhotoJobsTable() { async function ensurePhotoJobsTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS photo_jobs ( await pool.query(`CREATE TABLE IF NOT EXISTS photo_jobs (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
entry_id INT NOT NULL REFERENCES entries(id) ON DELETE CASCADE, entry_id INT REFERENCES entries(id) ON DELETE CASCADE,
group_photo_id INT REFERENCES group_photos(id) ON DELETE CASCADE,
action VARCHAR(20) NOT NULL DEFAULT 'ai', action VARCHAR(20) NOT NULL DEFAULT 'ai',
params JSONB, params JSONB,
before_path VARCHAR(255), before_path VARCHAR(255),
@@ -1702,8 +1746,11 @@ async function ensurePhotoJobsTable() {
finished_at TIMESTAMPTZ finished_at TIMESTAMPTZ
)`); )`);
await pool.query(`ALTER TABLE photo_jobs ADD COLUMN IF NOT EXISTS applied BOOLEAN NOT NULL DEFAULT false`); await pool.query(`ALTER TABLE photo_jobs ADD COLUMN IF NOT EXISTS applied BOOLEAN NOT NULL DEFAULT false`);
await pool.query(`ALTER TABLE photo_jobs ADD COLUMN IF NOT EXISTS group_photo_id INT REFERENCES group_photos(id) ON DELETE CASCADE`);
await pool.query(`ALTER TABLE photo_jobs ALTER COLUMN entry_id DROP NOT NULL`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending'`); await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending'`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id)`); await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id)`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_group_photo_id ON photo_jobs(group_photo_id)`);
await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true') ON CONFLICT (key) DO NOTHING`); await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true') ON CONFLICT (key) DO NOTHING`);
await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_ai_face_mode', 'off') ON CONFLICT (key) DO NOTHING`); await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_ai_face_mode', 'off') ON CONFLICT (key) DO NOTHING`);
await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_ai_face_model', $1) ON CONFLICT (key) DO NOTHING`, [PHOTO_AI_FACE_MODEL]); await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_ai_face_model', $1) ON CONFLICT (key) DO NOTHING`, [PHOTO_AI_FACE_MODEL]);
@@ -4706,11 +4753,18 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
); );
} }
for (const x of ndata.photo_jobs) { for (const x of ndata.photo_jobs) {
const ex = await client.query('SELECT 1 FROM entries WHERE id = $1', [x.entry_id]); let ok = false;
if (!ex.rowCount) continue; if (x.group_photo_id) {
const gpx = await client.query('SELECT 1 FROM group_photos WHERE id = $1', [x.group_photo_id]);
ok = !!gpx.rowCount;
} else if (x.entry_id) {
const ex = await client.query('SELECT 1 FROM entries WHERE id = $1', [x.entry_id]);
ok = !!ex.rowCount;
}
if (!ok) continue;
await client.query( await client.query(
'INSERT INTO photo_jobs (id, entry_id, action, params, before_path, after_path, status, applied, attempts, error, created_at, finished_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)', 'INSERT INTO photo_jobs (id, entry_id, group_photo_id, action, params, before_path, after_path, status, applied, attempts, error, created_at, finished_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)',
[x.id, x.entry_id, x.action, x.params, x.before_path, x.after_path, x.status, x.applied, x.attempts, x.error, x.created_at, x.finished_at] [x.id, x.entry_id || null, x.group_photo_id || null, x.action, x.params, x.before_path, x.after_path, x.status, x.applied, x.attempts, x.error, x.created_at, x.finished_at]
); );
} }
for (const x of ndata.project_files) { for (const x of ndata.project_files) {
@@ -4721,8 +4775,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
} }
for (const x of ndata.group_photos) { for (const x of ndata.group_photos) {
await client.query( await client.query(
'INSERT INTO group_photos (id, group_id, photo_path, caption, taken_at, sort_order, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)', 'INSERT INTO group_photos (id, group_id, photo_path, photo_original_path, caption, taken_at, sort_order, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
[x.id, x.group_id, x.photo_path, x.caption, x.taken_at, x.sort_order, x.created_at] [x.id, x.group_id, x.photo_path, x.photo_original_path || null, x.caption, x.taken_at, x.sort_order, x.created_at]
); );
} }
for (const x of ndata.entry_photos) { for (const x of ndata.entry_photos) {
@@ -5310,7 +5364,9 @@ async function hardDeleteGroup(groupId) {
await client.query('BEGIN'); await client.query('BEGIN');
const g = await client.query('SELECT id FROM groups WHERE id = $1', [groupId]); const g = await client.query('SELECT id FROM groups WHERE id = $1', [groupId]);
if (!g.rowCount) { await client.query('ROLLBACK'); return null; } if (!g.rowCount) { await client.query('ROLLBACK'); return null; }
const gres = await client.query('SELECT photo_path AS p FROM group_photos WHERE group_id = $1', [groupId]); const gres = await client.query(`SELECT photo_path AS p FROM group_photos WHERE group_id = $1
UNION ALL
SELECT photo_original_path AS p FROM group_photos WHERE group_id = $1 AND photo_original_path IS NOT NULL`, [groupId]);
const eres = await client.query( const eres = await client.query(
`SELECT photo_path AS p FROM entries WHERE group_id = $1 `SELECT photo_path AS p FROM entries WHERE group_id = $1
UNION ALL UNION ALL
@@ -5612,11 +5668,12 @@ app.delete('/api/groups/:id/photos/:photoId', requireAuth, async (req, res) => {
return res.status(403).json({ error: 'Нет доступа к этой группе' }); return res.status(403).json({ error: 'Нет доступа к этой группе' });
} }
const { rows } = await pool.query( const { rows } = await pool.query(
'SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', 'SELECT photo_path, photo_original_path FROM group_photos WHERE id = $1 AND group_id = $2',
[req.params.photoId, req.params.id] [req.params.photoId, req.params.id]
); );
if (!rows.length) return res.status(404).json({ error: 'Не найдено' }); if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
safeUnlink(rows[0].photo_path); safeUnlink(rows[0].photo_path);
if (rows[0].photo_original_path) safeUnlink(rows[0].photo_original_path);
await pool.query('UPDATE groups SET cover_path = NULL WHERE id = $1 AND cover_path = $2', [req.params.id, rows[0].photo_path]); await pool.query('UPDATE groups SET cover_path = NULL WHERE id = $1 AND cover_path = $2', [req.params.id, rows[0].photo_path]);
await pool.query('DELETE FROM group_photos WHERE id = $1', [req.params.photoId]); await pool.query('DELETE FROM group_photos WHERE id = $1', [req.params.photoId]);
await logAudit(req, 'group.photo.delete', { group_id: req.params.id, photo_id: req.params.photoId }); await logAudit(req, 'group.photo.delete', { group_id: req.params.id, photo_id: req.params.photoId });
@@ -5643,6 +5700,314 @@ app.put('/api/groups/:id/photos/:photoId/cover', requireAuth, async (req, res) =
res.json(gRows[0]); res.json(gRows[0]);
}); });
app.post('/api/groups/:id/photos/:photoId/enhance-ai', requireAuth, async (req, res) => {
if (!PHOTO_AI_URL) return res.status(503).json({ error: 'ИИ-обработка фото не настроена' });
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(photoId)) return res.status(404).json({ error: 'Фото не найдено' });
const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {};
const hasParams = Object.keys(body).some((k) => body[k] !== undefined && body[k] !== null && body[k] !== '');
const parsed = hasParams ? parsePhotoAiRequest(body) : { action: 'ai', params: null };
if (parsed.error) return res.status(400).json({ error: parsed.error });
const { rows: cur } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, req.params.id]);
if (!cur.length) return res.status(404).json({ error: 'Фото не найдено' });
if (!cur[0].photo_path) return res.status(400).json({ error: 'У фото нет изображения' });
try {
const { rows } = await pool.query(
`INSERT INTO photo_jobs (group_photo_id, action, status, params) VALUES ($1, $2, 'pending', $3) RETURNING id`,
[photoId, parsed.action, parsed.params ? JSON.stringify(parsed.params) : null]
);
if (photoWorker) photoWorker.notify();
await logAudit(req, 'group.photo.enhance-ai.queue', {
group_id: req.params.id,
photo_id: photoId,
job_id: rows[0].id,
action: parsed.action,
params: parsed.params,
});
res.json({ jobId: rows[0].id, action: parsed.action, params: parsed.params });
} catch (e) {
console.error('POST /api/groups/:id/photos/:photoId/enhance-ai:', e);
res.status(500).json({ error: 'Ошибка постановки задания в очередь' });
}
});
app.get('/api/groups/:id/photos/:photoId/enhance-ai/:jobId', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
try {
const jobId = parseInt(req.params.jobId, 10);
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
const { rows } = await pool.query(
'SELECT id, status, error, after_path, applied FROM photo_jobs WHERE id = $1 AND group_photo_id = $2',
[jobId, photoId]
);
if (!rows.length) return res.status(404).json({ error: 'Задание не найдено' });
const job = rows[0];
const out = { status: job.status, applied: job.applied, job_id: job.id };
if (job.status === 'error') out.error = job.error;
if (job.status === 'done') out.photo_path = job.after_path;
res.json(out);
} catch (e) {
console.error('GET /api/groups/:id/photos/:photoId/enhance-ai/:jobId:', e);
res.status(500).json({ error: 'Ошибка получения статуса задания' });
}
});
app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/apply', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
const client = await pool.connect();
try {
const jobId = parseInt(req.params.jobId, 10);
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
await client.query('BEGIN');
const { rows: jobRows } = await client.query(
`SELECT id, group_photo_id, action, status, applied, after_path FROM photo_jobs
WHERE id = $1 AND group_photo_id = $2 FOR UPDATE`,
[jobId, photoId]
);
const job = jobRows[0];
if (!job) { await client.query('ROLLBACK'); return res.status(404).json({ error: 'Задание не найдено' }); }
if (job.status !== 'done') { await client.query('ROLLBACK'); return res.status(400).json({ error: 'Результат ещё не готов' }); }
if (job.applied) { await client.query('ROLLBACK'); return res.status(400).json({ error: 'Результат уже применён' }); }
if (!job.after_path || !isSafeUploadPath(job.after_path)) {
await client.query('ROLLBACK');
return res.status(400).json({ error: 'Некорректный путь результата' });
}
if (!(await storage.exists(job.after_path))) {
await client.query('ROLLBACK');
return res.status(400).json({ error: 'Файл результата не найден' });
}
const { rows: photoRows } = await client.query(
'SELECT group_id, photo_path, photo_original_path FROM group_photos WHERE id = $1 AND group_id = $2 FOR UPDATE',
[photoId, req.params.id]
);
if (!photoRows.length) { await client.query('ROLLBACK'); return res.status(404).json({ error: 'Фото не найдено' }); }
const oldPath = photoRows[0].photo_path;
if (oldPath === job.after_path) {
await client.query('UPDATE photo_jobs SET applied = true WHERE id = $1', [jobId]);
await client.query('COMMIT');
await logAudit(req, 'group.photo.apply', { group_id: req.params.id, photo_id: photoId, job_id: jobId, after_path: job.after_path });
invalidateShare();
invalidateGroups();
invalidateStats();
return res.json({ ok: true, photo_path: job.after_path });
}
let originalPath = photoRows[0].photo_original_path;
let beforePath = originalPath;
const oldKey = oldPath ? storage.keyFromPath(oldPath) : null;
if (oldKey && (await storage.exists(oldKey))) {
try {
const backupKey = `.originals/${crypto.randomBytes(12).toString('hex')}${path.extname(oldKey) || '.jpg'}`;
if (await storage.copyObject(oldKey, backupKey)) {
beforePath = `/uploads/${backupKey}`;
if (!originalPath) originalPath = beforePath;
safeUnlink(oldKey);
}
} catch (e) {
console.error('group photo apply backup failed:', e);
}
}
await client.query('UPDATE group_photos SET photo_path = $1, photo_original_path = $2 WHERE id = $3 AND group_id = $4', [job.after_path, originalPath, photoId, req.params.id]);
await client.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [job.after_path, req.params.id, oldPath]);
thumbUnlinkFor(oldPath);
await client.query(`UPDATE photo_jobs SET applied = true, before_path = COALESCE(before_path, $1) WHERE id = $2`, [beforePath, jobId]);
await client.query('COMMIT');
await logAudit(req, 'group.photo.apply', { group_id: req.params.id, photo_id: photoId, job_id: jobId, before_path: beforePath, after_path: job.after_path });
invalidateShare();
invalidateGroups();
invalidateStats();
res.json({ ok: true, photo_path: job.after_path });
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
console.error('POST /api/groups/:id/photos/:photoId/jobs/:jobId/apply:', e);
res.status(500).json({ error: 'Ошибка применения фотографии' });
} finally {
client.release();
}
});
app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/reject', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
try {
const jobId = parseInt(req.params.jobId, 10);
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
const { rows } = await pool.query(
`SELECT id, status, applied, after_path FROM photo_jobs WHERE id = $1 AND group_photo_id = $2`,
[jobId, photoId]
);
const job = rows[0];
if (!job) return res.status(404).json({ error: 'Задание не найдено' });
if (job.applied) return res.status(400).json({ error: 'Результат уже применён' });
if (job.status === 'done' && job.after_path && isSafeUploadPath(job.after_path)) safeUnlink(job.after_path);
await pool.query(
`UPDATE photo_jobs SET status = 'rejected', error = 'Отклонено пользователем', finished_at = now()
WHERE id = $1 AND applied = false`,
[jobId]
);
await logAudit(req, 'group.photo.reject', { group_id: req.params.id, photo_id: photoId, job_id: jobId });
res.json({ ok: true });
} catch (e) {
console.error('POST /api/groups/:id/photos/:photoId/jobs/:jobId/reject:', e);
res.status(500).json({ error: 'Ошибка отклонения результата' });
}
});
app.put('/api/groups/:id/photos/:photoId/enhance', requireAuth, (req, res, next) => {
if (req.is('json')) return next();
upload.single('photo')(req, res, next);
}, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
try {
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(photoId)) {
if (req.file) safeUnlink(req.file.path);
return res.status(404).json({ error: 'Фото не найдено' });
}
const { rows: cur } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, req.params.id]);
if (!cur.length) {
if (req.file) safeUnlink(req.file.path);
return res.status(404).json({ error: 'Фото не найдено' });
}
const oldPath = cur[0].photo_path;
if (!oldPath) {
if (req.file) safeUnlink(req.file.path);
return res.status(400).json({ error: 'У фото нет изображения' });
}
let newPath;
let engine = 'client';
if (req.is('json')) {
if (!sharp) return res.status(503).json({ error: 'sharp недоступен на сервере' });
const p = req.body.params || {};
const brightness = clampEnhanceParam(p.brightness, 10, 300, 100);
const contrast = clampEnhanceParam(p.contrast, 10, 300, 100);
const saturate = clampEnhanceParam(p.saturate, 0, 300, 100);
const sharpAmt = clampEnhanceParam(p.sharp, 0, 100, 0);
const denoise = clampEnhanceParam(p.denoise, 0, 100, 0);
const srcKey = storage.keyFromPath(oldPath);
const srcPath = srcKey ? await storage.localize(srcKey) : null;
if (!srcPath) return res.status(400).json({ error: 'Файл фото не найден' });
let pipeline = sharp(srcPath).rotate();
if (denoise > 0) pipeline = pipeline.median(denoise > 70 ? 5 : 3);
pipeline = pipeline.modulate({ brightness: brightness / 100, saturation: saturate / 100 });
if (contrast !== 100) {
const a = contrast / 100;
pipeline = pipeline.linear(a, 128 * (1 - a));
}
if (sharpAmt > 0) {
pipeline = pipeline.sharpen({ sigma: 0.5 + (sharpAmt / 100) * 1.5, m1: 0, m2: 1 + sharpAmt / 50 });
}
const newName = crypto.randomBytes(12).toString('hex') + '.jpg';
const outPath = path.join(UPLOADS_DIR, newName);
await pipeline.jpeg({ quality: 92, mozjpeg: true }).toFile(outPath);
await storage.persist(newName, outPath);
newPath = `/uploads/${newName}`;
engine = 'sharp';
} else {
if (!req.file) return res.status(400).json({ error: 'Нет файла' });
await convertPhoto(req.file);
newPath = `/uploads/${req.file.filename}`;
}
await swapGroupPhotoFiles(req, req.params.id, photoId, oldPath, newPath, { action: 'enhance' });
res.json({ ok: true, photo_path: newPath, engine });
} catch (e) {
if (req.file) safeUnlink(req.file.path);
console.error('PUT /api/groups/:id/photos/:photoId/enhance:', e);
res.status(500).json({ error: 'Ошибка замены фото' });
}
});
app.get('/api/groups/:id/photos/:photoId/jobs', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(photoId)) return res.status(404).json({ error: 'Фото не найдено' });
const { rows } = await pool.query(
`SELECT j.id, j.action, j.status, j.applied, j.params, j.before_path, j.after_path, j.error, j.created_at, j.finished_at
FROM photo_jobs j
JOIN group_photos p ON p.id = j.group_photo_id
WHERE j.group_photo_id = $1 AND p.group_id = $2
ORDER BY j.id DESC LIMIT 50`,
[photoId, req.params.id]
);
res.json(rows);
});
app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/rollback', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
try {
const jobId = parseInt(req.params.jobId, 10);
const photoId = parseInt(req.params.photoId, 10);
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
const { rows: jobRows } = await pool.query(
`SELECT id, before_path FROM photo_jobs WHERE id = $1 AND group_photo_id = $2 AND status = 'done'`,
[jobId, photoId]
);
if (!jobRows.length) return res.status(404).json({ error: 'Задание не найдено' });
const job = jobRows[0];
if (!job.before_path || !job.before_path.startsWith('/uploads/.originals/')) {
return res.status(400).json({ error: 'Нет сохранённой версии для отката' });
}
const beforeName = path.basename(job.before_path);
if (!/^[A-Za-z0-9._-]+$/.test(beforeName)) return res.status(400).json({ error: 'Некорректный путь' });
const beforeKey = `.originals/${beforeName}`;
if (!(await storage.exists(beforeKey))) return res.status(400).json({ error: 'Файл версии не найден' });
const { rows: cur } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, req.params.id]);
if (!cur.length) return res.status(404).json({ error: 'Фото не найдено' });
const oldPath = cur[0].photo_path;
if (!oldPath) return res.status(400).json({ error: 'У фото нет изображения' });
const ext = path.extname(beforeName) || '.jpg';
const newKey = `${crypto.randomBytes(12).toString('hex')}${ext}`;
const newPath = `/uploads/${newKey}`;
if (!(await storage.copyObject(beforeKey, newKey))) {
return res.status(400).json({ error: 'Файл версии не найден' });
}
const oldKey = storage.keyFromPath(oldPath);
let rollbackBefore = null;
if (oldKey && (await storage.exists(oldKey))) {
try {
const backupKey = `.originals/${crypto.randomBytes(12).toString('hex')}${path.extname(oldKey) || '.jpg'}`;
if (await storage.copyObject(oldKey, backupKey)) {
rollbackBefore = `/uploads/${backupKey}`;
safeUnlink(oldKey);
}
} catch (e) {
console.error('group photo rollback backup failed:', e);
}
}
thumbUnlinkFor(oldPath);
await pool.query('UPDATE group_photos SET photo_path = $1 WHERE id = $2 AND group_id = $3', [newPath, photoId, req.params.id]);
await pool.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [newPath, req.params.id, oldPath]);
await pool.query(
'INSERT INTO photo_jobs (group_photo_id, action, status, before_path, after_path, finished_at) VALUES ($1, $2, $3, $4, $5, now())',
[photoId, 'rollback', 'done', rollbackBefore, newPath]
);
await logAudit(req, 'group.photo.rollback', { group_id: req.params.id, photo_id: photoId, job_id: jobId, restored_path: newPath });
invalidateShare();
invalidateGroups();
invalidateStats();
res.json({ ok: true, photo_path: newPath });
} catch (e) {
console.error('POST /api/groups/:id/photos/:photoId/jobs/:jobId/rollback:', e);
res.status(500).json({ error: 'Ошибка отката фотографии' });
}
});
// --- Modules (темы модулей) --- // --- Modules (темы модулей) ---
app.get('/api/modules', apiLimiter, async (req, res) => { app.get('/api/modules', apiLimiter, async (req, res) => {
const { limit, offset, search, active } = req.query; const { limit, offset, search, active } = req.query;
@@ -6321,7 +6686,7 @@ app.delete('/api/students/:id', requireAuth, async (req, res) => {
); );
if (!cur.length) return res.status(404).json({ error: 'Not found' }); if (!cur.length) return res.status(404).json({ error: 'Not found' });
const gid = cur[0].group_id; const gid = cur[0].group_id;
if (gid && !(await groupBelongsToBranches(req.user, gid))) { if (!(await groupBelongsToBranches(req.user, gid))) {
return res.status(403).json({ error: 'Нет доступа к этому ученику' }); return res.status(403).json({ error: 'Нет доступа к этому ученику' });
} }
} }
@@ -6344,7 +6709,7 @@ app.put('/api/students/:id/restore', requireAuth, async (req, res) => {
); );
if (!cur.length) return res.status(404).json({ error: 'Not found' }); if (!cur.length) return res.status(404).json({ error: 'Not found' });
const gid = cur[0].group_id; const gid = cur[0].group_id;
if (gid && !(await groupBelongsToBranches(req.user, gid))) { if (!(await groupBelongsToBranches(req.user, gid))) {
return res.status(403).json({ error: 'Нет доступа к этому ученику' }); return res.status(403).json({ error: 'Нет доступа к этому ученику' });
} }
} }
@@ -6367,7 +6732,7 @@ app.delete('/api/students/:id/permanent', requireAuth, async (req, res) => {
); );
if (!cur.length) return res.status(404).json({ error: 'Not found' }); if (!cur.length) return res.status(404).json({ error: 'Not found' });
const gid = cur[0].group_id; const gid = cur[0].group_id;
if (gid && !(await groupBelongsToBranches(req.user, gid))) { if (!(await groupBelongsToBranches(req.user, gid))) {
return res.status(403).json({ error: 'Нет доступа к этому ученику' }); return res.status(403).json({ error: 'Нет доступа к этому ученику' });
} }
} }
@@ -6392,7 +6757,7 @@ app.put('/api/students/:id/unschedule', requireAuth, async (req, res) => {
); );
if (!cur.length) return res.status(404).json({ error: 'Not found' }); if (!cur.length) return res.status(404).json({ error: 'Not found' });
const gid = cur[0].group_id; const gid = cur[0].group_id;
if (gid && !(await groupBelongsToBranches(req.user, gid))) { if (!(await groupBelongsToBranches(req.user, gid))) {
return res.status(403).json({ error: 'Нет доступа к этому ученику' }); return res.status(403).json({ error: 'Нет доступа к этому ученику' });
} }
} }
@@ -7445,7 +7810,7 @@ app.post('/api/files/:id/detach', requireAuth, async (req, res) => {
); );
if (!rows.length) return res.status(404).json({ error: 'Не найдено' }); if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
const { entry_id, group_id } = rows[0]; const { entry_id, group_id } = rows[0];
if (!entry_id || (group_id && !(await groupBelongsToBranches(req.user, group_id)))) { if (!entry_id || !(await groupBelongsToBranches(req.user, group_id))) {
return res.status(403).json({ error: 'Нет доступа к этому файлу' }); return res.status(403).json({ error: 'Нет доступа к этому файлу' });
} }
} }
@@ -7467,7 +7832,7 @@ app.delete('/api/files/:id', requireAuth, async (req, res) => {
); );
if (!rows.length) return res.status(404).json({ error: 'Не найдено' }); if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
const { entry_id, group_id } = rows[0]; const { entry_id, group_id } = rows[0];
if (!entry_id || (group_id && !(await groupBelongsToBranches(req.user, group_id)))) { if (!entry_id || !(await groupBelongsToBranches(req.user, group_id))) {
return res.status(403).json({ error: 'Нет доступа к этому файлу' }); return res.status(403).json({ error: 'Нет доступа к этому файлу' });
} }
} }
@@ -8163,6 +8528,40 @@ async function swapEntryPhotoFiles(req, entryId, oldPath, newPath, { keepOrigina
invalidateEntries(); invalidateEntries();
} }
async function swapGroupPhotoFiles(req, groupId, photoId, oldPath, newPath, { keepOriginal = true, action = 'enhance' } = {}) {
let originalPath = null;
const { rows: prevRows } = await pool.query('SELECT photo_original_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, groupId]);
const prevOriginal = prevRows.length ? prevRows[0].photo_original_path : null;
const oldKey = storage.keyFromPath(oldPath);
if (prevOriginal) {
originalPath = prevOriginal;
if (oldKey) safeUnlink(oldKey);
} else if (keepOriginal && oldKey && (await storage.exists(oldKey))) {
try {
const backupKey = `.originals/${crypto.randomBytes(12).toString('hex')}${path.extname(oldKey) || '.jpg'}`;
if (await storage.copyObject(oldKey, backupKey)) {
originalPath = `/uploads/${backupKey}`;
safeUnlink(oldKey);
}
} catch (e) {
console.error('photo original backup failed:', e);
}
} else if (oldKey) {
safeUnlink(oldKey);
}
await pool.query('UPDATE group_photos SET photo_path = $1, photo_original_path = $2 WHERE id = $3 AND group_id = $4', [newPath, originalPath, photoId, groupId]);
await pool.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [newPath, groupId, oldPath]);
thumbUnlinkFor(oldPath);
await pool.query(
'INSERT INTO photo_jobs (group_photo_id, action, status, before_path, after_path, finished_at) VALUES ($1, $2, $3, $4, $5, now())',
[photoId, action, 'done', originalPath, newPath]
);
await logAudit(req, 'group.photo.enhance', { group_id: groupId, photo_id: photoId, old_path: oldPath, new_path: newPath, original_path: originalPath });
invalidateShare();
invalidateGroups();
invalidateStats();
}
app.put('/api/entries/:id/photo/enhance', requireAuth, (req, res, next) => { app.put('/api/entries/:id/photo/enhance', requireAuth, (req, res, next) => {
if (req.is('json')) return next(); if (req.is('json')) return next();
upload.single('photo')(req, res, next); upload.single('photo')(req, res, next);
@@ -8578,7 +8977,7 @@ app.delete('/api/entries/:id', requireAuth, async (req, res) => {
if (!acc.found) return res.status(404).json({ error: 'Not found' }); if (!acc.found) return res.status(404).json({ error: 'Not found' });
if (!acc.allowed) return res.status(403).json({ error: 'Нет доступа к этой записи' }); if (!acc.allowed) return res.status(403).json({ error: 'Нет доступа к этой записи' });
} }
await pool.query('UPDATE entries SET deleted_at = now() WHERE id = $1', [req.params.id]); await pool.query('UPDATE entries SET deleted_at = now(), purge_at = NULL WHERE id = $1 AND deleted_at IS NULL', [req.params.id]);
await logAudit(req, 'entry.soft-delete', { id: req.params.id }); await logAudit(req, 'entry.soft-delete', { id: req.params.id });
invalidateEntries(); invalidateEntries();
invalidateStats(); invalidateStats();
@@ -8590,12 +8989,10 @@ app.put('/api/entries/:id/restore', requireAuth, async (req, res) => {
const acc = await entryAccessible(req.user, req.params.id); const acc = await entryAccessible(req.user, req.params.id);
if (!acc.found) return res.status(404).json({ error: 'Not found' }); if (!acc.found) return res.status(404).json({ error: 'Not found' });
if (!acc.allowed) { if (!acc.allowed) {
console.warn(`[RESTORE DENIED] User ${req.user.id} (${req.user.username}) role=${req.user.role} branches=${JSON.stringify(req.user.branch_ids)} tried to restore entry ${req.params.id} (group_id=${acc.group_id})`);
return res.status(403).json({ error: 'Нет доступа к этой записи' }); return res.status(403).json({ error: 'Нет доступа к этой записи' });
} }
} }
const result = await pool.query('UPDATE entries SET deleted_at = NULL, purge_at = NULL WHERE id = $1', [req.params.id]); const result = await pool.query('UPDATE entries SET deleted_at = NULL, purge_at = NULL WHERE id = $1 AND deleted_at IS NOT NULL', [req.params.id]);
console.log(`[RESTORE] User ${req.user.id} (${req.user.username}) restored entry ${req.params.id}, rowCount=${result.rowCount}`);
if (result.rowCount === 0) { if (result.rowCount === 0) {
return res.status(404).json({ error: 'Запись не найдена или уже восстановлена' }); return res.status(404).json({ error: 'Запись не найдена или уже восстановлена' });
} }
@@ -8610,7 +9007,6 @@ app.delete('/api/entries/:id/permanent', requireAuth, async (req, res) => {
const acc = await entryAccessible(req.user, req.params.id); const acc = await entryAccessible(req.user, req.params.id);
if (!acc.found) return res.status(404).json({ error: 'Not found' }); if (!acc.found) return res.status(404).json({ error: 'Not found' });
if (!acc.allowed) { if (!acc.allowed) {
console.warn(`[PERM DELETE DENIED] User ${req.user.id} (${req.user.username}) role=${req.user.role} branches=${JSON.stringify(req.user.branch_ids)} tried to perm delete entry ${req.params.id} (group_id=${acc.group_id})`);
return res.status(403).json({ error: 'Нет доступа к этой записи' }); return res.status(403).json({ error: 'Нет доступа к этой записи' });
} }
} }
@@ -9140,7 +9536,7 @@ async function trashData(req, mode, limit, offset) {
const stparams = []; const stparams = [];
const stscoped = req.user.role !== 'admin'; const stscoped = req.user.role !== 'admin';
const gsco2 = stscoped const gsco2 = stscoped
? (bw.ids.length ? ` AND s.group_id IN (${bw.ids.map(id => `$${stparams.push(id)})`).join(',')}` : ' AND 1 = 0') ? (bw.ids.length ? ` AND s.group_id IN (SELECT g.id FROM groups g WHERE g.branch_id = ANY($${stparams.push(bw.ids)}))` : ' AND 1 = 0')
: ''; : '';
const stOrder = isPending ? 's.purge_at' : 's.deleted_at'; const stOrder = isPending ? 's.purge_at' : 's.deleted_at';
const { rows: stcount } = await pool.query(`SELECT count(*)::int AS n FROM students s${stWhere}${gsco2}`, stparams); const { rows: stcount } = await pool.query(`SELECT count(*)::int AS n FROM students s${stWhere}${gsco2}`, stparams);
@@ -9149,15 +9545,26 @@ async function trashData(req, mode, limit, offset) {
} }
app.get('/api/trash', requireAuth, async (req, res) => { app.get('/api/trash', requireAuth, async (req, res) => {
const limit = parseInt(req.query.limit, 10); try {
const offset = parseInt(req.query.offset, 10); const limit = parseInt(req.query.limit, 10);
res.json(await trashData(req, 'visible', limit, offset)); const offset = parseInt(req.query.offset, 10);
const data = await trashData(req, 'visible', isNaN(limit) ? 100 : limit, isNaN(offset) ? 0 : offset);
res.json(data);
} catch (err) {
console.error('GET /api/trash error:', err.message);
res.status(500).json({ error: 'Ошибка загрузки корзины' });
}
}); });
app.get('/api/trash/pending', requireAuth, async (req, res) => { app.get('/api/trash/pending', requireAuth, async (req, res) => {
const data = await trashData(req, 'pending'); try {
data.purge_days = await trashPurgeDays(); const data = await trashData(req, 'pending');
res.json(data); data.purge_days = await trashPurgeDays();
res.json(data);
} catch (err) {
console.error('GET /api/trash/pending error:', err.message);
res.status(500).json({ error: 'Ошибка загрузки корзины' });
}
}); });
app.delete('/api/trash', requireAuth, requireAdmin, async (req, res) => { app.delete('/api/trash', requireAuth, requireAdmin, async (req, res) => {
+49 -31
View File
@@ -52,10 +52,10 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
const DEFAULT_MODEL = String(defaultModel || PHOTO_AI_DEFAULT_MODEL).trim() || PHOTO_AI_DEFAULT_MODEL; const DEFAULT_MODEL = String(defaultModel || PHOTO_AI_DEFAULT_MODEL).trim() || PHOTO_AI_DEFAULT_MODEL;
const DEFAULT_FACE_MODEL = String(defaultFaceModel || PHOTO_AI_DEFAULT_FACE_MODEL).trim() || PHOTO_AI_DEFAULT_FACE_MODEL; const DEFAULT_FACE_MODEL = String(defaultFaceModel || PHOTO_AI_DEFAULT_FACE_MODEL).trim() || PHOTO_AI_DEFAULT_FACE_MODEL;
async function sendNotification(entryId, payload) { async function sendNotification(job, payload) {
if (!notifyEvent) return; if (!notifyEvent) return;
try { try {
await notifyEvent(entryId, payload); await notifyEvent(job, payload);
} catch (e) { } catch (e) {
console.error('Photo worker notification failed:', e.message); console.error('Photo worker notification failed:', e.message);
} }
@@ -112,7 +112,7 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
try { try {
await client.query('BEGIN'); await client.query('BEGIN');
const { rows } = await client.query( const { rows } = await client.query(
`SELECT j.id, j.entry_id, j.action, j.params `SELECT j.id, j.entry_id, j.group_photo_id, j.action, j.params
FROM photo_jobs j FROM photo_jobs j
WHERE j.status = 'pending' WHERE j.status = 'pending'
ORDER BY j.id ASC LIMIT 1 FOR UPDATE SKIP LOCKED` ORDER BY j.id ASC LIMIT 1 FOR UPDATE SKIP LOCKED`
@@ -297,7 +297,8 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
); );
if (logAudit) { if (logAudit) {
await logAudit(null, 'photo.job.preview', { await logAudit(null, 'photo.job.preview', {
entry_id: job.entry_id, entry_id: job.entry_id || null,
group_photo_id: job.group_photo_id || null,
job_id: job.id, job_id: job.id,
action: job.action, action: job.action,
after_path: newPath, after_path: newPath,
@@ -310,18 +311,22 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
warnings: m.warnings && m.warnings.length ? m.warnings : null, warnings: m.warnings && m.warnings.length ? m.warnings : null,
}); });
} }
const isGroup = !!job.group_photo_id;
const title = job.action === 'ai_face' const title = job.action === 'ai_face'
? 'Фото обработано нейросетью с восстановлением лиц: {student}' ? (isGroup ? 'Фото группы обработано нейросетью с восстановлением лиц: {group}' : 'Фото обработано нейросетью с восстановлением лиц: {student}')
: job.action === 'ai_upscale' : job.action === 'ai_upscale'
? 'Фото обработано нейросетью (апскейл): {student}' ? (isGroup ? 'Фото группы обработано нейросетью (апскейл): {group}' : 'Фото обработано нейросетью (апскейл): {student}')
: job.action === 'ai' : job.action === 'ai'
? 'Фото обработано нейросетью: {student}' ? (isGroup ? 'Фото группы обработано нейросетью: {group}' : 'Фото обработано нейросетью: {student}')
: 'Фото улучшено на сервере: {student}'; : (isGroup ? 'Фото группы улучшено на сервере: {group}' : 'Фото улучшено на сервере: {student}');
const warn = m.warnings && m.warnings.length ? ' · ' + m.warnings.join('; ').slice(0, 300) : ''; const warn = m.warnings && m.warnings.length ? ' · ' + m.warnings.join('; ').slice(0, 300) : '';
await sendNotification(job.entry_id, { const body = isGroup
? `Группа {group} · фото #${job.group_photo_id} · результат ждёт применения${warn}`
: `Группа {group} · запись #${job.entry_id} · результат ждёт применения${warn}`;
await sendNotification(job, {
type: 'photo.job.done', type: 'photo.job.done',
title, title,
body: `Группа {group} · запись #${job.entry_id} · результат ждёт применения${warn}`, body,
target: { target: {
job_id: job.id, job_id: job.id,
action: job.action, action: job.action,
@@ -332,6 +337,8 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
device: m.device, device: m.device,
faces_found: m.faces_found, faces_found: m.faces_found,
elapsed_ms: m.elapsed_ms, elapsed_ms: m.elapsed_ms,
group_photo_id: job.group_photo_id || null,
entry_id: job.entry_id || null,
}, },
}); });
} }
@@ -343,7 +350,8 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
await pool.query(`UPDATE photo_jobs SET status = 'pending', error = $1 WHERE id = $2`, [message, job.id]); await pool.query(`UPDATE photo_jobs SET status = 'pending', error = $1 WHERE id = $2`, [message, job.id]);
if (logAudit && (n === 1 || n % 10 === 0)) { if (logAudit && (n === 1 || n % 10 === 0)) {
await logAudit(null, 'photo.job.soft_retry', { await logAudit(null, 'photo.job.soft_retry', {
entry_id: job.entry_id, entry_id: job.entry_id || null,
group_photo_id: job.group_photo_id || null,
job_id: job.id, job_id: job.id,
soft_attempt: n, soft_attempt: n,
soft_limit: PHOTO_SOFT_MAX_RETRIES, soft_limit: PHOTO_SOFT_MAX_RETRIES,
@@ -362,37 +370,46 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
stats.errors++; stats.errors++;
stats.last_error = text; stats.last_error = text;
if (logAudit) { if (logAudit) {
await logAudit(null, 'photo.job.error', { entry_id: job.entry_id, job_id: job.id, error: text, soft_attempts: PHOTO_SOFT_MAX_RETRIES }); await logAudit(null, 'photo.job.error', { entry_id: job.entry_id || null, group_photo_id: job.group_photo_id || null, job_id: job.id, error: text, soft_attempts: PHOTO_SOFT_MAX_RETRIES });
} }
await sendNotification(job.entry_id, { const isGroup = !!job.group_photo_id;
await sendNotification(job, {
type: 'photo.job.error', type: 'photo.job.error',
title: 'Ошибка обработки фото: {student}', title: isGroup ? 'Ошибка обработки фото группы: {group}' : 'Ошибка обработки фото: {student}',
body: `Группа {group} · запись #${job.entry_id} · ${text}`, body: isGroup ? `Группа {group} · фото #${job.group_photo_id} · ${text}` : `Группа {group} · запись #${job.entry_id} · ${text}`,
target: { job_id: job.id, action: job.action, error: text }, target: { job_id: job.id, action: job.action, error: text, group_photo_id: job.group_photo_id || null, entry_id: job.entry_id || null },
}); });
return { ok: true, delay: 0 }; return { ok: true, delay: 0 };
} }
async function processOne(job) { async function processOne(job) {
stats.jobs++; stats.jobs++;
const { rows } = await pool.query('SELECT photo_path FROM entries WHERE id = $1', [job.entry_id]); let photoPath = null;
if (!rows.length || !rows[0].photo_path) { if (job.group_photo_id) {
const { rows } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1', [job.group_photo_id]);
if (rows.length) photoPath = rows[0].photo_path;
} else {
const { rows } = await pool.query('SELECT photo_path FROM entries WHERE id = $1', [job.entry_id]);
if (rows.length) photoPath = rows[0].photo_path;
}
if (!photoPath) {
const errMsg = job.group_photo_id ? 'У фото группы не найден путь' : 'У записи нет фото';
await pool.query( await pool.query(
`UPDATE photo_jobs SET status = 'error', error = 'У записи нет фото', finished_at = now() WHERE id = $1`, `UPDATE photo_jobs SET status = 'error', error = $1, finished_at = now() WHERE id = $2`,
[job.id] [errMsg, job.id]
); );
stats.errors++; stats.errors++;
stats.last_at = new Date().toISOString(); stats.last_at = new Date().toISOString();
stats.last_error = 'У записи нет фото'; stats.last_error = errMsg;
await sendNotification(job.entry_id, { const isGroup = !!job.group_photo_id;
await sendNotification(job, {
type: 'photo.job.error', type: 'photo.job.error',
title: 'Ошибка обработки фото: {student}', title: isGroup ? 'Ошибка обработки фото группы: {group}' : 'Ошибка обработки фото: {student}',
body: `Группа {group} · запись #${job.entry_id} · у записи нет фото для обработки`, body: isGroup ? `Группа {group} · фото #${job.group_photo_id} · нет фото для обработки` : `Группа {group} · запись #${job.entry_id} · у записи нет фото для обработки`,
target: { job_id: job.id, action: job.action }, target: { job_id: job.id, action: job.action, group_photo_id: job.group_photo_id || null, entry_id: job.entry_id || null },
}); });
return { ok: true, delay: 0 }; return { ok: true, delay: 0 };
} }
const photoPath = rows[0].photo_path;
try { try {
const result = PHOTO_AI_ACTIONS.has(job.action) const result = PHOTO_AI_ACTIONS.has(job.action)
? await enhanceWithAi(photoPath, job) ? await enhanceWithAi(photoPath, job)
@@ -412,7 +429,7 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
const tries = ((cur[0] && cur[0].attempts) || 0) + 1; const tries = ((cur[0] && cur[0].attempts) || 0) + 1;
if (tries < PHOTO_MAX_ATTEMPTS) { if (tries < PHOTO_MAX_ATTEMPTS) {
await pool.query(`UPDATE photo_jobs SET status = 'pending', attempts = $1, error = $2 WHERE id = $3`, [tries, message, job.id]); await pool.query(`UPDATE photo_jobs SET status = 'pending', attempts = $1, error = $2 WHERE id = $3`, [tries, message, job.id]);
if (logAudit) await logAudit(null, 'photo.job.retry', { entry_id: job.entry_id, job_id: job.id, attempt: tries, error: message }); if (logAudit) await logAudit(null, 'photo.job.retry', { entry_id: job.entry_id || null, group_photo_id: job.group_photo_id || null, job_id: job.id, attempt: tries, error: message });
return { ok: false, delay: 0 }; return { ok: false, delay: 0 };
} }
softTries.delete(job.id); softTries.delete(job.id);
@@ -422,11 +439,12 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie
); );
stats.errors++; stats.errors++;
if (logAudit) await logAudit(null, 'photo.job.error', { entry_id: job.entry_id, job_id: job.id, error: message }); if (logAudit) await logAudit(null, 'photo.job.error', { entry_id: job.entry_id, job_id: job.id, error: message });
await sendNotification(job.entry_id, { const isGroup = !!job.group_photo_id;
await sendNotification(job, {
type: 'photo.job.error', type: 'photo.job.error',
title: 'Ошибка обработки фото: {student}', title: isGroup ? 'Ошибка обработки фото группы: {group}' : 'Ошибка обработки фото: {student}',
body: `Группа {group} · запись #${job.entry_id} · ${message}`, body: isGroup ? `Группа {group} · фото #${job.group_photo_id} · ${message}` : `Группа {group} · запись #${job.entry_id} · ${message}`,
target: { job_id: job.id, action: job.action, error: message }, target: { job_id: job.id, action: job.action, error: message, group_photo_id: job.group_photo_id || null, entry_id: job.entry_id || null },
}); });
return { ok: true, delay: 0 }; return { ok: true, delay: 0 };
} }