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
+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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user