feat: increment version to 0.8.50 and enhance media asset features
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 30s
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 30s
- Updated APP_VERSION to 0.8.50 and DB_SCHEMA_VERSION to 20260507046. - Enhanced media assets with new tagging functionality, allowing users to filter and search by tags. - Improved media library UI with new filters for media kind and uploader, enhancing user experience. - Updated changelog to reflect the latest changes and improvements in media management.
This commit is contained in:
1 parent
3d321857ec
commit
1bc7ea95fb
7 files changed
+637
-52
No files matched your search
+262
-15
@@ -1,7 +1,7 @@
|
||||
"""Medien-Archiv (Liste, Datei) und Lifecycle — MEDIA_ASSETS_AND_ARCHIVE_SPEC."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal, Optional
|
||||
from typing import Any, Literal, Optional, Union
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
@@ -63,6 +63,7 @@ class MediaAssetPatch(BaseModel):
|
||||
original_filename: Optional[str] = Field(None, max_length=300)
|
||||
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
||||
club_id: Optional[int] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
class MediaBulkLifecycleBody(BaseModel):
|
||||
@@ -93,9 +94,157 @@ class MediaBulkPatchBody(BaseModel):
|
||||
original_filename: Optional[str] = Field(None, max_length=300)
|
||||
visibility: Optional[str] = Field(None, pattern="^(private|club|official)$")
|
||||
club_id: Optional[int] = None
|
||||
tags: Optional[list[str]] = None
|
||||
|
||||
|
||||
_LIFECYCLE_LIST_FILTERS = frozenset({"active", "trash_soft", "trash_hidden", "all"})
|
||||
_MEDIA_KIND_FILTERS = frozenset({"all", "image", "video", "pdf", "other"})
|
||||
_MAX_TAGS = 40
|
||||
_MAX_TAG_LEN = 48
|
||||
|
||||
|
||||
def _normalize_media_tags(raw: Union[list[str], None]) -> list[str]:
|
||||
"""PostgreSQL text[]; Einträge gekürzt und ohne Dubletten (case-insensitive)."""
|
||||
if raw is None:
|
||||
return []
|
||||
if not isinstance(raw, list):
|
||||
raise HTTPException(status_code=400, detail="tags muss eine Liste von Strings sein")
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in raw:
|
||||
s = str(item).strip()
|
||||
if not s:
|
||||
continue
|
||||
s = s[:_MAX_TAG_LEN]
|
||||
key = s.lower()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
out.append(s)
|
||||
if len(out) >= _MAX_TAGS:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _usage_for_media_assets(cur: Any, asset_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
"""Übungen und Trainingseinheiten, die dieses Archiv-Medium nutzen."""
|
||||
if not asset_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
"""SELECT em.media_asset_id, e.id AS exercise_id, e.title AS exercise_title
|
||||
FROM exercise_media em
|
||||
JOIN exercises e ON e.id = em.exercise_id
|
||||
WHERE em.media_asset_id = ANY(%s)
|
||||
ORDER BY em.media_asset_id, e.title NULLS LAST, e.id""",
|
||||
(asset_ids,),
|
||||
)
|
||||
ex_by_asset: dict[int, list[dict]] = {int(aid): [] for aid in asset_ids}
|
||||
seen_ex: dict[int, set[int]] = {int(aid): set() for aid in asset_ids}
|
||||
exercise_ids: set[int] = set()
|
||||
for r in cur.fetchall():
|
||||
d = r2d(r)
|
||||
aid = int(d["media_asset_id"])
|
||||
eid = int(d["exercise_id"])
|
||||
if aid not in seen_ex or eid in seen_ex[aid]:
|
||||
continue
|
||||
seen_ex[aid].add(eid)
|
||||
exercise_ids.add(eid)
|
||||
title = (d.get("exercise_title") or "").strip() or f"Übung #{eid}"
|
||||
ex_by_asset[aid].append({"id": eid, "title": title})
|
||||
exercise_to_units: dict[int, list[dict]] = {}
|
||||
if exercise_ids:
|
||||
cur.execute(
|
||||
"""SELECT tue.exercise_id, tu.id AS unit_id, tu.planned_date,
|
||||
COALESCE(tg.name, '') AS group_name
|
||||
FROM training_unit_exercises tue
|
||||
JOIN training_units tu ON tu.id = tue.training_unit_id
|
||||
LEFT JOIN training_groups tg ON tg.id = tu.group_id
|
||||
WHERE tue.exercise_id = ANY(%s)""",
|
||||
(list(exercise_ids),),
|
||||
)
|
||||
for row in cur.fetchall():
|
||||
d = r2d(row)
|
||||
eid = int(d["exercise_id"])
|
||||
uid = int(d["unit_id"])
|
||||
pd = d.get("planned_date")
|
||||
planned: Optional[str]
|
||||
if pd is None:
|
||||
planned = None
|
||||
elif hasattr(pd, "isoformat"):
|
||||
planned = str(pd.isoformat())
|
||||
else:
|
||||
planned = str(pd)
|
||||
exercise_to_units.setdefault(eid, []).append(
|
||||
{
|
||||
"id": uid,
|
||||
"planned_date": planned,
|
||||
"group_name": d.get("group_name") or "",
|
||||
}
|
||||
)
|
||||
for eid, units in exercise_to_units.items():
|
||||
seen_u: set[int] = set()
|
||||
uniq: list[dict] = []
|
||||
for u in units:
|
||||
if u["id"] not in seen_u:
|
||||
seen_u.add(u["id"])
|
||||
uniq.append(u)
|
||||
exercise_to_units[eid] = uniq
|
||||
out: dict[int, dict[str, Any]] = {}
|
||||
for aid in asset_ids:
|
||||
aid_i = int(aid)
|
||||
exs = ex_by_asset.get(aid_i, [])
|
||||
seen_u2: set[int] = set()
|
||||
units_agg: list[dict] = []
|
||||
for ex in exs:
|
||||
for u in exercise_to_units.get(ex["id"], []):
|
||||
if u["id"] not in seen_u2:
|
||||
seen_u2.add(u["id"])
|
||||
units_agg.append(u)
|
||||
out[aid_i] = {"exercises": exs, "training_units": units_agg}
|
||||
return out
|
||||
|
||||
|
||||
def _fetch_filter_uploaders(cur: Any, is_adm: bool, profile_id: int) -> list[dict]:
|
||||
cur.execute(
|
||||
"""SELECT DISTINCT ma.uploaded_by_profile_id AS id, pr.name, pr.email
|
||||
FROM media_assets ma
|
||||
LEFT JOIN profiles pr ON pr.id = ma.uploaded_by_profile_id
|
||||
WHERE ma.uploaded_by_profile_id IS NOT NULL
|
||||
AND ma.lifecycle_state IN ('active', 'trash_soft', 'trash_hidden')
|
||||
AND (
|
||||
%s
|
||||
OR lower(trim(ma.visibility)) = 'official'
|
||||
OR (
|
||||
lower(trim(ma.visibility)) = 'private'
|
||||
AND ma.uploaded_by_profile_id = %s
|
||||
)
|
||||
OR (
|
||||
lower(trim(ma.visibility)) = 'club'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM club_members cm
|
||||
WHERE cm.profile_id = %s
|
||||
AND cm.club_id = ma.club_id
|
||||
AND cm.status = 'active'
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY pr.name NULLS LAST, ma.uploaded_by_profile_id
|
||||
LIMIT 400""",
|
||||
(is_adm, profile_id, profile_id),
|
||||
)
|
||||
rows = [r2d(x) for x in cur.fetchall()]
|
||||
out: list[dict] = []
|
||||
for r in rows:
|
||||
pid = r.get("id")
|
||||
if pid is None:
|
||||
continue
|
||||
label = (r.get("name") or "").strip()
|
||||
if not label:
|
||||
label = (r.get("email") or "").strip()
|
||||
if not label:
|
||||
label = f"Profil #{pid}"
|
||||
out.append({"id": int(pid), "label": label})
|
||||
return out
|
||||
|
||||
|
||||
def _effective_media_patch_fields(patch_fields: dict, asset: dict) -> dict:
|
||||
@@ -264,29 +413,101 @@ def list_media_assets(
|
||||
"active",
|
||||
description="active | trash_soft | trash_hidden | all (nicht purgierte Zustände)",
|
||||
),
|
||||
media_kind: str = Query(
|
||||
"all",
|
||||
description="all | image | video | pdf | other",
|
||||
),
|
||||
club_id: Optional[int] = Query(
|
||||
None,
|
||||
ge=1,
|
||||
description="Nur Superadmin: nach Verein filtern",
|
||||
),
|
||||
uploaded_by: Optional[int] = Query(
|
||||
None,
|
||||
ge=1,
|
||||
description="Nach Uploader (Profil-ID), wenn erlaubt",
|
||||
),
|
||||
include_filter_meta: bool = Query(
|
||||
False,
|
||||
description="Uploader-Liste für Filter (nur wenn Metadaten sichtbar)",
|
||||
),
|
||||
limit: int = Query(30, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
):
|
||||
lc_where = _lifecycle_where_sql(lifecycle)
|
||||
mk = (media_kind or "all").strip().lower()
|
||||
if mk not in _MEDIA_KIND_FILTERS:
|
||||
raise HTTPException(status_code=400, detail="Ungültiger media_kind")
|
||||
role = tenant.global_role or ""
|
||||
is_adm = is_platform_admin(role)
|
||||
sup = is_superadmin(role)
|
||||
profile_id = tenant.profile_id
|
||||
needle = (q or "").strip()
|
||||
params: list[Any] = [is_adm, profile_id, profile_id]
|
||||
search_sql = ""
|
||||
if needle:
|
||||
like = f"%{needle}%"
|
||||
params.extend([like, like])
|
||||
search_sql = " AND (ma.original_filename ILIKE %s OR ma.storage_key ILIKE %s)"
|
||||
params.extend([limit, offset])
|
||||
|
||||
if club_id is not None and not sup:
|
||||
raise HTTPException(status_code=403, detail="Vereinsfilter nur für Superadmin")
|
||||
|
||||
media_kind_sql = ""
|
||||
if mk == "image":
|
||||
media_kind_sql = " AND lower(COALESCE(ma.mime_type, '')) LIKE 'image/%'"
|
||||
elif mk == "video":
|
||||
media_kind_sql = " AND lower(COALESCE(ma.mime_type, '')) LIKE 'video/%'"
|
||||
elif mk == "pdf":
|
||||
media_kind_sql = (
|
||||
" AND (lower(COALESCE(ma.mime_type, '')) = 'application/pdf'"
|
||||
" OR lower(COALESCE(ma.mime_type, '')) LIKE '%pdf%')"
|
||||
)
|
||||
elif mk == "other":
|
||||
media_kind_sql = (
|
||||
" AND COALESCE(ma.mime_type, '') <> ''"
|
||||
" AND lower(ma.mime_type) NOT LIKE 'image/%'"
|
||||
" AND lower(ma.mime_type) NOT LIKE 'video/%'"
|
||||
" AND lower(ma.mime_type) <> 'application/pdf'"
|
||||
" AND lower(ma.mime_type) NOT LIKE '%pdf%'"
|
||||
)
|
||||
|
||||
club_sql = ""
|
||||
club_sql_params: list[Any] = []
|
||||
if club_id is not None:
|
||||
club_sql = " AND ma.club_id = %s"
|
||||
club_sql_params.append(club_id)
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
admin_club_ids = club_ids_for_profile_with_roles(cur, profile_id, "club_admin")
|
||||
show_uploader = sup or is_adm or bool(admin_club_ids)
|
||||
if uploaded_by is not None and not show_uploader:
|
||||
raise HTTPException(status_code=403, detail="Uploader-Filter nicht erlaubt")
|
||||
|
||||
uploaded_sql = ""
|
||||
uploaded_params: list[Any] = []
|
||||
if uploaded_by is not None:
|
||||
uploaded_sql = " AND ma.uploaded_by_profile_id = %s"
|
||||
uploaded_params.append(uploaded_by)
|
||||
|
||||
search_sql = ""
|
||||
search_params: list[Any] = []
|
||||
if needle:
|
||||
like = f"%{needle}%"
|
||||
search_params = [like, like, like, like]
|
||||
search_sql = (
|
||||
" AND (ma.original_filename ILIKE %s OR ma.storage_key ILIKE %s"
|
||||
" OR COALESCE(ma.copyright_notice, '') ILIKE %s"
|
||||
" OR EXISTS (SELECT 1 FROM unnest(ma.tags) AS t WHERE t::text ILIKE %s))"
|
||||
)
|
||||
|
||||
params: list[Any] = (
|
||||
[is_adm, profile_id, profile_id]
|
||||
+ club_sql_params
|
||||
+ uploaded_params
|
||||
+ search_params
|
||||
+ [limit, offset]
|
||||
)
|
||||
|
||||
cur.execute(
|
||||
f"""SELECT ma.id, ma.mime_type, ma.byte_size, ma.original_filename, ma.visibility, ma.club_id,
|
||||
ma.uploaded_by_profile_id, ma.lifecycle_state, ma.created_at, ma.sha256,
|
||||
ma.copyright_notice, ma.storage_key,
|
||||
ma.copyright_notice, ma.storage_key, ma.tags,
|
||||
pr.name AS uploader_name,
|
||||
pr.email AS uploader_email,
|
||||
cl.name AS club_name
|
||||
@@ -311,16 +532,27 @@ def list_media_assets(
|
||||
)
|
||||
)
|
||||
)
|
||||
{club_sql}
|
||||
{uploaded_sql}
|
||||
{media_kind_sql}
|
||||
{search_sql}
|
||||
ORDER BY ma.updated_at DESC NULLS LAST, ma.created_at DESC
|
||||
LIMIT %s OFFSET %s""",
|
||||
params,
|
||||
)
|
||||
rows = [r2d(r) for r in cur.fetchall()]
|
||||
show_uploader = is_superadmin(role) or is_platform_admin(role) or bool(admin_club_ids)
|
||||
show_club = is_superadmin(role) or is_platform_admin(role)
|
||||
show_club = sup or is_adm
|
||||
asset_ids = [int(r["id"]) for r in rows]
|
||||
usage_map = _usage_for_media_assets(cur, asset_ids)
|
||||
for r in rows:
|
||||
r["permissions"] = _item_permissions(r, tenant, admin_club_ids)
|
||||
tid = int(r["id"])
|
||||
r["usage"] = usage_map.get(tid, {"exercises": [], "training_units": []})
|
||||
tags_val = r.get("tags")
|
||||
if tags_val is None:
|
||||
r["tags"] = []
|
||||
elif not isinstance(tags_val, list):
|
||||
r["tags"] = list(tags_val) if tags_val else []
|
||||
if not show_uploader:
|
||||
r["uploader_name"] = None
|
||||
r["uploader_email"] = None
|
||||
@@ -329,16 +561,21 @@ def list_media_assets(
|
||||
viewer = {
|
||||
"show_uploader_meta": show_uploader,
|
||||
"show_club_meta": show_club,
|
||||
"is_superadmin": is_superadmin(role),
|
||||
"is_platform_admin": is_platform_admin(role),
|
||||
"is_superadmin": sup,
|
||||
"is_platform_admin": is_adm,
|
||||
}
|
||||
filter_meta = None
|
||||
if include_filter_meta and show_uploader:
|
||||
filter_meta = {"uploaders": _fetch_filter_uploaders(cur, is_adm, profile_id)}
|
||||
|
||||
return {
|
||||
"items": rows,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"lifecycle": lifecycle.strip().lower(),
|
||||
"media_kind": mk,
|
||||
"viewer": viewer,
|
||||
"filter_meta": filter_meta,
|
||||
}
|
||||
|
||||
|
||||
@@ -415,7 +652,11 @@ def bulk_media_patch(
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
raw = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body.dict(exclude_unset=True)
|
||||
patch_fields = {k: v for k, v in raw.items() if k != "media_asset_ids" and v is not None}
|
||||
patch_fields = {
|
||||
k: v
|
||||
for k, v in raw.items()
|
||||
if k != "media_asset_ids" and (k == "tags" or v is not None)
|
||||
}
|
||||
if not patch_fields:
|
||||
raise HTTPException(status_code=400, detail="Keine Felder zum Aktualisieren")
|
||||
|
||||
@@ -461,6 +702,9 @@ def bulk_media_patch(
|
||||
if "original_filename" in patch_fields:
|
||||
sets.append("original_filename = %s")
|
||||
vals.append(patch_fields["original_filename"])
|
||||
if "tags" in patch_fields:
|
||||
sets.append("tags = %s")
|
||||
vals.append(_normalize_media_tags(patch_fields["tags"]))
|
||||
if "visibility" in patch_fields or "club_id" in patch_fields:
|
||||
sets.append("visibility = %s")
|
||||
vals.append(str(eff.get("visibility", asset["visibility"])).strip())
|
||||
@@ -529,6 +773,9 @@ def patch_media_asset(
|
||||
if "original_filename" in data:
|
||||
sets.append("original_filename = %s")
|
||||
vals.append(data["original_filename"])
|
||||
if "tags" in data:
|
||||
sets.append("tags = %s")
|
||||
vals.append(_normalize_media_tags(data["tags"]))
|
||||
if "visibility" in data or "club_id" in data:
|
||||
sets.append("visibility = %s")
|
||||
vals.append(str(eff.get("visibility", asset["visibility"])).strip())
|
||||
@@ -544,7 +791,7 @@ def patch_media_asset(
|
||||
conn.commit()
|
||||
cur.execute(
|
||||
"""SELECT id, mime_type, byte_size, original_filename, visibility, club_id,
|
||||
uploaded_by_profile_id, lifecycle_state, created_at, sha256, copyright_notice
|
||||
uploaded_by_profile_id, lifecycle_state, created_at, sha256, copyright_notice, tags
|
||||
FROM media_assets WHERE id = %s""",
|
||||
(asset_id,),
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user