11 Commits
Author SHA1 Message Date
LarsandCursor b8842cf98e feat(docker): Mediumpfade über .env (SHINKAN_MEDIA_HOST, MEDIA_ROOT)
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 22s
Bind-Mount statt Named-Volumes für Backend-/app/media; MEDIA_ROOT wird
an den Container durchgereicht (entspricht FastAPI). .env.example: MEDIA_DIR
durch SHINKAN_MEDIA_HOST/MEDIA_ROOT ersetzt, Kommentare für Prod/Dev.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:22:03 +02:00
LarsandCursor f8a7247ccc revert: Dev/Compose/Frontend auf Stand ceef6f0 (07.05.2026 22:02)
Deploy Development / deploy (push) Successful in 36s
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
Alle Änderungen nach dem letzten verifizierten Deploy (ceef6f0) für
docker-compose.dev-env.yml, docker-compose.yml, .env.example sowie
main.jsx, MediaLibraryPage, ExerciseFormPage zurückgesetzt;
ErrorBoundary entfernt. Entspricht dem funktionierenden develop-Stand
von Gitea an diesem Zeitpunkt.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 09:18:07 +02:00
Lars d758de3852 feat: add MEDIAWIKI_CATEGORY_MODELS to docker-compose and refactor MediaLibraryPage
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 7s
Test Suite / playwright-tests (push) Failing after 1m43s
- Introduced MEDIAWIKI_CATEGORY_MODELS environment variable in docker-compose.yml for better configuration.
- Refactored MediaLibraryPage to simplify video rendering by replacing createElement with JSX syntax, enhancing readability and maintainability.
- Removed lazy loading and Suspense for MediaLibraryPage to streamline component rendering.
2026-05-08 09:07:51 +02:00
Lars c1d1c2d7e0 feat: implement lazy loading for MediaLibraryPage and optimize video rendering
Deploy Development / deploy (push) Successful in 35s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Failing after 1m43s
- Refactored MediaLibraryPage to use React's lazy loading and Suspense for improved performance during page load.
- Updated video rendering logic to utilize createElement for better flexibility and maintainability.
- Enhanced loading state with a spinner to improve user experience while media content is being fetched.
2026-05-08 09:02:19 +02:00
Lars bebcf5af73 refactor: update media icons in MediaLibraryPage for clarity
Deploy Development / deploy (push) Successful in 37s
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) Failing after 1m42s
- Renamed imported media icons to avoid naming conflicts, using 'LucideImage' and 'LucideVideo' for better clarity.
- Updated the MediaTypeGlyph component to utilize the renamed icons for rendering media types, ensuring consistent icon representation.
2026-05-08 08:59:13 +02:00
Lars 5b13a0a526 chore: refine media path configuration in environment files
Deploy Development / deploy (push) Successful in 36s
Test Suite / pytest-backend (push) Successful in 25s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 8s
Test Suite / playwright-tests (push) Failing after 1m43s
- Updated .env.example to clarify SHINKAN_MEDIA_HOST usage for different environments.
- Modified docker-compose files to set default values for SHINKAN_MEDIA_HOST, ensuring consistent media path handling in development and production.
- Enhanced comments for better understanding of media path configurations.
2026-05-08 08:41:27 +02:00
Lars c921f0dd8f refactor: update media handling configuration and improve upload acceptance
Deploy Development / deploy (push) Successful in 38s
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) Failing after 1m45s
- Modified .env.example to include SHINKAN_MEDIA_HOST and MEDIA_ROOT for better media path management.
- Updated docker-compose files to utilize SHINKAN_MEDIA_HOST for volume mounts, ensuring consistent media directory handling across environments.
- Enhanced ExerciseFormPage and MediaLibraryPage to specify accepted media types explicitly, improving compatibility and user experience during uploads.
2026-05-08 08:35:15 +02:00
Lars ceef6f09e2 feat: improve media library layout and loading behavior
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 7s
Test Suite / playwright-tests (push) Successful in 28s
- Added a hidden anchor element to the media library for smooth scrolling to the top of the grid after uploads.
- Introduced a sequence reference to manage concurrent media item fetch requests, ensuring accurate loading states.
- Updated upload summary messaging to include a note about the list being refreshed after uploads.
- Enhanced loading state management to prevent unnecessary updates when fetch requests are out of sync.
2026-05-07 22:02:18 +02:00
Lars cc4e621f95 feat: enhance media upload handling and MIME type resolution
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 7s
Test Suite / playwright-tests (push) Successful in 24s
- Expanded the allowed upload MIME types to include HEIC, HEIF, and QuickTime formats.
- Introduced a new function to resolve MIME types based on file content, filename extensions, and client-provided content types.
- Updated media upload logic in both the exercises and media assets routers to utilize the new MIME resolution function.
- Adjusted frontend file input accept attributes to allow broader media types, improving user experience.
- Enhanced media library components to handle HEIC/HEIF formats with appropriate fallback messaging for browser compatibility.
2026-05-07 21:55:22 +02:00
Lars d213746bd2 fix: update media card positioning and styles
Deploy Development / deploy (push) Successful in 34s
Test Suite / pytest-backend (push) Successful in 28s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 7s
Test Suite / playwright-tests (push) Successful in 24s
- Removed unnecessary positioning styles from media library card types.
- Added a new style for the thumbnail card type to adjust its position.
- Updated the MediaLibraryPage component to apply the new thumbnail style conditionally based on the compact view.
2026-05-07 21:42:10 +02:00
Lars f9e6e61244 feat: implement bulk upload functionality for media assets
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 6s
Test Suite / playwright-tests (push) Successful in 29s
- Added a new API endpoint for bulk uploading media assets, allowing users to upload multiple files in a single request.
- Implemented validation for file types and sizes during the upload process, ensuring compliance with allowed formats and limits.
- Enhanced the MediaLibraryPage component to support bulk file selection and visibility options, improving user experience.
- Updated CSS styles for the upload interface to enhance layout and accessibility.
- Added tests to verify the functionality of the new bulk upload feature and its integration with existing media asset management.
2026-05-07 21:36:35 +02:00
10 changed files with 587 additions and 24 deletions

No files matched your search

+8 -1
View File
@@ -12,6 +12,8 @@
# APP_URL=https://shinkan.jinkendo.de # APP_URL=https://shinkan.jinkendo.de
# ALLOWED_ORIGINS=https://shinkan.jinkendo.de # ALLOWED_ORIGINS=https://shinkan.jinkendo.de
# ENVIRONMENT=production # ENVIRONMENT=production
# SHINKAN_MEDIA_HOST=/shinkan-media
# MEDIA_ROOT=/app/media
# ─── Typische Werte DEV (docker-compose.dev-env.yml) ───────────────────────── # ─── Typische Werte DEV (docker-compose.dev-env.yml) ─────────────────────────
# DB_NAME=shinkan_dev # DB_NAME=shinkan_dev
@@ -20,6 +22,8 @@
# APP_URL=https://dev.shinkan.jinkendo.de # APP_URL=https://dev.shinkan.jinkendo.de
# ALLOWED_ORIGINS=https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098 # ALLOWED_ORIGINS=https://dev.shinkan.jinkendo.de,http://192.168.2.49:3098
# ENVIRONMENT=development # ENVIRONMENT=development
# SHINKAN_MEDIA_HOST=/shinkan-media/dev
# MEDIA_ROOT=/app/media
# ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ─────────── # ─── Ab hier: eine ausfüllbare Vorlage (bei uns meist Prod-Defaults) ───────────
DB_HOST=postgres DB_HOST=postgres
@@ -46,7 +50,10 @@ APP_URL=https://shinkan.jinkendo.de
ALLOWED_ORIGINS=https://shinkan.jinkendo.de ALLOWED_ORIGINS=https://shinkan.jinkendo.de
ENVIRONMENT=production ENVIRONMENT=production
MEDIA_DIR=/app/media # Medien (Docker Compose): SHINKAN_MEDIA_HOST = Verzeichnis auf dem Host (Bind-Mount),
# MEDIA_ROOT = gleicher Pfad im Container (muss mit dem Mount-Ziel übereinstimmen — FastAPI).
SHINKAN_MEDIA_HOST=/shinkan-media
MEDIA_ROOT=/app/media
MEDIAWIKI_API_URL=https://karatetrainer.net/api.php MEDIAWIKI_API_URL=https://karatetrainer.net/api.php
MEDIAWIKI_USER=Jinkendo MEDIAWIKI_USER=Jinkendo
+78 -7
View File
@@ -107,9 +107,76 @@ _MAX_UPLOAD_MB_ADMIN = max(_MAX_UPLOAD_MB_USER, int(os.getenv("EXERCISE_MEDIA_AD
MAX_UPLOAD_BYTES_USER = _MAX_UPLOAD_MB_USER * 1024 * 1024 MAX_UPLOAD_BYTES_USER = _MAX_UPLOAD_MB_USER * 1024 * 1024
MAX_UPLOAD_BYTES_ADMIN = _MAX_UPLOAD_MB_ADMIN * 1024 * 1024 MAX_UPLOAD_BYTES_ADMIN = _MAX_UPLOAD_MB_ADMIN * 1024 * 1024
ALLOWED_UPLOAD_MIMES = frozenset( ALLOWED_UPLOAD_MIMES = frozenset(
{"image/jpeg", "image/png", "image/gif", "video/mp4", "application/pdf"} {
"image/jpeg",
"image/png",
"image/gif",
"image/heic",
"image/heif",
"video/mp4",
"video/quicktime",
"application/pdf",
}
) )
# Dateiendung → MIME wenn der Client keinen sinnvollen Content-Type sendet (häufig mobil / iOS).
_UPLOAD_FILENAME_MIME_FALLBACK = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".heic": "image/heic",
".heif": "image/heif",
".mp4": "video/mp4",
".mov": "video/quicktime",
".pdf": "application/pdf",
}
def _sniff_allowed_upload_mime(raw: bytes) -> Optional[str]:
"""Erkennt erlaubte MIME-Typen anhand weniger Magic Bytes (ohne Pillow/python-magic)."""
if len(raw) < 12:
return None
if raw[:3] == b"\xff\xd8\xff":
return "image/jpeg"
if raw[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
if raw[:6] in (b"GIF87a", b"GIF89a"):
return "image/gif"
if raw[:4] == b"%PDF":
return "application/pdf"
if raw[4:8] != b"ftyp":
return None
brand = raw[8:12]
# HEIC / HEIF (u. a. iPhone „高效率“)
if brand in (b"heic", b"heix", b"hevx", b"hevc", b"mif1", b"msf1"):
return "image/heic"
if brand in (b"isom", b"iso2", b"iso5", b"iso6", b"mp41", b"mp42", b"M4V ", b"dash", b"msdh"):
return "video/mp4"
# iPhone-Kamera / Fotos: MOV (QuickTime-Container)
if brand == b"qt ":
return "video/quicktime"
return None
def resolve_upload_mime_type(
raw: bytes,
content_type: Optional[str],
filename: Optional[str],
) -> str:
"""Ermittelt ein erlaubtes MIME (Client-Header, Magic Bytes oder Dateiendung)."""
ct = (content_type or "").split(";")[0].strip().lower()
if ct in ALLOWED_UPLOAD_MIMES:
return ct
guessed = _sniff_allowed_upload_mime(raw)
if guessed in ALLOWED_UPLOAD_MIMES:
return guessed
ext = Path(filename or "").suffix.lower()
fb = _UPLOAD_FILENAME_MIME_FALLBACK.get(ext)
if fb in ALLOWED_UPLOAD_MIMES:
return fb
raise ValueError(f"Dateityp nicht erlaubt: {ct or 'unbekannt'}")
def _upload_limit_bytes(tenant: TenantContext) -> int: def _upload_limit_bytes(tenant: TenantContext) -> int:
role = tenant.global_role or "" role = tenant.global_role or ""
@@ -2302,17 +2369,21 @@ async def upload_exercise_media(
status_code=413, status_code=413,
detail=f"Datei zu groß (max. {max_upload // (1024 * 1024)} MB)", detail=f"Datei zu groß (max. {max_upload // (1024 * 1024)} MB)",
) )
mime = file.content_type or "" try:
if mime not in ALLOWED_UPLOAD_MIMES: mime = resolve_upload_mime_type(raw, file.content_type, file.filename)
raise HTTPException( except ValueError as e:
status_code=400, raise HTTPException(status_code=400, detail=str(e)) from e
detail=f"Dateityp nicht erlaubt: {mime or 'unbekannt'}",
)
ext = Path(file.filename or "").suffix[:12] if file.filename else "" ext = Path(file.filename or "").suffix[:12] if file.filename else ""
if not ext and mime == "image/jpeg": if not ext and mime == "image/jpeg":
ext = ".jpg" ext = ".jpg"
elif not ext and mime == "image/png": elif not ext and mime == "image/png":
ext = ".png" ext = ".png"
elif not ext and mime in ("image/heic", "image/heif"):
ext = ".heic"
elif not ext and mime == "video/mp4":
ext = ".mp4"
elif not ext and mime == "video/quicktime":
ext = ".mov"
cur.execute( cur.execute(
"SELECT visibility, club_id, created_by FROM exercises WHERE id = %s", "SELECT visibility, club_id, created_by FROM exercises WHERE id = %s",
+201 -7
View File
@@ -3,7 +3,10 @@ from __future__ import annotations
from typing import Any, Literal, Optional, Union from typing import Any, Literal, Optional, Union
from fastapi import APIRouter, Depends, HTTPException, Query, Request import hashlib
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
from pydantic import BaseModel, Field, model_validator from pydantic import BaseModel, Field, model_validator
from club_tenancy import ( from club_tenancy import (
@@ -33,6 +36,8 @@ from media_lifecycle import (
from media_storage import get_effective_media_root, path_under_media_root from media_storage import get_effective_media_root, path_under_media_root
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
router = APIRouter(prefix="/api/media-assets", tags=["media-assets"]) router = APIRouter(prefix="/api/media-assets", tags=["media-assets"])
@@ -445,6 +450,194 @@ def _apply_lifecycle_action(
raise HTTPException(status_code=500, detail="Interner Fehler: lifecycle action") raise HTTPException(status_code=500, detail="Interner Fehler: lifecycle action")
_MAX_BULK_LIBRARY_FILES = 25
def _ingest_library_media_file(
cur: Any,
tenant: TenantContext,
raw: bytes,
filename: Optional[str],
content_type: Optional[str],
visibility: str,
club_id_form: Optional[int],
) -> dict:
"""Neues Archiv-Medium oder aktiver Dedupe-Treffer (sha256 + Sichtbarkeit + Verein). Kein exercise_media."""
profile_id = tenant.profile_id
role = tenant.global_role or ""
vis = (visibility or "private").strip().lower()
if vis not in ("private", "club", "official"):
raise HTTPException(status_code=400, detail="Ungültige Sichtbarkeit")
next_cid: Optional[int] = None
if vis == "club":
if club_id_form is None:
raise HTTPException(status_code=400, detail="Verein erforderlich für Sichtbarkeit „Verein“")
next_cid = int(club_id_form)
assert_valid_governance_visibility(cur, profile_id, role, vis, next_cid)
max_b = _upload_limit_bytes(tenant)
if len(raw) > max_b:
raise HTTPException(
status_code=413,
detail=f"Datei zu groß (max. {max_b // (1024 * 1024)} MB)",
)
try:
mime = resolve_upload_mime_type(raw, content_type, filename)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
full_sha = hashlib.sha256(raw).hexdigest()
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()
if existing_asset:
ea = r2d(existing_asset)
lc = (ea.get("lifecycle_state") or "").strip().lower()
if lc == "active":
return {
"status": "duplicate",
"media_asset_id": int(ea["id"]),
"original_filename": ea.get("original_filename"),
}
if lc in ("trash_soft", "trash_hidden"):
raise HTTPException(
status_code=409,
detail={
"code": "MEDIA_ASSET_IN_TRASH",
"message": (
"Diese Datei ist inhaltsgleich (SHA-256) mit einem Archiv-Medium im Papierkorb."
),
"media_asset_id": ea["id"],
"lifecycle_state": lc,
},
)
raise HTTPException(
status_code=409,
detail="Es existiert bereits ein Archiv-Eintrag zu dieser Datei in einem nicht nutzbaren Zustand.",
)
ext = Path(filename or "").suffix[:12] if filename else ""
if not ext and mime == "image/jpeg":
ext = ".jpg"
elif not ext and mime == "image/png":
ext = ".png"
elif not ext and mime in ("image/heic", "image/heif"):
ext = ".heic"
elif not ext and mime == "video/mp4":
ext = ".mp4"
elif not ext and mime == "video/quicktime":
ext = ".mov"
media_root = get_effective_media_root(cur)
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,
filename or storage_key,
vis,
next_cid,
profile_id,
storage_key,
),
)
ar = cur.fetchone()
aid = int(r2d(ar)["id"])
return {"status": "created", "media_asset_id": aid, "original_filename": filename or storage_key}
@router.post("/bulk-upload")
async def bulk_upload_media_assets(
tenant: TenantContext = Depends(get_tenant_context),
files: list[UploadFile] = File(..., description="Mehrere Dateien (jpeg, png, gif, mp4, pdf)"),
visibility: str = Form("private"),
club_id: Optional[int] = Form(None),
):
"""Mehrere Dateien ins Archiv; Dedupe wie Übungs-Upload. Pro Datei eigene DB-Transaktion."""
if not files:
raise HTTPException(status_code=400, detail="Keine Dateien übermittelt")
if len(files) > _MAX_BULK_LIBRARY_FILES:
raise HTTPException(
status_code=400,
detail=f"Maximal {_MAX_BULK_LIBRARY_FILES} Dateien pro Anfrage",
)
results: list[dict[str, Any]] = []
created = duplicate = failed = 0
for uf in files:
fn = uf.filename or "ohne_name"
try:
raw = await uf.read()
if not raw:
results.append({"filename": fn, "ok": False, "detail": "Leere Datei"})
failed += 1
continue
with get_db() as conn:
cur = get_cursor(conn)
r = _ingest_library_media_file(
cur,
tenant,
raw,
uf.filename,
uf.content_type,
visibility,
club_id,
)
results.append({"filename": fn, "ok": True, **r})
if r["status"] == "created":
created += 1
else:
duplicate += 1
except HTTPException as e:
detail = e.detail
if isinstance(detail, dict):
detail_s = detail.get("message") or detail.get("code") or str(detail)
else:
detail_s = str(detail)
results.append(
{
"filename": fn,
"ok": False,
"status_code": e.status_code,
"detail": detail_s,
},
)
failed += 1
except Exception as e:
results.append({"filename": fn, "ok": False, "detail": str(e)})
failed += 1
return {
"results": results,
"created_count": created,
"duplicate_count": duplicate,
"failed_count": failed,
}
@router.get("") @router.get("")
def list_media_assets( def list_media_assets(
tenant: TenantContext = Depends(get_tenant_context), tenant: TenantContext = Depends(get_tenant_context),
@@ -489,21 +682,22 @@ def list_media_assets(
media_kind_sql = "" media_kind_sql = ""
if mk == "image": if mk == "image":
media_kind_sql = " AND lower(COALESCE(ma.mime_type, '')) LIKE 'image/%'" # %% für psycopg2: sonst wird % als Platzhalter-Syntax interpretiert
media_kind_sql = " AND lower(COALESCE(ma.mime_type, '')) LIKE 'image/%%'"
elif mk == "video": elif mk == "video":
media_kind_sql = " AND lower(COALESCE(ma.mime_type, '')) LIKE 'video/%'" media_kind_sql = " AND lower(COALESCE(ma.mime_type, '')) LIKE 'video/%%'"
elif mk == "pdf": elif mk == "pdf":
media_kind_sql = ( media_kind_sql = (
" AND (lower(COALESCE(ma.mime_type, '')) = 'application/pdf'" " AND (lower(COALESCE(ma.mime_type, '')) = 'application/pdf'"
" OR lower(COALESCE(ma.mime_type, '')) LIKE '%pdf%')" " OR lower(COALESCE(ma.mime_type, '')) LIKE '%%pdf%%')"
) )
elif mk == "other": elif mk == "other":
media_kind_sql = ( media_kind_sql = (
" AND COALESCE(ma.mime_type, '') <> ''" " AND COALESCE(ma.mime_type, '') <> ''"
" AND lower(ma.mime_type) NOT LIKE 'image/%'" " AND lower(ma.mime_type) NOT LIKE 'image/%%'"
" AND lower(ma.mime_type) NOT LIKE 'video/%'" " AND lower(ma.mime_type) NOT LIKE 'video/%%'"
" AND lower(ma.mime_type) <> 'application/pdf'" " AND lower(ma.mime_type) <> 'application/pdf'"
" AND lower(ma.mime_type) NOT LIKE '%pdf%'" " AND lower(ma.mime_type) NOT LIKE '%%pdf%%'"
) )
club_sql = "" club_sql = ""
@@ -87,6 +87,32 @@ def test_list_media_assets_ok_mocked(client: TestClient) -> None:
assert "viewer" in body assert "viewer" in body
def test_list_media_assets_media_kind_image_ok_mocked(client: TestClient) -> None:
"""media_kind=image setzt %% in SQL — Regression gegen psycopg2-%-Platzhalter."""
app.dependency_overrides[require_auth] = lambda: {"profile_id": 10, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
profile_id=10,
global_role="trainer",
effective_club_id=5,
club_ids=frozenset({5}),
memberships=[],
)
mock_cur = MagicMock()
mock_cur.fetchall.side_effect = [[], []]
mock_cm = _mock_db(mock_cur)
with patch("routers.media_assets.get_db", return_value=mock_cm), patch(
"routers.media_assets.get_cursor", return_value=mock_cur
), patch("routers.media_assets.club_ids_for_profile_with_roles", return_value=set()):
r = client.get("/api/media-assets?media_kind=image", headers={"X-Auth-Token": "t"})
assert r.status_code == 200
calls = [str(c) for c in mock_cur.execute.call_args_list]
joined = " ".join(calls)
assert "image/%%" in joined
def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None: def test_attach_from_asset_duplicate_returns_400(client: TestClient) -> None:
app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"} app.dependency_overrides[require_auth] = lambda: {"profile_id": 1, "role": "trainer"}
app.dependency_overrides[get_tenant_context] = lambda: TenantContext( app.dependency_overrides[get_tenant_context] = lambda: TenantContext(
+4 -3
View File
@@ -1,5 +1,6 @@
# Keine festen container_name — Compose-Namen haben Projektprefix (<projekt>-postgres-1). # Keine festen container_name — Compose-Namen haben Projektprefix (<projekt>-postgres-1).
# Gleiche Variablennamen wie docker-compose.yml; andere Werte in einer eigenen .env neben dieser Datei. # Medien: In .env SHINKAN_MEDIA_HOST (Host-Pfad) und optional MEDIA_ROOT (Container-Pfad) setzen.
# Default Host /shinkan-media/dev — Verzeichnis ggf. anlegen oder Compose legt es an.
services: services:
postgres: postgres:
@@ -43,8 +44,9 @@ services:
MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}" MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}"
MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}" MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}"
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}" MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
volumes: volumes:
- dev-shinkan-media:/app/media - ${SHINKAN_MEDIA_HOST:-/shinkan-media/dev}:${MEDIA_ROOT:-/app/media}
ports: ports:
- "8098:8000" - "8098:8000"
depends_on: depends_on:
@@ -70,7 +72,6 @@ services:
volumes: volumes:
dev-shinkan-db-data: dev-shinkan-db-data:
dev-shinkan-media:
networks: networks:
dev-shinkan-network: dev-shinkan-network:
+3 -2
View File
@@ -52,8 +52,10 @@ services:
MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}" MEDIAWIKI_CATEGORY_SKILLS: "${MEDIAWIKI_CATEGORY_SKILLS:-Fähigkeitsbeschreibung}"
MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}" MEDIAWIKI_CATEGORY_METHODS: "${MEDIAWIKI_CATEGORY_METHODS:-Methodenbeschreibung}"
MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}" MEDIAWIKI_CATEGORY_MODELS: "${MEDIAWIKI_CATEGORY_MODELS:-Reifegradmodelle}"
# Medien: Host-Pfad SHINKAN_MEDIA_HOST (in .env), Ziel im Container MEDIA_ROOT.
MEDIA_ROOT: "${MEDIA_ROOT:-/app/media}"
volumes: volumes:
- shinkan-media:/app/media - ${SHINKAN_MEDIA_HOST:-/shinkan-media}:${MEDIA_ROOT:-/app/media}
ports: ports:
- "8003:8000" - "8003:8000"
depends_on: depends_on:
@@ -79,7 +81,6 @@ services:
volumes: volumes:
shinkan-db-data: shinkan-db-data:
shinkan-media:
networks: networks:
shinkan-network: shinkan-network:
+69
View File
@@ -5546,6 +5546,74 @@ a.analysis-split__nav-item {
flex: 1 1 140px; flex: 1 1 140px;
max-width: 240px; max-width: 240px;
} }
.media-library__upload-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin-top: 12px;
}
.media-library__upload-row .form-input {
min-width: 0;
flex: 0 1 160px;
max-width: 220px;
}
.media-library__upload-summary {
font-size: 0.85rem;
color: var(--text2);
flex: 1 1 200px;
}
.media-library__grid-top-anchor {
height: 1px;
margin: 0;
padding: 0;
overflow: hidden;
visibility: hidden;
pointer-events: none;
}
.media-library__upload-icon {
vertical-align: middle;
margin-right: 6px;
}
.media-library__sr-file {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.media-library__card-type {
position: absolute;
z-index: 2;
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.92);
color: var(--text2);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
pointer-events: none;
}
/* Kachel: unten links — Checkbox liegt oben links */
.media-library__card-type--thumb-bl {
left: 6px;
bottom: 6px;
top: auto;
}
.media-library__card-type--compact {
width: 22px;
height: 22px;
left: 3px;
top: 3px;
bottom: auto;
border-radius: 6px;
}
.media-library__card-copyright { .media-library__card-copyright {
position: absolute; position: absolute;
right: 6px; right: 6px;
@@ -5797,6 +5865,7 @@ a.analysis-split__nav-item {
width: 72px; width: 72px;
} }
.media-library__table-thumb { .media-library__table-thumb {
position: relative;
width: 56px; width: 56px;
height: 56px; height: 56px;
border-radius: 8px; border-radius: 8px;
+1 -1
View File
@@ -1460,7 +1460,7 @@ function ExerciseFormPage() {
<label className="form-label">Datei</label> <label className="form-label">Datei</label>
<input <input
type="file" type="file"
accept="image/jpeg,image/png,image/gif,video/mp4,application/pdf" accept="image/*,video/*,application/pdf"
onChange={(e) => setMediaFile(e.target.files?.[0] || null)} onChange={(e) => setMediaFile(e.target.files?.[0] || null)}
/> />
<div className="form-row" style={{ marginTop: '8px' }}> <div className="form-row" style={{ marginTop: '8px' }}>
+152 -2
View File
@@ -1,4 +1,4 @@
import { useEffect, useState, useCallback } from 'react' import { useEffect, useState, useCallback, useRef } from 'react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { import {
LayoutGrid, LayoutGrid,
@@ -13,6 +13,11 @@ import {
CircleDot, CircleDot,
FilePenLine, FilePenLine,
Copyright, Copyright,
Image,
Video,
FileText,
File,
Upload,
} from 'lucide-react' } from 'lucide-react'
import { useAuth } from '../context/AuthContext' import { useAuth } from '../context/AuthContext'
import api from '../utils/api' import api from '../utils/api'
@@ -148,6 +153,10 @@ function uploaderLabel(it, viewer) {
function MediaThumb({ mediaId, mimeType }) { function MediaThumb({ mediaId, mimeType }) {
const url = resolveMediaAssetFileUrl(mediaId) const url = resolveMediaAssetFileUrl(mediaId)
const mime = (mimeType || '').toLowerCase() const mime = (mimeType || '').toLowerCase()
/* iPhone-Fotos: Browser-Vorschau oft nicht nutzbar */
if (mime.includes('heic') || mime.includes('heif')) {
return <div className="media-library__thumb-ph">HEIC</div>
}
if (mime.startsWith('video/')) { if (mime.startsWith('video/')) {
return ( return (
<video <video
@@ -195,6 +204,32 @@ function previewDisplayKind(mimeType) {
return 'other' return 'other'
} }
const MEDIA_KIND_LABELS = {
image: 'Bild',
video: 'Video',
pdf: 'PDF',
other: 'Sonstiges',
}
function MediaTypeGlyph({ mimeType, compact }) {
const kind = previewDisplayKind(mimeType)
const label = MEDIA_KIND_LABELS[kind] || 'Medium'
let Icon = File
if (kind === 'image') Icon = Image
else if (kind === 'video') Icon = Video
else if (kind === 'pdf') Icon = FileText
const sz = compact ? 12 : 14
return (
<span
className={`media-library__card-type${compact ? ' media-library__card-type--compact' : ' media-library__card-type--thumb-bl'}`}
title={label}
aria-label={`Medientyp: ${label}`}
>
<Icon size={sz} strokeWidth={2} aria-hidden />
</span>
)
}
export default function MediaLibraryPage() { export default function MediaLibraryPage() {
const { user } = useAuth() const { user } = useAuth()
const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin' const isPlatformAdmin = user?.role === 'admin' || user?.role === 'superadmin'
@@ -222,6 +257,13 @@ export default function MediaLibraryPage() {
const [filterClubId, setFilterClubId] = useState('') const [filterClubId, setFilterClubId] = useState('')
const [filterUploaderId, setFilterUploaderId] = useState('') const [filterUploaderId, setFilterUploaderId] = useState('')
const [uploaderFilterOptions, setUploaderFilterOptions] = useState([]) const [uploaderFilterOptions, setUploaderFilterOptions] = useState([])
const bulkFileInputRef = useRef(null)
const [uploadVis, setUploadVis] = useState('private')
const [uploadClubId, setUploadClubId] = useState('')
const [uploadBusy, setUploadBusy] = useState(false)
const [uploadSummary, setUploadSummary] = useState('')
const mediaListFetchSeqRef = useRef(0)
const gridTopAnchorRef = useRef(null)
const loadClubs = useCallback(async () => { const loadClubs = useCallback(async () => {
try { try {
@@ -237,6 +279,7 @@ export default function MediaLibraryPage() {
}, [loadClubs]) }, [loadClubs])
const loadItems = useCallback(async () => { const loadItems = useCallback(async () => {
const seq = ++mediaListFetchSeqRef.current
setLoading(true) setLoading(true)
setError('') setError('')
try { try {
@@ -254,6 +297,7 @@ export default function MediaLibraryPage() {
? { uploaded_by: Number(filterUploaderId) } ? { uploaded_by: Number(filterUploaderId) }
: {}), : {}),
}) })
if (seq !== mediaListFetchSeqRef.current) return
setItems(res.items || []) setItems(res.items || [])
setViewer(res.viewer || null) setViewer(res.viewer || null)
if (res.filter_meta?.uploaders?.length) { if (res.filter_meta?.uploaders?.length) {
@@ -261,9 +305,10 @@ export default function MediaLibraryPage() {
} }
setSelected(new Set()) setSelected(new Set())
} catch (e) { } catch (e) {
if (seq !== mediaListFetchSeqRef.current) return
setError(e.message || String(e)) setError(e.message || String(e))
} finally { } finally {
setLoading(false) if (seq === mediaListFetchSeqRef.current) setLoading(false)
} }
}, [lifecycle, q, mediaKind, filterClubId, filterUploaderId, isSuperadmin, viewer?.show_uploader_meta]) }, [lifecycle, q, mediaKind, filterClubId, filterUploaderId, isSuperadmin, viewer?.show_uploader_meta])
@@ -428,6 +473,39 @@ export default function MediaLibraryPage() {
const selCount = selected.size const selCount = selected.size
const onBulkArchiveFiles = async (e) => {
const fl = e.target.files
if (!fl?.length) return
const list = Array.from(fl)
e.target.value = ''
if (uploadVis === 'club' && !Number(uploadClubId)) {
window.alert('Bitte einen Verein für die Sichtbarkeit „Verein“ wählen.')
return
}
setUploadBusy(true)
setUploadSummary('')
try {
const res = await api.bulkUploadMediaAssets(list, {
visibility: uploadVis,
...(uploadVis === 'club' ? { club_id: Number(uploadClubId) } : {}),
})
setUploadSummary(
`Archiv-Upload: neu ${res.created_count}, bereits vorhanden ${res.duplicate_count}, fehlgeschlagen ${res.failed_count}. Liste aktualisiert.`,
)
if (res.created_count > 0 || res.duplicate_count > 0) {
setFilterUploaderId('')
}
await loadItems()
window.requestAnimationFrame(() => {
gridTopAnchorRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
})
} catch (err) {
window.alert(err.message || String(err))
} finally {
setUploadBusy(false)
}
}
return ( return (
<div className="app-page media-library"> <div className="app-page media-library">
{isPlatformAdmin ? <AdminPageNav /> : null} {isPlatformAdmin ? <AdminPageNav /> : null}
@@ -541,6 +619,61 @@ export default function MediaLibraryPage() {
</select> </select>
) : null} ) : null}
</div> </div>
<div className="media-library__upload-row" aria-label="Archiv hochladen">
<input
ref={bulkFileInputRef}
type="file"
className="media-library__sr-file"
accept="image/*,video/*,application/pdf"
multiple
onChange={onBulkArchiveFiles}
/>
<button
type="button"
className="btn btn-secondary"
disabled={uploadBusy}
onClick={() => bulkFileInputRef.current?.click()}
title="Mehrere Dateien ins Archiv laden"
>
<Upload size={18} aria-hidden className="media-library__upload-icon" />
Archiv-Upload
</button>
<select
className="form-input"
value={uploadVis}
onChange={(e) => {
setUploadVis(e.target.value)
setUploadSummary('')
}}
aria-label="Sichtbarkeit für neuen Upload"
>
{VIS_OPTIONS.map((o) => (
<option key={o.value} value={o.value}>
Upload: {o.label}
</option>
))}
</select>
{uploadVis === 'club' ? (
<select
className="form-input"
value={uploadClubId}
onChange={(e) => setUploadClubId(e.target.value)}
aria-label="Verein für Upload"
>
<option value="">Verein wählen…</option>
{clubs.map((c) => (
<option key={c.id} value={String(c.id)}>
{c.name || c.id}
</option>
))}
</select>
) : null}
{uploadSummary ? (
<span className="media-library__upload-summary" role="status">
{uploadSummary}
</span>
) : null}
</div>
<div className="media-library__toolbar-meta"> <div className="media-library__toolbar-meta">
<label className="media-library__check-all"> <label className="media-library__check-all">
<input type="checkbox" checked={items.length > 0 && selCount === items.length} onChange={selectAll} /> <input type="checkbox" checked={items.length > 0 && selCount === items.length} onChange={selectAll} />
@@ -560,6 +693,8 @@ export default function MediaLibraryPage() {
</p> </p>
) : null} ) : null}
<div ref={gridTopAnchorRef} className="media-library__grid-top-anchor" aria-hidden="true" />
{loading && !items.length ? <div className="spinner media-library__spinner" /> : null} {loading && !items.length ? <div className="spinner media-library__spinner" /> : null}
{!loading && !items.length && !error ? ( {!loading && !items.length && !error ? (
@@ -591,6 +726,7 @@ export default function MediaLibraryPage() {
title="Vorschau" title="Vorschau"
> >
<div className="media-library__card-thumb-wrap"> <div className="media-library__card-thumb-wrap">
<MediaTypeGlyph mimeType={it.mime_type} />
<MediaThumb mediaId={it.id} mimeType={it.mime_type} /> <MediaThumb mediaId={it.id} mimeType={it.mime_type} />
{(it.copyright_notice || '').trim() ? ( {(it.copyright_notice || '').trim() ? (
<span <span
@@ -658,6 +794,7 @@ export default function MediaLibraryPage() {
title="Vorschau" title="Vorschau"
> >
<div className="media-library__table-thumb"> <div className="media-library__table-thumb">
<MediaTypeGlyph mimeType={it.mime_type} compact />
<MediaThumb mediaId={it.id} mimeType={it.mime_type} /> <MediaThumb mediaId={it.id} mimeType={it.mime_type} />
</div> </div>
</button> </button>
@@ -737,9 +874,22 @@ export default function MediaLibraryPage() {
{(() => { {(() => {
const url = resolveMediaAssetFileUrl(preview.id) const url = resolveMediaAssetFileUrl(preview.id)
const kind = previewDisplayKind(preview.mime_type) const kind = previewDisplayKind(preview.mime_type)
const mlow = (preview.mime_type || '').toLowerCase()
if (!url) { if (!url) {
return <p className="media-library__hint">Keine Datei-URL.</p> return <p className="media-library__hint">Keine Datei-URL.</p>
} }
if (mlow.includes('heic') || mlow.includes('heif')) {
return (
<div className="media-library__preview-fallback">
<p className="media-library__hint">
HEIC/HEIF — in diesem Browser oft keine eingebettete Vorschau. Zum Ansehen herunterladen oder im neuen Tab öffnen.
</p>
<a className="btn btn-secondary" href={url} target="_blank" rel="noopener noreferrer">
Datei öffnen
</a>
</div>
)
}
if (kind === 'image') { if (kind === 'image') {
return ( return (
<img <img
+45 -1
View File
@@ -464,7 +464,7 @@ export function buildExerciseApiPayload(formData, extras = {}) {
export async function uploadExerciseMedia(exerciseId, formData) { export async function uploadExerciseMedia(exerciseId, formData) {
const token = localStorage.getItem('authToken') const token = localStorage.getItem('authToken')
const headers = {} const headers = mergeActiveClubHeader({})
if (token) headers['X-Auth-Token'] = token if (token) headers['X-Auth-Token'] = token
const response = await fetch(`${API_URL}/api/exercises/${exerciseId}/media`, { const response = await fetch(`${API_URL}/api/exercises/${exerciseId}/media`, {
method: 'POST', method: 'POST',
@@ -564,6 +564,49 @@ export async function bulkPatchMediaAssets(data) {
}) })
} }
/**
* Mehrere Dateien ins Medienarchiv (`POST /api/media-assets/bulk-upload`).
* @param {File[]} files
* @param {{ visibility?: string, club_id?: number }} [options]
*/
export async function bulkUploadMediaAssets(files, options = {}) {
const visibility = options.visibility || 'private'
const token = localStorage.getItem('authToken')
const headers = mergeActiveClubHeader({})
if (token) headers['X-Auth-Token'] = token
const formData = new FormData()
formData.append('visibility', String(visibility))
if (options.club_id != null && options.club_id !== '') {
formData.append('club_id', String(options.club_id))
}
const arr = Array.isArray(files) ? files : [files]
for (const f of arr) {
if (f) formData.append('files', f)
}
const url = `${API_URL}/api/media-assets/bulk-upload`
const response = await fetch(url, {
method: 'POST',
headers,
body: formData,
})
if (!response.ok) {
const text = await response.text()
let parsed = null
try {
parsed = JSON.parse(text)
} catch {
parsed = null
}
if (parsed?.detail != null) {
const d = parsed.detail
throw new Error(typeof d === 'string' ? d : JSON.stringify(d))
}
const snippet = (text || '').replace(/\s+/g, ' ').trim().slice(0, 180)
throw new Error(snippet ? `HTTP ${response.status}: ${snippet}` : `HTTP ${response.status}`)
}
return response.json()
}
/** Übung: bestehendes Archiv-Medium verknüpfen (`POST /api/exercises/{id}/media/from-asset`). */ /** Übung: bestehendes Archiv-Medium verknüpfen (`POST /api/exercises/{id}/media/from-asset`). */
export async function attachExerciseMediaFromAsset(exerciseId, body) { export async function attachExerciseMediaFromAsset(exerciseId, body) {
return request(`/api/exercises/${exerciseId}/media/from-asset`, { return request(`/api/exercises/${exerciseId}/media/from-asset`, {
@@ -1313,6 +1356,7 @@ export const api = {
patchMediaAsset, patchMediaAsset,
bulkMediaLifecycle, bulkMediaLifecycle,
bulkPatchMediaAssets, bulkPatchMediaAssets,
bulkUploadMediaAssets,
attachExerciseMediaFromAsset, attachExerciseMediaFromAsset,
listExerciseProgressionGraphs, listExerciseProgressionGraphs,
getExerciseProgressionGraph, getExerciseProgressionGraph,