feat: enhance media management and governance in the project
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 6s
Test Suite / playwright-tests (push) Successful in 27s
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 6s
Test Suite / playwright-tests (push) Successful in 27s
- Added new documentation for media assets and lifecycle management, establishing a single source of truth in MEDIA_ASSETS_AND_ARCHIVE_SPEC.md. - Updated project status to reflect the addition of media archive and lifecycle governance. - Introduced a new API endpoint for platform media storage, allowing superadmin access for media management. - Enhanced exercise media handling with improved database integration for media assets, including deduplication and effective media root resolution. - Updated frontend API utilities to support new media storage functionalities, ensuring seamless integration with the backend. - Incremented version to 0.8.41, reflecting the latest changes and improvements in media handling.
This commit is contained in:
1 parent
161d520329
commit
7284c577d7
15 files changed
+678
-60
No files matched your search
+2
-1
@@ -192,7 +192,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, admin_users, platform_media_storage, skills, training_planning, training_framework_programs, catalogs, maturity_models, matrix_stack_bundle, import_wiki, import_wiki_admin
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -202,6 +202,7 @@ app.include_router(clubs.router)
|
||||
app.include_router(club_memberships.router)
|
||||
app.include_router(club_join_requests.router)
|
||||
app.include_router(admin_users.router)
|
||||
app.include_router(platform_media_storage.router)
|
||||
app.include_router(skills.router)
|
||||
app.include_router(training_planning.router)
|
||||
app.include_router(training_framework_programs.router)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Effektives Medien-Wurzelverzeichnis (MEDIA_ROOT + Superadmin-relativer Pfad). Siehe MEDIA_ASSETS_AND_ARCHIVE_SPEC.md §7.1."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
|
||||
def _default_media_root() -> Path:
|
||||
return Path(os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media")))
|
||||
|
||||
|
||||
def normalize_local_relative_root(raw: str) -> str:
|
||||
s = (raw or "").strip().replace("\\", "/")
|
||||
s = s.strip("/")
|
||||
if not s:
|
||||
return ""
|
||||
if ".." in s.split("/"):
|
||||
raise ValueError("Pfad darf nicht '..' enthalten")
|
||||
if s.startswith("/"):
|
||||
raise ValueError("Nur relativer Pfad erlaubt")
|
||||
return s
|
||||
|
||||
|
||||
def get_effective_media_root(cur: Any) -> Path:
|
||||
"""
|
||||
MEDIA_ROOT aus ENV mit optionalem local_relative_root aus platform_media_storage (id=1).
|
||||
"""
|
||||
base = _default_media_root().resolve()
|
||||
rel = ""
|
||||
try:
|
||||
cur.execute(
|
||||
"SELECT local_relative_root FROM platform_media_storage WHERE id = 1",
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is not None:
|
||||
v = row["local_relative_root"] if isinstance(row, dict) else row[0]
|
||||
rel = normalize_local_relative_root(str(v or ""))
|
||||
except Exception:
|
||||
rel = ""
|
||||
if not rel:
|
||||
return base
|
||||
return (base / rel).resolve()
|
||||
|
||||
|
||||
def path_under_media_root(media_root: Path, storage_key: str) -> Optional[Path]:
|
||||
"""Gibt absoluten Pfad zurück oder None bei Path-Traversal."""
|
||||
key = (storage_key or "").strip().replace("\\", "/").lstrip("/")
|
||||
if not key or ".." in key.split("/"):
|
||||
return None
|
||||
p = (media_root / key).resolve()
|
||||
try:
|
||||
p.relative_to(media_root.resolve())
|
||||
except ValueError:
|
||||
return None
|
||||
return p
|
||||
@@ -0,0 +1,106 @@
|
||||
-- Migration 045: Zentrale media_assets, exercise_media.media_asset_id, platform_media_storage (Superadmin-Pfad).
|
||||
-- Siehe .claude/docs/technical/MEDIA_ASSETS_AND_ARCHIVE_SPEC.md
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
CREATE TABLE platform_media_storage (
|
||||
id SMALLINT PRIMARY KEY DEFAULT 1,
|
||||
CONSTRAINT platform_media_storage_singleton CHECK (id = 1),
|
||||
storage_backend VARCHAR(32) NOT NULL DEFAULT 'local',
|
||||
local_relative_root VARCHAR(512) NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
INSERT INTO platform_media_storage (id, storage_backend, local_relative_root)
|
||||
VALUES (1, 'local', '')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE TABLE media_assets (
|
||||
id SERIAL PRIMARY KEY,
|
||||
mime_type VARCHAR(100),
|
||||
byte_size INT,
|
||||
sha256 CHAR(64) NOT NULL,
|
||||
original_filename VARCHAR(300),
|
||||
visibility VARCHAR(32) NOT NULL DEFAULT 'private',
|
||||
club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
|
||||
uploaded_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
|
||||
copyright_notice TEXT,
|
||||
storage_backend VARCHAR(32) NOT NULL DEFAULT 'local',
|
||||
storage_key TEXT NOT NULL,
|
||||
lifecycle_state VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||
trash_soft_at TIMESTAMP WITH TIME ZONE,
|
||||
trash_hidden_at TIMESTAMP WITH TIME ZONE,
|
||||
purge_after_at TIMESTAMP WITH TIME ZONE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_media_assets_club ON media_assets(club_id);
|
||||
CREATE INDEX idx_media_assets_sha256 ON media_assets(sha256);
|
||||
CREATE INDEX idx_media_assets_lifecycle ON media_assets(lifecycle_state);
|
||||
CREATE UNIQUE INDEX ux_media_assets_storage_key ON media_assets(storage_key);
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ADD COLUMN IF NOT EXISTS media_asset_id INT REFERENCES media_assets(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_exercise_media_asset ON exercise_media(media_asset_id);
|
||||
|
||||
-- Bestand: je distinct storage_key ein Asset; sha256 aus DB-Pfad (Migrations-Platzhalter, nicht Content-Hash)
|
||||
INSERT INTO media_assets (
|
||||
mime_type,
|
||||
byte_size,
|
||||
sha256,
|
||||
original_filename,
|
||||
visibility,
|
||||
club_id,
|
||||
uploaded_by_profile_id,
|
||||
storage_backend,
|
||||
storage_key,
|
||||
copyright_notice,
|
||||
lifecycle_state,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
SELECT
|
||||
s.mime_type,
|
||||
s.byte_size,
|
||||
s.sha256,
|
||||
s.original_filename,
|
||||
s.visibility,
|
||||
s.club_id,
|
||||
s.uploaded_by_profile_id,
|
||||
'local',
|
||||
s.storage_key,
|
||||
NULL,
|
||||
'active',
|
||||
s.created_at,
|
||||
NOW()
|
||||
FROM (
|
||||
SELECT DISTINCT ON (storage_key)
|
||||
em.mime_type,
|
||||
em.file_size AS byte_size,
|
||||
encode(digest(trim(em.file_path), 'sha256'), 'hex') AS sha256,
|
||||
em.original_filename,
|
||||
lower(trim(e.visibility)) AS visibility,
|
||||
e.club_id,
|
||||
e.created_by AS uploaded_by_profile_id,
|
||||
regexp_replace(trim(em.file_path), '^/+media/+', '') AS storage_key,
|
||||
em.created_at
|
||||
FROM exercise_media em
|
||||
JOIN exercises e ON e.id = em.exercise_id
|
||||
WHERE em.file_path IS NOT NULL
|
||||
AND trim(em.file_path) <> ''
|
||||
AND em.embed_url IS NULL
|
||||
ORDER BY regexp_replace(trim(em.file_path), '^/+media/+', ''), em.id
|
||||
) s
|
||||
WHERE NOT EXISTS (SELECT 1 FROM media_assets ma WHERE ma.storage_key = s.storage_key);
|
||||
|
||||
UPDATE exercise_media em
|
||||
SET media_asset_id = ma.id
|
||||
FROM media_assets ma
|
||||
WHERE em.media_asset_id IS NULL
|
||||
AND em.file_path IS NOT NULL
|
||||
AND trim(em.file_path) <> ''
|
||||
AND em.embed_url IS NULL
|
||||
AND ma.storage_key = regexp_replace(trim(em.file_path), '^/+media/+', '');
|
||||
+177
-51
@@ -27,6 +27,7 @@ from club_tenancy import (
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
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
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -285,12 +286,6 @@ def _row_created_by(row) -> int:
|
||||
return row[0]
|
||||
|
||||
|
||||
def _ensure_media_dirs():
|
||||
sub = MEDIA_ROOT / "exercises"
|
||||
sub.mkdir(parents=True, exist_ok=True)
|
||||
return sub
|
||||
|
||||
|
||||
def _detect_embed_platform(url: str) -> Optional[str]:
|
||||
if not url:
|
||||
return None
|
||||
@@ -393,19 +388,29 @@ def _count_exercise_media(cur, exercise_id: int) -> int:
|
||||
return int(r["c"] if isinstance(r, dict) else r[0])
|
||||
|
||||
|
||||
def _abs_media_path(file_path_db: str) -> Optional[Path]:
|
||||
def _abs_media_path(file_path_db: str, media_root: Path) -> Optional[Path]:
|
||||
if not file_path_db or file_path_db.startswith("http"):
|
||||
return None
|
||||
rel = file_path_db.lstrip("/")
|
||||
if rel.startswith("media/"):
|
||||
rel = rel[len("media/") :]
|
||||
p = MEDIA_ROOT / rel
|
||||
p = (media_root / rel).resolve()
|
||||
try:
|
||||
p.resolve().relative_to(MEDIA_ROOT.resolve())
|
||||
p.relative_to(media_root.resolve())
|
||||
except ValueError:
|
||||
return None
|
||||
return p
|
||||
|
||||
|
||||
def _resolve_local_media_file(
|
||||
media_root: Path,
|
||||
file_path_db: Optional[str],
|
||||
asset_storage_key: Optional[str],
|
||||
) -> Optional[Path]:
|
||||
if asset_storage_key:
|
||||
return path_under_media_root(media_root, asset_storage_key)
|
||||
return _abs_media_path(file_path_db or "", media_root) if file_path_db else None
|
||||
|
||||
def enrich_exercise_detail(exercise_id: int, cur) -> dict:
|
||||
"""
|
||||
Lädt alle M:N Relations für eine Übung und gibt ein vollständiges
|
||||
@@ -515,11 +520,13 @@ def enrich_exercise_detail(exercise_id: int, cur) -> dict:
|
||||
|
||||
# Media (1:N)
|
||||
cur.execute(
|
||||
"""SELECT id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context
|
||||
FROM exercise_media
|
||||
WHERE exercise_id = %s
|
||||
ORDER BY sort_order, id""",
|
||||
"""SELECT em.id, em.media_type, em.file_path, em.file_size, em.mime_type, em.original_filename,
|
||||
em.embed_url, em.embed_platform, em.title, em.description, em.sort_order, em.is_primary, em.context,
|
||||
em.media_asset_id, ma.copyright_notice AS asset_copyright_notice
|
||||
FROM exercise_media em
|
||||
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
|
||||
WHERE em.exercise_id = %s
|
||||
ORDER BY em.sort_order, em.id""",
|
||||
(exercise_id,)
|
||||
)
|
||||
exercise["media"] = [r2d(r) for r in cur.fetchall()]
|
||||
@@ -1939,9 +1946,12 @@ def _binary_media_response(
|
||||
|
||||
def _fetch_media_row(cur, exercise_id: int, media_id: int) -> Optional[dict]:
|
||||
cur.execute(
|
||||
"""SELECT id, exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context, created_at
|
||||
FROM exercise_media WHERE id = %s AND exercise_id = %s""",
|
||||
"""SELECT em.id, em.exercise_id, em.media_type, em.file_path, em.file_size, em.mime_type, em.original_filename,
|
||||
em.embed_url, em.embed_platform, em.title, em.description, em.sort_order, em.is_primary, em.context, em.created_at,
|
||||
em.media_asset_id, ma.storage_key AS asset_storage_key
|
||||
FROM exercise_media em
|
||||
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
|
||||
WHERE em.id = %s AND em.exercise_id = %s""",
|
||||
(media_id, exercise_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
@@ -1969,7 +1979,12 @@ def download_exercise_media_file(
|
||||
raise HTTPException(status_code=400, detail="Embed-Medien haben keine Datei-URL")
|
||||
|
||||
fp = media.get("file_path")
|
||||
abs_p = _abs_media_path(fp) if fp else None
|
||||
media_root = get_effective_media_root(cur)
|
||||
abs_p = _resolve_local_media_file(
|
||||
media_root,
|
||||
fp,
|
||||
media.get("asset_storage_key"),
|
||||
)
|
||||
if not abs_p or not abs_p.is_file():
|
||||
raise HTTPException(status_code=404, detail="Datei nicht gefunden")
|
||||
|
||||
@@ -2065,35 +2080,116 @@ async def upload_exercise_media(
|
||||
ext = ".jpg"
|
||||
elif not ext and mime == "image/png":
|
||||
ext = ".png"
|
||||
digest = hashlib.sha256(raw).hexdigest()[:12]
|
||||
fname = f"{digest}_{exercise_id}{ext}"
|
||||
dest_dir = _ensure_media_dirs()
|
||||
dest_path = dest_dir / fname
|
||||
dest_path.write_bytes(raw)
|
||||
db_path = f"/media/exercises/{fname}"
|
||||
|
||||
cur.execute(
|
||||
f"""INSERT INTO exercise_media (
|
||||
exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, context, is_primary, sort_order
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, NULL, NULL, %s, %s, %s, %s, {sort_sql}
|
||||
)
|
||||
RETURNING id, exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context, created_at""",
|
||||
(
|
||||
exercise_id,
|
||||
media_type,
|
||||
db_path,
|
||||
len(raw),
|
||||
mime,
|
||||
file.filename,
|
||||
title or None,
|
||||
description or None,
|
||||
context,
|
||||
is_primary,
|
||||
exercise_id,
|
||||
),
|
||||
"SELECT visibility, club_id, created_by FROM exercises WHERE id = %s",
|
||||
(exercise_id,),
|
||||
)
|
||||
ex_gov = cur.fetchone()
|
||||
if not ex_gov:
|
||||
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
||||
ex_vis = (r2d(ex_gov).get("visibility") or "private").strip().lower()
|
||||
ex_club = r2d(ex_gov).get("club_id")
|
||||
media_root = get_effective_media_root(cur)
|
||||
full_sha = hashlib.sha256(raw).hexdigest()
|
||||
|
||||
cur.execute(
|
||||
"""SELECT id, storage_key, byte_size FROM media_assets
|
||||
WHERE sha256 = %s AND lower(trim(visibility)) = %s
|
||||
AND (club_id IS NOT DISTINCT FROM %s)
|
||||
AND lifecycle_state = 'active'
|
||||
LIMIT 1""",
|
||||
(full_sha, ex_vis, ex_club),
|
||||
)
|
||||
existing_asset = cur.fetchone()
|
||||
|
||||
if existing_asset:
|
||||
ea = r2d(existing_asset)
|
||||
aid = ea["id"]
|
||||
sk = ea["storage_key"]
|
||||
sz = ea.get("byte_size") or len(raw)
|
||||
db_path = f"/media/{sk}"
|
||||
cur.execute(
|
||||
f"""INSERT INTO exercise_media (
|
||||
exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, context, is_primary, sort_order,
|
||||
media_asset_id
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, NULL, NULL, %s, %s, %s, %s, {sort_sql}, %s
|
||||
)
|
||||
RETURNING id, exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context, created_at,
|
||||
media_asset_id""",
|
||||
(
|
||||
exercise_id,
|
||||
media_type,
|
||||
db_path,
|
||||
sz,
|
||||
mime,
|
||||
file.filename,
|
||||
title or None,
|
||||
description or None,
|
||||
context,
|
||||
is_primary,
|
||||
exercise_id,
|
||||
aid,
|
||||
),
|
||||
)
|
||||
else:
|
||||
storage_key = f"exercises/{full_sha}{ext}"
|
||||
dest_path = path_under_media_root(media_root, storage_key)
|
||||
if dest_path is None:
|
||||
raise HTTPException(status_code=500, detail="Ungültiger Speicherpfad")
|
||||
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not dest_path.is_file():
|
||||
dest_path.write_bytes(raw)
|
||||
|
||||
cur.execute(
|
||||
"""INSERT INTO media_assets (
|
||||
mime_type, byte_size, sha256, original_filename, visibility, club_id,
|
||||
uploaded_by_profile_id, copyright_notice, storage_backend, storage_key, lifecycle_state
|
||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, NULL, 'local', %s, 'active')
|
||||
RETURNING id""",
|
||||
(
|
||||
mime,
|
||||
len(raw),
|
||||
full_sha,
|
||||
file.filename,
|
||||
ex_vis,
|
||||
ex_club,
|
||||
profile_id,
|
||||
storage_key,
|
||||
),
|
||||
)
|
||||
ar = cur.fetchone()
|
||||
aid = r2d(ar)["id"]
|
||||
db_path = f"/media/{storage_key}"
|
||||
cur.execute(
|
||||
f"""INSERT INTO exercise_media (
|
||||
exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, context, is_primary, sort_order,
|
||||
media_asset_id
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, NULL, NULL, %s, %s, %s, %s, {sort_sql}, %s
|
||||
)
|
||||
RETURNING id, exercise_id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context, created_at,
|
||||
media_asset_id""",
|
||||
(
|
||||
exercise_id,
|
||||
media_type,
|
||||
db_path,
|
||||
len(raw),
|
||||
mime,
|
||||
file.filename,
|
||||
title or None,
|
||||
description or None,
|
||||
context,
|
||||
is_primary,
|
||||
exercise_id,
|
||||
aid,
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return r2d(row)
|
||||
@@ -2165,7 +2261,8 @@ def update_exercise_media(
|
||||
conn.commit()
|
||||
cur.execute(
|
||||
"""SELECT id, media_type, file_path, file_size, mime_type, original_filename,
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context, created_at
|
||||
embed_url, embed_platform, title, description, sort_order, is_primary, context, created_at,
|
||||
media_asset_id
|
||||
FROM exercise_media WHERE id = %s""",
|
||||
(media_id,),
|
||||
)
|
||||
@@ -2179,27 +2276,56 @@ def delete_exercise_media(
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
profile_id = tenant.profile_id
|
||||
unlink_path: Optional[Path] = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, profile_id)
|
||||
media_root = get_effective_media_root(cur)
|
||||
cur.execute(
|
||||
"""SELECT file_path FROM exercise_media WHERE id = %s AND exercise_id = %s""",
|
||||
"""SELECT em.file_path, em.media_asset_id, ma.storage_key AS asset_storage_key
|
||||
FROM exercise_media em
|
||||
LEFT JOIN media_assets ma ON ma.id = em.media_asset_id
|
||||
WHERE em.id = %s AND em.exercise_id = %s""",
|
||||
(media_id, exercise_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
fp = row["file_path"] if isinstance(row, dict) else row[0]
|
||||
rec = r2d(row)
|
||||
fp = rec.get("file_path")
|
||||
media_asset_id = rec.get("media_asset_id")
|
||||
asset_storage_key = rec.get("asset_storage_key")
|
||||
|
||||
cur.execute(
|
||||
"DELETE FROM exercise_media WHERE id = %s AND exercise_id = %s",
|
||||
(media_id, exercise_id),
|
||||
)
|
||||
|
||||
if media_asset_id:
|
||||
cur.execute(
|
||||
"SELECT COUNT(*) AS c FROM exercise_media WHERE media_asset_id = %s",
|
||||
(media_asset_id,),
|
||||
)
|
||||
cnt = int(r2d(cur.fetchone())["c"])
|
||||
if cnt == 0:
|
||||
cur.execute(
|
||||
"DELETE FROM media_assets WHERE id = %s RETURNING storage_key",
|
||||
(media_asset_id,),
|
||||
)
|
||||
del_asset = cur.fetchone()
|
||||
sk = None
|
||||
if del_asset:
|
||||
sk = r2d(del_asset).get("storage_key") or asset_storage_key
|
||||
if sk:
|
||||
unlink_path = path_under_media_root(media_root, sk)
|
||||
elif fp:
|
||||
unlink_path = _abs_media_path(fp, media_root)
|
||||
|
||||
conn.commit()
|
||||
|
||||
abs_p = _abs_media_path(fp) if fp else None
|
||||
if abs_p and abs_p.is_file():
|
||||
if unlink_path and unlink_path.is_file():
|
||||
try:
|
||||
abs_p.unlink()
|
||||
unlink_path.unlink()
|
||||
except OSError as e:
|
||||
logger.warning("Medien-Datei konnte nicht gelöscht werden: %s", e)
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Superadmin: Speicherpfad-Konfiguration (§7.1 MEDIA_ASSETS_AND_ARCHIVE_SPEC.md)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from club_tenancy import is_platform_admin
|
||||
from db import get_db, get_cursor, r2d
|
||||
from auth import require_auth
|
||||
from media_storage import _default_media_root, get_effective_media_root, normalize_local_relative_root
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin", "media-storage"])
|
||||
|
||||
|
||||
class PlatformMediaStorageUpdate(BaseModel):
|
||||
local_relative_root: str = Field(
|
||||
"",
|
||||
description="Relativer Unterordner unter MEDIA_ROOT (z. B. nas/videos). Leer = nur MEDIA_ROOT.",
|
||||
max_length=512,
|
||||
)
|
||||
|
||||
|
||||
class PlatformMediaStorageOut(BaseModel):
|
||||
storage_backend: str
|
||||
local_relative_root: str
|
||||
media_root_env: str
|
||||
effective_media_root: str
|
||||
|
||||
|
||||
def _require_superadmin(session: dict) -> None:
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if role != "superadmin":
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmin")
|
||||
|
||||
|
||||
@router.get("/platform-media-storage", response_model=PlatformMediaStorageOut)
|
||||
def get_platform_media_storage(session: dict = Depends(require_auth)):
|
||||
"""Lesen: Plattform-Admin (admin/superadmin) – Hilfe für Betrieb."""
|
||||
role = (session.get("role") or "").strip().lower()
|
||||
if not is_platform_admin(role):
|
||||
raise HTTPException(status_code=403, detail="Keine Berechtigung")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""SELECT storage_backend, local_relative_root
|
||||
FROM platform_media_storage WHERE id = 1""",
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
backend, rel = "local", ""
|
||||
else:
|
||||
d = r2d(row)
|
||||
backend = d.get("storage_backend") or "local"
|
||||
rel = str(d.get("local_relative_root") or "")
|
||||
eff = get_effective_media_root(cur)
|
||||
return PlatformMediaStorageOut(
|
||||
storage_backend=backend,
|
||||
local_relative_root=rel,
|
||||
media_root_env=str(_default_media_root().resolve()),
|
||||
effective_media_root=str(eff),
|
||||
)
|
||||
|
||||
|
||||
@router.put("/platform-media-storage", response_model=PlatformMediaStorageOut)
|
||||
def put_platform_media_storage(
|
||||
body: PlatformMediaStorageUpdate,
|
||||
session: dict = Depends(require_auth),
|
||||
):
|
||||
"""Schreiben: nur superadmin."""
|
||||
_require_superadmin(session)
|
||||
profile_id = session["profile_id"]
|
||||
try:
|
||||
rel_norm = normalize_local_relative_root(body.local_relative_root)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""UPDATE platform_media_storage
|
||||
SET local_relative_root = %s, updated_at = NOW(), updated_by_profile_id = %s
|
||||
WHERE id = 1
|
||||
RETURNING storage_backend, local_relative_root""",
|
||||
(rel_norm, profile_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
if not row:
|
||||
raise HTTPException(status_code=500, detail="platform_media_storage fehlt")
|
||||
d = r2d(row)
|
||||
eff = get_effective_media_root(cur)
|
||||
return PlatformMediaStorageOut(
|
||||
storage_backend=str(d.get("storage_backend") or "local"),
|
||||
local_relative_root=str(d.get("local_relative_root") or ""),
|
||||
media_root_env=str(_default_media_root().resolve()),
|
||||
effective_media_root=str(eff),
|
||||
)
|
||||
@@ -21,6 +21,7 @@ EXEMPT_ROUTERS: frozenset[str] = frozenset(
|
||||
{
|
||||
"auth.py",
|
||||
"admin_users.py",
|
||||
"platform_media_storage.py",
|
||||
"catalogs.py",
|
||||
"skills.py",
|
||||
"maturity_models.py",
|
||||
|
||||
+15
-4
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.40"
|
||||
BUILD_DATE = "2026-05-06"
|
||||
DB_SCHEMA_VERSION = "20260506043"
|
||||
APP_VERSION = "0.8.41"
|
||||
BUILD_DATE = "2026-05-07"
|
||||
DB_SCHEMA_VERSION = "20260507045"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"auth": "1.2.1", # Login-Rate-Limit 30/minute pro IP (vorher 5/minute)
|
||||
@@ -12,10 +12,11 @@ MODULE_VERSIONS = {
|
||||
"club_memberships": "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
|
||||
"platform_media_storage": "1.0.0", # GET/PUT /api/admin/platform-media-storage (Superadmin-Pfad unter MEDIA_ROOT)
|
||||
"groups": "0.1.0",
|
||||
"skills": "0.1.0",
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.10.0", # GET /exercises: focus_area_must_include/exclude_ids, focus_only_without_focus_areas; UI +/- Fokusregeln
|
||||
"exercises": "2.11.0", # media_assets + Dedupe-Upload; effektives MEDIA_ROOT aus platform_media_storage
|
||||
"training_units": "0.2.0",
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.8.1", # Vorlagen Leseprüfung library_content_visible_to_profile
|
||||
@@ -27,6 +28,16 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.41",
|
||||
"date": "2026-05-07",
|
||||
"changes": [
|
||||
"DB 045: media_assets, exercise_media.media_asset_id, platform_media_storage; Migration bestehender Medien; Upload-Dedupe pro sha256+visibility+club_id",
|
||||
"Effektives Medien-Verzeichnis: MEDIA_ROOT + Superadmin local_relative_root (GET/PUT /api/admin/platform-media-storage)",
|
||||
"Neue Uploads: storage_key exercises/{sha256}{ext}; Download/Delete nutzen media_assets",
|
||||
"api.js: getPlatformMediaStorage, putPlatformMediaStorage",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.40",
|
||||
"date": "2026-05-06",
|
||||
|
||||
Reference in new issue
Block a user