feat: správa poznávaček, optimalizace fotek do WebP a úložiště
This commit is contained in:
1 parent
7a8dccb2f7
commit
c46bb74386
27 files changed
+4367
-5
No files matched your search
@@ -23,3 +23,7 @@ SMTP_USER=
|
|||||||
SMTP_PASS=
|
SMTP_PASS=
|
||||||
SMTP_FROM=poznavacky@example.com
|
SMTP_FROM=poznavacky@example.com
|
||||||
SMTP_TLS=true
|
SMTP_TLS=true
|
||||||
|
|
||||||
|
# Limity velikosti nahrávaných obrázků (v MB)
|
||||||
|
POZNAVACKY_MAX_UPLOAD_MB=15
|
||||||
|
POZNAVACKY_MAX_REQUEST_MB=100
|
||||||
+37
-2
@@ -6,10 +6,20 @@ from collections.abc import Mapping
|
|||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from flask import Flask
|
from flask import Flask, render_template
|
||||||
|
from werkzeug.exceptions import RequestEntityTooLarge
|
||||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||||
|
|
||||||
from poznavacky import admin_users, auth, db, health, password_reset
|
from poznavacky import (
|
||||||
|
admin_sets,
|
||||||
|
admin_storage,
|
||||||
|
admin_users,
|
||||||
|
auth,
|
||||||
|
db,
|
||||||
|
health,
|
||||||
|
media,
|
||||||
|
password_reset,
|
||||||
|
)
|
||||||
from poznavacky.config import AppConfig, load_config
|
from poznavacky.config import AppConfig, load_config
|
||||||
from poznavacky.mailer import SmtpMailer
|
from poznavacky.mailer import SmtpMailer
|
||||||
from poznavacky.security import RateLimiter
|
from poznavacky.security import RateLimiter
|
||||||
@@ -39,8 +49,30 @@ def create_app(
|
|||||||
SESSION_COOKIE_SAMESITE="Lax",
|
SESSION_COOKIE_SAMESITE="Lax",
|
||||||
SESSION_COOKIE_SECURE=cfg.session_cookie_secure,
|
SESSION_COOKIE_SECURE=cfg.session_cookie_secure,
|
||||||
RATE_LIMITS=dict(auth.DEFAULT_RATE_LIMITS),
|
RATE_LIMITS=dict(auth.DEFAULT_RATE_LIMITS),
|
||||||
|
MAX_CONTENT_LENGTH=cfg.max_request_bytes,
|
||||||
|
MAX_UPLOAD_BYTES=cfg.max_upload_bytes,
|
||||||
|
MAX_UPLOAD_MB=cfg.max_upload_mb,
|
||||||
|
MAX_REQUEST_MB=cfg.max_request_mb,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@app.errorhandler(413)
|
||||||
|
def _handle_request_too_large(
|
||||||
|
error: RequestEntityTooLarge,
|
||||||
|
) -> tuple[str, int]:
|
||||||
|
del error
|
||||||
|
return (
|
||||||
|
render_template(
|
||||||
|
"base.html",
|
||||||
|
page_title="Požadavek je příliš velký",
|
||||||
|
standalone_error=(
|
||||||
|
"Nahraná data přesáhla maximální povolenou velikost "
|
||||||
|
f"požadavku ({cfg.max_request_mb} MB). Rozdělte "
|
||||||
|
"nahrávání na menší dávky."
|
||||||
|
),
|
||||||
|
),
|
||||||
|
413,
|
||||||
|
)
|
||||||
|
|
||||||
if cfg.trust_proxy > 0:
|
if cfg.trust_proxy > 0:
|
||||||
app.wsgi_app = ProxyFix( # type: ignore[method-assign]
|
app.wsgi_app = ProxyFix( # type: ignore[method-assign]
|
||||||
app.wsgi_app,
|
app.wsgi_app,
|
||||||
@@ -62,5 +94,8 @@ def create_app(
|
|||||||
app.register_blueprint(health.bp)
|
app.register_blueprint(health.bp)
|
||||||
auth.init_app(app)
|
auth.init_app(app)
|
||||||
app.register_blueprint(admin_users.bp)
|
app.register_blueprint(admin_users.bp)
|
||||||
|
app.register_blueprint(admin_sets.bp)
|
||||||
|
app.register_blueprint(admin_storage.bp)
|
||||||
|
app.register_blueprint(media.bp)
|
||||||
app.register_blueprint(password_reset.bp)
|
app.register_blueprint(password_reset.bp)
|
||||||
return app
|
return app
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,76 @@
|
|||||||
|
"""Administrace využití diskového úložiště a úklidu osiřelých souborů."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from flask import (
|
||||||
|
Blueprint,
|
||||||
|
Response,
|
||||||
|
current_app,
|
||||||
|
flash,
|
||||||
|
redirect,
|
||||||
|
render_template,
|
||||||
|
request,
|
||||||
|
url_for,
|
||||||
|
)
|
||||||
|
|
||||||
|
from poznavacky import db, storage
|
||||||
|
from poznavacky.auth import teacher_required
|
||||||
|
|
||||||
|
bp = Blueprint("admin_storage", __name__, url_prefix="/admin")
|
||||||
|
|
||||||
|
_VALID_SORTS = frozenset({"size", "photos", "name"})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.get("/uloziste")
|
||||||
|
@teacher_required
|
||||||
|
def overview() -> str:
|
||||||
|
"""Přehled využití úložiště, rozpad po sadách a seznam sirotků."""
|
||||||
|
sort_raw = request.args.get("sort", "size").strip().lower()
|
||||||
|
sort_by = sort_raw if sort_raw in _VALID_SORTS else "size"
|
||||||
|
|
||||||
|
dir_raw = request.args.get("dir", "").strip().lower()
|
||||||
|
if dir_raw in {"asc", "desc"}:
|
||||||
|
direction = dir_raw
|
||||||
|
else:
|
||||||
|
direction = "asc" if sort_by == "name" else "desc"
|
||||||
|
|
||||||
|
conn = db.get_db()
|
||||||
|
stats = storage.collect_storage_stats(
|
||||||
|
conn,
|
||||||
|
data_dir=Path(current_app.config["DATA_DIR"]),
|
||||||
|
db_path=Path(current_app.config["DB_PATH"]),
|
||||||
|
media_dir=Path(current_app.config["MEDIA_DIR"]),
|
||||||
|
sort_by=sort_by,
|
||||||
|
direction=direction,
|
||||||
|
)
|
||||||
|
return render_template(
|
||||||
|
"admin/storage.html",
|
||||||
|
stats=stats,
|
||||||
|
sort_by=sort_by,
|
||||||
|
direction=direction,
|
||||||
|
format_mb=storage.format_mb,
|
||||||
|
format_human_size=storage.format_human_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.post("/uloziste/uklid-sirotku")
|
||||||
|
@teacher_required
|
||||||
|
def cleanup_orphans() -> Response:
|
||||||
|
"""Smaže všechny zjištěné osiřelé soubory v media_dir."""
|
||||||
|
conn = db.get_db()
|
||||||
|
result = storage.cleanup_orphan_files(
|
||||||
|
conn,
|
||||||
|
Path(current_app.config["MEDIA_DIR"]),
|
||||||
|
)
|
||||||
|
if result.deleted_count == 0:
|
||||||
|
flash("Nebyly nalezeny žádné osiřelé soubory.", "info")
|
||||||
|
else:
|
||||||
|
freed = storage.format_human_size(result.freed_bytes)
|
||||||
|
flash(
|
||||||
|
f"Uklizeno {result.deleted_count} osiřelých souborů "
|
||||||
|
f"(uvolněno {freed}).",
|
||||||
|
"success",
|
||||||
|
)
|
||||||
|
return redirect(url_for("admin_storage.overview"))
|
||||||
@@ -3,12 +3,14 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from flask import (
|
from flask import (
|
||||||
Blueprint,
|
Blueprint,
|
||||||
Response,
|
Response,
|
||||||
abort,
|
abort,
|
||||||
|
current_app,
|
||||||
flash,
|
flash,
|
||||||
redirect,
|
redirect,
|
||||||
render_template,
|
render_template,
|
||||||
@@ -16,7 +18,7 @@ from flask import (
|
|||||||
url_for,
|
url_for,
|
||||||
)
|
)
|
||||||
|
|
||||||
from poznavacky import db
|
from poznavacky import db, storage
|
||||||
from poznavacky.auth import teacher_required, utc_now_iso
|
from poznavacky.auth import teacher_required, utc_now_iso
|
||||||
|
|
||||||
bp = Blueprint("admin_users", __name__, url_prefix="/admin")
|
bp = Blueprint("admin_users", __name__, url_prefix="/admin")
|
||||||
@@ -129,12 +131,27 @@ def index() -> str:
|
|||||||
active_class_count = conn.execute(
|
active_class_count = conn.execute(
|
||||||
"SELECT COUNT(*) FROM tridy WHERE aktivni = 1"
|
"SELECT COUNT(*) FROM tridy WHERE aktivni = 1"
|
||||||
).fetchone()[0]
|
).fetchone()[0]
|
||||||
|
set_count = conn.execute("SELECT COUNT(*) FROM sady").fetchone()[0]
|
||||||
|
published_set_count = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM sady WHERE stav = 'publikovano'"
|
||||||
|
).fetchone()[0]
|
||||||
|
photo_count = conn.execute("SELECT COUNT(*) FROM fotky").fetchone()[0]
|
||||||
|
referenced = storage.get_referenced_media_paths(conn)
|
||||||
|
media_bytes, orphans = storage.scan_media_dir(
|
||||||
|
Path(current_app.config["MEDIA_DIR"]),
|
||||||
|
referenced,
|
||||||
|
)
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
"admin/index.html",
|
"admin/index.html",
|
||||||
pending_count=pending_count,
|
pending_count=pending_count,
|
||||||
student_count=student_count,
|
student_count=student_count,
|
||||||
active_class_count=active_class_count,
|
active_class_count=active_class_count,
|
||||||
|
set_count=set_count,
|
||||||
|
published_set_count=published_set_count,
|
||||||
|
photo_count=photo_count,
|
||||||
|
media_size_mb=storage.format_mb(media_bytes),
|
||||||
|
orphan_count=len(orphans),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,18 @@ class AppConfig:
|
|||||||
session_cookie_secure: bool = False
|
session_cookie_secure: bool = False
|
||||||
trust_proxy: int = 0
|
trust_proxy: int = 0
|
||||||
password_reset_ttl_minutes: int = 60
|
password_reset_ttl_minutes: int = 60
|
||||||
|
max_upload_mb: int = 15
|
||||||
|
max_request_mb: int = 100
|
||||||
|
|
||||||
|
@property
|
||||||
|
def max_upload_bytes(self) -> int:
|
||||||
|
"""Maximální povolená velikost jednoho nahraného souboru v bajtech."""
|
||||||
|
return self.max_upload_mb * 1024 * 1024
|
||||||
|
|
||||||
|
@property
|
||||||
|
def max_request_bytes(self) -> int:
|
||||||
|
"""Maximální povolená velikost těla HTTP požadavku v bajtech."""
|
||||||
|
return self.max_request_mb * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
def _parse_bool(value: Any, name: str) -> bool:
|
def _parse_bool(value: Any, name: str) -> bool:
|
||||||
@@ -167,6 +179,24 @@ def load_config(
|
|||||||
else:
|
else:
|
||||||
password_reset_ttl_minutes = _parse_positive_int(ttl_raw, ttl_name)
|
password_reset_ttl_minutes = _parse_positive_int(ttl_raw, ttl_name)
|
||||||
|
|
||||||
|
max_upload_raw = merged.get("POZNAVACKY_MAX_UPLOAD_MB")
|
||||||
|
if max_upload_raw is None or str(max_upload_raw).strip() == "":
|
||||||
|
max_upload_mb = 15
|
||||||
|
else:
|
||||||
|
max_upload_mb = _parse_positive_int(
|
||||||
|
max_upload_raw,
|
||||||
|
"POZNAVACKY_MAX_UPLOAD_MB",
|
||||||
|
)
|
||||||
|
|
||||||
|
max_request_raw = merged.get("POZNAVACKY_MAX_REQUEST_MB")
|
||||||
|
if max_request_raw is None or str(max_request_raw).strip() == "":
|
||||||
|
max_request_mb = 100
|
||||||
|
else:
|
||||||
|
max_request_mb = _parse_positive_int(
|
||||||
|
max_request_raw,
|
||||||
|
"POZNAVACKY_MAX_REQUEST_MB",
|
||||||
|
)
|
||||||
|
|
||||||
return AppConfig(
|
return AppConfig(
|
||||||
secret_key=secret_raw,
|
secret_key=secret_raw,
|
||||||
data_dir=data_dir,
|
data_dir=data_dir,
|
||||||
@@ -187,4 +217,6 @@ def load_config(
|
|||||||
session_cookie_secure=session_cookie_secure,
|
session_cookie_secure=session_cookie_secure,
|
||||||
trust_proxy=trust_proxy,
|
trust_proxy=trust_proxy,
|
||||||
password_reset_ttl_minutes=password_reset_ttl_minutes,
|
password_reset_ttl_minutes=password_reset_ttl_minutes,
|
||||||
|
max_upload_mb=max_upload_mb,
|
||||||
|
max_request_mb=max_request_mb,
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
"""Validace, EXIF autorotace, strip metadat a WebP optimalizace obrázků."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
import warnings
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import BinaryIO
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
DEFAULT_MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
||||||
|
MAX_IMAGE_PIXELS = 40_000_000
|
||||||
|
FULL_MAX_SIDE = 1600
|
||||||
|
FULL_QUALITY = 82
|
||||||
|
THUMB_MAX_SIDE = 400
|
||||||
|
THUMB_QUALITY = 78
|
||||||
|
WEBP_METHOD = 4
|
||||||
|
_READ_CHUNK_SIZE = 64 * 1024
|
||||||
|
|
||||||
|
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||||
|
|
||||||
|
|
||||||
|
class ImageValidationError(ValueError):
|
||||||
|
"""Chyba validace nebo dekódování nahraného obrázku."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ProcessedPhoto:
|
||||||
|
"""Výsledek zpracování a uložení dvou WebP variant jedné fotky."""
|
||||||
|
|
||||||
|
soubor_plny: str
|
||||||
|
soubor_nahled: str
|
||||||
|
velikost_plny_b: int
|
||||||
|
velikost_nahled_b: int
|
||||||
|
sirka: int
|
||||||
|
vyska: int
|
||||||
|
|
||||||
|
|
||||||
|
def _format_limit_label(max_bytes: int) -> str:
|
||||||
|
if max_bytes >= 1024 * 1024 and max_bytes % (1024 * 1024) == 0:
|
||||||
|
return f"{max_bytes // (1024 * 1024)} MB"
|
||||||
|
if max_bytes >= 1024 and max_bytes % 1024 == 0:
|
||||||
|
return f"{max_bytes // 1024} kB"
|
||||||
|
return f"{max_bytes} B"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_bounded_bytes(source: bytes | BinaryIO, max_bytes: int) -> bytes:
|
||||||
|
if isinstance(source, (bytes, bytearray, memoryview)):
|
||||||
|
data = bytes(source)
|
||||||
|
if not data:
|
||||||
|
raise ImageValidationError("Soubor je prázdný.")
|
||||||
|
if len(data) > max_bytes:
|
||||||
|
raise ImageValidationError(
|
||||||
|
"Soubor překračuje maximální povolenou velikost "
|
||||||
|
f"({_format_limit_label(max_bytes)})."
|
||||||
|
)
|
||||||
|
return data
|
||||||
|
|
||||||
|
chunks: list[bytes] = []
|
||||||
|
total = 0
|
||||||
|
while True:
|
||||||
|
chunk = source.read(_READ_CHUNK_SIZE)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
total += len(chunk)
|
||||||
|
if total > max_bytes:
|
||||||
|
raise ImageValidationError(
|
||||||
|
"Soubor překračuje maximální povolenou velikost "
|
||||||
|
f"({_format_limit_label(max_bytes)})."
|
||||||
|
)
|
||||||
|
chunks.append(chunk)
|
||||||
|
|
||||||
|
if total == 0:
|
||||||
|
raise ImageValidationError("Soubor je prázdný.")
|
||||||
|
return b"".join(chunks)
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_mode(img: Image.Image) -> Image.Image:
|
||||||
|
has_alpha = img.mode in {"RGBA", "LA"} or (
|
||||||
|
img.mode == "P" and "transparency" in img.info
|
||||||
|
)
|
||||||
|
target_mode = "RGBA" if has_alpha else "RGB"
|
||||||
|
if img.mode == target_mode:
|
||||||
|
return img
|
||||||
|
return img.convert(target_mode)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_and_prepare(
|
||||||
|
source: bytes | BinaryIO,
|
||||||
|
*,
|
||||||
|
max_bytes: int = DEFAULT_MAX_UPLOAD_BYTES,
|
||||||
|
max_pixels: int = MAX_IMAGE_PIXELS,
|
||||||
|
) -> Image.Image:
|
||||||
|
"""Ověří limit, dekóduje obrázek, provede EXIF rotaci a strip metadat."""
|
||||||
|
raw = _read_bounded_bytes(source, max_bytes)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("ignore", Image.DecompressionBombWarning)
|
||||||
|
with Image.open(BytesIO(raw)) as img:
|
||||||
|
width, height = img.size
|
||||||
|
if width <= 0 or height <= 0:
|
||||||
|
raise ImageValidationError("Obrázek má neplatné rozměry.")
|
||||||
|
if width * height > max_pixels:
|
||||||
|
raise ImageValidationError(
|
||||||
|
"Obrázek má příliš velké rozlišení "
|
||||||
|
"(překračuje povolený limit pixelů)."
|
||||||
|
)
|
||||||
|
|
||||||
|
transposed = ImageOps.exif_transpose(img)
|
||||||
|
try:
|
||||||
|
converted = _normalize_mode(transposed)
|
||||||
|
try:
|
||||||
|
return Image.frombytes(
|
||||||
|
converted.mode,
|
||||||
|
converted.size,
|
||||||
|
converted.tobytes(),
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
if converted is not transposed:
|
||||||
|
converted.close()
|
||||||
|
finally:
|
||||||
|
if transposed is not img:
|
||||||
|
transposed.close()
|
||||||
|
except ImageValidationError:
|
||||||
|
raise
|
||||||
|
except Image.DecompressionBombError as exc:
|
||||||
|
raise ImageValidationError(
|
||||||
|
"Obrázek má příliš velké rozlišení "
|
||||||
|
"(překračuje povolený limit pixelů)."
|
||||||
|
) from exc
|
||||||
|
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
|
||||||
|
raise ImageValidationError(
|
||||||
|
"Soubor není platný podporovaný obrázek."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _resize_variant(img: Image.Image, max_side: int) -> Image.Image:
|
||||||
|
resized = img.copy()
|
||||||
|
resized.thumbnail((max_side, max_side), Image.Resampling.LANCZOS)
|
||||||
|
return resized
|
||||||
|
|
||||||
|
|
||||||
|
def _save_webp(img: Image.Image, path: Path, *, quality: int) -> int:
|
||||||
|
img.save(
|
||||||
|
path,
|
||||||
|
format="WEBP",
|
||||||
|
quality=quality,
|
||||||
|
method=WEBP_METHOD,
|
||||||
|
)
|
||||||
|
return path.stat().st_size
|
||||||
|
|
||||||
|
|
||||||
|
def process_and_save_photo(
|
||||||
|
source: bytes | BinaryIO,
|
||||||
|
media_dir: Path,
|
||||||
|
sada_id: int,
|
||||||
|
*,
|
||||||
|
max_bytes: int = DEFAULT_MAX_UPLOAD_BYTES,
|
||||||
|
max_pixels: int = MAX_IMAGE_PIXELS,
|
||||||
|
) -> ProcessedPhoto:
|
||||||
|
"""Zpracuje obrázek a uloží plnou i náhledovou WebP variantu bez EXIF."""
|
||||||
|
clean = decode_and_prepare(
|
||||||
|
source,
|
||||||
|
max_bytes=max_bytes,
|
||||||
|
max_pixels=max_pixels,
|
||||||
|
)
|
||||||
|
full_img: Image.Image | None = None
|
||||||
|
thumb_img: Image.Image | None = None
|
||||||
|
|
||||||
|
uid = uuid.uuid4().hex
|
||||||
|
rel_full = f"{sada_id}/{uid}.webp"
|
||||||
|
rel_thumb = f"{sada_id}/{uid}_thumb.webp"
|
||||||
|
set_dir = media_dir / str(sada_id)
|
||||||
|
full_path = set_dir / f"{uid}.webp"
|
||||||
|
thumb_path = set_dir / f"{uid}_thumb.webp"
|
||||||
|
|
||||||
|
try:
|
||||||
|
full_img = _resize_variant(clean, FULL_MAX_SIDE)
|
||||||
|
thumb_img = _resize_variant(clean, THUMB_MAX_SIDE)
|
||||||
|
sirka, vyska = full_img.size
|
||||||
|
|
||||||
|
set_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
size_full = _save_webp(full_img, full_path, quality=FULL_QUALITY)
|
||||||
|
size_thumb = _save_webp(thumb_img, thumb_path, quality=THUMB_QUALITY)
|
||||||
|
|
||||||
|
return ProcessedPhoto(
|
||||||
|
soubor_plny=rel_full,
|
||||||
|
soubor_nahled=rel_thumb,
|
||||||
|
velikost_plny_b=size_full,
|
||||||
|
velikost_nahled_b=size_thumb,
|
||||||
|
sirka=sirka,
|
||||||
|
vyska=vyska,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
full_path.unlink(missing_ok=True)
|
||||||
|
thumb_path.unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
clean.close()
|
||||||
|
if full_img is not None:
|
||||||
|
full_img.close()
|
||||||
|
if thumb_img is not None:
|
||||||
|
thumb_img.close()
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Přístupem řízený výdej optimalizovaných WebP médií."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from flask import Blueprint, Response, abort, current_app, send_file
|
||||||
|
|
||||||
|
from poznavacky import db, storage
|
||||||
|
from poznavacky.auth import current_user
|
||||||
|
|
||||||
|
bp = Blueprint("media", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_approved_teacher() -> bool:
|
||||||
|
user = current_user()
|
||||||
|
if user is None:
|
||||||
|
return False
|
||||||
|
return user["role"] == "ucitelka" and user["stav"] == "schvaleny"
|
||||||
|
|
||||||
|
|
||||||
|
@bp.get("/media/<int:sada_id>/<filename>")
|
||||||
|
def serve_media(sada_id: int, filename: str) -> Response:
|
||||||
|
"""Vydá evidovaný WebP soubor podle stavu sady a oprávnění uživatele."""
|
||||||
|
if (
|
||||||
|
not filename
|
||||||
|
or "/" in filename
|
||||||
|
or "\\" in filename
|
||||||
|
or ".." in filename
|
||||||
|
or "\x00" in filename
|
||||||
|
):
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
rel_path = f"{sada_id}/{filename}"
|
||||||
|
conn = db.get_db()
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT s.stav
|
||||||
|
FROM fotky f
|
||||||
|
INNER JOIN polozky p ON p.id = f.polozka_id
|
||||||
|
INNER JOIN sady s ON s.id = p.sada_id
|
||||||
|
WHERE p.sada_id = ?
|
||||||
|
AND (f.soubor_plny = ? OR f.soubor_nahled = ?)
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(sada_id, rel_path, rel_path),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
stav = str(row["stav"])
|
||||||
|
if stav == "koncept":
|
||||||
|
if not _is_approved_teacher():
|
||||||
|
abort(404)
|
||||||
|
cache_control = "private, no-store"
|
||||||
|
elif stav == "publikovano":
|
||||||
|
cache_control = "public, max-age=31536000, immutable"
|
||||||
|
else:
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
media_dir = Path(current_app.config["MEDIA_DIR"])
|
||||||
|
try:
|
||||||
|
target = storage.resolve_media_path(media_dir, rel_path)
|
||||||
|
except storage.UnsafeMediaPathError:
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
if not target.is_file():
|
||||||
|
abort(404)
|
||||||
|
|
||||||
|
response = send_file(target, mimetype="image/webp", conditional=True)
|
||||||
|
response.headers["Cache-Control"] = cache_control
|
||||||
|
return response
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Indexy pro rychlé dohledání mediálních souborů v tabulce fotky.
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fotky_soubor_plny
|
||||||
|
ON fotky (soubor_plny);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_fotky_soubor_nahled
|
||||||
|
ON fotky (soubor_nahled);
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"""Generování URL slugů a parsování skupin názvů souborů při uploadu."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import unicodedata
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
_SLUG_VALID_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
|
||||||
|
_NON_SLUG_RE = re.compile(r"[^a-z0-9]+")
|
||||||
|
_SEP_RE = re.compile(r"[_-]+")
|
||||||
|
_WHITESPACE_RE = re.compile(r"\s+")
|
||||||
|
_TRAILING_INDEX_PATTERNS = (
|
||||||
|
re.compile(r"[\s_-]*\(\s*\d+\s*\)$"),
|
||||||
|
re.compile(r"[\s_-]*\[\s*\d+\s*\]$"),
|
||||||
|
re.compile(r"[\s_-]+\d+$"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class UploadGroup:
|
||||||
|
"""Výsledek rozboru názvu nahraného souboru pro seskupení položek."""
|
||||||
|
|
||||||
|
group_key: str
|
||||||
|
display_name: str
|
||||||
|
|
||||||
|
|
||||||
|
def strip_diacritics(text: str) -> str:
|
||||||
|
"""Odstraní diakritiku pomocí Unicode NFKD dekompozice."""
|
||||||
|
decomposed = unicodedata.normalize("NFKD", text)
|
||||||
|
return "".join(ch for ch in decomposed if unicodedata.category(ch) != "Mn")
|
||||||
|
|
||||||
|
|
||||||
|
def slugify(text: str) -> str:
|
||||||
|
"""Převede text na URL-bezpečný malý ASCII slug s pomlčkami."""
|
||||||
|
ascii_text = strip_diacritics(text).lower()
|
||||||
|
collapsed = _NON_SLUG_RE.sub("-", ascii_text)
|
||||||
|
return collapsed.strip("-")
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_slug(slug: str) -> bool:
|
||||||
|
"""Ověří, zda řetězec splňuje tvar platného URL slugu."""
|
||||||
|
return bool(_SLUG_VALID_RE.fullmatch(slug))
|
||||||
|
|
||||||
|
|
||||||
|
def generate_unique_slug(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
name: str,
|
||||||
|
*,
|
||||||
|
exclude_set_id: int | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Odvozením z názvu zajistí unikátní slug v tabulce sady."""
|
||||||
|
base = slugify(name) or "sada"
|
||||||
|
if exclude_set_id is None:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT slug FROM sady WHERE slug = ? OR slug LIKE ?",
|
||||||
|
(base, f"{base}-%"),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT slug FROM sady
|
||||||
|
WHERE id != ? AND (slug = ? OR slug LIKE ?)
|
||||||
|
""",
|
||||||
|
(exclude_set_id, base, f"{base}-%"),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
existing = {str(row["slug"]) for row in rows}
|
||||||
|
if base not in existing:
|
||||||
|
return base
|
||||||
|
|
||||||
|
suffix = 2
|
||||||
|
while f"{base}-{suffix}" in existing:
|
||||||
|
suffix += 1
|
||||||
|
return f"{base}-{suffix}"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_group_key(text: str) -> str:
|
||||||
|
"""Normalizuje název položky/kmene pro porovnávání bez diakritiky."""
|
||||||
|
no_diacritics = strip_diacritics(text).lower()
|
||||||
|
spaced = _SEP_RE.sub(" ", no_diacritics)
|
||||||
|
return _WHITESPACE_RE.sub(" ", spaced).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_trailing_sequence(stem: str) -> str:
|
||||||
|
current = stem.strip()
|
||||||
|
while current:
|
||||||
|
changed = False
|
||||||
|
for pattern in _TRAILING_INDEX_PATTERNS:
|
||||||
|
candidate = pattern.sub("", current).strip(" _-")
|
||||||
|
if candidate != current and candidate:
|
||||||
|
current = candidate
|
||||||
|
changed = True
|
||||||
|
break
|
||||||
|
if not changed:
|
||||||
|
break
|
||||||
|
return current
|
||||||
|
|
||||||
|
|
||||||
|
def parse_upload_group(filename: str) -> UploadGroup:
|
||||||
|
"""Odvodí skupinový klíč a čitelný název položky z názvu souboru."""
|
||||||
|
safe_name = Path(filename.replace("\\", "/")).name
|
||||||
|
stem = Path(safe_name).stem.strip()
|
||||||
|
stripped = _strip_trailing_sequence(stem)
|
||||||
|
|
||||||
|
cleaned = _WHITESPACE_RE.sub(" ", _SEP_RE.sub(" ", stripped)).strip()
|
||||||
|
if not cleaned:
|
||||||
|
fallback = _WHITESPACE_RE.sub(" ", _SEP_RE.sub(" ", stem)).strip()
|
||||||
|
cleaned = fallback or stem or "Položka"
|
||||||
|
|
||||||
|
display_name = cleaned[0].upper() + cleaned[1:].lower()
|
||||||
|
group_key = normalize_group_key(cleaned) or "polozka"
|
||||||
|
return UploadGroup(group_key=group_key, display_name=display_name)
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
// Vanilla ES modul pro dvoukrokový náhled hromadného nahrávání fotek.
|
||||||
|
|
||||||
|
const TRAILING_PATTERNS = [
|
||||||
|
/[\s_-]*\(\s*\d+\s*\)$/,
|
||||||
|
/[\s_-]*\[\s*\d+\s*\]$/,
|
||||||
|
/[\s_-]+\d+$/,
|
||||||
|
];
|
||||||
|
|
||||||
|
export function stripDiacritics(text) {
|
||||||
|
return text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeGroupKey(text) {
|
||||||
|
return stripDiacritics(text)
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[_-]+/g, " ")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripTrailingSequence(stem) {
|
||||||
|
let current = stem.trim();
|
||||||
|
while (current) {
|
||||||
|
let changed = false;
|
||||||
|
for (const pattern of TRAILING_PATTERNS) {
|
||||||
|
const candidate = current
|
||||||
|
.replace(pattern, "")
|
||||||
|
.replace(/^[\s_-]+|[\s_-]+$/g, "");
|
||||||
|
if (candidate !== current && candidate.length > 0) {
|
||||||
|
current = candidate;
|
||||||
|
changed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseUploadGroup(filename) {
|
||||||
|
const safeName = String(filename).replace(/\\/g, "/").split("/").pop() || "";
|
||||||
|
const dotIdx = safeName.lastIndexOf(".");
|
||||||
|
const stem = (dotIdx > 0 ? safeName.slice(0, dotIdx) : safeName).trim();
|
||||||
|
const stripped = stripTrailingSequence(stem);
|
||||||
|
|
||||||
|
let cleaned = stripped.replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
|
||||||
|
if (!cleaned) {
|
||||||
|
cleaned =
|
||||||
|
stem.replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim() ||
|
||||||
|
stem ||
|
||||||
|
"Položka";
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayName = cleaned[0].toUpperCase() + cleaned.slice(1).toLowerCase();
|
||||||
|
const groupKey = normalizeGroupKey(cleaned) || "polozka";
|
||||||
|
return { groupKey, displayName };
|
||||||
|
}
|
||||||
|
|
||||||
|
function initBulkUpload(form) {
|
||||||
|
const fileInput = form.querySelector("[data-bulk-file-input]");
|
||||||
|
const previewBox = form.querySelector("[data-bulk-preview]");
|
||||||
|
const groupsBox = form.querySelector("[data-bulk-groups]");
|
||||||
|
const fallbackSubmit = form.querySelector("[data-bulk-fallback-submit]");
|
||||||
|
const confirmBtn = form.querySelector("[data-bulk-confirm]");
|
||||||
|
const resetBtn = form.querySelector("[data-bulk-reset]");
|
||||||
|
const statusEl = form.querySelector("[data-bulk-status]");
|
||||||
|
const csrfInput = form.querySelector('input[name="csrf_token"]');
|
||||||
|
|
||||||
|
if (!fileInput || !previewBox || !groupsBox || !confirmBtn || !resetBtn) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextGroupId = 1;
|
||||||
|
let nextEntryId = 1;
|
||||||
|
/** @type {Array<{id: number, name: string}>} */
|
||||||
|
let groups = [];
|
||||||
|
/** @type {Array<{id: number, file: File, url: string, groupId: number}>} */
|
||||||
|
let entries = [];
|
||||||
|
|
||||||
|
if (fallbackSubmit) {
|
||||||
|
fallbackSubmit.hidden = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function revokeAllUrls() {
|
||||||
|
for (const entry of entries) {
|
||||||
|
URL.revokeObjectURL(entry.url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSelection() {
|
||||||
|
revokeAllUrls();
|
||||||
|
groups = [];
|
||||||
|
entries = [];
|
||||||
|
fileInput.value = "";
|
||||||
|
previewBox.hidden = true;
|
||||||
|
groupsBox.innerHTML = "";
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function pruneEmptyGroups() {
|
||||||
|
const usedIds = new Set(entries.map((entry) => entry.groupId));
|
||||||
|
groups = groups.filter((group) => usedIds.has(group.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
pruneEmptyGroups();
|
||||||
|
groupsBox.innerHTML = "";
|
||||||
|
|
||||||
|
if (entries.length === 0) {
|
||||||
|
previewBox.hidden = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
previewBox.hidden = false;
|
||||||
|
for (const group of groups) {
|
||||||
|
const groupEntries = entries.filter((entry) => entry.groupId === group.id);
|
||||||
|
const card = document.createElement("fieldset");
|
||||||
|
card.style.marginBottom = "1rem";
|
||||||
|
card.style.padding = "0.75rem";
|
||||||
|
card.style.border = "1px solid #ccc";
|
||||||
|
|
||||||
|
const legend = document.createElement("legend");
|
||||||
|
legend.textContent = `Skupina (${groupEntries.length} fotek)`;
|
||||||
|
card.appendChild(legend);
|
||||||
|
|
||||||
|
const nameLabel = document.createElement("label");
|
||||||
|
nameLabel.textContent = "Název položky";
|
||||||
|
const nameInput = document.createElement("input");
|
||||||
|
nameInput.type = "text";
|
||||||
|
nameInput.value = group.name;
|
||||||
|
nameInput.required = true;
|
||||||
|
nameInput.addEventListener("input", () => {
|
||||||
|
group.name = nameInput.value;
|
||||||
|
});
|
||||||
|
nameLabel.appendChild(document.createElement("br"));
|
||||||
|
nameLabel.appendChild(nameInput);
|
||||||
|
card.appendChild(nameLabel);
|
||||||
|
|
||||||
|
const grid = document.createElement("div");
|
||||||
|
grid.style.display = "flex";
|
||||||
|
grid.style.flexWrap = "wrap";
|
||||||
|
grid.style.gap = "0.75rem";
|
||||||
|
grid.style.marginTop = "0.75rem";
|
||||||
|
|
||||||
|
for (const entry of groupEntries) {
|
||||||
|
const itemBox = document.createElement("div");
|
||||||
|
itemBox.style.border = "1px solid #ddd";
|
||||||
|
itemBox.style.padding = "0.5rem";
|
||||||
|
itemBox.style.width = "11rem";
|
||||||
|
|
||||||
|
const img = document.createElement("img");
|
||||||
|
img.src = entry.url;
|
||||||
|
img.alt = entry.file.name;
|
||||||
|
img.style.maxWidth = "100%";
|
||||||
|
img.style.maxHeight = "7rem";
|
||||||
|
img.style.display = "block";
|
||||||
|
img.style.objectFit = "contain";
|
||||||
|
itemBox.appendChild(img);
|
||||||
|
|
||||||
|
const caption = document.createElement("div");
|
||||||
|
caption.textContent = entry.file.name;
|
||||||
|
caption.style.fontSize = "0.85rem";
|
||||||
|
caption.style.wordBreak = "break-all";
|
||||||
|
caption.style.margin = "0.35rem 0";
|
||||||
|
itemBox.appendChild(caption);
|
||||||
|
|
||||||
|
const moveSelect = document.createElement("select");
|
||||||
|
moveSelect.style.minWidth = "100%";
|
||||||
|
moveSelect.style.width = "100%";
|
||||||
|
for (const target of groups) {
|
||||||
|
const opt = document.createElement("option");
|
||||||
|
opt.value = String(target.id);
|
||||||
|
opt.textContent = target.name || "(bez názvu)";
|
||||||
|
if (target.id === group.id) {
|
||||||
|
opt.selected = true;
|
||||||
|
}
|
||||||
|
moveSelect.appendChild(opt);
|
||||||
|
}
|
||||||
|
const newOpt = document.createElement("option");
|
||||||
|
newOpt.value = "__new__";
|
||||||
|
newOpt.textContent = "+ Nová skupina…";
|
||||||
|
moveSelect.appendChild(newOpt);
|
||||||
|
|
||||||
|
moveSelect.addEventListener("change", () => {
|
||||||
|
if (moveSelect.value === "__new__") {
|
||||||
|
const proposed = window.prompt(
|
||||||
|
"Název nové položky:",
|
||||||
|
parseUploadGroup(entry.file.name).displayName,
|
||||||
|
);
|
||||||
|
const trimmed = proposed ? proposed.trim() : "";
|
||||||
|
if (!trimmed) {
|
||||||
|
moveSelect.value = String(entry.groupId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const created = { id: nextGroupId++, name: trimmed };
|
||||||
|
groups.push(created);
|
||||||
|
entry.groupId = created.id;
|
||||||
|
render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
entry.groupId = Number(moveSelect.value);
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
itemBox.appendChild(moveSelect);
|
||||||
|
|
||||||
|
const removeBtn = document.createElement("button");
|
||||||
|
removeBtn.type = "button";
|
||||||
|
removeBtn.textContent = "Odebrat";
|
||||||
|
removeBtn.addEventListener("click", () => {
|
||||||
|
URL.revokeObjectURL(entry.url);
|
||||||
|
entries = entries.filter((item) => item.id !== entry.id);
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
itemBox.appendChild(removeBtn);
|
||||||
|
|
||||||
|
grid.appendChild(itemBox);
|
||||||
|
}
|
||||||
|
|
||||||
|
card.appendChild(grid);
|
||||||
|
groupsBox.appendChild(card);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fileInput.addEventListener("change", () => {
|
||||||
|
revokeAllUrls();
|
||||||
|
groups = [];
|
||||||
|
entries = [];
|
||||||
|
|
||||||
|
const byKey = new Map();
|
||||||
|
for (const file of Array.from(fileInput.files || [])) {
|
||||||
|
const parsed = parseUploadGroup(file.name);
|
||||||
|
let group = byKey.get(parsed.groupKey);
|
||||||
|
if (!group) {
|
||||||
|
group = { id: nextGroupId++, name: parsed.displayName };
|
||||||
|
groups.push(group);
|
||||||
|
byKey.set(parsed.groupKey, group);
|
||||||
|
}
|
||||||
|
entries.push({
|
||||||
|
id: nextEntryId++,
|
||||||
|
file,
|
||||||
|
url: URL.createObjectURL(file),
|
||||||
|
groupId: group.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = "";
|
||||||
|
}
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
|
||||||
|
resetBtn.addEventListener("click", clearSelection);
|
||||||
|
|
||||||
|
async function submitConfirmed() {
|
||||||
|
if (entries.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const groupMap = new Map(groups.map((g) => [g.id, g.name.trim()]));
|
||||||
|
const formData = new FormData();
|
||||||
|
if (csrfInput) {
|
||||||
|
formData.append("csrf_token", csrfInput.value);
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
const groupName = groupMap.get(entry.groupId) || "";
|
||||||
|
if (!groupName) {
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = "Vyplňte název u všech skupin před odesláním.";
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
formData.append("files", entry.file, entry.file.name);
|
||||||
|
formData.append("item_names", groupName);
|
||||||
|
}
|
||||||
|
|
||||||
|
confirmBtn.disabled = true;
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = "Nahrávám a optimalizuji fotky…";
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch(form.action, {
|
||||||
|
method: "POST",
|
||||||
|
body: formData,
|
||||||
|
redirect: "follow",
|
||||||
|
});
|
||||||
|
if (resp.redirected) {
|
||||||
|
window.location.assign(resp.url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const html = await resp.text();
|
||||||
|
document.open();
|
||||||
|
document.write(html);
|
||||||
|
document.close();
|
||||||
|
} catch {
|
||||||
|
confirmBtn.disabled = false;
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = "Nahrávání selhalo. Zkuste to prosím znovu.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
confirmBtn.addEventListener("click", submitConfirmed);
|
||||||
|
form.addEventListener("submit", (event) => {
|
||||||
|
if (entries.length > 0) {
|
||||||
|
event.preventDefault();
|
||||||
|
submitConfirmed();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof document !== "undefined") {
|
||||||
|
for (const form of document.querySelectorAll("[data-bulk-upload-form]")) {
|
||||||
|
initBulkUpload(form);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,405 @@
|
|||||||
|
"""Správa mediálního úložiště, statistiky disku a bezpečný úklid sirotků."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
|
||||||
|
|
||||||
|
class UnsafeMediaPathError(ValueError):
|
||||||
|
"""Cesta k médiu ukazuje mimo media_dir nebo přes symlink."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class OrphanFile:
|
||||||
|
"""Osiřelý soubor nalezený na disku bez reference v tabulce fotky."""
|
||||||
|
|
||||||
|
relative_path: str
|
||||||
|
size_bytes: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SetStorageRow:
|
||||||
|
"""Agregované statistiky jedné sady pro přehled úložiště."""
|
||||||
|
|
||||||
|
id: int
|
||||||
|
nazev: str
|
||||||
|
slug: str
|
||||||
|
stav: str
|
||||||
|
item_count: int
|
||||||
|
photo_count: int
|
||||||
|
round_count: int
|
||||||
|
size_bytes: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class StorageStats:
|
||||||
|
"""Souhrnné metriky úložiště pro /admin/uloziste."""
|
||||||
|
|
||||||
|
media_bytes: int
|
||||||
|
db_bytes: int
|
||||||
|
disk_free_bytes: int
|
||||||
|
disk_total_bytes: int
|
||||||
|
orphan_files: list[OrphanFile]
|
||||||
|
orphan_count: int
|
||||||
|
orphan_bytes: int
|
||||||
|
sets: list[SetStorageRow]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class OrphanCleanupResult:
|
||||||
|
"""Výsledek ručně spuštěného úklidu osiřelých souborů."""
|
||||||
|
|
||||||
|
deleted_count: int
|
||||||
|
freed_bytes: int
|
||||||
|
deleted_paths: list[str]
|
||||||
|
|
||||||
|
|
||||||
|
def format_mb(size_bytes: int) -> str:
|
||||||
|
"""Formátuje velikost v bajtech jako MB s českou desetinnou čárkou."""
|
||||||
|
megabytes = max(0, size_bytes) / (1024 * 1024)
|
||||||
|
return f"{megabytes:.2f}".replace(".", ",") + " MB"
|
||||||
|
|
||||||
|
|
||||||
|
def format_human_size(size_bytes: int) -> str:
|
||||||
|
"""Formátuje velikost čitelně v B, kB, MB nebo GB."""
|
||||||
|
size = max(0, size_bytes)
|
||||||
|
if size < 1024:
|
||||||
|
return f"{size} B"
|
||||||
|
if size < 1024 * 1024:
|
||||||
|
return f"{size / 1024:.1f}".replace(".", ",") + " kB"
|
||||||
|
if size < 1024 * 1024 * 1024:
|
||||||
|
return format_mb(size)
|
||||||
|
gb = size / (1024 * 1024 * 1024)
|
||||||
|
return f"{gb:.2f}".replace(".", ",") + " GB"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_relative_media_path(relative_path: str) -> str:
|
||||||
|
"""Ověří a znormalizuje relativní POSIX cestu uvnitř media_dir."""
|
||||||
|
if not relative_path or "\x00" in relative_path:
|
||||||
|
raise UnsafeMediaPathError("Prázdná nebo neplatná cesta k médiu.")
|
||||||
|
if "\\" in relative_path or relative_path.startswith("/"):
|
||||||
|
raise UnsafeMediaPathError(f"Zakázaná cesta k médiu: {relative_path!r}")
|
||||||
|
|
||||||
|
posix = PurePosixPath(relative_path)
|
||||||
|
parts = posix.parts
|
||||||
|
if not parts or any(part in {"", ".", ".."} for part in parts):
|
||||||
|
raise UnsafeMediaPathError(f"Zakázaná cesta k médiu: {relative_path!r}")
|
||||||
|
return "/".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_media_path(media_dir: Path, relative_path: str) -> Path:
|
||||||
|
"""Bezpečně přeloží relativní cestu na absolutní Path uvnitř media_dir."""
|
||||||
|
normalized = normalize_relative_media_path(relative_path)
|
||||||
|
root = media_dir.resolve()
|
||||||
|
current = root
|
||||||
|
for part in normalized.split("/"):
|
||||||
|
current = current / part
|
||||||
|
if current.is_symlink():
|
||||||
|
raise UnsafeMediaPathError(
|
||||||
|
f"Symlink v cestě k médiu není povolen: {relative_path!r}"
|
||||||
|
)
|
||||||
|
|
||||||
|
resolved = current.resolve()
|
||||||
|
if resolved == root or not resolved.is_relative_to(root):
|
||||||
|
raise UnsafeMediaPathError(
|
||||||
|
f"Cesta ukazuje mimo media_dir: {relative_path!r}"
|
||||||
|
)
|
||||||
|
return current
|
||||||
|
|
||||||
|
|
||||||
|
def _prune_empty_parents(media_dir: Path, start_dir: Path) -> None:
|
||||||
|
root = media_dir.resolve()
|
||||||
|
current = start_dir
|
||||||
|
while True:
|
||||||
|
if current.is_symlink():
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
resolved = current.resolve()
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
if resolved == root or not resolved.is_relative_to(root):
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
current.rmdir()
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
current = current.parent
|
||||||
|
|
||||||
|
|
||||||
|
def delete_media_files(
|
||||||
|
media_dir: Path,
|
||||||
|
relative_paths: Iterable[str],
|
||||||
|
) -> int:
|
||||||
|
"""Okamžitě smaže zadané soubory v media_dir a prázdné podadresáře."""
|
||||||
|
deleted = 0
|
||||||
|
parent_dirs: set[Path] = set()
|
||||||
|
for rel in relative_paths:
|
||||||
|
target = resolve_media_path(media_dir, rel)
|
||||||
|
parent_dirs.add(target.parent)
|
||||||
|
try:
|
||||||
|
target.unlink()
|
||||||
|
deleted += 1
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for parent in sorted(
|
||||||
|
parent_dirs,
|
||||||
|
key=lambda p: len(p.parts),
|
||||||
|
reverse=True,
|
||||||
|
):
|
||||||
|
_prune_empty_parents(media_dir, parent)
|
||||||
|
return deleted
|
||||||
|
|
||||||
|
|
||||||
|
def remove_empty_set_dir(media_dir: Path, sada_id: int) -> bool:
|
||||||
|
"""Odstraní prázdný podadresář <media_dir>/<sada_id>, pokud existuje."""
|
||||||
|
target = resolve_media_path(media_dir, str(sada_id))
|
||||||
|
if not target.is_dir() or target.is_symlink():
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
target.rmdir()
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_size_bytes(db_path: Path) -> int:
|
||||||
|
"""Vrátí součet velikostí hlavní SQLite databáze a -wal/-shm souborů."""
|
||||||
|
candidates = (
|
||||||
|
db_path,
|
||||||
|
Path(f"{db_path}-wal"),
|
||||||
|
Path(f"{db_path}-shm"),
|
||||||
|
)
|
||||||
|
total = 0
|
||||||
|
for path in candidates:
|
||||||
|
try:
|
||||||
|
total += path.stat().st_size
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
def get_referenced_media_paths(conn: sqlite3.Connection) -> set[str]:
|
||||||
|
"""Načte množinu všech relativních cest evidovaných v tabulce fotky."""
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT soubor_plny, soubor_nahled FROM fotky"
|
||||||
|
).fetchall()
|
||||||
|
referenced: set[str] = set()
|
||||||
|
for row in rows:
|
||||||
|
for col in ("soubor_plny", "soubor_nahled"):
|
||||||
|
raw = str(row[col])
|
||||||
|
try:
|
||||||
|
referenced.add(normalize_relative_media_path(raw))
|
||||||
|
except UnsafeMediaPathError:
|
||||||
|
continue
|
||||||
|
return referenced
|
||||||
|
|
||||||
|
|
||||||
|
def scan_media_dir(
|
||||||
|
media_dir: Path,
|
||||||
|
referenced_paths: set[str],
|
||||||
|
) -> tuple[int, list[OrphanFile]]:
|
||||||
|
"""Prochází media_dir bez následování symlinků a hledá sirotky."""
|
||||||
|
if not media_dir.is_dir():
|
||||||
|
return 0, []
|
||||||
|
|
||||||
|
root = media_dir.resolve()
|
||||||
|
total_bytes = 0
|
||||||
|
orphans: list[OrphanFile] = []
|
||||||
|
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
||||||
|
current_dir = Path(dirpath)
|
||||||
|
# Odfiltrujeme symlinky na adresáře, aby se do nich os.walk nevnořil.
|
||||||
|
dirnames[:] = [
|
||||||
|
d for d in dirnames if not (current_dir / d).is_symlink()
|
||||||
|
]
|
||||||
|
for filename in filenames:
|
||||||
|
file_path = current_dir / filename
|
||||||
|
if file_path.is_symlink():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
stat_res = file_path.lstat()
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
size = int(stat_res.st_size)
|
||||||
|
total_bytes += size
|
||||||
|
rel_posix = file_path.relative_to(root).as_posix()
|
||||||
|
if rel_posix not in referenced_paths:
|
||||||
|
orphans.append(
|
||||||
|
OrphanFile(relative_path=rel_posix, size_bytes=size)
|
||||||
|
)
|
||||||
|
|
||||||
|
orphans.sort(key=lambda item: item.relative_path)
|
||||||
|
return total_bytes, orphans
|
||||||
|
|
||||||
|
|
||||||
|
def find_orphan_files(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
media_dir: Path,
|
||||||
|
) -> list[OrphanFile]:
|
||||||
|
"""Vrátí seznam všech osiřelých souborů v media_dir."""
|
||||||
|
referenced = get_referenced_media_paths(conn)
|
||||||
|
_, orphans = scan_media_dir(media_dir, referenced)
|
||||||
|
return orphans
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup_orphan_files(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
media_dir: Path,
|
||||||
|
) -> OrphanCleanupResult:
|
||||||
|
"""Smaže všechny osiřelé soubory i následně prázdné podadresáře."""
|
||||||
|
orphans = find_orphan_files(conn, media_dir)
|
||||||
|
deleted_paths: list[str] = []
|
||||||
|
freed_bytes = 0
|
||||||
|
|
||||||
|
for orphan in orphans:
|
||||||
|
target = resolve_media_path(media_dir, orphan.relative_path)
|
||||||
|
try:
|
||||||
|
actual_size = target.lstat().st_size
|
||||||
|
target.unlink()
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
deleted_paths.append(orphan.relative_path)
|
||||||
|
freed_bytes += int(actual_size)
|
||||||
|
|
||||||
|
if media_dir.is_dir():
|
||||||
|
root = media_dir.resolve()
|
||||||
|
for dirpath, dirnames, _ in os.walk(
|
||||||
|
root,
|
||||||
|
topdown=False,
|
||||||
|
followlinks=False,
|
||||||
|
):
|
||||||
|
current = Path(dirpath)
|
||||||
|
if current == root or current.is_symlink():
|
||||||
|
continue
|
||||||
|
del dirnames
|
||||||
|
try:
|
||||||
|
current.rmdir()
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
return OrphanCleanupResult(
|
||||||
|
deleted_count=len(deleted_paths),
|
||||||
|
freed_bytes=freed_bytes,
|
||||||
|
deleted_paths=deleted_paths,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_set_storage_breakdown(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
*,
|
||||||
|
sort_by: str = "size",
|
||||||
|
direction: str = "desc",
|
||||||
|
) -> list[SetStorageRow]:
|
||||||
|
"""Vrátí rozpad počtu položek, fotek, kol a bajtů pro všechny sady."""
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
s.id,
|
||||||
|
s.nazev,
|
||||||
|
s.slug,
|
||||||
|
s.stav,
|
||||||
|
COALESCE(p_agg.item_count, 0) AS item_count,
|
||||||
|
COALESCE(f_agg.photo_count, 0) AS photo_count,
|
||||||
|
COALESCE(f_agg.size_bytes, 0) AS size_bytes,
|
||||||
|
COALESCE(k_agg.round_count, 0) AS round_count
|
||||||
|
FROM sady s
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT sada_id, COUNT(*) AS item_count
|
||||||
|
FROM polozky
|
||||||
|
GROUP BY sada_id
|
||||||
|
) p_agg ON p_agg.sada_id = s.id
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT
|
||||||
|
p.sada_id,
|
||||||
|
COUNT(f.id) AS photo_count,
|
||||||
|
COALESCE(
|
||||||
|
SUM(f.velikost_plny_b + f.velikost_nahled_b), 0
|
||||||
|
) AS size_bytes
|
||||||
|
FROM polozky p
|
||||||
|
INNER JOIN fotky f ON f.polozka_id = p.id
|
||||||
|
GROUP BY p.sada_id
|
||||||
|
) f_agg ON f_agg.sada_id = s.id
|
||||||
|
LEFT JOIN (
|
||||||
|
SELECT sada_id, COUNT(*) AS round_count
|
||||||
|
FROM kola
|
||||||
|
GROUP BY sada_id
|
||||||
|
) k_agg ON k_agg.sada_id = s.id
|
||||||
|
ORDER BY s.id ASC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
result = [
|
||||||
|
SetStorageRow(
|
||||||
|
id=int(row["id"]),
|
||||||
|
nazev=str(row["nazev"]),
|
||||||
|
slug=str(row["slug"]),
|
||||||
|
stav=str(row["stav"]),
|
||||||
|
item_count=int(row["item_count"]),
|
||||||
|
photo_count=int(row["photo_count"]),
|
||||||
|
round_count=int(row["round_count"]),
|
||||||
|
size_bytes=int(row["size_bytes"]),
|
||||||
|
)
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
valid_sort = sort_by if sort_by in {"size", "photos", "name"} else "size"
|
||||||
|
reverse = direction != "asc"
|
||||||
|
|
||||||
|
if valid_sort == "name":
|
||||||
|
result.sort(
|
||||||
|
key=lambda item: (item.nazev.casefold(), item.id),
|
||||||
|
reverse=reverse,
|
||||||
|
)
|
||||||
|
elif valid_sort == "photos":
|
||||||
|
result.sort(
|
||||||
|
key=lambda item: (item.photo_count, item.size_bytes, -item.id),
|
||||||
|
reverse=reverse,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
result.sort(
|
||||||
|
key=lambda item: (item.size_bytes, item.photo_count, -item.id),
|
||||||
|
reverse=reverse,
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def collect_storage_stats(
|
||||||
|
conn: sqlite3.Connection,
|
||||||
|
*,
|
||||||
|
data_dir: Path,
|
||||||
|
db_path: Path,
|
||||||
|
media_dir: Path,
|
||||||
|
sort_by: str = "size",
|
||||||
|
direction: str = "desc",
|
||||||
|
) -> StorageStats:
|
||||||
|
"""Shromáždí kompletní statistiky úložiště pro administraci."""
|
||||||
|
referenced = get_referenced_media_paths(conn)
|
||||||
|
media_bytes, orphans = scan_media_dir(media_dir, referenced)
|
||||||
|
db_bytes = get_db_size_bytes(db_path)
|
||||||
|
|
||||||
|
usage_target = data_dir if data_dir.exists() else data_dir.parent
|
||||||
|
disk = shutil.disk_usage(usage_target)
|
||||||
|
|
||||||
|
sets = get_set_storage_breakdown(
|
||||||
|
conn,
|
||||||
|
sort_by=sort_by,
|
||||||
|
direction=direction,
|
||||||
|
)
|
||||||
|
orphan_bytes = sum(item.size_bytes for item in orphans)
|
||||||
|
|
||||||
|
return StorageStats(
|
||||||
|
media_bytes=media_bytes,
|
||||||
|
db_bytes=db_bytes,
|
||||||
|
disk_free_bytes=int(disk.free),
|
||||||
|
disk_total_bytes=int(disk.total),
|
||||||
|
orphan_files=orphans,
|
||||||
|
orphan_count=len(orphans),
|
||||||
|
orphan_bytes=orphan_bytes,
|
||||||
|
sets=sets,
|
||||||
|
)
|
||||||
@@ -14,5 +14,15 @@
|
|||||||
<a href="{{ url_for('admin_users.classes') }}">Správa tříd</a>
|
<a href="{{ url_for('admin_users.classes') }}">Správa tříd</a>
|
||||||
– aktivních tříd: <strong>{{ active_class_count }}</strong>
|
– aktivních tříd: <strong>{{ active_class_count }}</strong>
|
||||||
</li>
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="{{ url_for('admin_sets.list_sets') }}">Správa sad poznávaček</a>
|
||||||
|
– celkem sad: <strong>{{ set_count }}</strong>
|
||||||
|
(publikovaných: {{ published_set_count }}, fotek: {{ photo_count }})
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="{{ url_for('admin_storage.overview') }}">Správa úložiště</a>
|
||||||
|
– média: <strong>{{ media_size_mb }}</strong>
|
||||||
|
(osiřelých souborů: {{ orphan_count }})
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}{{ quiz_set['nazev'] }} – Poznávačky{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>{{ quiz_set['nazev'] }}</h1>
|
||||||
|
<p>
|
||||||
|
<a href="{{ url_for('admin_sets.list_sets') }}">Zpět na seznam sad</a>
|
||||||
|
| <a href="{{ url_for('admin_sets.edit_set', set_id=quiz_set['id']) }}">
|
||||||
|
Upravit sadu
|
||||||
|
</a>
|
||||||
|
| <a href="{{ url_for('admin_storage.overview') }}">Úložiště</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Stav:
|
||||||
|
<strong>
|
||||||
|
{{ 'Publikováno' if quiz_set['stav'] == 'publikovano' else 'Koncept' }}
|
||||||
|
</strong>
|
||||||
|
| Slug: <code>{{ quiz_set['slug'] }}</code>
|
||||||
|
| Ročník: {{ (quiz_set['rocnik'] ~ '.') if quiz_set['rocnik'] else '–' }}
|
||||||
|
| Kategorie: {{ quiz_set['kategorie'] or '–' }}
|
||||||
|
| Položek s fotkou: <strong>{{ items_with_photos }}</strong>
|
||||||
|
</p>
|
||||||
|
{% if quiz_set['popis'] %}
|
||||||
|
<p>{{ quiz_set['popis'] }}</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div style="display: flex; gap: 0.75rem; flex-wrap: wrap; margin-bottom: 1rem;">
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.toggle_set_status', set_id=quiz_set['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit">
|
||||||
|
{{ 'Přepnout na koncept' if quiz_set['stav'] == 'publikovano' else 'Publikovat sadu' }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{% if round_count > 0 %}
|
||||||
|
{% set confirm_msg = "Opravdu smazat sadu „" ~ quiz_set['nazev'] ~ "“? Pozor: sada má " ~ round_count ~ " odehraných kol a smazáním se odstraní i historie výsledků žáků." %}
|
||||||
|
{% else %}
|
||||||
|
{% set confirm_msg = "Opravdu smazat sadu „" ~ quiz_set['nazev'] ~ "“ včetně všech položek a fotek?" %}
|
||||||
|
{% endif %}
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.delete_set', set_id=quiz_set['id']) }}"
|
||||||
|
data-confirm="{{ confirm_msg }}"
|
||||||
|
onsubmit="return window.confirm(this.dataset.confirm)">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit">Smazat sadu</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if errors %}
|
||||||
|
<div class="flash flash-error">
|
||||||
|
<ul>
|
||||||
|
{% for err in errors %}
|
||||||
|
<li>{{ err }}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Hromadné nahrání fotek</h2>
|
||||||
|
<p>
|
||||||
|
Vyberte fotky (max {{ max_upload_mb }} MB na soubor,
|
||||||
|
{{ max_request_mb }} MB na dávku). Soubory se seskupí podle názvu
|
||||||
|
(např. <code>sykora_konadra_1.jpg</code>, <code>sykora_konadra_2.jpg</code>).
|
||||||
|
</p>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.bulk_upload', set_id=quiz_set['id']) }}"
|
||||||
|
enctype="multipart/form-data"
|
||||||
|
data-bulk-upload-form>
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<label for="bulk-files">Soubory fotek</label>
|
||||||
|
<input id="bulk-files" name="files" type="file" accept="image/*"
|
||||||
|
multiple data-bulk-file-input>
|
||||||
|
<div data-bulk-fallback-submit>
|
||||||
|
<button type="submit">Nahrát a seskupit fotky</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div data-bulk-preview hidden>
|
||||||
|
<h3>Náhled seskupení před nahráním</h3>
|
||||||
|
<div data-bulk-groups></div>
|
||||||
|
<p data-bulk-status></p>
|
||||||
|
<button type="button" data-bulk-confirm>Potvrdit a nahrát</button>
|
||||||
|
<button type="button" data-bulk-reset>Zrušit výběr</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Přidat položku</h2>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.add_item', set_id=quiz_set['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<label for="item-nazev">Název položky</label>
|
||||||
|
<input id="item-nazev" name="nazev" type="text" required>
|
||||||
|
|
||||||
|
<label for="item-poradi">Pořadí (volitelné)</label>
|
||||||
|
<input id="item-poradi" name="poradi" type="number">
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button type="submit">Přidat položku</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Položky v sadě ({{ items_data|length }})</h2>
|
||||||
|
{% if items_data %}
|
||||||
|
{% for entry in items_data %}
|
||||||
|
{% set item = entry['item'] %}
|
||||||
|
{% set photos = entry['photos'] %}
|
||||||
|
<article style="border: 1px solid #ddd; padding: 0.75rem; margin: 1rem 0;">
|
||||||
|
<h3>{{ item['nazev'] }}</h3>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.edit_item', set_id=quiz_set['id'], item_id=item['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<input name="nazev" type="text" value="{{ item['nazev'] }}" required>
|
||||||
|
<input name="poradi" type="number" value="{{ item['poradi'] }}"
|
||||||
|
required style="min-width: 5rem; width: 6rem;">
|
||||||
|
<button type="submit">Uložit položku</button>
|
||||||
|
</form>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.delete_item', set_id=quiz_set['id'], item_id=item['id']) }}"
|
||||||
|
data-confirm="Opravdu smazat položku včetně všech jejích fotek?"
|
||||||
|
onsubmit="return window.confirm(this.dataset.confirm)">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit">Smazat položku</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<h4>Fotky ({{ photos|length }})</h4>
|
||||||
|
{% if photos %}
|
||||||
|
<div style="display: flex; flex-wrap: wrap; gap: 0.75rem;">
|
||||||
|
{% for photo in photos %}
|
||||||
|
<div style="border: 1px solid #eee; padding: 0.5rem;">
|
||||||
|
<a href="/media/{{ photo['soubor_plny'] }}" target="_blank">
|
||||||
|
<img src="/media/{{ photo['soubor_nahled'] }}"
|
||||||
|
alt="{{ item['nazev'] }}"
|
||||||
|
style="max-width: 160px; max-height: 120px; display: block;">
|
||||||
|
</a>
|
||||||
|
<small>
|
||||||
|
{{ photo['sirka'] }}×{{ photo['vyska'] }} px,
|
||||||
|
{{ format_human_size(photo['velikost_plny_b'] + photo['velikost_nahled_b']) }}
|
||||||
|
</small>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.update_photo_order', set_id=quiz_set['id'], photo_id=photo['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<input name="poradi" type="number" value="{{ photo['poradi'] }}"
|
||||||
|
required style="min-width: 4rem; width: 5rem;">
|
||||||
|
<button type="submit">Pořadí</button>
|
||||||
|
</form>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.delete_photo', set_id=quiz_set['id'], photo_id=photo['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit">Smazat fotku</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p>Položka zatím nemá žádné fotky.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.upload_item_photos', set_id=quiz_set['id'], item_id=item['id']) }}"
|
||||||
|
enctype="multipart/form-data">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<label for="add-photos-{{ item['id'] }}">Přidat fotky k položce</label>
|
||||||
|
<input id="add-photos-{{ item['id'] }}" name="files" type="file"
|
||||||
|
accept="image/*" multiple required>
|
||||||
|
<button type="submit">Nahrát fotky</button>
|
||||||
|
</form>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
{% else %}
|
||||||
|
<p>Sada zatím neobsahuje žádné položky.</p>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script type="module"
|
||||||
|
src="{{ url_for('static', filename='js/bulk_upload.js') }}"></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}
|
||||||
|
{{ 'Nová sada' if mode == 'create' else 'Upravit sadu' }} – Poznávačky
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>{{ 'Nová sada poznávaček' if mode == 'create' else 'Upravit sadu' }}</h1>
|
||||||
|
<p>
|
||||||
|
<a href="{{ url_for('admin_sets.list_sets') }}">Zpět na seznam sad</a>
|
||||||
|
{% if quiz_set %}
|
||||||
|
| <a href="{{ url_for('admin_sets.set_detail', set_id=quiz_set['id']) }}">
|
||||||
|
Zpět na detail sady
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if errors %}
|
||||||
|
<div class="flash flash-error">
|
||||||
|
<ul>
|
||||||
|
{% for err in errors %}
|
||||||
|
<li>{{ err }}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.create_set') if mode == 'create' else url_for('admin_sets.edit_set', set_id=quiz_set['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
|
||||||
|
<label for="nazev">Název sady</label>
|
||||||
|
<input id="nazev" name="nazev" type="text"
|
||||||
|
value="{{ form_data['nazev'] }}" required>
|
||||||
|
|
||||||
|
<label for="slug">URL slug (volitelný – prázdný se vygeneruje z názvu)</label>
|
||||||
|
<input id="slug" name="slug" type="text"
|
||||||
|
value="{{ form_data['slug_input'] }}">
|
||||||
|
|
||||||
|
<label for="rocnik">Ročník (volitelný)</label>
|
||||||
|
<input id="rocnik" name="rocnik" type="number" min="1"
|
||||||
|
value="{{ form_data['rocnik_input'] }}">
|
||||||
|
|
||||||
|
<label for="kategorie">Kategorie (volitelná)</label>
|
||||||
|
<input id="kategorie" name="kategorie" type="text"
|
||||||
|
value="{{ form_data['kategorie'] }}">
|
||||||
|
|
||||||
|
<label for="popis">Popis (volitelný)</label>
|
||||||
|
<textarea id="popis" name="popis" rows="3"
|
||||||
|
cols="50">{{ form_data['popis'] }}</textarea>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button type="submit">
|
||||||
|
{{ 'Vytvořit sadu' if mode == 'create' else 'Uložit změny' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Správa sad – Poznávačky{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Správa sad poznávaček</h1>
|
||||||
|
<p>
|
||||||
|
<a href="{{ url_for('admin_users.index') }}">Zpět do administrace</a>
|
||||||
|
| <a href="{{ url_for('admin_sets.create_set') }}">Nová sada</a>
|
||||||
|
| <a href="{{ url_for('admin_storage.overview') }}">Správa úložiště</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if errors %}
|
||||||
|
<div class="flash flash-error">
|
||||||
|
<ul>
|
||||||
|
{% for err in errors %}
|
||||||
|
<li>{{ err }}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if sets %}
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Název</th>
|
||||||
|
<th>Ročník</th>
|
||||||
|
<th>Kategorie</th>
|
||||||
|
<th>Stav</th>
|
||||||
|
<th>Položek</th>
|
||||||
|
<th>Fotek</th>
|
||||||
|
<th>Kol</th>
|
||||||
|
<th>Akce</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for s in sets %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="{{ url_for('admin_sets.set_detail', set_id=s['id']) }}">
|
||||||
|
{{ s['nazev'] }}
|
||||||
|
</a>
|
||||||
|
<br><small><code>{{ s['slug'] }}</code></small>
|
||||||
|
</td>
|
||||||
|
<td>{{ (s['rocnik'] ~ '.') if s['rocnik'] else '–' }}</td>
|
||||||
|
<td>{{ s['kategorie'] or '–' }}</td>
|
||||||
|
<td>
|
||||||
|
{{ 'Publikováno' if s['stav'] == 'publikovano' else 'Koncept' }}
|
||||||
|
</td>
|
||||||
|
<td>{{ s['item_count'] }}</td>
|
||||||
|
<td>{{ s['photo_count'] }}</td>
|
||||||
|
<td>{{ s['round_count'] }}</td>
|
||||||
|
<td>
|
||||||
|
<a href="{{ url_for('admin_sets.edit_set', set_id=s['id']) }}">
|
||||||
|
Upravit
|
||||||
|
</a>
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.toggle_set_status', set_id=s['id']) }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<input type="hidden" name="next"
|
||||||
|
value="{{ url_for('admin_sets.list_sets') }}">
|
||||||
|
<button type="submit">
|
||||||
|
{{ 'Přepnout na koncept' if s['stav'] == 'publikovano' else 'Publikovat' }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{% if s['round_count'] > 0 %}
|
||||||
|
{% set confirm_msg = "Opravdu smazat sadu „" ~ s['nazev'] ~ "“? Pozor: sada má " ~ s['round_count'] ~ " odehraných kol a smazáním se odstraní i historie výsledků žáků." %}
|
||||||
|
{% else %}
|
||||||
|
{% set confirm_msg = "Opravdu smazat sadu „" ~ s['nazev'] ~ "“ včetně všech položek a fotek?" %}
|
||||||
|
{% endif %}
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.delete_set', set_id=s['id']) }}"
|
||||||
|
data-confirm="{{ confirm_msg }}"
|
||||||
|
onsubmit="return window.confirm(this.dataset.confirm)">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<input type="hidden" name="next"
|
||||||
|
value="{{ url_for('admin_sets.list_sets') }}">
|
||||||
|
<button type="submit">Smazat</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{% else %}
|
||||||
|
<p>Zatím nejsou vytvořené žádné sady poznávaček.</p>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Správa úložiště – Poznávačky{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<h1>Správa úložiště</h1>
|
||||||
|
<p>
|
||||||
|
<a href="{{ url_for('admin_users.index') }}">Zpět do administrace</a>
|
||||||
|
| <a href="{{ url_for('admin_sets.list_sets') }}">Správa sad</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h2>Souhrnné metriky</h2>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
Celková velikost médií na disku:
|
||||||
|
<strong>{{ format_mb(stats.media_bytes) }}</strong>
|
||||||
|
({{ format_human_size(stats.media_bytes) }})
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Velikost SQLite databáze (včetně WAL/SHM):
|
||||||
|
<strong>{{ format_human_size(stats.db_bytes) }}</strong>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Volné místo na disku:
|
||||||
|
<strong>{{ format_human_size(stats.disk_free_bytes) }}</strong>
|
||||||
|
z {{ format_human_size(stats.disk_total_bytes) }}
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
Osiřelé soubory:
|
||||||
|
<strong>{{ stats.orphan_count }}</strong>
|
||||||
|
({{ format_human_size(stats.orphan_bytes) }})
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Úklid osiřelých souborů</h2>
|
||||||
|
{% if stats.orphan_files %}
|
||||||
|
<details>
|
||||||
|
<summary>
|
||||||
|
Zobrazit seznam osiřelých souborů ({{ stats.orphan_count }})
|
||||||
|
</summary>
|
||||||
|
<ul>
|
||||||
|
{% for orphan in stats.orphan_files %}
|
||||||
|
<li>
|
||||||
|
<code>{{ orphan.relative_path }}</code>
|
||||||
|
– {{ format_human_size(orphan.size_bytes) }}
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
{% else %}
|
||||||
|
<p>Žádné osiřelé soubory nebyly zjištěny.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_storage.cleanup_orphans') }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button type="submit">Uklidit osiřelé soubory</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Využití místa podle sad</h2>
|
||||||
|
{% set next_size_dir = 'asc' if sort_by == 'size' and direction == 'desc' else 'desc' %}
|
||||||
|
{% set next_photos_dir = 'asc' if sort_by == 'photos' and direction == 'desc' else 'desc' %}
|
||||||
|
{% set next_name_dir = 'desc' if sort_by == 'name' and direction == 'asc' else 'asc' %}
|
||||||
|
|
||||||
|
{% if stats.sets %}
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>
|
||||||
|
<a href="{{ url_for('admin_storage.overview', sort='name', dir=next_name_dir) }}">
|
||||||
|
Název sady
|
||||||
|
</a>
|
||||||
|
</th>
|
||||||
|
<th>Stav</th>
|
||||||
|
<th>Položek</th>
|
||||||
|
<th>
|
||||||
|
<a href="{{ url_for('admin_storage.overview', sort='photos', dir=next_photos_dir) }}">
|
||||||
|
Fotek
|
||||||
|
</a>
|
||||||
|
</th>
|
||||||
|
<th>Odehraných kol</th>
|
||||||
|
<th>
|
||||||
|
<a href="{{ url_for('admin_storage.overview', sort='size', dir=next_size_dir) }}">
|
||||||
|
Velikost
|
||||||
|
</a>
|
||||||
|
</th>
|
||||||
|
<th>Akce</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for s in stats.sets %}
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<a href="{{ url_for('admin_sets.set_detail', set_id=s.id) }}">
|
||||||
|
{{ s.nazev }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ 'Publikováno' if s.stav == 'publikovano' else 'Koncept' }}
|
||||||
|
</td>
|
||||||
|
<td>{{ s.item_count }}</td>
|
||||||
|
<td>{{ s.photo_count }}</td>
|
||||||
|
<td>{{ s.round_count }}</td>
|
||||||
|
<td>{{ format_mb(s.size_bytes) }}</td>
|
||||||
|
<td>
|
||||||
|
{% if s.round_count > 0 %}
|
||||||
|
{% set confirm_msg = "Opravdu smazat sadu „" ~ s.nazev ~ "“? Pozor: sada má " ~ s.round_count ~ " odehraných kol a smazáním se nenávratně odstraní i historie výsledků žáků." %}
|
||||||
|
{% else %}
|
||||||
|
{% set confirm_msg = "Opravdu smazat sadu „" ~ s.nazev ~ "“ včetně všech položek a fotek?" %}
|
||||||
|
{% endif %}
|
||||||
|
<form method="post"
|
||||||
|
action="{{ url_for('admin_sets.delete_set', set_id=s.id) }}"
|
||||||
|
data-confirm="{{ confirm_msg }}"
|
||||||
|
onsubmit="return window.confirm(this.dataset.confirm)">
|
||||||
|
<input type="hidden" name="csrf_token"
|
||||||
|
value="{{ csrf_token() }}">
|
||||||
|
<input type="hidden" name="next"
|
||||||
|
value="{{ url_for('admin_storage.overview') }}">
|
||||||
|
<button type="submit">Smazat sadu</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{% else %}
|
||||||
|
<p>Zatím nejsou vytvořené žádné sady.</p>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -15,8 +15,10 @@
|
|||||||
border: 1px solid #ccc; border-radius: 4px; }
|
border: 1px solid #ccc; border-radius: 4px; }
|
||||||
.flash-error { border-color: #c33; background: #fee; }
|
.flash-error { border-color: #c33; background: #fee; }
|
||||||
.flash-success { border-color: #393; background: #efe; }
|
.flash-success { border-color: #393; background: #efe; }
|
||||||
|
.flash-warning { border-color: #c90; background: #ffd; }
|
||||||
|
.flash-info { border-color: #36c; background: #eef; }
|
||||||
label { display: block; margin-top: 0.75rem; font-weight: 600; }
|
label { display: block; margin-top: 0.75rem; font-weight: 600; }
|
||||||
input, select { padding: 0.4rem; min-width: 16rem; }
|
input, select, textarea { padding: 0.4rem; min-width: 16rem; }
|
||||||
button { margin-top: 0.75rem; padding: 0.45rem 0.9rem; cursor: pointer; }
|
button { margin-top: 0.75rem; padding: 0.45rem 0.9rem; cursor: pointer; }
|
||||||
table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
|
table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
|
||||||
th, td { border: 1px solid #ddd; padding: 0.45rem; text-align: left; }
|
th, td { border: 1px solid #ddd; padding: 0.45rem; text-align: left; }
|
||||||
|
|||||||
+1
-1
@@ -24,7 +24,7 @@ dev = [
|
|||||||
include = ["poznavacky*"]
|
include = ["poznavacky*"]
|
||||||
|
|
||||||
[tool.setuptools.package-data]
|
[tool.setuptools.package-data]
|
||||||
poznavacky = ["migrations/*.sql", "templates/**/*.html"]
|
poznavacky = ["migrations/*.sql", "templates/**/*.html", "static/**/*"]
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
|
|||||||
@@ -0,0 +1,649 @@
|
|||||||
|
"""Testy správy sad, položek, více fotek a hromadného uploadu v /admin."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import Flask
|
||||||
|
from flask.testing import FlaskClient
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from poznavacky import admin_sets
|
||||||
|
from poznavacky.security import hash_password
|
||||||
|
|
||||||
|
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
def _csrf(client: FlaskClient, path: str) -> str:
|
||||||
|
resp = client.get(path)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
match = _CSRF_RE.search(resp.get_data(as_text=True))
|
||||||
|
assert match is not None
|
||||||
|
return match.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def _insert_user(
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
role: str = "ucitelka",
|
||||||
|
stav: str = "schvaleny",
|
||||||
|
) -> int:
|
||||||
|
cur = db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO uzivatele (
|
||||||
|
email, heslo_hash, jmeno, prijmeni, role, stav
|
||||||
|
) VALUES (?, ?, 'Jana', 'Testova', ?, ?)
|
||||||
|
""",
|
||||||
|
(email, hash_password(password), role, stav),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert cur.lastrowid is not None
|
||||||
|
return int(cur.lastrowid)
|
||||||
|
|
||||||
|
|
||||||
|
def _login(client: FlaskClient, email: str, password: str) -> None:
|
||||||
|
token = _csrf(client, "/prihlaseni")
|
||||||
|
resp = client.post(
|
||||||
|
"/prihlaseni",
|
||||||
|
data={"csrf_token": token, "email": email, "heslo": password},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 302
|
||||||
|
|
||||||
|
|
||||||
|
def _make_img(
|
||||||
|
size: tuple[int, int] = (400, 300),
|
||||||
|
*,
|
||||||
|
fmt: str = "JPEG",
|
||||||
|
exif: Image.Exif | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
img = Image.new("RGB", size, (30, 140, 80))
|
||||||
|
buf = BytesIO()
|
||||||
|
kwargs: dict = {"format": fmt}
|
||||||
|
if exif is not None:
|
||||||
|
kwargs["exif"] = exif
|
||||||
|
img.save(buf, **kwargs)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_sets_access_and_csrf_protection(
|
||||||
|
client: FlaskClient,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(db, email="zak@example.test", password="heslo-zak", role="zak")
|
||||||
|
_insert_user(
|
||||||
|
db,
|
||||||
|
email="ucitelka@example.test",
|
||||||
|
password="heslo-ucitelka",
|
||||||
|
role="ucitelka",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert client.get("/admin/sady").status_code == 302
|
||||||
|
assert client.get("/admin/sady/nova").status_code == 302
|
||||||
|
|
||||||
|
_login(client, "zak@example.test", "heslo-zak")
|
||||||
|
assert client.get("/admin/sady").status_code == 403
|
||||||
|
|
||||||
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
assert client.get("/admin/sady").status_code == 200
|
||||||
|
no_csrf = client.post("/admin/sady/nova", data={"nazev": "Bez CSRF"})
|
||||||
|
assert no_csrf.status_code == 403
|
||||||
|
|
||||||
|
# Rozcestník /admin obsahuje odkazy na sady i úložiště a ES modul funguje.
|
||||||
|
admin_html = client.get("/admin").get_data(as_text=True)
|
||||||
|
assert "/admin/sady" in admin_html
|
||||||
|
assert "/admin/uloziste" in admin_html
|
||||||
|
with client.get("/static/js/bulk_upload.js") as js_resp:
|
||||||
|
assert js_resp.status_code == 200
|
||||||
|
assert "parseUploadGroup" in js_resp.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_set_crud_slug_collision_validation_and_publishing_rules(
|
||||||
|
app: Flask,
|
||||||
|
client: FlaskClient,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(db, email="ucitelka@example.test", password="heslo-ucitelka")
|
||||||
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
token = _csrf(client, "/admin/sady/nova")
|
||||||
|
|
||||||
|
# Vytvoření sady s automatickým slugem.
|
||||||
|
resp = client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"nazev": "Ptáci naší přírody",
|
||||||
|
"rocnik": "6",
|
||||||
|
"kategorie": "Ptáci",
|
||||||
|
"popis": "Poznávačka ptáků",
|
||||||
|
"slug": "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 302
|
||||||
|
sada1 = db.execute("SELECT * FROM sady").fetchone()
|
||||||
|
assert sada1 is not None
|
||||||
|
assert sada1["slug"] == "ptaci-nasi-prirody"
|
||||||
|
assert sada1["stav"] == "koncept"
|
||||||
|
assert sada1["rocnik"] == 6
|
||||||
|
sada1_id = int(sada1["id"])
|
||||||
|
|
||||||
|
# Kolize automatického slugu -> -2.
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": "Ptáci", "slug": ""},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": "Ptáci", "slug": ""},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
slugs = [
|
||||||
|
row["slug"]
|
||||||
|
for row in db.execute(
|
||||||
|
"SELECT slug FROM sady WHERE slug LIKE 'ptaci%' ORDER BY id"
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
assert slugs == ["ptaci-nasi-prirody", "ptaci", "ptaci-2"]
|
||||||
|
|
||||||
|
# Prázdný název, neplatný a duplicitní ruční slug -> HTTP 400.
|
||||||
|
bad_empty = client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": " ", "slug": ""},
|
||||||
|
)
|
||||||
|
assert bad_empty.status_code == 400
|
||||||
|
bad_dup = client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": "Jiná sada", "slug": "ptaci"},
|
||||||
|
)
|
||||||
|
assert bad_dup.status_code == 400
|
||||||
|
bad_slug = client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": "Jiná sada", "slug": "Spatny Slug"},
|
||||||
|
)
|
||||||
|
assert bad_slug.status_code == 400
|
||||||
|
|
||||||
|
# Publikování prázdné sady musí vrátit HTTP 400 a ponechat koncept.
|
||||||
|
pub_empty = client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/stav",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
)
|
||||||
|
assert pub_empty.status_code == 400
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT stav FROM sady WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
).fetchone()["stav"]
|
||||||
|
== "koncept"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Nastavíme starý timestamp, abychom ověřili aktualizaci upraveno_at.
|
||||||
|
db.execute(
|
||||||
|
"UPDATE sady SET upraveno_at = '2020-01-01T00:00:00Z' WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
# Přidáme dvě položky s fotkami a publikujeme -> projde s upozorněním A–D.
|
||||||
|
for nazev in ("Sýkora koňadra", "Kos černý"):
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/polozky",
|
||||||
|
data={"csrf_token": token, "nazev": nazev},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
item_ids = [
|
||||||
|
int(row["id"])
|
||||||
|
for row in db.execute(
|
||||||
|
"SELECT id FROM polozky WHERE sada_id = ? ORDER BY id",
|
||||||
|
(sada1_id,),
|
||||||
|
).fetchall()
|
||||||
|
]
|
||||||
|
for item_id in item_ids:
|
||||||
|
up = client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/polozky/{item_id}/fotky",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": (BytesIO(_make_img()), "ptak.jpg"),
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert up.status_code == 302
|
||||||
|
|
||||||
|
db.execute(
|
||||||
|
"UPDATE sady SET upraveno_at = '2020-01-01T00:00:00Z' WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
pub_small = client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/stav",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
assert pub_small.status_code == 200
|
||||||
|
pub_html = pub_small.get_data(as_text=True)
|
||||||
|
assert "režim A–D" in pub_html
|
||||||
|
row_pub = db.execute(
|
||||||
|
"SELECT stav, upraveno_at FROM sady WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
).fetchone()
|
||||||
|
assert row_pub["stav"] == "publikovano"
|
||||||
|
assert row_pub["upraveno_at"] != "2020-01-01T00:00:00Z"
|
||||||
|
|
||||||
|
# Smazání všech fotek z publikované sady automaticky přepne zpět na koncept.
|
||||||
|
photo_ids = [
|
||||||
|
int(row["id"])
|
||||||
|
for row in db.execute("SELECT id FROM fotky ORDER BY id").fetchall()
|
||||||
|
]
|
||||||
|
assert len(photo_ids) == 2
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/fotky/{photo_ids[0]}/smazat",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT stav FROM sady WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
).fetchone()["stav"]
|
||||||
|
== "publikovano"
|
||||||
|
)
|
||||||
|
last_del = client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/fotky/{photo_ids[1]}/smazat",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
assert last_del.status_code == 200
|
||||||
|
assert "koncept" in last_del.get_data(as_text=True).lower()
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT stav FROM sady WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
).fetchone()["stav"]
|
||||||
|
== "koncept"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Úprava metadat sady změní název a aktualizuje upraveno_at.
|
||||||
|
edit_resp = client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/upravit",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"nazev": "Ptáci ČR",
|
||||||
|
"slug": "ptaci-cr",
|
||||||
|
"rocnik": "7",
|
||||||
|
"kategorie": "Ptáci",
|
||||||
|
"popis": "Upraveno",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert edit_resp.status_code == 302
|
||||||
|
edited = db.execute(
|
||||||
|
"SELECT nazev, slug, rocnik FROM sady WHERE id = ?",
|
||||||
|
(sada1_id,),
|
||||||
|
).fetchone()
|
||||||
|
assert edited["nazev"] == "Ptáci ČR"
|
||||||
|
assert edited["slug"] == "ptaci-cr"
|
||||||
|
assert edited["rocnik"] == 7
|
||||||
|
|
||||||
|
# Smazání sady smaže DB záznamy i adresář na disku.
|
||||||
|
zak_id = _insert_user(
|
||||||
|
db,
|
||||||
|
email="zak2@example.test",
|
||||||
|
password="heslo-zak2",
|
||||||
|
role="zak",
|
||||||
|
)
|
||||||
|
db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO kola (uzivatel_id, sada_id, rezim, typ_kola, pocet_otazek)
|
||||||
|
VALUES (?, ?, 'abcd', 'cele', 2)
|
||||||
|
""",
|
||||||
|
(zak_id, sada1_id),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
# Nahrajeme fotku, ať ověříme její smazání ze disku při smazání sady.
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/polozky/{item_ids[0]}/fotky",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": (BytesIO(_make_img()), "konec.jpg"),
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
media_set_dir = Path(app.config["MEDIA_DIR"]) / str(sada1_id)
|
||||||
|
assert list(media_set_dir.glob("*.webp"))
|
||||||
|
|
||||||
|
sets_html = client.get("/admin/sady").get_data(as_text=True)
|
||||||
|
assert "odehraných kol" in sets_html
|
||||||
|
|
||||||
|
del_set = client.post(
|
||||||
|
f"/admin/sady/{sada1_id}/smazat",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
)
|
||||||
|
assert del_set.status_code == 302
|
||||||
|
assert (
|
||||||
|
db.execute("SELECT id FROM sady WHERE id = ?", (sada1_id,)).fetchone()
|
||||||
|
is None
|
||||||
|
)
|
||||||
|
assert not media_set_dir.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_item_crud_preserves_metadata_and_multi_photo_management(
|
||||||
|
app: Flask,
|
||||||
|
client: FlaskClient,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(db, email="ucitelka@example.test", password="heslo-ucitelka")
|
||||||
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
token = _csrf(client, "/admin/sady/nova")
|
||||||
|
|
||||||
|
client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": "Rostliny", "slug": "rostliny"},
|
||||||
|
)
|
||||||
|
set_id = int(db.execute("SELECT id FROM sady").fetchone()["id"])
|
||||||
|
|
||||||
|
# Prázdný název položky -> HTTP 400.
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{set_id}/polozky",
|
||||||
|
data={"csrf_token": token, "nazev": " "},
|
||||||
|
).status_code
|
||||||
|
== 400
|
||||||
|
)
|
||||||
|
|
||||||
|
# Přidání položky a ruční doplnění metadat, která musí editace zachovat.
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{set_id}/polozky",
|
||||||
|
data={"csrf_token": token, "nazev": "Pampeliška"},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
item_id = int(db.execute("SELECT id FROM polozky").fetchone()["id"])
|
||||||
|
db.execute(
|
||||||
|
"""
|
||||||
|
UPDATE polozky
|
||||||
|
SET latinsky_nazev = ?, synonyma_json = ?, vlastni_distraktory_json = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
"Taraxacum officinale",
|
||||||
|
json.dumps(["smetánka lékařská"], ensure_ascii=False),
|
||||||
|
json.dumps(["sedmikráska"], ensure_ascii=False),
|
||||||
|
item_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
# Nahrání 2 fotek najednou a poté ještě 1 další (včetně EXIF autorotace).
|
||||||
|
exif = Image.Exif()
|
||||||
|
exif[274] = 6
|
||||||
|
exif[271] = "SecretCamera"
|
||||||
|
resp1 = client.post(
|
||||||
|
f"/admin/sady/{set_id}/polozky/{item_id}/fotky",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": [
|
||||||
|
(BytesIO(_make_img((600, 400), exif=exif)), "a.jpg"),
|
||||||
|
(BytesIO(_make_img((500, 300), fmt="PNG")), "b.png"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert resp1.status_code == 302
|
||||||
|
resp2 = client.post(
|
||||||
|
f"/admin/sady/{set_id}/polozky/{item_id}/fotky",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": (BytesIO(_make_img((300, 200), fmt="WEBP")), "c.webp"),
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert resp2.status_code == 302
|
||||||
|
|
||||||
|
photos = db.execute(
|
||||||
|
"SELECT * FROM fotky WHERE polozka_id = ? ORDER BY poradi, id",
|
||||||
|
(item_id,),
|
||||||
|
).fetchall()
|
||||||
|
assert len(photos) == 3
|
||||||
|
assert [int(p["poradi"]) for p in photos] == [1, 2, 3]
|
||||||
|
assert (photos[0]["sirka"], photos[0]["vyska"]) == (400, 600)
|
||||||
|
|
||||||
|
# Kontrola přesných bajtů v DB a prázdného EXIFu na disku.
|
||||||
|
media_dir = Path(app.config["MEDIA_DIR"])
|
||||||
|
for p in photos:
|
||||||
|
full_file = media_dir / p["soubor_plny"]
|
||||||
|
thumb_file = media_dir / p["soubor_nahled"]
|
||||||
|
assert p["velikost_plny_b"] == full_file.stat().st_size
|
||||||
|
assert p["velikost_nahled_b"] == thumb_file.stat().st_size
|
||||||
|
with Image.open(full_file) as img:
|
||||||
|
assert img.format == "WEBP"
|
||||||
|
assert len(img.getexif()) == 0
|
||||||
|
|
||||||
|
# Úprava názvu a pořadí položky zachová metadata i všechny 3 fotky.
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{set_id}/polozky/{item_id}/upravit",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"nazev": "Smetánka lékařská",
|
||||||
|
"poradi": "5",
|
||||||
|
},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
updated_item = db.execute(
|
||||||
|
"SELECT * FROM polozky WHERE id = ?",
|
||||||
|
(item_id,),
|
||||||
|
).fetchone()
|
||||||
|
assert updated_item["nazev"] == "Smetánka lékařská"
|
||||||
|
assert updated_item["poradi"] == 5
|
||||||
|
assert updated_item["latinsky_nazev"] == "Taraxacum officinale"
|
||||||
|
assert "smetánka lékařská" in updated_item["synonyma_json"]
|
||||||
|
assert "sedmikráska" in updated_item["vlastni_distraktory_json"]
|
||||||
|
|
||||||
|
# Změna pořadí 3. fotky na 0 -> přesune ji před ostatní v detailu sady.
|
||||||
|
third_photo = photos[2]
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{set_id}/fotky/{third_photo['id']}/poradi",
|
||||||
|
data={"csrf_token": token, "poradi": "0"},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
detail_html = client.get(f"/admin/sady/{set_id}").get_data(as_text=True)
|
||||||
|
pos_third = detail_html.index(third_photo["soubor_nahled"])
|
||||||
|
pos_first = detail_html.index(photos[0]["soubor_nahled"])
|
||||||
|
assert pos_third < pos_first
|
||||||
|
|
||||||
|
# Smazání 2. fotky odstraní jen její soubory a ostatní 2 ponechá.
|
||||||
|
second_photo = photos[1]
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{set_id}/fotky/{second_photo['id']}/smazat",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
assert not (media_dir / second_photo["soubor_plny"]).exists()
|
||||||
|
assert not (media_dir / second_photo["soubor_nahled"]).exists()
|
||||||
|
remaining_photos = db.execute(
|
||||||
|
"SELECT id FROM fotky WHERE polozka_id = ?",
|
||||||
|
(item_id,),
|
||||||
|
).fetchall()
|
||||||
|
assert len(remaining_photos) == 2
|
||||||
|
|
||||||
|
# Smazání položky smaže i zbývající soubory na disku.
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
f"/admin/sady/{set_id}/polozky/{item_id}/smazat",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
).status_code
|
||||||
|
== 302
|
||||||
|
)
|
||||||
|
assert db.execute("SELECT COUNT(*) FROM fotky").fetchone()[0] == 0
|
||||||
|
assert list(media_dir.rglob("*.webp")) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_bulk_upload_grouping_preview_override_merge_and_partial_errors(
|
||||||
|
app: Flask,
|
||||||
|
client: FlaskClient,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(db, email="ucitelka@example.test", password="heslo-ucitelka")
|
||||||
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
token = _csrf(client, "/admin/sady/nova")
|
||||||
|
|
||||||
|
client.post(
|
||||||
|
"/admin/sady/nova",
|
||||||
|
data={"csrf_token": token, "nazev": "Hromadná", "slug": "hromadna"},
|
||||||
|
)
|
||||||
|
set_id = int(db.execute("SELECT id FROM sady").fetchone()["id"])
|
||||||
|
|
||||||
|
# 1) Automatické serverové seskupení bez item_names (fallback bez JS).
|
||||||
|
resp = client.post(
|
||||||
|
f"/admin/sady/{set_id}/hromadny-upload",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": [
|
||||||
|
(BytesIO(_make_img()), "sykora_konadra_1.jpg"),
|
||||||
|
(BytesIO(_make_img()), "sykora_konadra_2.jpg"),
|
||||||
|
(BytesIO(_make_img(fmt="PNG")), "kos_cerny.png"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert resp.status_code == 302
|
||||||
|
items = db.execute(
|
||||||
|
"SELECT id, nazev FROM polozky WHERE sada_id = ? ORDER BY poradi, id",
|
||||||
|
(set_id,),
|
||||||
|
).fetchall()
|
||||||
|
assert [row["nazev"] for row in items] == ["Sykora konadra", "Kos cerny"]
|
||||||
|
counts = [
|
||||||
|
db.execute(
|
||||||
|
"SELECT COUNT(*) FROM fotky WHERE polozka_id = ?",
|
||||||
|
(row["id"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
for row in items
|
||||||
|
]
|
||||||
|
assert counts == [2, 1]
|
||||||
|
|
||||||
|
# 2) Připojení další fotky k již existující položce (bez diakritiky).
|
||||||
|
db.execute(
|
||||||
|
"UPDATE polozky SET nazev = 'Sýkora koňadra' WHERE id = ?",
|
||||||
|
(items[0]["id"],),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
resp_merge = client.post(
|
||||||
|
f"/admin/sady/{set_id}/hromadny-upload",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": [(BytesIO(_make_img()), "sykora_konadra_3.jpg")],
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert resp_merge.status_code == 302
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT COUNT(*) FROM polozky WHERE sada_id = ?",
|
||||||
|
(set_id,),
|
||||||
|
).fetchone()[0]
|
||||||
|
== 2
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT COUNT(*) FROM fotky WHERE polozka_id = ?",
|
||||||
|
(items[0]["id"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
== 3
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3) Potvrzení upraveného přiřazení z klientského náhledu (item_names).
|
||||||
|
resp_override = client.post(
|
||||||
|
f"/admin/sady/{set_id}/hromadny-upload",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"item_names": ["Červenka obecná", "Červenka obecná"],
|
||||||
|
"files": [
|
||||||
|
(BytesIO(_make_img()), "cervenka_1.jpg"),
|
||||||
|
(BytesIO(_make_img()), "IMG_4021.jpg"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert resp_override.status_code == 302
|
||||||
|
cervenka = db.execute(
|
||||||
|
"SELECT id FROM polozky WHERE sada_id = ? AND nazev = ?",
|
||||||
|
(set_id, "Červenka obecná"),
|
||||||
|
).fetchone()
|
||||||
|
assert cervenka is not None
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT COUNT(*) FROM fotky WHERE polozka_id = ?",
|
||||||
|
(cervenka["id"],),
|
||||||
|
).fetchone()[0]
|
||||||
|
== 2
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4) Částečně neplatná dávka (platný PNG + neobrazový TXT).
|
||||||
|
resp_partial = client.post(
|
||||||
|
f"/admin/sady/{set_id}/hromadny-upload",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": [
|
||||||
|
(BytesIO(_make_img(fmt="PNG")), "vrabec_1.png"),
|
||||||
|
(BytesIO(b"nejaky text"), "poznamky.txt"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
assert resp_partial.status_code == 200
|
||||||
|
body = resp_partial.get_data(as_text=True)
|
||||||
|
assert "poznamky.txt" in body
|
||||||
|
assert (
|
||||||
|
db.execute(
|
||||||
|
"SELECT id FROM polozky WHERE sada_id = ? AND nazev = 'Vrabec'",
|
||||||
|
(set_id,),
|
||||||
|
).fetchone()
|
||||||
|
is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5) Čistě neplatná dávka -> HTTP 400 a nevzniknou soubory navíc.
|
||||||
|
media_dir = Path(app.config["MEDIA_DIR"])
|
||||||
|
files_before = set(media_dir.rglob("*"))
|
||||||
|
resp_all_bad = client.post(
|
||||||
|
f"/admin/sady/{set_id}/hromadny-upload",
|
||||||
|
data={
|
||||||
|
"csrf_token": token,
|
||||||
|
"files": [(BytesIO(b"spatny obsah"), "falesna_fotka.jpg")],
|
||||||
|
},
|
||||||
|
content_type="multipart/form-data",
|
||||||
|
)
|
||||||
|
assert resp_all_bad.status_code == 400
|
||||||
|
assert set(media_dir.rglob("*")) == files_before
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_photo_cleans_up_files_on_db_error(
|
||||||
|
app: Flask,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
media_dir = Path(app.config["MEDIA_DIR"])
|
||||||
|
with pytest.raises(sqlite3.IntegrityError):
|
||||||
|
admin_sets.save_photo_for_item(
|
||||||
|
db,
|
||||||
|
media_dir,
|
||||||
|
sada_id=999,
|
||||||
|
polozka_id=999_999,
|
||||||
|
source=_make_img(),
|
||||||
|
)
|
||||||
|
assert list(media_dir.rglob("*.webp")) == []
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
"""Testy sekce správy úložiště /admin/uloziste a úklidu osiřelých souborů."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
from flask.testing import FlaskClient
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from poznavacky import admin_sets, storage
|
||||||
|
from poznavacky.security import hash_password
|
||||||
|
|
||||||
|
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
def _csrf(client: FlaskClient, path: str) -> str:
|
||||||
|
resp = client.get(path)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
match = _CSRF_RE.search(resp.get_data(as_text=True))
|
||||||
|
assert match is not None
|
||||||
|
return match.group(1)
|
||||||
|
|
||||||
|
|
||||||
|
def _insert_user(
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
role: str,
|
||||||
|
) -> int:
|
||||||
|
cur = db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO uzivatele (
|
||||||
|
email, heslo_hash, jmeno, prijmeni, role, stav
|
||||||
|
) VALUES (?, ?, 'Jana', 'Testova', ?, 'schvaleny')
|
||||||
|
""",
|
||||||
|
(email, hash_password(password), role),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert cur.lastrowid is not None
|
||||||
|
return int(cur.lastrowid)
|
||||||
|
|
||||||
|
|
||||||
|
def _login(client: FlaskClient, email: str, password: str) -> None:
|
||||||
|
token = _csrf(client, "/prihlaseni")
|
||||||
|
resp = client.post(
|
||||||
|
"/prihlaseni",
|
||||||
|
data={"csrf_token": token, "email": email, "heslo": password},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 302
|
||||||
|
|
||||||
|
|
||||||
|
def _make_img(size: tuple[int, int] = (500, 400)) -> bytes:
|
||||||
|
buf = BytesIO()
|
||||||
|
Image.new("RGB", size, (180, 90, 30)).save(buf, format="PNG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_storage_page_access_control(
|
||||||
|
client: FlaskClient,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(db, email="zak@example.test", password="heslo-zak", role="zak")
|
||||||
|
_insert_user(
|
||||||
|
db,
|
||||||
|
email="ucitelka@example.test",
|
||||||
|
password="heslo-ucitelka",
|
||||||
|
role="ucitelka",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert client.get("/admin/uloziste").status_code == 302
|
||||||
|
_login(client, "zak@example.test", "heslo-zak")
|
||||||
|
assert client.get("/admin/uloziste").status_code == 403
|
||||||
|
|
||||||
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
assert client.get("/admin/uloziste").status_code == 200
|
||||||
|
assert client.post("/admin/uloziste/uklid-sirotku").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_storage_overview_sorting_set_deletion_and_orphan_cleanup(
|
||||||
|
app: Flask,
|
||||||
|
client: FlaskClient,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(
|
||||||
|
db,
|
||||||
|
email="ucitelka@example.test",
|
||||||
|
password="heslo-ucitelka",
|
||||||
|
role="ucitelka",
|
||||||
|
)
|
||||||
|
zak_id = _insert_user(
|
||||||
|
db,
|
||||||
|
email="zak@example.test",
|
||||||
|
password="heslo-zak",
|
||||||
|
role="zak",
|
||||||
|
)
|
||||||
|
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
|
||||||
|
# Sada A (větší, 2 položky, 3 fotky, 1 odehrané kolo) a prázdná sada B.
|
||||||
|
cur_a = db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sady (slug, nazev, stav)
|
||||||
|
VALUES ('zvire-sada', 'Zvířata', 'publikovano')
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
sada_a = int(cur_a.lastrowid)
|
||||||
|
cur_a1 = db.execute(
|
||||||
|
"INSERT INTO polozky (sada_id, nazev) VALUES (?, 'Liška')",
|
||||||
|
(sada_a,),
|
||||||
|
)
|
||||||
|
item_a1 = int(cur_a1.lastrowid)
|
||||||
|
cur_a2 = db.execute(
|
||||||
|
"INSERT INTO polozky (sada_id, nazev) VALUES (?, 'Vlk')",
|
||||||
|
(sada_a,),
|
||||||
|
)
|
||||||
|
item_a2 = int(cur_a2.lastrowid)
|
||||||
|
db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO kola (uzivatel_id, sada_id, rezim, typ_kola, pocet_otazek)
|
||||||
|
VALUES (?, ?, 'psani', 'cele', 2)
|
||||||
|
""",
|
||||||
|
(zak_id, sada_a),
|
||||||
|
)
|
||||||
|
|
||||||
|
cur_b = db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sady (slug, nazev, stav)
|
||||||
|
VALUES ('alpha-prazdna', 'Alpha prázdná', 'koncept')
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
sada_b = int(cur_b.lastrowid)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
media_dir = Path(app.config["MEDIA_DIR"])
|
||||||
|
_, p1 = admin_sets.save_photo_for_item(
|
||||||
|
db, media_dir, sada_a, item_a1, _make_img((900, 600))
|
||||||
|
)
|
||||||
|
admin_sets.save_photo_for_item(
|
||||||
|
db, media_dir, sada_a, item_a1, _make_img((800, 600))
|
||||||
|
)
|
||||||
|
admin_sets.save_photo_for_item(
|
||||||
|
db, media_dir, sada_a, item_a2, _make_img((700, 500))
|
||||||
|
)
|
||||||
|
|
||||||
|
# Vytvoříme dva osiřelé soubory.
|
||||||
|
orphan_in_set = media_dir / str(sada_a) / "sirotek_v_sade.webp"
|
||||||
|
orphan_in_set.write_bytes(b"o" * 400)
|
||||||
|
orphan_dir = media_dir / "99"
|
||||||
|
orphan_dir.mkdir()
|
||||||
|
orphan_foreign = orphan_dir / "zapomenuta.webp"
|
||||||
|
orphan_foreign.write_bytes(b"z" * 600)
|
||||||
|
|
||||||
|
# Výchozí zobrazení: metrika médií, DB, volné místo, rozbalitelný seznam
|
||||||
|
# sirotků, sada A před sadou B a varování na odehraná kola.
|
||||||
|
resp = client.get("/admin/uloziste")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
html = resp.get_data(as_text=True)
|
||||||
|
assert "99/zapomenuta.webp" in html
|
||||||
|
assert f"{sada_a}/sirotek_v_sade.webp" in html
|
||||||
|
assert "0,00 MB" in html
|
||||||
|
assert "odehraných kol" in html
|
||||||
|
assert html.index("Zvířata") < html.index("Alpha prázdná")
|
||||||
|
|
||||||
|
# Řazení podle názvu vzestupně -> Alpha prázdná před Zvířata.
|
||||||
|
sorted_html = client.get("/admin/uloziste?sort=name&dir=asc").get_data(
|
||||||
|
as_text=True
|
||||||
|
)
|
||||||
|
assert sorted_html.index("Alpha prázdná") < sorted_html.index("Zvířata")
|
||||||
|
|
||||||
|
# Úklid sirotků smaže jen oba sirotky a cizí prázdný adresář 99.
|
||||||
|
token = _csrf(client, "/admin/uloziste")
|
||||||
|
clean_resp = client.post(
|
||||||
|
"/admin/uloziste/uklid-sirotku",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
assert clean_resp.status_code == 200
|
||||||
|
assert "Uklizeno 2 osiřelých souborů" in clean_resp.get_data(as_text=True)
|
||||||
|
assert not orphan_in_set.exists()
|
||||||
|
assert not orphan_foreign.exists()
|
||||||
|
assert not orphan_dir.exists()
|
||||||
|
assert (media_dir / p1.soubor_plny).is_file()
|
||||||
|
assert media_dir.is_dir()
|
||||||
|
|
||||||
|
# Opakovaný úklid je idempotentní.
|
||||||
|
clean_again = client.post(
|
||||||
|
"/admin/uloziste/uklid-sirotku",
|
||||||
|
data={"csrf_token": token},
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
assert "Nebyly nalezeny žádné osiřelé soubory" in clean_again.get_data(
|
||||||
|
as_text=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# Odolnost proti chybějícímu souboru + okamžité uvolnění místa při smazání.
|
||||||
|
(media_dir / p1.soubor_plny).unlink()
|
||||||
|
bytes_before, _ = storage.scan_media_dir(
|
||||||
|
media_dir,
|
||||||
|
storage.get_referenced_media_paths(db),
|
||||||
|
)
|
||||||
|
assert bytes_before > 0
|
||||||
|
|
||||||
|
del_resp = client.post(
|
||||||
|
f"/admin/sady/{sada_a}/smazat",
|
||||||
|
data={"csrf_token": token, "next": "/admin/uloziste"},
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
assert del_resp.status_code == 200
|
||||||
|
assert not (media_dir / str(sada_a)).exists()
|
||||||
|
bytes_after, _ = storage.scan_media_dir(
|
||||||
|
media_dir,
|
||||||
|
storage.get_referenced_media_paths(db),
|
||||||
|
)
|
||||||
|
assert bytes_after == 0
|
||||||
|
sada_b_row = db.execute(
|
||||||
|
"SELECT id FROM sady WHERE id = ?",
|
||||||
|
(sada_b,),
|
||||||
|
).fetchone()
|
||||||
|
assert sada_b_row is not None
|
||||||
@@ -41,6 +41,10 @@ def test_load_config_from_environ(tmp_path: Path) -> None:
|
|||||||
assert cfg.session_cookie_secure is True
|
assert cfg.session_cookie_secure is True
|
||||||
assert cfg.trust_proxy == 0
|
assert cfg.trust_proxy == 0
|
||||||
assert cfg.password_reset_ttl_minutes == 60
|
assert cfg.password_reset_ttl_minutes == 60
|
||||||
|
assert cfg.max_upload_mb == 15
|
||||||
|
assert cfg.max_request_mb == 100
|
||||||
|
assert cfg.max_upload_bytes == 15 * 1024 * 1024
|
||||||
|
assert cfg.max_request_bytes == 100 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
def test_security_and_reset_config_options() -> None:
|
def test_security_and_reset_config_options() -> None:
|
||||||
@@ -84,6 +88,10 @@ def test_security_and_reset_config_options() -> None:
|
|||||||
("POZNAVACKY_TRUST_PROXY", "abc"),
|
("POZNAVACKY_TRUST_PROXY", "abc"),
|
||||||
("POZNAVACKY_PASSWORD_RESET_TTL_MINUTES", "0"),
|
("POZNAVACKY_PASSWORD_RESET_TTL_MINUTES", "0"),
|
||||||
("POZNAVACKY_SESSION_COOKIE_SECURE", "mozna"),
|
("POZNAVACKY_SESSION_COOKIE_SECURE", "mozna"),
|
||||||
|
("POZNAVACKY_MAX_UPLOAD_MB", "0"),
|
||||||
|
("POZNAVACKY_MAX_UPLOAD_MB", "-5"),
|
||||||
|
("POZNAVACKY_MAX_REQUEST_MB", "0"),
|
||||||
|
("POZNAVACKY_MAX_REQUEST_MB", "abc"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_invalid_security_config_raises(env_key: str, bad_value: str) -> None:
|
def test_invalid_security_config_raises(env_key: str, bad_value: str) -> None:
|
||||||
@@ -165,5 +173,39 @@ def test_env_example_documents_all_required_variables() -> None:
|
|||||||
"SMTP_PASS",
|
"SMTP_PASS",
|
||||||
"SMTP_FROM",
|
"SMTP_FROM",
|
||||||
"SMTP_TLS",
|
"SMTP_TLS",
|
||||||
|
"POZNAVACKY_MAX_UPLOAD_MB",
|
||||||
|
"POZNAVACKY_MAX_REQUEST_MB",
|
||||||
}
|
}
|
||||||
assert expected.issubset(defined_keys)
|
assert expected.issubset(defined_keys)
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_limits_and_http_413_handler(tmp_path: Path) -> None:
|
||||||
|
cfg = load_config(
|
||||||
|
environ={
|
||||||
|
"POZNAVACKY_SECRET_KEY": "klic",
|
||||||
|
"POZNAVACKY_MAX_UPLOAD_MB": "8",
|
||||||
|
"POZNAVACKY_MAX_REQUEST_MB": "25",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assert cfg.max_upload_mb == 8
|
||||||
|
assert cfg.max_request_mb == 25
|
||||||
|
assert cfg.max_upload_bytes == 8 * 1024 * 1024
|
||||||
|
assert cfg.max_request_bytes == 25 * 1024 * 1024
|
||||||
|
|
||||||
|
app = create_app(
|
||||||
|
{
|
||||||
|
"TESTING": True,
|
||||||
|
"POZNAVACKY_DATA_DIR": str(tmp_path / "data"),
|
||||||
|
"POZNAVACKY_MAX_REQUEST_MB": "2",
|
||||||
|
},
|
||||||
|
environ={},
|
||||||
|
)
|
||||||
|
assert app.config["MAX_CONTENT_LENGTH"] == 2 * 1024 * 1024
|
||||||
|
app.config["MAX_CONTENT_LENGTH"] = 256
|
||||||
|
|
||||||
|
client = app.test_client()
|
||||||
|
resp = client.post("/prihlaseni", data={"payload": "x" * 1024})
|
||||||
|
assert resp.status_code == 413
|
||||||
|
body = resp.get_data(as_text=True)
|
||||||
|
assert "maximální povolenou velikost" in body
|
||||||
|
assert "2 MB" in body
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
"""Jednotkové testy optimalizace obrázků přes Pillow."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from poznavacky import images
|
||||||
|
|
||||||
|
|
||||||
|
def _make_image_bytes(
|
||||||
|
size: tuple[int, int],
|
||||||
|
*,
|
||||||
|
fmt: str = "JPEG",
|
||||||
|
mode: str = "RGB",
|
||||||
|
color: tuple[int, ...] = (40, 120, 200),
|
||||||
|
exif: Image.Exif | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
img = Image.new(mode, size, color)
|
||||||
|
buf = BytesIO()
|
||||||
|
save_kwargs: dict = {"format": fmt}
|
||||||
|
if exif is not None:
|
||||||
|
save_kwargs["exif"] = exif
|
||||||
|
img.save(buf, **save_kwargs)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("fmt", ["JPEG", "PNG", "WEBP"])
|
||||||
|
def test_supported_formats_produce_only_two_webp_variants(
|
||||||
|
tmp_path: Path,
|
||||||
|
fmt: str,
|
||||||
|
) -> None:
|
||||||
|
raw = _make_image_bytes((600, 400), fmt=fmt)
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
|
||||||
|
photo = images.process_and_save_photo(raw, media_dir, sada_id=7)
|
||||||
|
|
||||||
|
assert photo.soubor_plny.startswith("7/")
|
||||||
|
assert photo.soubor_plny.endswith(".webp")
|
||||||
|
assert photo.soubor_nahled.endswith("_thumb.webp")
|
||||||
|
assert photo.sirka == 600
|
||||||
|
assert photo.vyska == 400
|
||||||
|
|
||||||
|
full_path = media_dir / photo.soubor_plny
|
||||||
|
thumb_path = media_dir / photo.soubor_nahled
|
||||||
|
assert full_path.is_file()
|
||||||
|
assert thumb_path.is_file()
|
||||||
|
assert photo.velikost_plny_b == full_path.stat().st_size
|
||||||
|
assert photo.velikost_nahled_b == thumb_path.stat().st_size
|
||||||
|
|
||||||
|
created_files = sorted(p.name for p in (media_dir / "7").iterdir())
|
||||||
|
assert len(created_files) == 2
|
||||||
|
assert all(name.endswith(".webp") for name in created_files)
|
||||||
|
|
||||||
|
|
||||||
|
def test_large_image_resized_and_small_image_not_upscaled(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
|
||||||
|
large_raw = _make_image_bytes((3200, 2400), fmt="JPEG")
|
||||||
|
large = images.process_and_save_photo(large_raw, media_dir, sada_id=1)
|
||||||
|
assert (large.sirka, large.vyska) == (1600, 1200)
|
||||||
|
with Image.open(media_dir / large.soubor_plny) as full_img:
|
||||||
|
assert full_img.format == "WEBP"
|
||||||
|
assert full_img.size == (1600, 1200)
|
||||||
|
with Image.open(media_dir / large.soubor_nahled) as thumb_img:
|
||||||
|
assert thumb_img.format == "WEBP"
|
||||||
|
assert thumb_img.size == (400, 300)
|
||||||
|
|
||||||
|
small_raw = _make_image_bytes((300, 200), fmt="PNG")
|
||||||
|
small = images.process_and_save_photo(small_raw, media_dir, sada_id=1)
|
||||||
|
assert (small.sirka, small.vyska) == (300, 200)
|
||||||
|
with Image.open(media_dir / small.soubor_plny) as full_img:
|
||||||
|
assert full_img.size == (300, 200)
|
||||||
|
with Image.open(media_dir / small.soubor_nahled) as thumb_img:
|
||||||
|
assert thumb_img.size == (300, 200)
|
||||||
|
|
||||||
|
|
||||||
|
def test_exif_autorotation_and_full_exif_strip(tmp_path: Path) -> None:
|
||||||
|
exif = Image.Exif()
|
||||||
|
exif[274] = 6 # Orientation: 90° CW
|
||||||
|
exif[271] = "TestCam" # Make
|
||||||
|
exif[272] = "Model X" # Model
|
||||||
|
exif[306] = "2026:01:02 10:20:30" # DateTime
|
||||||
|
exif[34853] = {1: "N", 2: (50.0, 4.0, 0.0)} # GPSInfo
|
||||||
|
|
||||||
|
raw = _make_image_bytes((1200, 800), fmt="JPEG", exif=exif)
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
|
||||||
|
photo = images.process_and_save_photo(raw, media_dir, sada_id=3)
|
||||||
|
assert (photo.sirka, photo.vyska) == (800, 1200)
|
||||||
|
|
||||||
|
for rel in (photo.soubor_plny, photo.soubor_nahled):
|
||||||
|
with Image.open(media_dir / rel) as saved:
|
||||||
|
assert len(saved.getexif()) == 0
|
||||||
|
assert not saved.info.get("exif")
|
||||||
|
|
||||||
|
with Image.open(media_dir / photo.soubor_plny) as full_img:
|
||||||
|
assert full_img.size == (800, 1200)
|
||||||
|
with Image.open(media_dir / photo.soubor_nahled) as thumb_img:
|
||||||
|
assert thumb_img.size == (267, 400)
|
||||||
|
|
||||||
|
|
||||||
|
def test_png_rgba_preserves_alpha_channel(tmp_path: Path) -> None:
|
||||||
|
raw = _make_image_bytes(
|
||||||
|
(200, 150),
|
||||||
|
fmt="PNG",
|
||||||
|
mode="RGBA",
|
||||||
|
color=(10, 20, 30, 0),
|
||||||
|
)
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
|
||||||
|
photo = images.process_and_save_photo(raw, media_dir, sada_id=2)
|
||||||
|
with Image.open(media_dir / photo.soubor_plny) as full_img:
|
||||||
|
assert full_img.mode == "RGBA"
|
||||||
|
assert full_img.getpixel((0, 0))[3] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_rejects_invalid_empty_oversized_and_decompression_bomb(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
|
||||||
|
with pytest.raises(images.ImageValidationError, match="prázdný"):
|
||||||
|
images.process_and_save_photo(b"", media_dir, sada_id=1)
|
||||||
|
|
||||||
|
with pytest.raises(images.ImageValidationError, match="neplatný|platný"):
|
||||||
|
images.process_and_save_photo(
|
||||||
|
b"toto neni obrazek",
|
||||||
|
media_dir,
|
||||||
|
sada_id=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
valid_raw = _make_image_bytes((200, 200), fmt="PNG")
|
||||||
|
with pytest.raises(images.ImageValidationError, match="překračuje"):
|
||||||
|
images.process_and_save_photo(
|
||||||
|
BytesIO(valid_raw),
|
||||||
|
media_dir,
|
||||||
|
sada_id=1,
|
||||||
|
max_bytes=64,
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(images.ImageValidationError, match="limit pixelů"):
|
||||||
|
images.process_and_save_photo(
|
||||||
|
valid_raw,
|
||||||
|
media_dir,
|
||||||
|
sada_id=1,
|
||||||
|
max_pixels=10_000,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert not media_dir.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cleanup_removes_first_file_when_second_save_fails(
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
raw = _make_image_bytes((500, 400), fmt="PNG")
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
|
||||||
|
original_save = images._save_webp
|
||||||
|
calls = 0
|
||||||
|
|
||||||
|
def flaky_save(img: Image.Image, path: Path, *, quality: int) -> int:
|
||||||
|
nonlocal calls
|
||||||
|
calls += 1
|
||||||
|
if calls == 2:
|
||||||
|
raise OSError("Simulovaná chyba zápisu náhledu")
|
||||||
|
return original_save(img, path, quality=quality)
|
||||||
|
|
||||||
|
monkeypatch.setattr(images, "_save_webp", flaky_save)
|
||||||
|
|
||||||
|
with pytest.raises(OSError, match="Simulovaná chyba"):
|
||||||
|
images.process_and_save_photo(raw, media_dir, sada_id=9)
|
||||||
|
|
||||||
|
remaining = list((media_dir / "9").glob("*"))
|
||||||
|
assert remaining == []
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""Testy přístupem řízeného výdeje médií /media/<sada_id>/<soubor>."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
from flask.testing import FlaskClient
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from poznavacky import admin_sets
|
||||||
|
from poznavacky.security import hash_password
|
||||||
|
|
||||||
|
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
def _insert_user(
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
role: str,
|
||||||
|
stav: str = "schvaleny",
|
||||||
|
) -> None:
|
||||||
|
db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO uzivatele (
|
||||||
|
email, heslo_hash, jmeno, prijmeni, role, stav
|
||||||
|
) VALUES (?, ?, 'Jana', 'Testova', ?, ?)
|
||||||
|
""",
|
||||||
|
(email, hash_password(password), role, stav),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _login(client: FlaskClient, email: str, password: str) -> None:
|
||||||
|
resp = client.get("/prihlaseni")
|
||||||
|
match = _CSRF_RE.search(resp.get_data(as_text=True))
|
||||||
|
assert match is not None
|
||||||
|
login_resp = client.post(
|
||||||
|
"/prihlaseni",
|
||||||
|
data={"csrf_token": match.group(1), "email": email, "heslo": password},
|
||||||
|
)
|
||||||
|
assert login_resp.status_code == 302
|
||||||
|
|
||||||
|
|
||||||
|
def _make_png() -> bytes:
|
||||||
|
buf = BytesIO()
|
||||||
|
Image.new("RGB", (200, 150), (10, 90, 180)).save(buf, format="PNG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_media_delivery_permissions_headers_and_traversal_protection(
|
||||||
|
app: Flask,
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
_insert_user(
|
||||||
|
db,
|
||||||
|
email="ucitelka@example.test",
|
||||||
|
password="heslo-ucitelka",
|
||||||
|
role="ucitelka",
|
||||||
|
)
|
||||||
|
_insert_user(
|
||||||
|
db,
|
||||||
|
email="zak@example.test",
|
||||||
|
password="heslo-zak",
|
||||||
|
role="zak",
|
||||||
|
)
|
||||||
|
|
||||||
|
cur_pub = db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sady (slug, nazev, stav)
|
||||||
|
VALUES ('pub', 'Pub', 'publikovano')
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
pub_set_id = int(cur_pub.lastrowid)
|
||||||
|
cur_pub_item = db.execute(
|
||||||
|
"INSERT INTO polozky (sada_id, nazev) VALUES (?, 'Položka P')",
|
||||||
|
(pub_set_id,),
|
||||||
|
)
|
||||||
|
pub_item_id = int(cur_pub_item.lastrowid)
|
||||||
|
|
||||||
|
cur_draft = db.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sady (slug, nazev, stav)
|
||||||
|
VALUES ('draft', 'Draft', 'koncept')
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
draft_set_id = int(cur_draft.lastrowid)
|
||||||
|
cur_draft_item = db.execute(
|
||||||
|
"INSERT INTO polozky (sada_id, nazev) VALUES (?, 'Položka K')",
|
||||||
|
(draft_set_id,),
|
||||||
|
)
|
||||||
|
draft_item_id = int(cur_draft_item.lastrowid)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
media_dir = Path(app.config["MEDIA_DIR"])
|
||||||
|
_, pub_photo = admin_sets.save_photo_for_item(
|
||||||
|
db,
|
||||||
|
media_dir,
|
||||||
|
pub_set_id,
|
||||||
|
pub_item_id,
|
||||||
|
_make_png(),
|
||||||
|
)
|
||||||
|
_, draft_photo = admin_sets.save_photo_for_item(
|
||||||
|
db,
|
||||||
|
media_dir,
|
||||||
|
draft_set_id,
|
||||||
|
draft_item_id,
|
||||||
|
_make_png(),
|
||||||
|
)
|
||||||
|
|
||||||
|
anon_client = app.test_client()
|
||||||
|
student_client = app.test_client()
|
||||||
|
teacher_client = app.test_client()
|
||||||
|
_login(student_client, "zak@example.test", "heslo-zak")
|
||||||
|
_login(teacher_client, "ucitelka@example.test", "heslo-ucitelka")
|
||||||
|
|
||||||
|
# Publikovaná sada -> veřejně dostupná (plná i náhled).
|
||||||
|
for rel in (pub_photo.soubor_plny, pub_photo.soubor_nahled):
|
||||||
|
with anon_client.get(f"/media/{rel}") as resp:
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.mimetype == "image/webp"
|
||||||
|
assert "public" in resp.headers["Cache-Control"]
|
||||||
|
assert "immutable" in resp.headers["Cache-Control"]
|
||||||
|
assert resp.data == (media_dir / rel).read_bytes()
|
||||||
|
|
||||||
|
# Koncept -> anonym i žák dostanou 404, učitelka dostane 200 + private.
|
||||||
|
draft_url = f"/media/{draft_photo.soubor_plny}"
|
||||||
|
assert anon_client.get(draft_url).status_code == 404
|
||||||
|
assert student_client.get(draft_url).status_code == 404
|
||||||
|
|
||||||
|
with teacher_client.get(draft_url) as teacher_resp:
|
||||||
|
assert teacher_resp.status_code == 200
|
||||||
|
assert teacher_resp.mimetype == "image/webp"
|
||||||
|
assert teacher_resp.headers["Cache-Control"] == "private, no-store"
|
||||||
|
|
||||||
|
# Neevidovaný soubor i path traversal -> 404.
|
||||||
|
untracked = media_dir / str(pub_set_id) / "neevidovany.webp"
|
||||||
|
untracked.write_bytes(b"RIFF....WEBP")
|
||||||
|
assert (
|
||||||
|
teacher_client.get(f"/media/{pub_set_id}/neevidovany.webp").status_code
|
||||||
|
== 404
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
anon_client.get(f"/media/{pub_set_id}/../poznavacky.db").status_code
|
||||||
|
== 404
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
anon_client.get(
|
||||||
|
f"/media/{pub_set_id}/..%2Fpoznavacky.db"
|
||||||
|
).status_code
|
||||||
|
== 404
|
||||||
|
)
|
||||||
|
# Soubor patří jiné sadě -> 404.
|
||||||
|
pub_filename = pub_photo.soubor_plny.split("/", 1)[1]
|
||||||
|
assert (
|
||||||
|
teacher_client.get(f"/media/{draft_set_id}/{pub_filename}").status_code
|
||||||
|
== 404
|
||||||
|
)
|
||||||
@@ -50,6 +50,7 @@ def test_migrations_applied_once_and_skipped_on_restart(
|
|||||||
assert first_versions == [
|
assert first_versions == [
|
||||||
"0001_initial_schema.sql",
|
"0001_initial_schema.sql",
|
||||||
"0002_token_hash_index.sql",
|
"0002_token_hash_index.sql",
|
||||||
|
"0003_fotky_soubor_indexes.sql",
|
||||||
]
|
]
|
||||||
|
|
||||||
# Opakovaný start nesmí selhat ani smazat data.
|
# Opakovaný start nesmí selhat ani smazat data.
|
||||||
@@ -159,3 +160,17 @@ def test_token_hash_unique_index_enforced(
|
|||||||
""",
|
""",
|
||||||
(user_id, "hash-tokenu-1", "2099-01-01T01:00:00Z"),
|
(user_id, "hash-tokenu-1", "2099-01-01T01:00:00Z"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fotky_file_indexes_created(db: sqlite3.Connection) -> None:
|
||||||
|
index_names = {
|
||||||
|
row["name"]
|
||||||
|
for row in db.execute(
|
||||||
|
"""
|
||||||
|
SELECT name FROM sqlite_master
|
||||||
|
WHERE type = 'index' AND tbl_name = 'fotky'
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
}
|
||||||
|
assert "idx_fotky_soubor_plny" in index_names
|
||||||
|
assert "idx_fotky_soubor_nahled" in index_names
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""Jednotkové testy generování slugů a seskupování názvů souborů."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from poznavacky.naming import (
|
||||||
|
generate_unique_slug,
|
||||||
|
is_valid_slug,
|
||||||
|
normalize_group_key,
|
||||||
|
parse_upload_group,
|
||||||
|
slugify,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("raw", "expected"),
|
||||||
|
[
|
||||||
|
("Ptáci naší přírody", "ptaci-nasi-prirody"),
|
||||||
|
(" Žluťoučký kůň úpěl! ", "zlutoucky-kun-upel"),
|
||||||
|
("Savci – 6. ročník", "savci-6-rocnik"),
|
||||||
|
("___---___", ""),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_slugify(raw: str, expected: str) -> None:
|
||||||
|
assert slugify(raw) == expected
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("slug", "valid"),
|
||||||
|
[
|
||||||
|
("ptaci", True),
|
||||||
|
("ptaci-nasi-prirody-2", True),
|
||||||
|
("6-rocnik", True),
|
||||||
|
("", False),
|
||||||
|
("Ptaci", False),
|
||||||
|
("ptáci", False),
|
||||||
|
("-ptaci", False),
|
||||||
|
("ptaci-", False),
|
||||||
|
("ptaci--2", False),
|
||||||
|
("ptaci_2", False),
|
||||||
|
("ptaci/2", False),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_is_valid_slug(slug: str, valid: bool) -> None:
|
||||||
|
assert is_valid_slug(slug) is valid
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_unique_slug_resolves_collisions(
|
||||||
|
db: sqlite3.Connection,
|
||||||
|
) -> None:
|
||||||
|
assert generate_unique_slug(db, "Ptáci") == "ptaci"
|
||||||
|
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO sady (slug, nazev) VALUES (?, ?)",
|
||||||
|
("ptaci", "Ptáci"),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert generate_unique_slug(db, "Ptáci") == "ptaci-2"
|
||||||
|
|
||||||
|
db.execute(
|
||||||
|
"INSERT INTO sady (slug, nazev) VALUES (?, ?)",
|
||||||
|
("ptaci-2", "Ptáci 2"),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert generate_unique_slug(db, "Ptáci") == "ptaci-3"
|
||||||
|
|
||||||
|
first_id = int(
|
||||||
|
db.execute("SELECT id FROM sady WHERE slug = 'ptaci'").fetchone()["id"]
|
||||||
|
)
|
||||||
|
assert generate_unique_slug(db, "Ptáci", exclude_set_id=first_id) == "ptaci"
|
||||||
|
assert generate_unique_slug(db, "!!!") == "sada"
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalize_group_key() -> None:
|
||||||
|
assert normalize_group_key("Sýkora koňadra") == "sykora konadra"
|
||||||
|
assert normalize_group_key("sykora_konadra") == "sykora konadra"
|
||||||
|
assert normalize_group_key(" Kos-černý ") == "kos cerny"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("filename", "expected_key", "expected_display"),
|
||||||
|
[
|
||||||
|
("sykora_konadra.jpg", "sykora konadra", "Sykora konadra"),
|
||||||
|
("sykora_konadra_1.jpg", "sykora konadra", "Sykora konadra"),
|
||||||
|
("sykora_konadra_2.jpg", "sykora konadra", "Sykora konadra"),
|
||||||
|
("sykora-konadra-03.png", "sykora konadra", "Sykora konadra"),
|
||||||
|
("sykora konadra (4).webp", "sykora konadra", "Sykora konadra"),
|
||||||
|
("sykora_konadra[5].jpeg", "sykora konadra", "Sykora konadra"),
|
||||||
|
("sykora_konadra_1 (2).jpg", "sykora konadra", "Sykora konadra"),
|
||||||
|
("Sýkora_koňadra_2.jpg", "sykora konadra", "Sýkora koňadra"),
|
||||||
|
("kos_cerny.png", "kos cerny", "Kos cerny"),
|
||||||
|
("01.jpg", "01", "01"),
|
||||||
|
("slozka/vrabec_domaci_1.PNG", "vrabec domaci", "Vrabec domaci"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_parse_upload_group(
|
||||||
|
filename: str,
|
||||||
|
expected_key: str,
|
||||||
|
expected_display: str,
|
||||||
|
) -> None:
|
||||||
|
parsed = parse_upload_group(filename)
|
||||||
|
assert parsed.group_key == expected_key
|
||||||
|
assert parsed.display_name == expected_display
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
"""Jednotkové testy správy úložiště, statistik a úklidu osiřelých souborů."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlite3
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from poznavacky import storage
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_media_path_blocks_traversal_and_symlinks(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
media_dir.mkdir()
|
||||||
|
outside = tmp_path / "tajne.txt"
|
||||||
|
outside.write_text("citlive", encoding="utf-8")
|
||||||
|
|
||||||
|
ok = storage.resolve_media_path(media_dir, "1/abc.webp")
|
||||||
|
assert ok == media_dir.resolve() / "1" / "abc.webp"
|
||||||
|
|
||||||
|
for bad in ("../tajne.txt", "1/../../tajne.txt", "/etc/passwd", "", "a\\b"):
|
||||||
|
with pytest.raises(storage.UnsafeMediaPathError):
|
||||||
|
storage.resolve_media_path(media_dir, bad)
|
||||||
|
|
||||||
|
link_path = media_dir / "1"
|
||||||
|
link_path.mkdir()
|
||||||
|
symlink = link_path / "unik.webp"
|
||||||
|
symlink.symlink_to(outside)
|
||||||
|
with pytest.raises(storage.UnsafeMediaPathError):
|
||||||
|
storage.resolve_media_path(media_dir, "1/unik.webp")
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_media_files_tolerant_to_missing_and_prunes_empty_dirs(
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
media_dir = tmp_path / "media"
|
||||||
|
set_dir = media_dir / "5"
|
||||||
|
set_dir.mkdir(parents=True)
|
||||||
|
f1 = set_dir / "a.webp"
|
||||||
|
f1.write_bytes(b"1234")
|
||||||
|
|
||||||
|
deleted = storage.delete_media_files(
|
||||||
|
media_dir,
|
||||||
|
["5/a.webp", "5/neexistuje.webp"],
|
||||||
|
)
|
||||||
|
assert deleted == 1
|
||||||
|
assert not f1.exists()
|
||||||
|
assert not set_dir.exists()
|
||||||
|
assert media_dir.is_dir()
|
||||||
|
|
||||||
|
|
||||||
|
def test_storage_stats_breakdown_sorting_and_orphan_cleanup(
|
||||||
|
tmp_path: Path,
|
||||||
|
seeded_db: dict,
|
||||||
|
) -> None:
|
||||||
|
conn: sqlite3.Connection = seeded_db["db"]
|
||||||
|
sada_a = int(seeded_db["sada_id"])
|
||||||
|
polozka_a1 = int(seeded_db["polozka_id"])
|
||||||
|
zak_id = int(seeded_db["zak_id"])
|
||||||
|
|
||||||
|
# Přidáme druhou položku a dvě další fotky do sady A + 1 odehrané kolo.
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO polozky (sada_id, nazev, poradi) VALUES (?, ?, ?)",
|
||||||
|
(sada_a, "Kos černý", 2),
|
||||||
|
)
|
||||||
|
polozka_a2 = int(cur.lastrowid)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO fotky (
|
||||||
|
polozka_id, soubor_plny, soubor_nahled,
|
||||||
|
velikost_plny_b, velikost_nahled_b, sirka, vyska, poradi
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
polozka_a1,
|
||||||
|
f"{sada_a}/f2.webp",
|
||||||
|
f"{sada_a}/f2_t.webp",
|
||||||
|
5000,
|
||||||
|
1000,
|
||||||
|
800,
|
||||||
|
600,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO fotky (
|
||||||
|
polozka_id, soubor_plny, soubor_nahled,
|
||||||
|
velikost_plny_b, velikost_nahled_b, sirka, vyska, poradi
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
polozka_a2,
|
||||||
|
f"{sada_a}/f3.webp",
|
||||||
|
f"{sada_a}/f3_t.webp",
|
||||||
|
3000,
|
||||||
|
500,
|
||||||
|
800,
|
||||||
|
600,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO kola (uzivatel_id, sada_id, rezim, typ_kola, pocet_otazek)
|
||||||
|
VALUES (?, ?, 'abcd', 'cele', 2)
|
||||||
|
""",
|
||||||
|
(zak_id, sada_a),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Prázdná sada B bez fotek.
|
||||||
|
cur_b = conn.execute(
|
||||||
|
"INSERT INTO sady (slug, nazev, stav) VALUES (?, ?, ?)",
|
||||||
|
("alpha-prazdna", "Alpha prázdná", "koncept"),
|
||||||
|
)
|
||||||
|
sada_b = int(cur_b.lastrowid)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
data_dir = tmp_path / "isolated_data"
|
||||||
|
media_dir = data_dir / "media"
|
||||||
|
(media_dir / str(sada_a)).mkdir(parents=True)
|
||||||
|
# Vytvoříme evidované soubory i sirotky a symlink ven.
|
||||||
|
(media_dir / f"{sada_a}/ukazka.webp").write_bytes(b"a" * 100)
|
||||||
|
(media_dir / f"{sada_a}/ukazka_thumb.webp").write_bytes(b"b" * 50)
|
||||||
|
orphan_1 = media_dir / f"{sada_a}/sirotek1.webp"
|
||||||
|
orphan_1.write_bytes(b"x" * 200)
|
||||||
|
orphan_dir = media_dir / "99"
|
||||||
|
orphan_dir.mkdir()
|
||||||
|
orphan_2 = orphan_dir / "zapomenuta.webp"
|
||||||
|
orphan_2.write_bytes(b"y" * 300)
|
||||||
|
|
||||||
|
outside = tmp_path / "outside.txt"
|
||||||
|
outside.write_text("nesahat", encoding="utf-8")
|
||||||
|
(media_dir / "odkaz.webp").symlink_to(outside)
|
||||||
|
|
||||||
|
db_path = data_dir / "poznavacky.db"
|
||||||
|
db_path.write_bytes(b"d" * 1024)
|
||||||
|
Path(f"{db_path}-wal").write_bytes(b"w" * 512)
|
||||||
|
|
||||||
|
stats = storage.collect_storage_stats(
|
||||||
|
conn,
|
||||||
|
data_dir=data_dir,
|
||||||
|
db_path=db_path,
|
||||||
|
media_dir=media_dir,
|
||||||
|
)
|
||||||
|
assert stats.media_bytes == 100 + 50 + 200 + 300
|
||||||
|
assert stats.db_bytes == 1024 + 512
|
||||||
|
assert stats.disk_total_bytes > 0
|
||||||
|
assert stats.disk_free_bytes > 0
|
||||||
|
assert stats.orphan_count == 2
|
||||||
|
assert stats.orphan_bytes == 500
|
||||||
|
assert [o.relative_path for o in stats.orphan_files] == [
|
||||||
|
f"{sada_a}/sirotek1.webp",
|
||||||
|
"99/zapomenuta.webp",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Výchozí řazení od největší sady (A před B) bez duplikace položek.
|
||||||
|
assert [s.id for s in stats.sets] == [sada_a, sada_b]
|
||||||
|
row_a, row_b = stats.sets
|
||||||
|
assert row_a.item_count == 2
|
||||||
|
assert row_a.photo_count == 3
|
||||||
|
assert row_a.round_count == 1
|
||||||
|
assert row_a.size_bytes == (12345 + 2345) + (5000 + 1000) + (3000 + 500)
|
||||||
|
assert row_b.item_count == 0
|
||||||
|
assert row_b.photo_count == 0
|
||||||
|
assert row_b.round_count == 0
|
||||||
|
assert row_b.size_bytes == 0
|
||||||
|
assert storage.format_mb(row_b.size_bytes) == "0,00 MB"
|
||||||
|
|
||||||
|
# Řazení podle názvu vzestupně dá "Alpha prázdná" před "Ptáci...".
|
||||||
|
by_name = storage.get_set_storage_breakdown(
|
||||||
|
conn,
|
||||||
|
sort_by="name",
|
||||||
|
direction="asc",
|
||||||
|
)
|
||||||
|
assert [s.id for s in by_name] == [sada_b, sada_a]
|
||||||
|
|
||||||
|
# Úklid sirotků smaže jen neevidované soubory a prázdný adresář 99.
|
||||||
|
res = storage.cleanup_orphan_files(conn, media_dir)
|
||||||
|
assert res.deleted_count == 2
|
||||||
|
assert res.freed_bytes == 500
|
||||||
|
assert not orphan_1.exists()
|
||||||
|
assert not orphan_2.exists()
|
||||||
|
assert not orphan_dir.exists()
|
||||||
|
assert (media_dir / f"{sada_a}/ukazka.webp").is_file()
|
||||||
|
assert outside.is_file()
|
||||||
|
assert media_dir.is_dir()
|
||||||
|
|
||||||
|
# Opakovaný úklid je idempotentní.
|
||||||
|
res2 = storage.cleanup_orphan_files(conn, media_dir)
|
||||||
|
assert res2.deleted_count == 0
|
||||||
|
assert res2.freed_bytes == 0
|
||||||
Reference in new issue
Block a user