Deploy Development / deploy (push) Successful in 53s
Test Suite / pytest-backend (push) Failing after 29s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m42s
The exercise list turns the live catalog on or off for the caller's edit rights. A distribution key reads that current selection and the changes since its last cursor. Co-authored-by: Cursor <cursoragent@cursor.com>
1834 lines
66 KiB
Python
1834 lines
66 KiB
Python
"""Datenbank und Bytekopien der Distributionsfreigabe."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import shutil
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Any, Optional
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from auth import hash_pin, verify_pin
|
|
from club_tenancy import has_club_role, is_superadmin
|
|
from db import r2d
|
|
from distribution_contract import (
|
|
LEGAL_HOLD_REASON,
|
|
REASON_CODES,
|
|
can_withdraw,
|
|
canonical_json,
|
|
catalog_available,
|
|
catalog_changes,
|
|
catalog_document,
|
|
catalog_hash,
|
|
decode_catalog_cursor,
|
|
encode_catalog_cursor,
|
|
changed_areas,
|
|
collect_blockers,
|
|
cut_hash,
|
|
decide_confirm,
|
|
cursor_secret,
|
|
exercise_offerable,
|
|
InvalidCursor,
|
|
key_covers,
|
|
package_state,
|
|
scope_denial,
|
|
default_cut,
|
|
distribution_enabled,
|
|
format_utc,
|
|
manifest_bytes,
|
|
new_id,
|
|
order_event,
|
|
parse_utc,
|
|
rate_decision,
|
|
release_denial,
|
|
sha256_bytes,
|
|
snapshot_hash,
|
|
)
|
|
|
|
_MEDIA_TYPE = {
|
|
"video": "video/mp4",
|
|
"image": "image/jpeg",
|
|
"document": "application/pdf",
|
|
"pdf": "application/pdf",
|
|
"sketch": "image/png",
|
|
}
|
|
|
|
|
|
def _now() -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def _rows(cur) -> list:
|
|
rows = cur.fetchall()
|
|
if not isinstance(rows, list):
|
|
return []
|
|
return rows
|
|
|
|
|
|
def _one(cur) -> Optional[dict]:
|
|
row = cur.fetchone()
|
|
if row is None or not isinstance(row, (dict, tuple)):
|
|
try:
|
|
mapped = r2d(row)
|
|
except Exception:
|
|
return None
|
|
return mapped
|
|
return r2d(row)
|
|
|
|
|
|
def distribution_media_root() -> Path:
|
|
base = os.getenv("MEDIA_ROOT", str(Path(__file__).resolve().parent / "media"))
|
|
root = Path(base) / "distribution"
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
return root
|
|
|
|
|
|
def require_enabled() -> None:
|
|
if not distribution_enabled():
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail={
|
|
"code": "distribution_disabled",
|
|
"message": "Die Distribution ist auf dieser Instanz nicht aktiv.",
|
|
},
|
|
)
|
|
|
|
|
|
def blocks_exercise_delete(cur, exercise_id: int) -> bool:
|
|
cur.execute(
|
|
"""
|
|
SELECT dr.release_id
|
|
FROM distribution_releases dr
|
|
JOIN exercises e ON e.public_id = dr.source_id
|
|
WHERE e.id = %s
|
|
LIMIT 1
|
|
""",
|
|
(exercise_id,),
|
|
)
|
|
return len(_rows(cur)) > 0
|
|
|
|
|
|
def blocks_media_delete(cur, media_id: int) -> bool:
|
|
cur.execute(
|
|
"""
|
|
SELECT a.asset_id
|
|
FROM distribution_release_assets a
|
|
JOIN exercise_media em ON em.public_id = a.source_media_public_id
|
|
WHERE em.id = %s
|
|
LIMIT 1
|
|
""",
|
|
(media_id,),
|
|
)
|
|
return len(_rows(cur)) > 0
|
|
|
|
|
|
def blocks_variant_delete(cur, variant_id: int) -> bool:
|
|
cur.execute(
|
|
"""
|
|
SELECT dr.release_id
|
|
FROM distribution_releases dr
|
|
JOIN exercise_variants v ON position(v.public_id::text in dr.manifest_text) > 0
|
|
WHERE v.id = %s
|
|
LIMIT 1
|
|
""",
|
|
(variant_id,),
|
|
)
|
|
return len(_rows(cur)) > 0
|
|
|
|
|
|
def _lock_recipient(cur, recipient_id: str) -> None:
|
|
cur.execute(
|
|
"SELECT id FROM distribution_recipients WHERE id = %s FOR UPDATE",
|
|
(str(recipient_id),),
|
|
)
|
|
if cur.fetchone() is None:
|
|
raise HTTPException(status_code=404, detail="Empfänger nicht gefunden")
|
|
|
|
|
|
def append_event(cur, recipient_id: str, event: dict) -> int:
|
|
_lock_recipient(cur, recipient_id)
|
|
cur.execute(
|
|
"SELECT COALESCE(MAX(seq), 0) AS seq FROM distribution_events WHERE recipient_id = %s",
|
|
(str(recipient_id),),
|
|
)
|
|
seq = int((_one(cur) or {"seq": 0})["seq"]) + 1
|
|
ordered = order_event(event)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_events (event_id, recipient_id, seq, event_type, release_id, occurred_at, body)
|
|
VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb)
|
|
""",
|
|
(
|
|
ordered["event_id"],
|
|
str(recipient_id),
|
|
seq,
|
|
ordered["type"],
|
|
ordered["release_id"],
|
|
parse_utc(ordered["occurred_at"]),
|
|
canonical_json(ordered).decode("utf-8"),
|
|
),
|
|
)
|
|
return seq
|
|
|
|
|
|
def _mark_blocked(cur, release_id: str) -> None:
|
|
cur.execute(
|
|
"UPDATE distribution_releases SET fetch_blocked = true WHERE release_id = %s",
|
|
(str(release_id),),
|
|
)
|
|
|
|
|
|
def withdraw_assets_for_media_asset(cur, asset_id: int, legal_reason: str) -> None:
|
|
reason = LEGAL_HOLD_REASON.get(legal_reason, "safety")
|
|
cur.execute(
|
|
"""
|
|
SELECT a.release_id, a.asset_id, r.recipient_id
|
|
FROM distribution_release_assets a
|
|
JOIN distribution_releases r ON r.release_id = a.release_id
|
|
WHERE a.source_asset_id = %s
|
|
""",
|
|
(asset_id,),
|
|
)
|
|
rows = _rows(cur)
|
|
now = format_utc(_now())
|
|
for row in rows:
|
|
item = r2d(row)
|
|
event = {
|
|
"event_id": new_id(),
|
|
"type": "asset.withdrawn",
|
|
"release_id": str(item["release_id"]),
|
|
"occurred_at": now,
|
|
"target_id": str(item["asset_id"]),
|
|
"reason_code": reason,
|
|
}
|
|
append_event(cur, str(item["recipient_id"]), event)
|
|
_mark_blocked(cur, str(item["release_id"]))
|
|
|
|
|
|
def _load_exercise(cur, exercise_id: int) -> dict:
|
|
cur.execute(
|
|
"""
|
|
SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes,
|
|
equipment, duration_min, duration_max, status, visibility, club_id,
|
|
exercise_kind, created_by
|
|
FROM exercises WHERE id = %s
|
|
""",
|
|
(exercise_id,),
|
|
)
|
|
row = _one(cur)
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
|
return row
|
|
|
|
|
|
def _load_variants(cur, exercise_id: int) -> list[dict]:
|
|
cur.execute(
|
|
"""
|
|
SELECT id, public_id, variant_name, description, execution_changes, duration_min, duration_max
|
|
FROM exercise_variants
|
|
WHERE exercise_id = %s
|
|
ORDER BY id
|
|
""",
|
|
(exercise_id,),
|
|
)
|
|
return [r2d(row) for row in _rows(cur)]
|
|
|
|
|
|
def _load_media(cur, exercise_id: int) -> list[dict]:
|
|
cur.execute(
|
|
"""
|
|
SELECT em.id, em.public_id, em.media_type, em.file_path, em.title, em.media_asset_id,
|
|
COALESCE(ma.legal_hold_active, false) AS legal_hold_active,
|
|
COALESCE(ma.rights_status, 'declared') AS rights_status,
|
|
ma.sha256 AS sha256
|
|
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 NULLS LAST, em.id
|
|
""",
|
|
(exercise_id,),
|
|
)
|
|
return [r2d(row) for row in _rows(cur)]
|
|
|
|
|
|
def _publisher(cur, publisher_id: str) -> dict:
|
|
cur.execute(
|
|
"SELECT id, name, kind, club_id, status FROM distribution_publishers WHERE id = %s",
|
|
(str(publisher_id),),
|
|
)
|
|
row = _one(cur)
|
|
if not row or row.get("status") != "active":
|
|
raise HTTPException(status_code=403, detail="Herausgeber ist nicht freigeschaltet.")
|
|
return row
|
|
|
|
|
|
def _is_owner(exercise: dict, profile_id: int) -> bool:
|
|
created = exercise.get("created_by")
|
|
try:
|
|
return created is not None and int(created) == int(profile_id)
|
|
except (TypeError, ValueError):
|
|
return False
|
|
|
|
|
|
def _is_club_admin(cur, exercise: dict, profile_id: int) -> bool:
|
|
if (exercise.get("visibility") or "").strip().lower() != "club":
|
|
return False
|
|
club_id = exercise.get("club_id")
|
|
if club_id is None:
|
|
return False
|
|
try:
|
|
return has_club_role(cur, int(profile_id), int(club_id), "club_admin")
|
|
except (TypeError, ValueError):
|
|
return False
|
|
|
|
|
|
def _denial_for(cur, exercise: dict, publisher: dict, profile_id: int, role: str) -> Optional[str]:
|
|
return release_denial(
|
|
visibility=exercise.get("visibility"),
|
|
role=role,
|
|
publisher_kind=publisher["kind"],
|
|
is_owner=_is_owner(exercise, profile_id),
|
|
is_club_admin=_is_club_admin(cur, exercise, profile_id),
|
|
publisher_club_id=publisher.get("club_id"),
|
|
exercise_club_id=exercise.get("club_id"),
|
|
)
|
|
|
|
|
|
def _assert_may_release(cur, exercise: dict, publisher: dict, profile_id: int, role: str) -> None:
|
|
denial = _denial_for(cur, exercise, publisher, profile_id, role)
|
|
if denial:
|
|
raise HTTPException(status_code=403, detail=denial)
|
|
|
|
|
|
def _relationship_ok(cur, publisher_id: str, recipient_id: str) -> bool:
|
|
cur.execute(
|
|
"""
|
|
SELECT 1 AS ok
|
|
FROM distribution_relationships rel
|
|
JOIN distribution_recipients rec ON rec.id = rel.recipient_id
|
|
WHERE rel.publisher_id = %s AND rel.recipient_id = %s
|
|
AND rel.status = 'active' AND rec.status = 'active'
|
|
""",
|
|
(str(publisher_id), str(recipient_id)),
|
|
)
|
|
return _one(cur) is not None
|
|
|
|
|
|
def _part_id(cur, source_id: str, part_key: str) -> str:
|
|
cur.execute(
|
|
"""
|
|
SELECT part_id FROM distribution_part_identities
|
|
WHERE source_id = %s AND part_key = %s
|
|
""",
|
|
(str(source_id), part_key),
|
|
)
|
|
row = _one(cur)
|
|
if row:
|
|
return str(row["part_id"])
|
|
part_id = new_id()
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_part_identities (source_id, part_key, part_id)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(str(source_id), part_key, part_id),
|
|
)
|
|
return part_id
|
|
|
|
|
|
def _variant_id(cur, source_id: str, variant_key: str, public_id: Optional[str]) -> str:
|
|
if public_id:
|
|
return str(public_id)
|
|
return _part_id(cur, source_id, f"variant-id:{variant_key}")
|
|
|
|
|
|
def _revision_for(cur, source_id: str, snap: str) -> int:
|
|
cur.execute(
|
|
"""
|
|
SELECT revision FROM distribution_source_revisions
|
|
WHERE source_id = %s AND snapshot_hash = %s
|
|
""",
|
|
(str(source_id), snap),
|
|
)
|
|
row = _one(cur)
|
|
if row:
|
|
return int(row["revision"])
|
|
cur.execute(
|
|
"SELECT COALESCE(MAX(revision), 0) AS revision FROM distribution_source_revisions WHERE source_id = %s",
|
|
(str(source_id),),
|
|
)
|
|
revision = int((_one(cur) or {"revision": 0})["revision"]) + 1
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_source_revisions (source_id, revision, snapshot_hash)
|
|
VALUES (%s, %s, %s)
|
|
""",
|
|
(str(source_id), revision, snap),
|
|
)
|
|
return revision
|
|
|
|
|
|
def hashlib_file(path: Path) -> tuple[str, int]:
|
|
import hashlib
|
|
|
|
hasher = hashlib.sha256()
|
|
size = 0
|
|
with path.open("rb") as handle:
|
|
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
hasher.update(chunk)
|
|
size += len(chunk)
|
|
return hasher.hexdigest(), size
|
|
|
|
|
|
def overview(cur, exercise_id: int, profile_id: int, role: str) -> dict:
|
|
exercise = _load_exercise(cur, exercise_id)
|
|
cur.execute(
|
|
"""
|
|
SELECT dr.release_id, dr.revision, dr.published_at, dr.fetch_blocked, dr.recipient_id,
|
|
rec.name AS recipient_name
|
|
FROM distribution_releases dr
|
|
JOIN distribution_recipients rec ON rec.id = dr.recipient_id
|
|
JOIN exercises e ON e.public_id = dr.source_id
|
|
WHERE e.id = %s
|
|
ORDER BY dr.published_at
|
|
""",
|
|
(exercise_id,),
|
|
)
|
|
releases = []
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
releases.append(
|
|
{
|
|
"release_id": str(item["release_id"]),
|
|
"revision": item["revision"],
|
|
"published_at": format_utc(item["published_at"]) if not isinstance(item["published_at"], str) else item["published_at"],
|
|
"fetch_blocked": bool(item["fetch_blocked"]),
|
|
"recipient_id": str(item["recipient_id"]),
|
|
"recipient_name": item["recipient_name"],
|
|
}
|
|
)
|
|
cur.execute(
|
|
"""
|
|
SELECT p.id, p.name, p.kind, p.club_id
|
|
FROM distribution_publishers p
|
|
WHERE p.status = 'active'
|
|
ORDER BY p.name
|
|
"""
|
|
)
|
|
keys, release_block = release_keys_for_exercise(cur, exercise, profile_id, role)
|
|
return {
|
|
"enabled": distribution_enabled(),
|
|
"visibility": exercise.get("visibility"),
|
|
"may_release": release_block is None and bool(keys),
|
|
"release_block": release_block,
|
|
"releases": releases,
|
|
"keys": keys,
|
|
"drift": exercise_release_drift(cur, exercise),
|
|
"profile_id": profile_id,
|
|
"role": role,
|
|
}
|
|
|
|
|
|
def create_draft(cur, exercise_id: int, publisher_id: str, recipient_id: str, profile_id: int, role: str, cut: Optional[dict]) -> dict:
|
|
require_enabled()
|
|
exercise = _load_exercise(cur, exercise_id)
|
|
variants = _load_variants(cur, exercise_id)
|
|
media = _load_media(cur, exercise_id)
|
|
publisher = _publisher(cur, publisher_id)
|
|
_assert_may_release(cur, exercise, publisher, profile_id, role)
|
|
if not _relationship_ok(cur, publisher_id, recipient_id):
|
|
raise HTTPException(status_code=403, detail="Für diesen Empfänger besteht keine zugelassene Beziehung.")
|
|
payload = cut if cut is not None else default_cut(exercise, variants, media)
|
|
blockers = collect_blockers(exercise, variants, media, payload, _now())
|
|
draft_id = new_id()
|
|
snap = snapshot_hash(exercise, variants, media)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_drafts (
|
|
id, exercise_id, publisher_id, recipient_id, prepared_by, cut, preview_hash
|
|
) VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s)
|
|
""",
|
|
(draft_id, exercise_id, str(publisher_id), str(recipient_id), profile_id, canonical_json(payload).decode("utf-8"), snap),
|
|
)
|
|
return {"draft_id": draft_id, "cut": payload, "blockers": blockers, "preview_hash": snap}
|
|
|
|
|
|
def update_draft(cur, exercise_id: int, draft_id: str, cut: dict, profile_id: int, role: str) -> dict:
|
|
require_enabled()
|
|
exercise = _load_exercise(cur, exercise_id)
|
|
variants = _load_variants(cur, exercise_id)
|
|
media = _load_media(cur, exercise_id)
|
|
cur.execute(
|
|
"SELECT id, publisher_id, release_id FROM distribution_drafts WHERE id = %s AND exercise_id = %s FOR UPDATE",
|
|
(str(draft_id), exercise_id),
|
|
)
|
|
draft = _one(cur)
|
|
if not draft:
|
|
raise HTTPException(status_code=404, detail="Entwurf nicht gefunden")
|
|
if draft.get("release_id"):
|
|
raise HTTPException(status_code=409, detail="Dieser Entwurf ist bereits bestätigt.")
|
|
_assert_may_release(cur, exercise, _publisher(cur, str(draft["publisher_id"])), profile_id, role)
|
|
snap = snapshot_hash(exercise, variants, media)
|
|
cur.execute(
|
|
"""
|
|
UPDATE distribution_drafts SET cut = %s::jsonb, preview_hash = %s WHERE id = %s
|
|
""",
|
|
(canonical_json(cut).decode("utf-8"), snap, str(draft_id)),
|
|
)
|
|
return {"draft_id": str(draft_id), "cut": cut, "blockers": collect_blockers(exercise, variants, media, cut, _now()), "preview_hash": snap}
|
|
|
|
|
|
def _load_cut(value) -> dict:
|
|
if isinstance(value, str):
|
|
import json
|
|
return json.loads(value)
|
|
return dict(value)
|
|
|
|
|
|
def confirm_draft(cur, exercise_id: int, draft_id: str, profile_id: int, role: str) -> dict:
|
|
require_enabled()
|
|
cur.execute("SELECT id FROM exercises WHERE id = %s FOR UPDATE", (exercise_id,))
|
|
if cur.fetchone() is None:
|
|
raise HTTPException(status_code=404, detail="Übung nicht gefunden")
|
|
cur.execute(
|
|
"""
|
|
SELECT id, publisher_id, recipient_id, cut, preview_hash, release_id
|
|
FROM distribution_drafts
|
|
WHERE id = %s AND exercise_id = %s
|
|
FOR UPDATE
|
|
""",
|
|
(str(draft_id), exercise_id),
|
|
)
|
|
draft = _one(cur)
|
|
if not draft:
|
|
raise HTTPException(status_code=404, detail="Entwurf nicht gefunden")
|
|
exercise = _load_exercise(cur, exercise_id)
|
|
publisher = _publisher(cur, str(draft["publisher_id"]))
|
|
_assert_may_release(cur, exercise, publisher, profile_id, role)
|
|
release_id, created = decide_confirm(
|
|
str(draft["release_id"]) if draft.get("release_id") else None,
|
|
new_id(),
|
|
)
|
|
if not created:
|
|
cur.execute(
|
|
"SELECT manifest_sha256 FROM distribution_releases WHERE release_id = %s",
|
|
(release_id,),
|
|
)
|
|
stored = _one(cur) or {}
|
|
return {"release_id": release_id, "replayed": True, "manifest_sha256": stored.get("manifest_sha256")}
|
|
|
|
variants = _load_variants(cur, exercise_id)
|
|
media = _load_media(cur, exercise_id)
|
|
snap = snapshot_hash(exercise, variants, media)
|
|
if snap != draft["preview_hash"]:
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="Die Übung wurde seit der Vorschau geändert. Bitte die Vorschau neu erstellen.",
|
|
)
|
|
cut = _load_cut(draft["cut"])
|
|
blockers = collect_blockers(exercise, variants, media, cut, _now())
|
|
if blockers:
|
|
raise HTTPException(status_code=400, detail={"code": "release_blocked", "blockers": blockers})
|
|
source_id = str(exercise["public_id"])
|
|
revision = _revision_for(cur, source_id, snap)
|
|
published_at = format_utc(_now())
|
|
part_ids = {part["key"]: _part_id(cur, source_id, part["key"]) for part in cut["parts"]}
|
|
variant_ids = {}
|
|
known_variants = {str(item["public_id"]): str(item["public_id"]) for item in variants}
|
|
for variant in cut["variants"]:
|
|
variant_ids[variant["key"]] = known_variants.get(variant["key"]) or _variant_id(
|
|
cur, source_id, variant["key"], None
|
|
)
|
|
media_by_public = {str(item["public_id"]): item for item in media}
|
|
copied: list[Path] = []
|
|
asset_rows = []
|
|
try:
|
|
for asset in cut["assets"]:
|
|
stored = media_by_public[str(asset["media_id"])]
|
|
source = Path(stored["file_path"])
|
|
if not source.is_file():
|
|
raise HTTPException(status_code=400, detail="Mediendatei fehlt auf dem Speicher.")
|
|
digest, size = hashlib_file(source)
|
|
asset_id = str(stored["public_id"])
|
|
target = distribution_media_root() / release_id / asset_id
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copyfile(source, target)
|
|
copied.append(target)
|
|
asset_rows.append(
|
|
{
|
|
"id": asset_id,
|
|
"role": asset["role"],
|
|
"media_type": _MEDIA_TYPE.get((stored.get("media_type") or "").lower(), "application/octet-stream"),
|
|
"size_bytes": size,
|
|
"sha256": digest,
|
|
"rights_id": asset["rights_id"],
|
|
"label": asset.get("label"),
|
|
"source_media_public_id": asset_id,
|
|
"source_asset_id": stored.get("media_asset_id"),
|
|
"path": str(target),
|
|
}
|
|
)
|
|
manifest = {
|
|
"schema_version": 1,
|
|
"resource_type": "exercise",
|
|
"release_id": release_id,
|
|
"source_id": source_id,
|
|
"revision": revision,
|
|
"publisher_id": str(publisher["id"]),
|
|
"published_at": published_at,
|
|
"exercise": {
|
|
"title": cut["title"],
|
|
"summary": cut.get("summary"),
|
|
"audience": cut.get("audience"),
|
|
"rights_id": cut["editorial_rights_id"],
|
|
"parts": [
|
|
{
|
|
"id": part_ids[part["key"]],
|
|
"role": part["role"],
|
|
"text": part["text"],
|
|
"rights_id": part["rights_id"],
|
|
}
|
|
for part in cut["parts"]
|
|
],
|
|
"assets": [
|
|
{
|
|
"id": row["id"],
|
|
"role": row["role"],
|
|
"media_type": row["media_type"],
|
|
"size_bytes": row["size_bytes"],
|
|
"sha256": row["sha256"],
|
|
"rights_id": row["rights_id"],
|
|
"label": row["label"],
|
|
}
|
|
for row in asset_rows
|
|
],
|
|
"common_part_ids": [part_ids[key] for key in cut.get("common_part_keys") or []],
|
|
"common_asset_ids": [str(item) for item in cut.get("common_media_ids") or []],
|
|
"variants": [
|
|
{
|
|
"id": variant_ids[variant["key"]],
|
|
"label": variant["label"],
|
|
"part_ids": [part_ids[key] for key in variant.get("part_keys") or []],
|
|
"asset_ids": [str(item) for item in variant.get("media_ids") or []],
|
|
}
|
|
for variant in cut["variants"]
|
|
],
|
|
},
|
|
"rights": [
|
|
{
|
|
"id": right["id"],
|
|
"evidence_ref": right["evidence_ref"],
|
|
"actions": right["actions"],
|
|
"territories": right.get("territories"),
|
|
"valid_from": right["valid_from"],
|
|
"valid_until": right.get("valid_until"),
|
|
"attribution": right.get("attribution"),
|
|
}
|
|
for right in cut["rights"]
|
|
],
|
|
}
|
|
body = manifest_bytes(manifest)
|
|
digest = sha256_bytes(body)
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_releases (
|
|
release_id, recipient_id, publisher_id, source_id, revision, cut_hash,
|
|
manifest_text, manifest_sha256, published_at, fetch_blocked, confirmed_by
|
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, false, %s)
|
|
""",
|
|
(
|
|
release_id,
|
|
str(draft["recipient_id"]),
|
|
str(publisher["id"]),
|
|
source_id,
|
|
revision,
|
|
cut_hash(cut),
|
|
body.decode("utf-8"),
|
|
digest,
|
|
parse_utc(published_at),
|
|
profile_id,
|
|
),
|
|
)
|
|
for row in asset_rows:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_release_assets (
|
|
release_id, asset_id, sha256, size_bytes, media_type, storage_path,
|
|
source_media_public_id, source_asset_id
|
|
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
|
""",
|
|
(
|
|
release_id,
|
|
row["id"],
|
|
row["sha256"],
|
|
row["size_bytes"],
|
|
row["media_type"],
|
|
row["path"],
|
|
row["source_media_public_id"],
|
|
row["source_asset_id"],
|
|
),
|
|
)
|
|
for right in cut["rights"]:
|
|
note = right.get("note")
|
|
if note:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_evidence (id, publisher_id, note, created_by)
|
|
VALUES (%s, %s, %s, %s)
|
|
ON CONFLICT (id) DO NOTHING
|
|
""",
|
|
(right["evidence_ref"], str(publisher["id"]), note, profile_id),
|
|
)
|
|
append_event(
|
|
cur,
|
|
str(draft["recipient_id"]),
|
|
{
|
|
"event_id": new_id(),
|
|
"type": "release.published",
|
|
"release_id": release_id,
|
|
"occurred_at": published_at,
|
|
"source_id": source_id,
|
|
"revision": revision,
|
|
"manifest_sha256": digest,
|
|
},
|
|
)
|
|
cur.execute(
|
|
"UPDATE distribution_drafts SET release_id = %s, confirmed_at = NOW() WHERE id = %s",
|
|
(release_id, str(draft_id)),
|
|
)
|
|
return {"release_id": release_id, "replayed": False, "manifest_sha256": digest}
|
|
except Exception:
|
|
for path in copied:
|
|
path.unlink(missing_ok=True)
|
|
raise
|
|
|
|
|
|
def _release_row(cur, release_id: str) -> dict:
|
|
cur.execute(
|
|
"""
|
|
SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text
|
|
FROM distribution_releases WHERE release_id = %s
|
|
""",
|
|
(str(release_id),),
|
|
)
|
|
row = _one(cur)
|
|
if not row:
|
|
raise HTTPException(status_code=404, detail="Paket nicht gefunden")
|
|
return row
|
|
|
|
|
|
def _assert_withdraw(cur, release: dict, profile_id: int, role: str) -> None:
|
|
require_enabled()
|
|
publisher = _publisher(cur, str(release["publisher_id"]))
|
|
cur.execute(
|
|
"""
|
|
SELECT id, public_id, visibility, club_id, created_by
|
|
FROM exercises WHERE public_id = %s
|
|
""",
|
|
(str(release["source_id"]),),
|
|
)
|
|
exercise = _one(cur)
|
|
denial = (
|
|
"Paket ohne zugehörige Übung."
|
|
if not exercise
|
|
else _denial_for(cur, exercise, publisher, profile_id, role)
|
|
)
|
|
if not can_withdraw(role=role, denial=denial):
|
|
raise HTTPException(status_code=403, detail=denial or "Keine Befugnis für diesen Rückzug.")
|
|
|
|
|
|
def retire_release(cur, release_id: str, profile_id: int, role: str) -> dict:
|
|
release = _release_row(cur, release_id)
|
|
_assert_withdraw(cur, release, profile_id, role)
|
|
cur.execute(
|
|
"""
|
|
SELECT 1 AS ok FROM distribution_events
|
|
WHERE release_id = %s AND event_type = 'release.retired'
|
|
""",
|
|
(str(release_id),),
|
|
)
|
|
if _one(cur):
|
|
return {"release_id": str(release_id), "replayed": True}
|
|
append_event(
|
|
cur,
|
|
str(release["recipient_id"]),
|
|
{
|
|
"event_id": new_id(),
|
|
"type": "release.retired",
|
|
"release_id": str(release_id),
|
|
"occurred_at": format_utc(_now()),
|
|
},
|
|
)
|
|
return {"release_id": str(release_id), "replayed": False}
|
|
|
|
|
|
def withdraw_release(cur, release_id: str, reason_code: str, profile_id: int, role: str, kind: str, target_id: Optional[str]) -> dict:
|
|
if reason_code not in REASON_CODES:
|
|
raise HTTPException(status_code=400, detail="Unbekannte Grundklasse.")
|
|
release = _release_row(cur, release_id)
|
|
_assert_withdraw(cur, release, profile_id, role)
|
|
event_type = {
|
|
"release": "release.withdrawn",
|
|
"variant": "variant.withdrawn",
|
|
"asset": "asset.withdrawn",
|
|
}[kind]
|
|
if kind != "release" and not target_id:
|
|
raise HTTPException(status_code=400, detail="Ziel fehlt.")
|
|
event = {
|
|
"event_id": new_id(),
|
|
"type": event_type,
|
|
"release_id": str(release_id),
|
|
"occurred_at": format_utc(_now()),
|
|
"reason_code": reason_code,
|
|
}
|
|
if target_id:
|
|
event["target_id"] = str(target_id)
|
|
append_event(cur, str(release["recipient_id"]), event)
|
|
_mark_blocked(cur, str(release_id))
|
|
return {"release_id": str(release_id), "type": event_type}
|
|
|
|
|
|
def enforce_expiry(cur, release: dict, now: Optional[datetime] = None) -> None:
|
|
if release.get("fetch_blocked"):
|
|
return
|
|
import json
|
|
|
|
manifest = json.loads(release["manifest_text"])
|
|
moment = now or _now()
|
|
expired = set()
|
|
for right in manifest.get("rights") or []:
|
|
until = right.get("valid_until")
|
|
if until and parse_utc(until) <= moment:
|
|
expired.add(right["id"])
|
|
if not expired:
|
|
return
|
|
exercise = manifest["exercise"]
|
|
events = []
|
|
if exercise.get("rights_id") in expired:
|
|
events.append({"type": "release.withdrawn"})
|
|
else:
|
|
for asset in exercise.get("assets") or []:
|
|
if asset.get("rights_id") in expired:
|
|
events.append({"type": "asset.withdrawn", "target_id": asset["id"]})
|
|
if not events:
|
|
events.append({"type": "release.withdrawn"})
|
|
stamp = format_utc(moment)
|
|
for event in events:
|
|
payload = {
|
|
"event_id": new_id(),
|
|
"type": event["type"],
|
|
"release_id": str(release["release_id"]),
|
|
"occurred_at": stamp,
|
|
"reason_code": "expired",
|
|
}
|
|
if event.get("target_id"):
|
|
payload["target_id"] = event["target_id"]
|
|
append_event(cur, str(release["recipient_id"]), payload)
|
|
_mark_blocked(cur, str(release["release_id"]))
|
|
release["fetch_blocked"] = True
|
|
|
|
|
|
def backlog_count(cur) -> int:
|
|
cur.execute(
|
|
"SELECT manifest_text, fetch_blocked FROM distribution_releases WHERE fetch_blocked = false"
|
|
)
|
|
import json
|
|
|
|
count = 0
|
|
moment = _now()
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
manifest = json.loads(item["manifest_text"])
|
|
for right in manifest.get("rights") or []:
|
|
until = right.get("valid_until")
|
|
if until and parse_utc(until) <= moment:
|
|
count += 1
|
|
break
|
|
return count
|
|
|
|
|
|
def issue_key(cur, binding_id: str, expires_at: Optional[str]) -> dict:
|
|
cur.execute(
|
|
"SELECT id, status, recipient_id FROM distribution_bindings WHERE id = %s",
|
|
(str(binding_id),),
|
|
)
|
|
binding = _one(cur)
|
|
if not binding or binding.get("status") != "active":
|
|
raise HTTPException(status_code=404, detail="Anbindung nicht gefunden")
|
|
import secrets
|
|
|
|
prefix = secrets.token_hex(6)
|
|
secret = secrets.token_urlsafe(32)
|
|
token = f"shk.{prefix}.{secret}"
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_keys (id, binding_id, key_prefix, secret_hash, expires_at)
|
|
VALUES (%s, %s, %s, %s, %s)
|
|
""",
|
|
(new_id(), str(binding_id), prefix, hash_pin(token), parse_utc(expires_at) if expires_at else None),
|
|
)
|
|
return {"token": token, "prefix": prefix, "expires_at": expires_at}
|
|
|
|
|
|
def resolve_bearer(cur, token: str) -> dict:
|
|
if not token or not token.startswith("shk.") or token.count(".") < 2:
|
|
raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel ungültig."})
|
|
prefix = token.split(".", 2)[1]
|
|
cur.execute(
|
|
"""
|
|
SELECT k.secret_hash, k.expires_at, k.revoked_at, k.objects, k.visibilities,
|
|
k.context_kind, k.context_profile_id, k.context_club_id, k.club_ids,
|
|
b.id AS binding_id, b.status AS binding_status,
|
|
b.recipient_id, r.status AS recipient_status
|
|
FROM distribution_keys k
|
|
JOIN distribution_bindings b ON b.id = k.binding_id
|
|
JOIN distribution_recipients r ON r.id = b.recipient_id
|
|
WHERE k.key_prefix = %s
|
|
""",
|
|
(prefix,),
|
|
)
|
|
row = _one(cur)
|
|
if not row or row.get("revoked_at") is not None or not verify_pin(token, row["secret_hash"]):
|
|
raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel ungültig."})
|
|
expires = row.get("expires_at")
|
|
if expires is not None:
|
|
exp = expires if isinstance(expires, datetime) else parse_utc(str(expires))
|
|
if exp <= _now():
|
|
raise HTTPException(status_code=401, detail={"code": "invalid_key", "message": "Schlüssel abgelaufen."})
|
|
if row.get("binding_status") != "active" or row.get("recipient_status") != "active":
|
|
raise HTTPException(status_code=403, detail={"code": "binding_suspended", "message": "Anbindung ohne Abrufumfang."})
|
|
allowed, blocked = touch_rate(cur, str(row["binding_id"]))
|
|
if blocked:
|
|
raise HTTPException(
|
|
status_code=429,
|
|
detail={"code": "rate_limited", "message": "Abrufgrenze erreicht."},
|
|
headers={"Retry-After": "60", "Cache-Control": "private, no-store"},
|
|
)
|
|
return {
|
|
"binding_id": str(row["binding_id"]),
|
|
"recipient_id": str(row["recipient_id"]),
|
|
"hits": allowed,
|
|
"objects": list(row.get("objects") or ["exercise"]),
|
|
"visibilities": list(row.get("visibilities") or ["official", "club", "private"]),
|
|
"context_kind": row.get("context_kind"),
|
|
"context_profile_id": row.get("context_profile_id"),
|
|
"context_club_id": row.get("context_club_id"),
|
|
"club_ids": [int(item) for item in (row.get("club_ids") or [])],
|
|
}
|
|
|
|
|
|
def touch_rate(cur, binding_id: str) -> tuple[int, bool]:
|
|
cur.execute(
|
|
"SELECT window_start, hits FROM distribution_rate_windows WHERE binding_id = %s FOR UPDATE",
|
|
(binding_id,),
|
|
)
|
|
row = _one(cur)
|
|
now = _now()
|
|
if row is None:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_rate_windows (binding_id, window_start, hits)
|
|
VALUES (%s, %s, 1)
|
|
""",
|
|
(binding_id, now),
|
|
)
|
|
return 1, False
|
|
started = row["window_start"]
|
|
if not isinstance(started, datetime):
|
|
started = parse_utc(str(started))
|
|
hits, blocked = rate_decision(int(row["hits"]), (now - started).total_seconds())
|
|
if (now - started).total_seconds() >= 60:
|
|
cur.execute(
|
|
"UPDATE distribution_rate_windows SET window_start = %s, hits = %s WHERE binding_id = %s",
|
|
(now, hits, binding_id),
|
|
)
|
|
else:
|
|
cur.execute(
|
|
"UPDATE distribution_rate_windows SET hits = %s WHERE binding_id = %s",
|
|
(hits, binding_id),
|
|
)
|
|
return hits, blocked
|
|
|
|
|
|
def assert_exercise_object(objects) -> None:
|
|
if "exercise" not in list(objects or ["exercise"]):
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail={"code": "scope", "message": "Dieser Schlüssel darf Übungen nicht abrufen."},
|
|
)
|
|
|
|
|
|
def _source_visibility(cur, source_id: str) -> Optional[str]:
|
|
cur.execute("SELECT visibility FROM exercises WHERE public_id = %s", (str(source_id),))
|
|
row = _one(cur)
|
|
if not row:
|
|
return None
|
|
return (row.get("visibility") or "private").strip().lower()
|
|
|
|
|
|
def assert_visibility_scope(visibilities, visibility: Optional[str]) -> None:
|
|
if visibility is None:
|
|
return
|
|
allowed = list(visibilities) if visibilities else ["official", "club", "private"]
|
|
if visibility not in allowed:
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."})
|
|
|
|
|
|
def grant_allows(cur, binding: dict, exercise: dict) -> bool:
|
|
"""Auslieferung folgt den Schlüsselrechten und den Rollen, die der Inhaber jetzt noch hat."""
|
|
vis = (exercise.get("visibility") or "private").strip().lower()
|
|
visibilities = list(binding.get("visibilities") or ["official", "club", "private"])
|
|
if vis not in visibilities:
|
|
return False
|
|
kind = binding.get("context_kind")
|
|
owner = binding.get("context_profile_id")
|
|
if kind != "user" or not owner:
|
|
legacy_club = binding.get("context_club_id")
|
|
if vis == "club" and legacy_club is not None and int(legacy_club) != int(exercise.get("club_id") or 0):
|
|
return False
|
|
return True
|
|
cur.execute("SELECT role FROM profiles WHERE id = %s", (int(owner),))
|
|
role = ((_one(cur) or {}).get("role") or "")
|
|
if vis == "official":
|
|
return is_superadmin(role)
|
|
if vis == "private":
|
|
created = exercise.get("created_by")
|
|
return created is not None and int(created) == int(owner)
|
|
if vis == "club":
|
|
club_id = exercise.get("club_id")
|
|
clubs = {int(item) for item in (binding.get("club_ids") or [])}
|
|
if binding.get("context_club_id") is not None:
|
|
clubs.add(int(binding["context_club_id"]))
|
|
if club_id is None or int(club_id) not in clubs:
|
|
return False
|
|
if not has_club_role(cur, int(owner), int(club_id), "club_admin"):
|
|
return False
|
|
return _api_enabled(cur, int(club_id))
|
|
return False
|
|
|
|
|
|
def assert_current_grant(cur, binding: Optional[dict], source_id: str) -> None:
|
|
if not binding or binding.get("context_kind") != "user":
|
|
assert_visibility_scope(
|
|
None if not binding else binding.get("visibilities"),
|
|
_source_visibility(cur, source_id),
|
|
)
|
|
return
|
|
cur.execute(
|
|
"SELECT visibility, club_id, created_by FROM exercises WHERE public_id = %s",
|
|
(str(source_id),),
|
|
)
|
|
exercise = _one(cur)
|
|
if exercise is None:
|
|
return
|
|
if not grant_allows(cur, binding, exercise):
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."})
|
|
|
|
|
|
def list_changes(cur, recipient_id: str, cursor_seq: int, limit: int, binding: Optional[dict] = None) -> dict:
|
|
cur.execute(
|
|
"""
|
|
SELECT seq, body FROM distribution_events
|
|
WHERE recipient_id = %s AND seq > %s
|
|
ORDER BY seq
|
|
LIMIT %s
|
|
""",
|
|
(str(recipient_id), cursor_seq, limit + 1),
|
|
)
|
|
rows = _rows(cur)
|
|
page = rows[:limit]
|
|
import json
|
|
|
|
events = []
|
|
last_seq = cursor_seq
|
|
for row in page:
|
|
item = r2d(row)
|
|
body = item["body"]
|
|
if isinstance(body, str):
|
|
body = json.loads(body)
|
|
events.append(order_event(body))
|
|
last_seq = int(item["seq"])
|
|
if binding and binding.get("context_kind") == "user":
|
|
events = _events_still_granted(cur, binding, events)
|
|
from distribution_contract import cursor_secret, encode_cursor
|
|
|
|
return {
|
|
"events": events,
|
|
"next_cursor": encode_cursor(cursor_secret(), recipient_id, last_seq),
|
|
"has_more": len(rows) > limit,
|
|
}
|
|
|
|
|
|
def _events_still_granted(cur, binding: dict, events: list[dict]) -> list[dict]:
|
|
ids = [str(event.get("release_id")) for event in events if event.get("release_id")]
|
|
if not ids:
|
|
return events
|
|
placeholders = ", ".join(["%s"] * len(ids))
|
|
cur.execute(
|
|
f"""
|
|
SELECT dr.release_id, e.visibility, e.club_id, e.created_by
|
|
FROM distribution_releases dr
|
|
LEFT JOIN exercises e ON e.public_id = dr.source_id
|
|
WHERE dr.release_id IN ({placeholders})
|
|
""",
|
|
tuple(ids),
|
|
)
|
|
allowed = set()
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
if item.get("visibility") is None or grant_allows(cur, binding, item):
|
|
allowed.add(str(item["release_id"]))
|
|
return [event for event in events if str(event.get("release_id")) in allowed]
|
|
|
|
|
|
def load_availability(cur, recipient_id: str, source_id: str, visibilities=None, binding: Optional[dict] = None) -> dict:
|
|
import json
|
|
import uuid
|
|
|
|
try:
|
|
uuid.UUID(str(source_id))
|
|
except ValueError:
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht gefunden."})
|
|
cur.execute(
|
|
"""
|
|
SELECT release_id, revision, fetch_blocked, manifest_text, publisher_id, recipient_id
|
|
FROM distribution_releases
|
|
WHERE source_id = %s AND recipient_id = %s
|
|
ORDER BY revision, published_at
|
|
""",
|
|
(str(source_id), str(recipient_id)),
|
|
)
|
|
rows = [r2d(row) for row in _rows(cur)]
|
|
if not rows:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail={"code": "not_found", "message": "Für diesen Empfänger liegt keine Freigabe dieser Übung vor."},
|
|
)
|
|
cur.execute(
|
|
"SELECT status, visibility, club_id, created_by FROM exercises WHERE public_id = %s",
|
|
(str(source_id),),
|
|
)
|
|
source = _one(cur)
|
|
releases = []
|
|
for row in rows:
|
|
enforce_expiry(cur, row)
|
|
cur.execute(
|
|
"""
|
|
SELECT event_type, body
|
|
FROM distribution_events
|
|
WHERE release_id = %s
|
|
AND event_type IN ('release.retired', 'release.withdrawn', 'variant.withdrawn', 'asset.withdrawn')
|
|
ORDER BY seq DESC
|
|
""",
|
|
(str(row["release_id"]),),
|
|
)
|
|
retired = False
|
|
reason = None
|
|
for event in _rows(cur):
|
|
item = r2d(event)
|
|
if item["event_type"] == "release.retired":
|
|
retired = True
|
|
continue
|
|
if reason is None:
|
|
body = item["body"]
|
|
if isinstance(body, str):
|
|
body = json.loads(body)
|
|
reason = (body or {}).get("reason_code")
|
|
state = package_state(fetch_blocked=bool(row.get("fetch_blocked")), retired=retired)
|
|
releases.append(
|
|
{
|
|
"release_id": str(row["release_id"]),
|
|
"revision": row["revision"],
|
|
"package": state,
|
|
"fetchable": state != "withdrawn",
|
|
"reason_code": reason if state == "withdrawn" else None,
|
|
}
|
|
)
|
|
status, offerable = exercise_offerable(
|
|
source.get("status") if source else None,
|
|
[item["package"] for item in releases],
|
|
)
|
|
visibility = (source.get("visibility") if source else None)
|
|
in_scope = visibility is None or (
|
|
grant_allows(cur, binding, source)
|
|
if binding and binding.get("context_kind") == "user"
|
|
else key_covers(
|
|
["exercise"], visibilities, resource="exercise", visibility=(visibility or "private").strip().lower()
|
|
)
|
|
)
|
|
return {
|
|
"source_id": str(source_id),
|
|
"source_status": status,
|
|
"in_scope": in_scope,
|
|
"offerable": bool(offerable and in_scope),
|
|
"releases": releases,
|
|
}
|
|
|
|
|
|
def load_manifest(cur, recipient_id: str, release_id: str, visibilities=None, binding: Optional[dict] = None) -> bytes:
|
|
cur.execute(
|
|
"""
|
|
SELECT release_id, recipient_id, publisher_id, source_id, fetch_blocked, manifest_text
|
|
FROM distribution_releases WHERE release_id = %s
|
|
""",
|
|
(str(release_id),),
|
|
)
|
|
row = _one(cur)
|
|
if not row or str(row["recipient_id"]) != str(recipient_id):
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Paket nicht gefunden."})
|
|
assert_current_grant(cur, binding, str(row["source_id"]))
|
|
enforce_expiry(cur, row)
|
|
if row.get("fetch_blocked"):
|
|
raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Paket zurückgezogen."})
|
|
return row["manifest_text"].encode("utf-8")
|
|
|
|
|
|
def load_asset(cur, recipient_id: str, release_id: str, asset_id: str, visibilities=None, binding: Optional[dict] = None) -> tuple[Path, str]:
|
|
cur.execute(
|
|
"""
|
|
SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_id, r.source_id,
|
|
a.storage_path, a.media_type, a.sha256
|
|
FROM distribution_releases r
|
|
JOIN distribution_release_assets a ON a.release_id = r.release_id
|
|
WHERE r.release_id = %s AND a.asset_id = %s
|
|
""",
|
|
(str(release_id), str(asset_id)),
|
|
)
|
|
row = _one(cur)
|
|
if not row or str(row["recipient_id"]) != str(recipient_id):
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Medium nicht gefunden."})
|
|
assert_current_grant(cur, binding, str(row["source_id"]))
|
|
enforce_expiry(cur, row)
|
|
if row.get("fetch_blocked"):
|
|
raise HTTPException(status_code=410, detail={"code": "withdrawn", "message": "Medium zurückgezogen."})
|
|
path = Path(row["storage_path"])
|
|
digest, _size = hashlib_file(path)
|
|
if digest != row["sha256"]:
|
|
raise HTTPException(status_code=500, detail={"code": "integrity", "message": "Medienprüfsumme stimmt nicht."})
|
|
return path, row["media_type"]
|
|
|
|
|
|
def _pg_text_array(values: list[str]) -> str:
|
|
return "{" + ",".join(values) + "}"
|
|
|
|
|
|
def _api_enabled(cur, club_id: int) -> bool:
|
|
cur.execute("SELECT distribution_api_enabled FROM clubs WHERE id = %s", (int(club_id),))
|
|
row = _one(cur)
|
|
return bool(row and row.get("distribution_api_enabled"))
|
|
|
|
|
|
def _club_ids_with_role(cur, profile_id: int, role_code: Optional[str]) -> set[int]:
|
|
if role_code:
|
|
cur.execute(
|
|
"""
|
|
SELECT cm.club_id
|
|
FROM club_members cm
|
|
JOIN club_member_roles r ON r.club_member_id = cm.id AND r.role_code = %s
|
|
WHERE cm.profile_id = %s AND cm.status = 'active'
|
|
""",
|
|
(role_code, int(profile_id)),
|
|
)
|
|
else:
|
|
cur.execute(
|
|
"""
|
|
SELECT club_id FROM club_members
|
|
WHERE profile_id = %s AND status = 'active'
|
|
""",
|
|
(int(profile_id),),
|
|
)
|
|
return {int(r2d(row)["club_id"]) for row in _rows(cur)}
|
|
|
|
|
|
def _ensure_publisher(cur, kind: str, club_id: Optional[int], name: str) -> str:
|
|
if kind == "platform":
|
|
cur.execute(
|
|
"SELECT id FROM distribution_publishers WHERE kind = 'platform' AND status = 'active' LIMIT 1"
|
|
)
|
|
elif kind == "club":
|
|
cur.execute(
|
|
"""
|
|
SELECT id FROM distribution_publishers
|
|
WHERE kind = 'club' AND club_id = %s AND status = 'active' LIMIT 1
|
|
""",
|
|
(int(club_id),),
|
|
)
|
|
else:
|
|
cur.execute(
|
|
"SELECT id FROM distribution_publishers WHERE kind = 'own' AND status = 'active' ORDER BY created_at LIMIT 1"
|
|
)
|
|
row = _one(cur)
|
|
if row:
|
|
return str(row["id"])
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_publishers (name, kind, club_id)
|
|
VALUES (%s, %s, %s)
|
|
RETURNING id
|
|
""",
|
|
(name, kind, int(club_id) if kind == "club" else None),
|
|
)
|
|
return str(_one(cur)["id"])
|
|
|
|
|
|
def _ensure_relationship(cur, publisher_id: str, recipient_id: str) -> None:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_relationships (publisher_id, recipient_id)
|
|
VALUES (%s, %s)
|
|
ON CONFLICT (publisher_id, recipient_id) DO UPDATE SET status = 'active'
|
|
""",
|
|
(str(publisher_id), str(recipient_id)),
|
|
)
|
|
|
|
|
|
def _key_visible(item: dict, profile_id: int, role: str, admin_ids: set[int]) -> bool:
|
|
kind = item.get("context_kind")
|
|
if kind == "user":
|
|
return int(item.get("context_profile_id") or 0) == int(profile_id)
|
|
if kind == "platform":
|
|
return is_superadmin(role)
|
|
if kind == "personal":
|
|
return int(item.get("context_profile_id") or 0) == int(profile_id)
|
|
if kind == "club":
|
|
return int(item.get("context_club_id") or 0) in admin_ids
|
|
return False
|
|
|
|
|
|
def access_home(cur, profile_id: int, role: str) -> dict:
|
|
admin_ids = _club_ids_with_role(cur, profile_id, "club_admin")
|
|
if is_superadmin(role):
|
|
cur.execute(
|
|
"""
|
|
SELECT id, name, distribution_api_enabled
|
|
FROM clubs
|
|
WHERE status = 'active'
|
|
ORDER BY name
|
|
"""
|
|
)
|
|
else:
|
|
if not admin_ids:
|
|
cur.execute("SELECT id, name, distribution_api_enabled FROM clubs WHERE false")
|
|
else:
|
|
ids = list(admin_ids)
|
|
placeholders = ", ".join(["%s"] * len(ids))
|
|
cur.execute(
|
|
f"""
|
|
SELECT id, name, distribution_api_enabled
|
|
FROM clubs
|
|
WHERE status = 'active' AND id IN ({placeholders})
|
|
ORDER BY name
|
|
""",
|
|
tuple(ids),
|
|
)
|
|
clubs = []
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
clubs.append(
|
|
{
|
|
"id": int(item["id"]),
|
|
"name": item["name"],
|
|
"api_enabled": bool(item.get("distribution_api_enabled")),
|
|
"is_club_admin": int(item["id"]) in admin_ids,
|
|
}
|
|
)
|
|
cur.execute(
|
|
"""
|
|
SELECT k.id, k.label, k.key_prefix, k.objects, k.visibilities, k.context_kind,
|
|
k.context_club_id, k.context_profile_id, k.created_at, k.token_value, k.club_ids,
|
|
c.name AS club_name
|
|
FROM distribution_keys k
|
|
LEFT JOIN clubs c ON c.id = k.context_club_id
|
|
WHERE k.revoked_at IS NULL
|
|
ORDER BY k.created_at DESC
|
|
"""
|
|
)
|
|
keys = []
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
if not _key_visible(item, profile_id, role, admin_ids):
|
|
continue
|
|
created = item.get("created_at")
|
|
keys.append(
|
|
{
|
|
"id": str(item["id"]),
|
|
"label": item.get("label") or item.get("key_prefix"),
|
|
"prefix": item.get("key_prefix"),
|
|
"objects": list(item.get("objects") or []),
|
|
"visibilities": list(item.get("visibilities") or []),
|
|
"context_kind": item.get("context_kind"),
|
|
"club_id": item.get("context_club_id"),
|
|
"club_ids": [int(value) for value in (item.get("club_ids") or [])],
|
|
"club_name": item.get("club_name"),
|
|
"token": item.get("token_value") or "",
|
|
"created_at": format_utc(created) if created and not isinstance(created, str) else created,
|
|
}
|
|
)
|
|
return {"is_superadmin": is_superadmin(role), "clubs": clubs, "keys": keys}
|
|
|
|
|
|
def set_club_api(cur, club_id: int, enabled: bool, role: str) -> dict:
|
|
if not is_superadmin(role):
|
|
raise HTTPException(status_code=403, detail="Nur ein Superadmin gibt die Schnittstelle für einen Verein frei.")
|
|
cur.execute(
|
|
"UPDATE clubs SET distribution_api_enabled = %s WHERE id = %s RETURNING id",
|
|
(bool(enabled), int(club_id)),
|
|
)
|
|
if _one(cur) is None:
|
|
raise HTTPException(status_code=404, detail="Verein nicht gefunden")
|
|
return {"club_id": int(club_id), "api_enabled": bool(enabled)}
|
|
|
|
|
|
def create_named_key(
|
|
cur,
|
|
*,
|
|
name: str,
|
|
objects: list[str],
|
|
visibilities: list[str],
|
|
context_kind: str,
|
|
club_id: Optional[int],
|
|
profile_id: int,
|
|
role: str,
|
|
club_ids: Optional[list[int]] = None,
|
|
) -> dict:
|
|
denial = scope_denial(context_kind, objects, visibilities)
|
|
if denial:
|
|
raise HTTPException(status_code=400, detail=denial)
|
|
owner_profile = None
|
|
stored_club = None
|
|
stored_clubs: list[int] = []
|
|
if context_kind == "user":
|
|
owner_profile = int(profile_id)
|
|
if "official" in visibilities and not is_superadmin(role):
|
|
raise HTTPException(status_code=403, detail="Globale Übungen darf nur ein Superadmin auf einen Schlüssel legen.")
|
|
if "club" in visibilities:
|
|
stored_clubs = sorted({int(item) for item in (club_ids or [])})
|
|
if not stored_clubs:
|
|
raise HTTPException(status_code=400, detail="Wähle mindestens einen Verein.")
|
|
for chosen in stored_clubs:
|
|
if not has_club_role(cur, profile_id, chosen, "club_admin"):
|
|
raise HTTPException(status_code=403, detail="Du bist nicht Vereinsadmin dieses Vereins.")
|
|
if not _api_enabled(cur, chosen):
|
|
raise HTTPException(status_code=403, detail="Die API-Schnittstelle ist für diesen Verein nicht freigegeben.")
|
|
elif context_kind == "platform":
|
|
if not is_superadmin(role):
|
|
raise HTTPException(status_code=403, detail="Plattform-Schlüssel legt ein Superadmin an.")
|
|
elif context_kind == "club":
|
|
if club_id is None:
|
|
raise HTTPException(status_code=400, detail="Verein fehlt.")
|
|
stored_club = int(club_id)
|
|
stored_clubs = [stored_club]
|
|
if not has_club_role(cur, profile_id, stored_club, "club_admin"):
|
|
raise HTTPException(status_code=403, detail="Nur ein Vereinsadmin legt Schlüssel für den Verein an.")
|
|
if not _api_enabled(cur, stored_club):
|
|
raise HTTPException(status_code=403, detail="Die API-Schnittstelle ist für diesen Verein nicht freigegeben.")
|
|
elif context_kind == "personal":
|
|
owner_profile = int(profile_id)
|
|
else:
|
|
raise HTTPException(status_code=400, detail="Unbekannter Schlüsselkontext.")
|
|
|
|
label = name.strip()
|
|
cur.execute("INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id", (label,))
|
|
recipient_id = str(_one(cur)["id"])
|
|
cur.execute(
|
|
"INSERT INTO distribution_bindings (recipient_id, name) VALUES (%s, %s) RETURNING id",
|
|
(recipient_id, label),
|
|
)
|
|
binding_id = str(_one(cur)["id"])
|
|
if "official" in visibilities:
|
|
_ensure_relationship(cur, _ensure_publisher(cur, "platform", None, "Plattform"), recipient_id)
|
|
if "club" in visibilities:
|
|
for chosen in stored_clubs:
|
|
cur.execute("SELECT name FROM clubs WHERE id = %s", (chosen,))
|
|
club = _one(cur) or {}
|
|
_ensure_relationship(
|
|
cur, _ensure_publisher(cur, "club", chosen, club.get("name") or "Verein"), recipient_id
|
|
)
|
|
if "private" in visibilities:
|
|
_ensure_relationship(cur, _ensure_publisher(cur, "own", None, "Eigener Bestand"), recipient_id)
|
|
|
|
import secrets
|
|
|
|
prefix = secrets.token_hex(6)
|
|
token = f"shk.{prefix}.{secrets.token_urlsafe(32)}"
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_keys (
|
|
id, binding_id, key_prefix, secret_hash, label, objects, visibilities,
|
|
context_kind, context_club_id, context_profile_id, token_value, club_ids
|
|
) VALUES (%s, %s, %s, %s, %s, %s::text[], %s::text[], %s, %s, %s, %s, %s::int[])
|
|
""",
|
|
(
|
|
new_id(),
|
|
binding_id,
|
|
prefix,
|
|
hash_pin(token),
|
|
label,
|
|
_pg_text_array(objects),
|
|
_pg_text_array(visibilities),
|
|
context_kind,
|
|
stored_club,
|
|
owner_profile,
|
|
token,
|
|
_pg_text_array([str(item) for item in stored_clubs]) if stored_clubs else "{}",
|
|
),
|
|
)
|
|
return {"token": token, "prefix": prefix, "label": label}
|
|
|
|
|
|
def revoke_named_key(cur, key_id: str, profile_id: int, role: str) -> dict:
|
|
cur.execute(
|
|
"""
|
|
SELECT id, context_kind, context_club_id, context_profile_id
|
|
FROM distribution_keys WHERE id = %s AND revoked_at IS NULL
|
|
""",
|
|
(str(key_id),),
|
|
)
|
|
item = _one(cur)
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Schlüssel nicht gefunden")
|
|
admin_ids = _club_ids_with_role(cur, profile_id, "club_admin")
|
|
if not _key_visible(item, profile_id, role, admin_ids):
|
|
raise HTTPException(status_code=403, detail="Keine Befugnis für diesen Schlüssel.")
|
|
cur.execute("UPDATE distribution_keys SET revoked_at = NOW() WHERE id = %s", (str(key_id),))
|
|
return {"ok": True}
|
|
|
|
|
|
def _granted_club_ids(item: dict) -> set[int]:
|
|
clubs = {int(value) for value in (item.get("club_ids") or [])}
|
|
if item.get("context_club_id") is not None:
|
|
clubs.add(int(item["context_club_id"]))
|
|
return clubs
|
|
|
|
|
|
def _key_matches_exercise(item: dict, exercise: dict, profile_id: int, role: str, admin_ids: set[int], member_ids: set[int]) -> bool:
|
|
vis = (exercise.get("visibility") or "private").strip().lower()
|
|
kind = item.get("context_kind")
|
|
club_id = item.get("context_club_id")
|
|
if kind == "user":
|
|
if int(item.get("context_profile_id") or 0) != int(profile_id):
|
|
return False
|
|
if vis == "official":
|
|
return is_superadmin(role)
|
|
if vis == "club":
|
|
exercise_club = int(exercise.get("club_id") or 0)
|
|
return exercise_club in _granted_club_ids(item) and exercise_club in admin_ids
|
|
if vis == "private":
|
|
return True
|
|
return False
|
|
if vis == "official":
|
|
return kind == "platform" and is_superadmin(role)
|
|
if vis == "club":
|
|
return kind == "club" and club_id is not None and int(club_id) == int(exercise.get("club_id") or 0) and int(club_id) in admin_ids
|
|
if kind == "personal":
|
|
return int(item.get("context_profile_id") or 0) == int(profile_id)
|
|
if kind == "club":
|
|
return club_id is not None and int(club_id) in member_ids and _api_enabled_cached(item)
|
|
if kind == "platform":
|
|
return is_superadmin(role)
|
|
return False
|
|
|
|
|
|
def _api_enabled_cached(item: dict) -> bool:
|
|
return bool(item.get("api_enabled"))
|
|
|
|
|
|
def release_keys_for_exercise(cur, exercise: dict, profile_id: int, role: str) -> tuple[list[dict], Optional[str]]:
|
|
vis = (exercise.get("visibility") or "private").strip().lower()
|
|
kind = {"official": "platform", "club": "club"}.get(vis, "own")
|
|
denial = _denial_for(
|
|
cur,
|
|
exercise,
|
|
{"kind": kind, "club_id": exercise.get("club_id")},
|
|
profile_id,
|
|
role,
|
|
)
|
|
if denial:
|
|
return [], denial
|
|
if vis == "club" and exercise.get("club_id") is not None and not _api_enabled(cur, int(exercise["club_id"])):
|
|
return [], "Die API-Schnittstelle ist für diesen Verein nicht freigegeben."
|
|
admin_ids = _club_ids_with_role(cur, profile_id, "club_admin")
|
|
member_ids = _club_ids_with_role(cur, profile_id, None)
|
|
cur.execute(
|
|
"""
|
|
SELECT k.id, k.label, k.context_kind, k.context_club_id, k.context_profile_id, k.club_ids,
|
|
b.recipient_id, c.distribution_api_enabled AS api_enabled
|
|
FROM distribution_keys k
|
|
JOIN distribution_bindings b ON b.id = k.binding_id
|
|
LEFT JOIN clubs c ON c.id = k.context_club_id
|
|
WHERE k.revoked_at IS NULL
|
|
AND %s = ANY(k.visibilities)
|
|
AND 'exercise' = ANY(k.objects)
|
|
ORDER BY k.label
|
|
""",
|
|
(vis,),
|
|
)
|
|
keys = []
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
if not _key_matches_exercise(item, exercise, profile_id, role, admin_ids, member_ids):
|
|
continue
|
|
keys.append(
|
|
{
|
|
"id": str(item["id"]),
|
|
"label": item.get("label") or "Schlüssel",
|
|
"context_kind": item.get("context_kind"),
|
|
"recipient_id": str(item["recipient_id"]),
|
|
}
|
|
)
|
|
if not keys:
|
|
return [], "Für diese Übung gibt es noch keinen passenden API-Schlüssel."
|
|
return keys, None
|
|
|
|
|
|
def _latest_release_row(cur, source_id: str) -> Optional[dict]:
|
|
cur.execute(
|
|
"""
|
|
SELECT r.release_id, r.revision, r.published_at, r.manifest_text, sr.snapshot_hash
|
|
FROM distribution_releases r
|
|
JOIN distribution_source_revisions sr
|
|
ON sr.source_id = r.source_id AND sr.revision = r.revision
|
|
WHERE r.source_id = %s
|
|
ORDER BY r.revision DESC, r.published_at DESC
|
|
LIMIT 1
|
|
""",
|
|
(str(source_id),),
|
|
)
|
|
return _one(cur)
|
|
|
|
|
|
def _drift_from_row(exercise: dict, variants: list[dict], media: list[dict], row: dict) -> dict:
|
|
published = row.get("published_at")
|
|
base = {
|
|
"differs": False,
|
|
"revision": row.get("revision"),
|
|
"release_id": str(row["release_id"]),
|
|
"published_at": format_utc(published) if published and not isinstance(published, str) else published,
|
|
}
|
|
if snapshot_hash(exercise, variants, media) == row.get("snapshot_hash"):
|
|
return base
|
|
manifest = row.get("manifest_text")
|
|
if isinstance(manifest, str):
|
|
import json
|
|
|
|
manifest = json.loads(manifest)
|
|
areas = changed_areas(exercise, variants, media, manifest or {})
|
|
return {**base, "differs": True, "areas": areas or ["Weitere Angaben"]}
|
|
|
|
|
|
def exercise_release_drift(cur, exercise: dict) -> dict:
|
|
row = _latest_release_row(cur, str(exercise["public_id"]))
|
|
if not row:
|
|
return {"differs": False}
|
|
variants = _load_variants(cur, int(exercise["id"]))
|
|
media = _load_media(cur, int(exercise["id"]))
|
|
return _drift_from_row(exercise, variants, media, row)
|
|
|
|
|
|
def _may_rerelease(cur, exercise: dict, profile_id: int, role: str) -> bool:
|
|
vis = (exercise.get("visibility") or "private").strip().lower()
|
|
kind = {"official": "platform", "club": "club"}.get(vis, "own")
|
|
return _denial_for(cur, exercise, {"kind": kind, "club_id": exercise.get("club_id")}, profile_id, role) is None
|
|
|
|
|
|
def _rows_for_ids(cur, sql: str, ids: list[int]) -> list[dict]:
|
|
if not ids:
|
|
return []
|
|
placeholders = ", ".join(["%s"] * len(ids))
|
|
cur.execute(sql.format(placeholders=placeholders), tuple(ids))
|
|
return [r2d(row) for row in _rows(cur)]
|
|
|
|
|
|
def _offered_exercises(cur) -> list[dict]:
|
|
cur.execute(
|
|
"""
|
|
SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes,
|
|
equipment, duration_min, duration_max, visibility, club_id, created_by, api_offered
|
|
FROM exercises
|
|
WHERE api_offered = true
|
|
ORDER BY title, id
|
|
"""
|
|
)
|
|
return [r2d(row) for row in _rows(cur)]
|
|
|
|
|
|
def _catalog_parts(cur, exercises: list[dict]) -> tuple[dict, dict]:
|
|
ids = [int(item["id"]) for item in exercises]
|
|
variants = _rows_for_ids(
|
|
cur,
|
|
"""
|
|
SELECT id, exercise_id, public_id, variant_name, description, execution_changes, sequence_order
|
|
FROM exercise_variants
|
|
WHERE exercise_id IN ({placeholders})
|
|
ORDER BY sequence_order NULLS LAST, id
|
|
""",
|
|
ids,
|
|
)
|
|
media = _rows_for_ids(
|
|
cur,
|
|
"""
|
|
SELECT id, exercise_id, public_id, media_type, title, sort_order
|
|
FROM exercise_media
|
|
WHERE exercise_id IN ({placeholders})
|
|
ORDER BY sort_order NULLS LAST, id
|
|
""",
|
|
ids,
|
|
)
|
|
by_variant: dict[int, list] = {}
|
|
by_media: dict[int, list] = {}
|
|
for item in variants:
|
|
by_variant.setdefault(int(item["exercise_id"]), []).append(item)
|
|
for item in media:
|
|
by_media.setdefault(int(item["exercise_id"]), []).append(item)
|
|
return by_variant, by_media
|
|
|
|
|
|
def _catalog_entry(exercise: dict, variants: list[dict], media: list[dict]) -> tuple[dict, str]:
|
|
document = catalog_document(exercise, variants, media)
|
|
return document, catalog_hash(document)
|
|
|
|
|
|
def load_catalog(cur, binding: dict, cursor_token: Optional[str]) -> dict:
|
|
previous: dict = {}
|
|
if cursor_token:
|
|
snapshot_id = decode_catalog_cursor(cursor_secret(), binding["binding_id"], cursor_token)
|
|
cur.execute(
|
|
"SELECT binding_id, snapshot FROM distribution_catalog_snapshots WHERE id = %s",
|
|
(snapshot_id,),
|
|
)
|
|
stored = _one(cur)
|
|
if not stored or str(stored.get("binding_id")) != str(binding["binding_id"]):
|
|
raise InvalidCursor()
|
|
snapshot = stored.get("snapshot") or {}
|
|
if isinstance(snapshot, str):
|
|
import json
|
|
|
|
snapshot = json.loads(snapshot)
|
|
previous = {str(key): value for key, value in dict(snapshot).items()}
|
|
offered = _offered_exercises(cur)
|
|
visible = [
|
|
item
|
|
for item in offered
|
|
if catalog_available(True, grant_allows(cur, binding, item))
|
|
]
|
|
by_variant, by_media = _catalog_parts(cur, visible)
|
|
current: dict[str, str] = {}
|
|
exercises = []
|
|
for item in visible:
|
|
document, digest = _catalog_entry(
|
|
item,
|
|
by_variant.get(int(item["id"]), []),
|
|
by_media.get(int(item["id"]), []),
|
|
)
|
|
current[document["source_id"]] = digest
|
|
exercises.append(
|
|
{"source_id": document["source_id"], "title": document["title"], "content_hash": digest}
|
|
)
|
|
snapshot_id = new_id()
|
|
import json
|
|
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO distribution_catalog_snapshots (id, binding_id, snapshot)
|
|
VALUES (%s, %s, %s::jsonb)
|
|
""",
|
|
(snapshot_id, binding["binding_id"], json.dumps(current, ensure_ascii=False, sort_keys=True)),
|
|
)
|
|
return {
|
|
"exercises": exercises,
|
|
"changes": catalog_changes(previous, current),
|
|
"next_cursor": encode_catalog_cursor(cursor_secret(), binding["binding_id"], snapshot_id),
|
|
}
|
|
|
|
|
|
def load_catalog_exercise(cur, binding: dict, source_id: str) -> dict:
|
|
import uuid
|
|
|
|
try:
|
|
uuid.UUID(str(source_id))
|
|
except ValueError:
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht verfügbar."})
|
|
cur.execute(
|
|
"""
|
|
SELECT id, public_id, title, summary, goal, execution, preparation, trainer_notes,
|
|
equipment, duration_min, duration_max, visibility, club_id, created_by, api_offered
|
|
FROM exercises
|
|
WHERE public_id = %s
|
|
""",
|
|
(str(source_id),),
|
|
)
|
|
exercise = _one(cur)
|
|
in_scope = bool(exercise) and grant_allows(cur, binding, exercise)
|
|
if not exercise or not catalog_available(bool(exercise.get("api_offered")), in_scope):
|
|
raise HTTPException(status_code=404, detail={"code": "not_found", "message": "Übung nicht verfügbar."})
|
|
by_variant, by_media = _catalog_parts(cur, [exercise])
|
|
document, digest = _catalog_entry(
|
|
exercise,
|
|
by_variant.get(int(exercise["id"]), []),
|
|
by_media.get(int(exercise["id"]), []),
|
|
)
|
|
return {**document, "content_hash": digest}
|
|
|
|
|
|
def list_release_drift(cur, profile_id: int, role: str) -> list[dict]:
|
|
cur.execute(
|
|
"""
|
|
SELECT DISTINCT ON (e.id)
|
|
e.id, e.public_id, e.title, e.summary, e.goal, e.execution, e.preparation,
|
|
e.trainer_notes, e.equipment, e.duration_min, e.duration_max, e.status,
|
|
e.visibility, e.club_id, e.exercise_kind, e.created_by,
|
|
c.name AS club_name,
|
|
r.release_id, r.revision, r.published_at, r.manifest_text, sr.snapshot_hash
|
|
FROM exercises e
|
|
JOIN distribution_releases r ON r.source_id = e.public_id
|
|
JOIN distribution_source_revisions sr
|
|
ON sr.source_id = r.source_id AND sr.revision = r.revision
|
|
LEFT JOIN clubs c ON c.id = e.club_id
|
|
ORDER BY e.id, r.revision DESC, r.published_at DESC
|
|
"""
|
|
)
|
|
rows = [r2d(row) for row in _rows(cur)]
|
|
items = []
|
|
for exercise in rows:
|
|
if not _may_rerelease(cur, exercise, profile_id, role):
|
|
continue
|
|
variants = _load_variants(cur, int(exercise["id"]))
|
|
media = _load_media(cur, int(exercise["id"]))
|
|
drift = _drift_from_row(exercise, variants, media, exercise)
|
|
if not drift["differs"]:
|
|
continue
|
|
vis = (exercise.get("visibility") or "private").strip().lower()
|
|
items.append(
|
|
{
|
|
"exercise_id": int(exercise["id"]),
|
|
"title": exercise.get("title") or "Übung",
|
|
"visibility": vis,
|
|
"club_name": exercise.get("club_name"),
|
|
"revision": drift["revision"],
|
|
"published_at": drift["published_at"],
|
|
"areas": drift["areas"],
|
|
}
|
|
)
|
|
items.sort(key=lambda item: (item["title"] or "").lower())
|
|
return items
|
|
|
|
|
|
def target_for_key(cur, exercise_id: int, key_id: str, profile_id: int, role: str) -> tuple[str, str]:
|
|
exercise = _load_exercise(cur, exercise_id)
|
|
keys, block = release_keys_for_exercise(cur, exercise, profile_id, role)
|
|
match = next((item for item in keys if item["id"] == str(key_id)), None)
|
|
if not match:
|
|
raise HTTPException(status_code=403, detail=block or "Dieser Schlüssel darf diese Übung nicht empfangen.")
|
|
vis = (exercise.get("visibility") or "private").strip().lower()
|
|
if vis == "official":
|
|
publisher_id = _ensure_publisher(cur, "platform", None, "Plattform")
|
|
elif vis == "club":
|
|
cur.execute("SELECT name FROM clubs WHERE id = %s", (int(exercise["club_id"]),))
|
|
club = _one(cur) or {}
|
|
publisher_id = _ensure_publisher(cur, "club", int(exercise["club_id"]), club.get("name") or "Verein")
|
|
else:
|
|
publisher_id = _ensure_publisher(cur, "own", None, "Eigener Bestand")
|
|
_ensure_relationship(cur, publisher_id, match["recipient_id"])
|
|
return publisher_id, match["recipient_id"]
|