5 Commits
Author SHA1 Message Date
LarsandCursor 01636b5baf Medien: Vereinsordner aus Namen statt library/club/c{id}
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / playwright-tests (push) Successful in 24s
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:06:05 +02:00
LarsandCursor 3e4fa0dc39 Medien: library-Pfade nach Medientyp (image/video/pdf/other) unterteilen
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:03:00 +02:00
LarsandCursor 8d85649cf8 refactor(media): Vereinsflache Ablage; private als u{profile} unter Verein
- club: library/club/c{id}/{sha} (kein shared/)
- private: library/club/c{id}/u{profile}/{sha} statt …/private/
- Dedupe private: sha + club_id + uploaded_by_profile_id
- version 0.8.54

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 10:00:37 +02:00
LarsandCursor 3f0d02edab fix(media): Vereinsordner für private/shared; kein library/private mehr
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / playwright-tests (push) Successful in 23s
- library/club/c{id}/private/* und …/shared/* (club visibility)
- Private Archiv-Upload: effective_club_id oder club_id Form; Plattform braucht Header
- media_assets.club_id bei private gesetzt; Dedupe pro Verein
- Übungs-Upload: dedupe_club für private aus exercise.club_id oder Mandant
- PATCH: club_id für private erhalten; Relocate inkl. private
- version 0.8.53

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:58:28 +02:00
LarsandCursor 4fb77d6927 feat(media): library/* Speicherpfade nach Sichtbarkeit und Verein
Deploy Development / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 24s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 23s
- media_storage.library_storage_key + relocate_local_media_file
- Übungs- und Archiv-Upload nutzen library/private|club/c*|official
- PATCH/Bulk-Patch: bei visibility/club_id Datei umziehen, storage_key + exercise_media.file_path
- pytest: test_library_storage_key; Mocks angepasst
- version 0.8.52 / media_assets 1.7.0 / exercises 2.17.0

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:47:16 +02:00
6 changed files with 555 additions and 37 deletions

No files matched your search

+169
View File
@@ -3,9 +3,23 @@ from __future__ import annotations
import os import os
import re import re
import shutil
import unicodedata
from pathlib import Path from pathlib import Path
from typing import Any, Optional from typing import Any, Optional
_CLUB_SLUG_TRANS = str.maketrans(
{
"ä": "ae",
"ö": "oe",
"ü": "ue",
"ß": "ss",
"Ä": "ae",
"Ö": "oe",
"Ü": "ue",
}
)
def _default_media_root() -> Path: def _default_media_root() -> Path:
return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))) return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")))
@@ -44,6 +58,70 @@ def get_effective_media_root(cur: Any) -> Path:
return (base / rel).resolve() return (base / rel).resolve()
def library_media_kind_dir(mime_type: Optional[str], ext: str) -> str:
"""
Unterordner unter library/* — an API-Filter media_kind angelehnt (image/video/pdf/other).
Bei fehlendem MIME wird anhand der Dateiendung geraten (letzte Instanz: other).
"""
m = (mime_type or "").strip().lower()
x = (ext or "").strip().lower()
if x and not x.startswith("."):
x = "." + x
if m.startswith("image/"):
return "image"
if m.startswith("video/"):
return "video"
if m == "application/pdf" or (m and "pdf" in m):
return "pdf"
if x in (
".jpg",
".jpeg",
".png",
".gif",
".webp",
".heic",
".heif",
".bmp",
".svg",
".avif",
):
return "image"
if x in (".mp4", ".mov", ".webm", ".mkv", ".avi", ".m4v"):
return "video"
if x == ".pdf":
return "pdf"
return "other"
def library_club_path_segment(club_id: int, club_name: Optional[str]) -> str:
"""
Ein Verzeichnissegment pro Verein: aus Anzeigenamen abgeleitet + „-c{id}“ für Eindeutigkeit
(Umbenennung, Kollisionen nach Slugify). Nur [a-z0-9-], keine Pfad-Sonderzeichen.
Fehlt der Name / Slug leer → „verein-c{id}“.
"""
cid = int(club_id)
if cid < 1:
raise ValueError("club_id muss eine positive Ganzzahl sein")
raw = unicodedata.normalize("NFKC", (club_name or "").strip()).translate(_CLUB_SLUG_TRANS).lower()
raw = re.sub(r"[^a-z0-9]+", "-", raw)
raw = raw.strip("-")
if len(raw) > 48:
raw = raw[:48].rstrip("-")
if not raw:
base = f"verein-c{cid}"
else:
base = f"{raw}-c{cid}"
if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", base):
raise ValueError("Ungültiger abgeleiteter Vereins-Ordnername")
return base
def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]: def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
"""Gibt absoluten Pfad zurück oder None bei Path-Traversal.""" """Gibt absoluten Pfad zurück oder None bei Path-Traversal."""
key = (storage_key or "").strip().replace("\\", "/").lstrip("/") key = (storage_key or "").strip().replace("\\", "/").lstrip("/")
@@ -55,3 +133,94 @@ def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
except ValueError: except ValueError:
return None return None
return p return p
def library_storage_key(
visibility: str,
club_id: Optional[int],
sha256_hex: str,
ext: str,
*,
uploader_profile_id: Optional[int] = None,
mime_type: Optional[str] = None,
club_name: Optional[str] = None,
) -> str:
"""
Relativer Speicherpfad unter MEDIA_ROOT für lokale media_assets.
- official → library/official/{kind}/{sha256}{ext}
- club (vereinsgeteilt) → library/{vereins-segment}/{kind}/{sha256}{ext}
- private (nur Hochlader) → library/{vereins-segment}/u{profile}/{kind}/{sha256}{ext}
Vereins-Segment: aus club_name abgeleitet + „-c{club_id}“ — siehe library_club_path_segment.
kind ∈ {image, video, pdf, other} — siehe library_media_kind_dir.
Kein Ordnername „private“ auf der Platte: Zuordnung erfolgt über Uploader unter dem Verein.
"""
vis = (visibility or "private").strip().lower()
if vis not in ("private", "club", "official"):
raise ValueError(f"Ungültige Sichtbarkeit für Speicherpfad: {visibility!r}")
sha = (sha256_hex or "").strip().lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
raise ValueError("sha256_hex muss 64 Hex-Zeichen sein")
e = (ext or "").strip()
if not e:
e = ".bin"
if not e.startswith("."):
e = "." + e
if ".." in e or "/" in e or "\\" in e or "\x00" in e:
raise ValueError("Ungültige Dateiendung")
kind = library_media_kind_dir(mime_type, e)
e = e[:16]
blob = f"{kind}/{sha}{e}"
if vis == "official":
return f"library/official/{blob}"
if club_id is None:
raise ValueError("Verein (club_id) ist für diese Sichtbarkeit auf der Platte erforderlich")
cid = int(club_id)
if cid < 1:
raise ValueError("club_id muss eine positive Ganzzahl sein")
club_seg = library_club_path_segment(cid, club_name)
if vis == "club":
return f"library/{club_seg}/{blob}"
if uploader_profile_id is None:
raise ValueError("uploader_profile_id ist für private Medien erforderlich (Ordner u{…} unter dem Verein)")
up = int(uploader_profile_id)
if up < 1:
raise ValueError("uploader_profile_id muss positiv sein")
return f"library/{club_seg}/u{up}/{blob}"
def relocate_local_media_file(media_root: Path, old_storage_key: str, new_storage_key: str) -> None:
"""
Physisches Verschieben bei geändertem library_*-Pfad (z. B. nach PATCH visibility/club_id).
- Kein Op, wenn Quelle fehlt aber Ziel bereits existiert (idempotent).
- Erwartet storage_backend=local; Aufrufer prüft das.
"""
if (old_storage_key or "").replace("\\", "/").lstrip("/") == (new_storage_key or "").replace(
"\\", "/"
).lstrip("/"):
return
old_p = path_under_media_root(media_root, old_storage_key)
new_p = path_under_media_root(media_root, new_storage_key)
if old_p is None or new_p is None:
raise ValueError("Ungültiger Speicherpfad (Path-Traversal)")
if new_p.is_file():
if not old_p.is_file():
return
if old_p.resolve() == new_p.resolve():
return
raise FileExistsError(f"Zieldatei existiert bereits: {new_storage_key}")
if not old_p.is_file():
raise FileNotFoundError(f"Medien-Quelldatei nicht gefunden: {old_storage_key}")
new_p.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(old_p), str(new_p))
+54 -10
View File
@@ -28,7 +28,7 @@ from club_tenancy import (
library_content_visible_to_profile, library_content_visible_to_profile,
) )
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
from media_storage import get_effective_media_root, path_under_media_root from media_storage import get_effective_media_root, library_storage_key, path_under_media_root
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -2397,13 +2397,41 @@ async def upload_exercise_media(
media_root = get_effective_media_root(cur) media_root = get_effective_media_root(cur)
full_sha = hashlib.sha256(raw).hexdigest() full_sha = hashlib.sha256(raw).hexdigest()
cur.execute( if ex_vis == "official":
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets dedupe_club: Optional[int] = None
WHERE sha256 = %s AND lower(trim(visibility)) = %s elif ex_vis == "private":
AND (club_id IS NOT DISTINCT FROM %s) dedupe_club = int(ex_club) if ex_club is not None else tenant.effective_club_id
LIMIT 1""", if dedupe_club is None:
(full_sha, ex_vis, ex_club), raise HTTPException(
) status_code=400,
detail=(
"Private Übungsmedien werden pro Verein gespeichert. Bitte der Übung einen Verein zuordnen "
"oder einen aktiven Verein wählen (X-Active-Club-Id)."
),
)
dedupe_club = int(dedupe_club)
else:
if ex_club is None:
raise HTTPException(status_code=400, detail="Vereinsübung ohne club_id")
dedupe_club = int(ex_club)
if ex_vis == "private":
cur.execute(
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
WHERE sha256 = %s AND lower(trim(visibility)) = 'private'
AND (club_id IS NOT DISTINCT FROM %s)
AND (uploaded_by_profile_id IS NOT DISTINCT FROM %s)
LIMIT 1""",
(full_sha, dedupe_club, profile_id),
)
else:
cur.execute(
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
WHERE sha256 = %s AND lower(trim(visibility)) = %s
AND (club_id IS NOT DISTINCT FROM %s)
LIMIT 1""",
(full_sha, ex_vis, dedupe_club),
)
existing_asset = cur.fetchone() existing_asset = cur.fetchone()
if existing_asset: if existing_asset:
@@ -2490,7 +2518,23 @@ async def upload_exercise_media(
}, },
) )
else: else:
storage_key = f"exercises/{full_sha}{ext}" club_nm = ""
if dedupe_club is not None:
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(dedupe_club),))
cnr = cur.fetchone()
club_nm = str(r2d(cnr).get("name") or "") if cnr else ""
try:
storage_key = library_storage_key(
ex_vis,
dedupe_club if ex_vis != "official" else None,
full_sha,
ext,
uploader_profile_id=profile_id if ex_vis == "private" else None,
mime_type=mime,
club_name=club_nm,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
dest_path = path_under_media_root(media_root, storage_key) dest_path = path_under_media_root(media_root, storage_key)
if dest_path is None: if dest_path is None:
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad") raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
@@ -2510,7 +2554,7 @@ async def upload_exercise_media(
full_sha, full_sha,
file.filename, file.filename,
ex_vis, ex_vis,
ex_club, dedupe_club,
profile_id, profile_id,
storage_key, storage_key,
), ),
+176 -18
View File
@@ -10,6 +10,7 @@ from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Reques
from pydantic import BaseModel, Field, model_validator from pydantic import BaseModel, Field, model_validator
from club_tenancy import ( from club_tenancy import (
assert_club_member,
assert_valid_governance_visibility, assert_valid_governance_visibility,
club_ids_for_profile_with_roles, club_ids_for_profile_with_roles,
is_platform_admin, is_platform_admin,
@@ -33,7 +34,7 @@ from media_lifecycle import (
transition_to_trash_hidden, transition_to_trash_hidden,
transition_to_trash_soft, transition_to_trash_soft,
) )
from media_storage import get_effective_media_root, path_under_media_root from media_storage import get_effective_media_root, library_storage_key, path_under_media_root, relocate_local_media_file
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible
from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type from routers.exercises import _upload_limit_bytes, resolve_upload_mime_type
@@ -293,17 +294,89 @@ def _fetch_filter_uploaders(cur: Any, is_adm: bool, profile_id: int) -> list[dic
def _effective_media_patch_fields(patch_fields: dict, asset: dict) -> dict: def _effective_media_patch_fields(patch_fields: dict, asset: dict) -> dict:
"""Nach visibility-Wechsel club_id konsistent setzen (official/private → NULL).""" """
Nach visibility-Wechsel club_id konsistent setzen.
official → club_id NULL. private/club: club_id aus Patch oder bisheriger Zeile beibehalten
(private nutzt club_id für Vereinsordner auf der Platte).
"""
eff = dict(patch_fields) eff = dict(patch_fields)
if eff.get("visibility") is not None: if eff.get("visibility") is not None:
v = str(eff["visibility"]).strip().lower() v = str(eff["visibility"]).strip().lower()
if v in ("official", "private"): if v == "official":
eff["club_id"] = None eff["club_id"] = None
elif v == "club" and "club_id" not in eff: elif v == "club" and "club_id" not in eff:
eff["club_id"] = asset.get("club_id") eff["club_id"] = asset.get("club_id")
elif v == "private" and "club_id" not in eff:
eff["club_id"] = asset.get("club_id")
return eff return eff
def _club_display_name_for_storage(cur: Any, club_id: int) -> str:
"""Anzeigename für library_club_path_segment; leer wenn Verein fehlt."""
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(club_id),))
row = cur.fetchone()
if not row:
return ""
return str(r2d(row).get("name") or "")
def _relocate_asset_file_if_governance_changed(
cur: Any,
media_root: Path,
asset_id: int,
asset: dict,
next_vis: str,
next_club_id: Optional[int],
) -> Optional[str]:
"""
Passt bei local-Assets den Dateipfad an, wenn sich Sichtbarkeit/Verein ändert.
Aktualisiert exercise_media.file_path. Gibt neuen storage_key oder None zurück.
"""
if (asset.get("storage_backend") or "local") != "local":
return None
old_key = (asset.get("storage_key") or "").strip()
sha = (asset.get("sha256") or "").strip().lower()
if not old_key or len(sha) != 64:
return None
ext = Path(old_key.replace("\\", "/")).suffix or ".bin"
try:
up = asset.get("uploaded_by_profile_id")
up_i = int(up) if up is not None else None
club_nm: Optional[str] = None
if next_vis in ("club", "private") and next_club_id is not None:
club_nm = _club_display_name_for_storage(cur, next_club_id)
new_key = library_storage_key(
next_vis,
next_club_id if next_vis != "official" else None,
sha,
ext,
uploader_profile_id=up_i if next_vis == "private" else None,
mime_type=str(asset.get("mime_type") or "") or None,
club_name=club_nm,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
old_norm = old_key.replace("\\", "/").lstrip("/")
if new_key == old_norm:
return None
try:
relocate_local_media_file(media_root, old_key, new_key)
except FileNotFoundError as e:
raise HTTPException(status_code=500, detail=f"Mediendatei fehlt auf der Platte: {e}") from e
except FileExistsError as e:
raise HTTPException(status_code=409, detail=str(e)) from e
except (ValueError, OSError) as e:
raise HTTPException(status_code=500, detail=str(e)) from e
db_path = f"/media/{new_key}"
cur.execute(
"UPDATE exercise_media SET file_path = %s WHERE media_asset_id = %s",
(db_path, asset_id),
)
return new_key
def _lifecycle_where_sql(lifecycle: str) -> str: def _lifecycle_where_sql(lifecycle: str) -> str:
lc = (lifecycle or "active").strip().lower() lc = (lifecycle or "active").strip().lower()
if lc not in _LIFECYCLE_LIST_FILTERS: if lc not in _LIFECYCLE_LIST_FILTERS:
@@ -474,8 +547,24 @@ def _ingest_library_media_file(
if club_id_form is None: if club_id_form is None:
raise HTTPException(status_code=400, detail="Verein erforderlich für Sichtbarkeit „Verein“") raise HTTPException(status_code=400, detail="Verein erforderlich für Sichtbarkeit „Verein“")
next_cid = int(club_id_form) next_cid = int(club_id_form)
elif vis == "private":
if club_id_form is not None:
next_cid = int(club_id_form)
else:
cid = tenant.effective_club_id
next_cid = int(cid) if cid is not None else None
if next_cid is None:
raise HTTPException(
status_code=400,
detail=(
"Private Medien werden pro Verein abgelegt. Bitte aktiven Verein setzen "
"(Header X-Active-Club-Id) oder club_id im Formular übergeben — auch für Plattform-Admins."
),
)
if not is_platform_admin(role):
assert_club_member(cur, profile_id, next_cid)
assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid) assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid if vis == "club" else None)
max_b = _upload_limit_bytes(tenant) max_b = _upload_limit_bytes(tenant)
if len(raw) > max_b: if len(raw) > max_b:
@@ -490,13 +579,23 @@ def _ingest_library_media_file(
raise HTTPException(status_code=400, detail=str(e)) from e raise HTTPException(status_code=400, detail=str(e)) from e
full_sha = hashlib.sha256(raw).hexdigest() full_sha = hashlib.sha256(raw).hexdigest()
cur.execute( if vis == "private":
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets cur.execute(
WHERE sha256 = %s AND lower(trim(visibility)) = %s """SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
AND (club_id IS NOT DISTINCT FROM %s) WHERE sha256 = %s AND lower(trim(visibility)) = %s
LIMIT 1""", AND (club_id IS NOT DISTINCT FROM %s)
(full_sha, vis, next_cid), AND (uploaded_by_profile_id IS NOT DISTINCT FROM %s)
) LIMIT 1""",
(full_sha, vis, next_cid, profile_id),
)
else:
cur.execute(
"""SELECT id, storage_key, byte_size, lifecycle_state, original_filename FROM media_assets
WHERE sha256 = %s AND lower(trim(visibility)) = %s
AND (club_id IS NOT DISTINCT FROM %s)
LIMIT 1""",
(full_sha, vis, next_cid),
)
existing_asset = cur.fetchone() existing_asset = cur.fetchone()
if existing_asset: if existing_asset:
@@ -537,8 +636,23 @@ def _ingest_library_media_file(
elif not ext and mime == "video/quicktime": elif not ext and mime == "video/quicktime":
ext = ".mov" ext = ".mov"
club_nm = ""
if next_cid is not None:
club_nm = _club_display_name_for_storage(cur, next_cid)
media_root = get_effective_media_root(cur) media_root = get_effective_media_root(cur)
storage_key = f"exercises/{full_sha}{ext}" try:
storage_key = library_storage_key(
vis,
next_cid,
full_sha,
ext,
uploader_profile_id=profile_id if vis == "private" else None,
mime_type=mime,
club_name=club_nm,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
dest_path = path_under_media_root(media_root, storage_key) dest_path = path_under_media_root(media_root, storage_key)
if dest_path is None: if dest_path is None:
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad") raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
@@ -915,7 +1029,7 @@ def bulk_media_patch(
try: try:
cur.execute( cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state, """SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
copyright_notice, original_filename copyright_notice, original_filename, sha256, storage_key, storage_backend, mime_type
FROM media_assets WHERE id = %s""", FROM media_assets WHERE id = %s""",
(asset_id,), (asset_id,),
) )
@@ -937,7 +1051,7 @@ def bulk_media_patch(
eff = _effective_media_patch_fields(patch_fields, asset) eff = _effective_media_patch_fields(patch_fields, asset)
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower() next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
next_cid = eff["club_id"] if "club_id" in eff else asset.get("club_id") next_cid = eff.get("club_id", asset.get("club_id"))
if "visibility" in patch_fields or "club_id" in patch_fields: if "visibility" in patch_fields or "club_id" in patch_fields:
assert_valid_governance_visibility( assert_valid_governance_visibility(
cur, cur,
@@ -946,6 +1060,26 @@ def bulk_media_patch(
next_vis, next_vis,
int(next_cid) if next_cid is not None else None, int(next_cid) if next_cid is not None else None,
) )
if next_vis in ("private", "club") and next_cid is None:
failed.append(
{
"id": asset_id,
"detail": (
"Für private oder Vereins-Medien wird club_id benötigt (Vereinsordner)."
),
}
)
continue
new_sk: Optional[str] = None
if "visibility" in patch_fields or "club_id" in patch_fields:
next_club_param: Optional[int] = None
if next_vis in ("club", "private"):
next_club_param = int(next_cid) if next_cid is not None else None
media_root = get_effective_media_root(cur)
new_sk = _relocate_asset_file_if_governance_changed(
cur, media_root, asset_id, asset, next_vis, next_club_param
)
sets: list[str] = [] sets: list[str] = []
vals: list[Any] = [] vals: list[Any] = []
@@ -962,7 +1096,10 @@ def bulk_media_patch(
sets.append("visibility = %s") sets.append("visibility = %s")
vals.append(str(eff.get("visibility", asset["visibility"])).strip()) vals.append(str(eff.get("visibility", asset["visibility"])).strip())
sets.append("club_id = %s") sets.append("club_id = %s")
vals.append(eff.get("club_id")) vals.append(next_cid)
if new_sk:
sets.append("storage_key = %s")
vals.append(new_sk)
if not sets: if not sets:
failed.append({"id": asset_id, "detail": "Nichts zu aktualisieren"}) failed.append({"id": asset_id, "detail": "Nichts zu aktualisieren"})
continue continue
@@ -996,7 +1133,7 @@ def patch_media_asset(
cur = get_cursor(conn) cur = get_cursor(conn)
cur.execute( cur.execute(
"""SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state, """SELECT id, visibility, club_id, uploaded_by_profile_id, lifecycle_state,
copyright_notice, original_filename copyright_notice, original_filename, sha256, storage_key, storage_backend, mime_type
FROM media_assets WHERE id = %s""", FROM media_assets WHERE id = %s""",
(asset_id,), (asset_id,),
) )
@@ -1014,7 +1151,7 @@ def patch_media_asset(
eff = _effective_media_patch_fields(data, asset) eff = _effective_media_patch_fields(data, asset)
next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower() next_vis = str(eff.get("visibility", asset["visibility"])).strip().lower()
next_cid = eff["club_id"] if "club_id" in eff else asset.get("club_id") next_cid = eff.get("club_id", asset.get("club_id"))
if "visibility" in data or "club_id" in data: if "visibility" in data or "club_id" in data:
assert_valid_governance_visibility( assert_valid_governance_visibility(
cur, cur,
@@ -1023,6 +1160,24 @@ def patch_media_asset(
next_vis, next_vis,
int(next_cid) if next_cid is not None else None, int(next_cid) if next_cid is not None else None,
) )
if next_vis in ("private", "club") and next_cid is None:
raise HTTPException(
status_code=400,
detail=(
"Für private oder Vereins-Medien wird club_id benötigt (Vereinsordner). "
"Bitte im PATCH setzen, z. B. bei Wechsel von „offiziell“ zu „privat“."
),
)
new_sk: Optional[str] = None
if "visibility" in data or "club_id" in data:
next_club_param: Optional[int] = None
if next_vis in ("club", "private"):
next_club_param = int(next_cid) if next_cid is not None else None
media_root = get_effective_media_root(cur)
new_sk = _relocate_asset_file_if_governance_changed(
cur, media_root, asset_id, asset, next_vis, next_club_param
)
sets: list[str] = [] sets: list[str] = []
vals: list[Any] = [] vals: list[Any] = []
@@ -1039,7 +1194,10 @@ def patch_media_asset(
sets.append("visibility = %s") sets.append("visibility = %s")
vals.append(str(eff.get("visibility", asset["visibility"])).strip()) vals.append(str(eff.get("visibility", asset["visibility"])).strip())
sets.append("club_id = %s") sets.append("club_id = %s")
vals.append(eff.get("club_id")) vals.append(next_cid)
if new_sk:
sets.append("storage_key = %s")
vals.append(new_sk)
if sets: if sets:
sets.append("updated_at = NOW()") sets.append("updated_at = NOW()")
vals.append(asset_id) vals.append(asset_id)
+107
View File
@@ -0,0 +1,107 @@
"""library_storage_key: Mandantenpfade unter MEDIA_ROOT."""
from __future__ import annotations
import pytest
from media_storage import library_club_path_segment, library_media_kind_dir, library_storage_key
_HEX64 = "a" * 64
def test_library_media_kind_dir_mime_overrides_ext() -> None:
assert library_media_kind_dir("image/png", ".bin") == "image"
assert library_media_kind_dir("application/pdf", ".tmp") == "pdf"
def test_library_club_path_segment_slug_and_fallback() -> None:
assert library_club_path_segment(3, "Grün & Weiß / Dojo!") == "gruen-weiss-dojo-c3"
assert library_club_path_segment(3, None) == "verein-c3"
assert library_club_path_segment(3, " ") == "verein-c3"
assert library_club_path_segment(12, "東道場") == "verein-c12"
def test_library_club_path_segment_long_name_truncated() -> None:
long = "a" * 80
seg = library_club_path_segment(5, long)
assert seg == "a" * 48 + "-c5"
def test_library_storage_key_private_is_uploader_under_club() -> None:
assert (
library_storage_key(
"private", 7, _HEX64, ".jpg", uploader_profile_id=99, club_name="Ost Dojo München"
)
== f"library/ost-dojo-muenchen-c7/u99/image/{_HEX64}.jpg"
)
def test_library_storage_key_club_flat_under_club() -> None:
assert (
library_storage_key("club", 42, _HEX64, ".png", club_name="Demo-Verein")
== f"library/demo-verein-c42/image/{_HEX64}.png"
)
def test_library_storage_key_official() -> None:
assert (
library_storage_key("official", None, _HEX64, ".mp4", uploader_profile_id=1)
== f"library/official/video/{_HEX64}.mp4"
)
def test_library_storage_key_normalizes_visibility() -> None:
assert (
library_storage_key(" CLUB ", 1, _HEX64, "pdf", club_name="Alpha")
== f"library/alpha-c1/pdf/{_HEX64}.pdf"
)
def test_library_storage_key_other_bin() -> None:
assert (
library_storage_key("official", None, _HEX64, "", mime_type="application/octet-stream")
== f"library/official/other/{_HEX64}.bin"
)
def test_library_storage_key_private_requires_uploader() -> None:
with pytest.raises(ValueError, match="uploader_profile_id"):
library_storage_key("private", 1, _HEX64, ".jpg", club_name="V")
def test_library_storage_key_private_requires_club() -> None:
with pytest.raises(ValueError, match="Verein"):
library_storage_key("private", None, _HEX64, ".jpg", uploader_profile_id=1)
def test_library_storage_key_club_requires_id() -> None:
with pytest.raises(ValueError, match="Verein"):
library_storage_key("club", None, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_club_id_positive() -> None:
with pytest.raises(ValueError, match="positiv"):
library_storage_key("club", 0, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_invalid_visibility() -> None:
with pytest.raises(ValueError, match="Sichtbarkeit"):
library_storage_key("public", 1, _HEX64, ".jpg", club_name="X")
def test_library_storage_key_invalid_sha() -> None:
with pytest.raises(ValueError, match="64"):
library_storage_key("private", 1, "deadbeef", ".jpg", uploader_profile_id=1, club_name="X")
def test_library_storage_key_extension() -> None:
with pytest.raises(ValueError):
library_storage_key(
"private", 1, _HEX64, "../x", uploader_profile_id=1, club_name="X"
)
def test_library_storage_key_private_no_club_name_fallback() -> None:
assert (
library_storage_key("private", 2, _HEX64, ".jpg", uploader_profile_id=3)
== f"library/verein-c2/u3/image/{_HEX64}.jpg"
)
+10 -5
View File
@@ -15,6 +15,11 @@ from auth import require_auth
from main import app from main import app
from tenant_context import TenantContext, get_tenant_context from tenant_context import TenantContext, get_tenant_context
# Gültige storage_key-Beispiele (64 Hex-Zeichen wie echter SHA-256)
_SK_OFF_A = f"library/official/image/{'a' * 64}.jpg"
_SK_OFF_B = f"library/official/image/{'b' * 64}.jpg"
_SK_PRIV_C = f"library/verein-c1/u1/video/{'c' * 64}.mp4"
@pytest.fixture @pytest.fixture
def client() -> TestClient: def client() -> TestClient:
@@ -136,7 +141,7 @@ def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
"club_id": None, "club_id": None,
"uploaded_by_profile_id": 1, "uploaded_by_profile_id": 1,
"lifecycle_state": "active", "lifecycle_state": "active",
"storage_key": "exercises/x.jpg", "storage_key": _SK_OFF_A,
}, },
{"id": 1}, {"id": 1},
] ]
@@ -175,7 +180,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
"id": 99, "id": 99,
"exercise_id": 3, "exercise_id": 3,
"media_type": "image", "media_type": "image",
"file_path": "/media/exercises/h.jpg", "file_path": f"/media/{_SK_OFF_B}",
"file_size": 10, "file_size": 10,
"mime_type": "image/jpeg", "mime_type": "image/jpeg",
"original_filename": "h.jpg", "original_filename": "h.jpg",
@@ -202,7 +207,7 @@ def test_attach_from_asset_ok_mocked(client: TestClient) -> None:
"club_id": None, "club_id": None,
"uploaded_by_profile_id": 1, "uploaded_by_profile_id": 1,
"lifecycle_state": "active", "lifecycle_state": "active",
"storage_key": "exercises/h.jpg", "storage_key": _SK_OFF_B,
}, },
None, None,
inserted, inserted,
@@ -326,10 +331,10 @@ def test_media_asset_lifecycle_reactivate_mocked(client: TestClient) -> None:
{ {
"id": 5, "id": 5,
"visibility": "private", "visibility": "private",
"club_id": None, "club_id": 1,
"uploaded_by_profile_id": 1, "uploaded_by_profile_id": 1,
"lifecycle_state": "trash_soft", "lifecycle_state": "trash_soft",
"storage_key": "exercises/a.mp4", "storage_key": _SK_PRIV_C,
"storage_backend": "local", "storage_backend": "local",
"trash_soft_at": None, "trash_soft_at": None,
"trash_hidden_at": None, "trash_hidden_at": None,
+39 -4
View File
@@ -1,8 +1,8 @@
# Shinkan Jinkendo Version Information # Shinkan Jinkendo Version Information
APP_VERSION = "0.8.51" APP_VERSION = "0.8.56"
BUILD_DATE = "2026-05-07" BUILD_DATE = "2026-05-07"
DB_SCHEMA_VERSION = "20260507046" DB_SCHEMA_VERSION = "20260508049"
MODULE_VERSIONS = { MODULE_VERSIONS = {
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute) "auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
@@ -13,11 +13,11 @@ MODULE_VERSIONS = {
"club_join_requests": "1.0.1", # Depends(get_tenant_context) "club_join_requests": "1.0.1", # Depends(get_tenant_context)
"admin_users": "1.0.0", # GET /api/admin/users "admin_users": "1.0.0", # GET /api/admin/users
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT) "platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
"media_assets": "1.5.1", # usage: training_unit_exercises optional (Schema ohne planning-Tabelle) "media_assets": "1.11.0", # library/{vereins-slug}-c{id}/ statt library/club/c{id}/
"groups": "0.1.0", "groups": "0.1.0",
"skills": "0.1.0", "skills": "0.1.0",
"methods": "0.1.0", "methods": "0.1.0",
"exercises": "2.16.0", # §4.2 official: angehängte media_assets + Copyright (PUT + bulk-metadata) "exercises": "2.17.4", # Übungs-Upload: Vereinsnamen für library-Pfad aus clubs
"training_units": "0.2.0", "training_units": "0.2.0",
"training_programs": "0.1.0", "training_programs": "0.1.0",
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile "planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
@@ -29,6 +29,41 @@ MODULE_VERSIONS = {
} }
CHANGELOG = [ CHANGELOG = [
{
"version": "0.8.56",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: Vereinsmedien unter library/{aus Name abgeleitet}-c{club_id}/ statt festem library/club/c{id}/; Sonderzeichen/Umlaute zu sicheren Ordnernamen; fehlender Name → verein-c{id}; Governance-Umzug liest aktuellen Vereinsnamen aus DB",
],
},
{
"version": "0.8.55",
"date": "2026-05-07",
"changes": [
"Medienbibliothek: Speicherpfad library/* mit Medientyp-Unterordnern (image, video, pdf, other) vor SHA-Dateinamen; Umzug bei Governance-PATCH nutzt mime_type aus DB",
],
},
{
"version": "0.8.54",
"date": "2026-05-08",
"changes": [
"Medienpfade: vereinsgeteilt (club) direkt unter library/club/c{id}/; private unter library/club/c{id}/u{profile}/ (kein Ordner „private“/„shared“); Dedupe private inkl. uploaded_by_profile_id",
],
},
{
"version": "0.8.53",
"date": "2026-05-08",
"changes": [
"Medienablage vereinsbezogen: private → library/club/c{id}/private, Vereinssichtbarkeit → …/shared, official unverändert; private Archiv-Upload: club_id oder X-Active-Club-Id; DB club_id bei private gesetzt; PATCH/Bulk: club_id für private nicht mehr blind auf NULL",
],
},
{
"version": "0.8.52",
"date": "2026-05-08",
"changes": [
"Neue lokale media_assets: hierarchische library/* Pfade; Dedupe nach sha+visibility+club_id; bei PATCH/Bulk-Patch Sichtbarkeit/Verein: Datei umziehen, exercise_media.file_path aktualisieren (Details siehe 0.8.53)",
],
},
{ {
"version": "0.8.51", "version": "0.8.51",
"date": "2026-05-07", "date": "2026-05-07",