From ec47659ec6bab95b2756fb178262fe03126cfd8b Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 9 Oct 2026 13:52:02 +0300 Subject: [PATCH] groups: AI enhance for gallery photos (photo_jobs.group_photo_id, before/after compare modal) --- Dockerfile | 4 +- backup-restore.js | 4 +- db/init.sql | 5 +- db/migration.sql | 6 +- install-whatido-cert.ps1 | 89 +++++ public/groups.html | 81 +++++ public/js/audit.js | 4 + public/js/groups.js | 704 ++++++++++++++++++++++++++++++++++++++- public/js/worker.js | 117 ++++++- public/worker.html | 12 +- server.js | 467 ++++++++++++++++++++++++-- worker.js | 80 +++-- 12 files changed, 1499 insertions(+), 74 deletions(-) create mode 100644 install-whatido-cert.ps1 diff --git a/Dockerfile b/Dockerfile index f924016..8865258 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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"; \ exit 1; \ 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 \ - -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 CMD ["node", "server.js"] \ No newline at end of file diff --git a/backup-restore.js b/backup-restore.js index 9fdfb27..7baaef2 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -384,6 +384,7 @@ function normalizeRestoreData(data) { id: reqInt(x.id), group_id: reqInt(x.group_id), photo_path: reqUploadPath(x.photo_path, 255), + photo_original_path: optUploadPath(x.photo_original_path, 255), caption: optStr(x.caption, 10000), taken_at: optDate(x.taken_at), 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_jobs = (data.photo_jobs || []).map(x => ({ 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', params: optJsonText(x.params, 20000), before_path: optPhotoRefPath(x.before_path, 255), diff --git a/db/init.sql b/db/init.sql index aed4173..364198b 100644 --- a/db/init.sql +++ b/db/init.sql @@ -169,6 +169,7 @@ CREATE TABLE IF NOT EXISTS group_photos ( id SERIAL PRIMARY KEY, group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, photo_path VARCHAR(255) NOT NULL, + photo_original_path VARCHAR(255), caption TEXT, taken_at DATE, 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 ( 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', params JSONB, 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_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') ON CONFLICT (key) DO NOTHING; diff --git a/db/migration.sql b/db/migration.sql index 6737b38..00ffc2f 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -220,12 +220,14 @@ CREATE TABLE IF NOT EXISTS group_photos ( id SERIAL PRIMARY KEY, group_id INT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, photo_path VARCHAR(255) NOT NULL, + photo_original_path VARCHAR(255), caption TEXT, taken_at DATE, 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 photo_original_path VARCHAR(255); 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 ( 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', params JSONB, 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_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') ON CONFLICT (key) DO NOTHING; diff --git a/install-whatido-cert.ps1 b/install-whatido-cert.ps1 new file mode 100644 index 0000000..e269329 --- /dev/null +++ b/install-whatido-cert.ps1 @@ -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 diff --git a/public/groups.html b/public/groups.html index 957f58f..f35d54d 100644 --- a/public/groups.html +++ b/public/groups.html @@ -5,6 +5,33 @@ Группы — Админ-панель +
@@ -135,6 +162,60 @@
+ + + + diff --git a/public/js/audit.js b/public/js/audit.js index 815fccb..2cf6042 100644 --- a/public/js/audit.js +++ b/public/js/audit.js @@ -19,6 +19,10 @@ const ACTION_LABELS = { 'group.photo.reorder': 'Изменён порядок фото группы', 'group.photo.set_cover': 'Обновлена обложка группы', 'group.photo.delete': 'Удалено фото группы', + 'group.photo.enhance': 'Улучшено фото группы', + 'group.photo.enhance-ai.queue': 'Постановка ИИ-обработки фото группы', + 'group.photo.apply': 'Применён результат ИИ для фото группы', + 'group.photo.reject': 'Отклонён результат ИИ для фото группы', 'branch.create': 'Создан филиал', 'branch.update': 'Изменён филиал', 'branch.delete': 'Удалён филиал', diff --git a/public/js/groups.js b/public/js/groups.js index c392828..6009aff 100644 --- a/public/js/groups.js +++ b/public/js/groups.js @@ -177,6 +177,7 @@ function photoHTML(p) {
+
@@ -523,6 +524,8 @@ document.getElementById('photoGrid').addEventListener('click', async e => { } const ed = e.target.closest('[data-edit-photo]'); 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]'); if (dl) { deletePhoto(parseInt(dl.dataset.delPhoto, 10)); } }); @@ -548,4 +551,703 @@ async function populateNewGroupBranch() { await populateNewGroupBranch(); loadGroups(); } -})(); \ No newline at end of file +})(); +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 = '
Загрузка...
'; + 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 = '
Изменений фотографии пока не было.
'; + return; + } + list.innerHTML = rows.map(r => { + const before = r.before_path ? `было` : '—'; + const after = r.after_path ? `стало` : '—'; + 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 ? `
${esc(r.error)}
` : ''; + const time = r.finished_at || r.created_at; + return `
+
+ ${before} + было +
+
→
+
+ ${after} + стало +
+
+
${esc(PHOTO_JOB_ACTION_LABELS[r.action] || r.action)} + ${esc(PHOTO_JOB_STATUS_LABELS[r.status] || r.status)} · ${esc(fmtFull(time))} +
+ ${err} +
+ ${canRollback ? `` : ''} + ${canApply ? `` : ''} +
`; + }).join(''); + } catch (e) { + list.innerHTML = `
${esc(e.message)}
`; + } +} + +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(); + diff --git a/public/js/worker.js b/public/js/worker.js index 0591f5f..34a5007 100644 --- a/public/js/worker.js +++ b/public/js/worker.js @@ -224,6 +224,43 @@ function render() { renderIcons(); } +function photoCellHtml(r, side) { + const rejected = r.status === 'rejected'; + if (side === 'before') { + if (!r.before_path) { + const title = rejected + ? 'Копия «Было» не создавалась: результат отклонён и не применялся' + : 'Копия «Было» не создавалась для этого задания'; + return `нет «было»`; + } + return `было`; + } + if (!r.after_path) { + const title = rejected ? 'Задание отклонено до создания результата' : 'Файл результата не создавался'; + return `нет «стало»`; + } + if (rejected) { + return 'удалён'; + } + return `стало`; +} + +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() { if (!photoState) return; 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; } empty.style.display = 'none'; tbody.innerHTML = rows.map(r => { - const before = r.before_path ? `было` : '—'; - const after = r.after_path ? `стало` : '—'; + const before = photoCellHtml(r, 'before'); + const after = photoCellHtml(r, 'after'); const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback'; const badge = `${esc(PHOTO_STATUS_LABELS[r.status] || r.status)}`; return ` @@ -272,6 +309,7 @@ function renderPhoto() { `; }).join(''); + bindPhotoThumbs(tbody); renderPager(pager, photoPage, maxPage, p => { photoPage = p; loadPhoto(); }); renderIcons(); } @@ -344,16 +382,87 @@ function renderPhotoJobMeta(r) { : 'Метаданные обработки недоступны'; } +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) { photoJobRow = r; document.getElementById('photoJobTitle').textContent = `Обработка фото — запись #${r.entry_id} ${r.student_name || ''}`; - document.getElementById('photoJobBefore').src = thumbUrl(r.before_path); - document.getElementById('photoJobAfter').src = r.after_path ? `${API}${r.after_path}` : ''; + document.getElementById('photoJobNote').style.display = 'none'; + document.getElementById('photoJobEmpty').style.display = 'none'; document.getElementById('photoJobRollbackBtn').style.display = (r.before_path && r.action !== 'rollback') ? '' : 'none'; renderPhotoJobMeta(r); loadPhotoJobMeta().then(() => { if (photoJobRow === r) renderPhotoJobMeta(r); }); setPhotoJobClip(50); document.getElementById('photoJobModal').classList.add('open'); + loadPhotoJobImages(r); } async function loadPhoto() { diff --git a/public/worker.html b/public/worker.html index a83746c..66f5ea2 100644 --- a/public/worker.html +++ b/public/worker.html @@ -19,6 +19,10 @@ .enhance-badge.left { left: 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-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); } @@ -163,7 +167,7 @@