feat(admin): persist sessions and refresh via websocket

This commit is contained in:
nyan404 committed 2026-08-21 14:13:44 +03:00
1 parent 351ceeb990
commit 0c59d8cb15
5 files changed
+80 -9

No files matched your search

+1
View File
@@ -27,6 +27,7 @@
- 2026-08-21: use Context7 for fresh official integration documentation and `prevent-eol` before dependency changes; lifecycle status is not a vulnerability verdict.
- 2026-08-21: project-local frontend instructions include `frontend-craft`, `frontend-design`, and `ui-ux-pro-max`; use them together for UI work.
- 2026-08-21: `/belki` is the single public Belki workspace: reports are available without `BELKI_WEB_PASSWORD`, while its “Заявки” tab uses the password-gated application flow. The old `/applications` route remains only as a direct legacy entry point.
- 2026-08-21: `/admin` now keeps a server-memory `HttpOnly` cookie session across page refreshes instead of retaining an admin password in the browser. Its authenticated WebSocket sends a refresh signal every 25 seconds; this needs the cwshed Nginx `/api/` Upgrade proxy settings.
# 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+60 -3
View File
@@ -2,9 +2,11 @@ from __future__ import annotations
import json
import base64
import hashlib
import mimetypes
import os
import secrets
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
@@ -23,6 +25,7 @@ _HISTORY_STORE: CalculationStore | None = None
_IDENTITY_DIR: IdentityDirectory | None = None
_APPLICATION_STORE: ApplicationStore | None = None
_WEB_SESSIONS: set[str] = set()
_ADMIN_SESSIONS: set[str] = set()
def history_store() -> CalculationStore:
@@ -79,6 +82,7 @@ def get_profile():
class Handler(BaseHTTPRequestHandler):
server_version = "BelkiCalculator/0.1"
protocol_version = "HTTP/1.1"
def _json(self, status: int, body: dict) -> None:
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
@@ -88,12 +92,19 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(encoded)
def _session_token(self, name: str) -> str:
cookies = self.headers.get("Cookie", "")
return next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith(f"{name}=")), "")
def _admin_session_authorized(self) -> bool:
return self._session_token("belki_admin_session") in _ADMIN_SESSIONS
def _admin_authorized(self) -> bool:
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return False
if self.headers.get("X-Admin-Password", "") != expected:
if not self._admin_session_authorized() and not secrets.compare_digest(self.headers.get("X-Admin-Password", ""), expected):
self._json(401, {"error": "Неверный пароль"})
return False
return True
@@ -119,6 +130,35 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(encoded)
def _admin_cookie(self, token: str) -> str:
secure = "; Secure" if self.headers.get("X-Forwarded-Proto", "") == "https" else ""
return f"belki_admin_session={token}; Path=/; HttpOnly; SameSite=Lax{secure}"
def _serve_admin_updates(self) -> None:
if not self._admin_session_authorized():
self._json(401, {"error": "Требуется авторизация"})
return
key = self.headers.get("Sec-WebSocket-Key", "")
if self.headers.get("Upgrade", "").lower() != "websocket" or not key:
self._json(400, {"error": "Требуется подключение WebSocket"})
return
accept = base64.b64encode(hashlib.sha1(f"{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11".encode("ascii")).digest()).decode("ascii")
self.send_response(101, "Switching Protocols")
self.send_header("Upgrade", "websocket")
self.send_header("Connection", "Upgrade")
self.send_header("Sec-WebSocket-Accept", accept)
self.end_headers()
self.close_connection = True
try:
while True:
payload = json.dumps({"type": "refresh"}, ensure_ascii=False).encode("utf-8")
size = len(payload)
header = bytes([0x81, size]) if size < 126 else bytes([0x81, 126]) + size.to_bytes(2, "big")
self.connection.sendall(header + payload)
time.sleep(25)
except (BrokenPipeError, ConnectionError, OSError):
return
def do_GET(self) -> None: # noqa: N802
path = urlparse(self.path).path
if path in ("/health", "/api/health"):
@@ -133,6 +173,12 @@ class Handler(BaseHTTPRequestHandler):
if path in ("/applications", "/applications/"):
self._file(WEB_ROOT / "applications.html")
return
if path == "/api/admin/session":
self._json(200, {"authenticated": self._admin_session_authorized()})
return
if path == "/api/admin/updates":
self._serve_admin_updates()
return
if path == "/api/admin/calculations":
if not self._admin_authorized():
return
@@ -174,14 +220,25 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(content)
def do_POST(self) -> None: # noqa: N802
if self.path not in ("/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
"/api/save-profile", "/api/get-profile", "/api/applications"):
self._json(404, {"error": "Не найдено"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
payload = json.loads(self.rfile.read(length)) if length else {}
if self.path == "/api/web/auth":
if self.path == "/api/admin/auth":
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
self._json(401, {"error": "Неверный пароль"})
return
token = secrets.token_urlsafe(32)
_ADMIN_SESSIONS.add(token)
self._json_with_cookie(200, {"authenticated": True}, self._admin_cookie(token))
elif self.path == "/api/admin/logout":
_ADMIN_SESSIONS.discard(self._session_token("belki_admin_session"))
self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
elif self.path == "/api/web/auth":
expected = os.getenv("BELKI_WEB_PASSWORD", "")
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
self._json(401, {"error": "Неверный пароль"})
+8
View File
@@ -10,6 +10,11 @@ events {
}
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
include /etc/nginx/mime.types;
default_type application/octet-stream;
@@ -85,10 +90,13 @@ http {
}
location ^~ /api/ {
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://10.12.0.212;
}
+1
View File
@@ -32,6 +32,7 @@
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
- `/admin` exchanges `BELKI_ADMIN_PASSWORD` for a server-memory `HttpOnly`, `SameSite=Lax` session cookie. The page restores that session after a refresh; it does not persist the password in browser storage. Authenticated browsers connect to `/api/admin/updates` over WebSocket and receive a `refresh` event every 25 seconds, which reloads report and application data. The cwshed Nginx `/api/` proxy upgrades WebSocket connections.
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. The “Заявки” tab within `/belki` reuses the existing password-gated web session and upload endpoint; `/applications` remains a legacy direct page. `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
+10 -6
View File
@@ -138,7 +138,7 @@
const galleryImage = document.querySelector('#galleryImage');
const galleryCounter = document.querySelector('#galleryCounter');
let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all';
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports';
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports', updatesSocket = null, updatesRetry = null;
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
function kittenEntries(input) {
@@ -158,13 +158,16 @@
function categoryFor(item) { const input = item.input || {}; if (input.mode === 'inspection') return 'inspection'; if (input.mode === 'training') return 'training'; if (input.skill === 'ЛУ') return 'lu'; if (input.skill === 'ЗУ') return 'zu'; return 'other'; }
function filteredItems() { const cat = catFilter.value; const kitten = kittenFilter.value; return items.filter(item => { const input = item.input || {}; const person = personData(input); const kittens = kittenEntries(input); return (activeCategory === 'all' || categoryFor(item) === activeCategory) && (!cat || String(person.id) === cat) && (!kitten || kittens.some(entry => String(entry.id) === kitten)); }).sort((a, b) => { const av = textForSort(a, sort.value), bv = textForSort(b, sort.value); const result = typeof av === 'number' && typeof bv === 'number' ? av - bv : String(av).localeCompare(String(bv), 'ru', {numeric: true, sensitivity: 'base'}); return direction.value === 'asc' ? result : -result; }); }
function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; }
function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.created_at || '—'; return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE', headers: {'X-Admin-Password': password.value}}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`, {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.created_at || '—'; return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE'}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color} — ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; }
function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${activeApplicationStatus === 'pending' ? 'новых' : 'принятых'} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=async()=>{accept.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/accept`,{method:'PATCH',headers:{'X-Admin-Password':password.value}});const data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось принять заявку');await loadApplications()}catch(err){error.textContent=err.message;accept.disabled=false}};detail.append(accept)} }
async function loadApplications() { try { const response=await fetch('/api/admin/applications',{headers:{'X-Admin-Password':password.value}}), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/calculations?limit=1', {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); authView.classList.add('hidden'); appView.classList.remove('hidden'); items = data.items || []; await load(); await loadApplications(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } }
function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${activeApplicationStatus === 'pending' ? 'новых' : 'принятых'} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=async()=>{accept.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/accept`,{method:'PATCH'});const data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось принять заявку');await loadApplications()}catch(err){error.textContent=err.message;accept.disabled=false}};detail.append(accept)} }
async function loadApplications() { try { const response=await fetch('/api/admin/applications'), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
async function openAdmin() { authView.classList.add('hidden'); appView.classList.remove('hidden'); await load(); await loadApplications(); connectUpdates(); }
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/auth', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({password: password.value})}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); password.value = ''; await openAdmin(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } }
function connectUpdates() { if (updatesSocket && (updatesSocket.readyState === WebSocket.OPEN || updatesSocket.readyState === WebSocket.CONNECTING)) return; const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; updatesSocket = new WebSocket(`${scheme}://${location.host}/api/admin/updates`); updatesSocket.onmessage = async event => { try { if (JSON.parse(event.data).type === 'refresh') { await load(); await loadApplications(); } } catch (_) {} }; updatesSocket.onclose = () => { updatesSocket = null; clearTimeout(updatesRetry); updatesRetry = setTimeout(connectUpdates, 5000); }; }
async function restoreAdminSession() { try { const response = await fetch('/api/admin/session'); const data = await response.json(); if (data.authenticated) await openAdmin(); } catch (_) {} }
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; }
function openGallery(photos, index) { galleryPhotos = photos.filter(photo => photo.mirror_url || photo.url); galleryIndex = Math.min(index, galleryPhotos.length - 1); updateGallery(); if (galleryDialog.showModal) galleryDialog.showModal(); else galleryDialog.setAttribute('open', ''); }
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
@@ -172,6 +175,7 @@
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', render); kittenFilter.addEventListener('change', render); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); render(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); renderApplications(); }));
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
restoreAdminSession();
</script>
</body>
</html>