Publish frozen exercise releases and report whether they stay offerable.
Deploy Development / deploy (push) Successful in 1m12s
Test Suite / pytest-backend (push) Failing after 30s
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
Deploy Development / deploy (push) Successful in 1m12s
Test Suite / pytest-backend (push) Failing after 30s
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
Recipients can ask whether a released exercise is still offerable. Archiving or removing the source stops new offers; the frozen copy stays fetchable until withdrawal. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b537750671
commit
fe3633ba8b
21 files changed
+3862
-12
No files matched your search
@@ -0,0 +1,627 @@
|
||||
"""Vertrag v1: kanonisches Manifest, Ereignisse, Freigaberegeln, Cursor.
|
||||
|
||||
Reine Funktionen. Die Datenbankschicht ruft sie auf, die Tests prüfen sie ohne Postgres.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from html import unescape
|
||||
from typing import Any, Iterable, Optional
|
||||
|
||||
PART_ROLES = (
|
||||
"goal",
|
||||
"prerequisites",
|
||||
"preparation",
|
||||
"instructions",
|
||||
"trainer_notes",
|
||||
"equipment",
|
||||
"duration_note",
|
||||
)
|
||||
ASSET_ROLES = ("demonstration", "worksheet", "illustration")
|
||||
ACTIONS = (
|
||||
"store",
|
||||
"render",
|
||||
"stream",
|
||||
"download",
|
||||
"print",
|
||||
"course_display",
|
||||
"commercial_course_use",
|
||||
"adapt",
|
||||
"public_preview",
|
||||
"grant_customer_use",
|
||||
)
|
||||
REASON_CODES = ("rights", "safety", "privacy", "expired", "editorial_error")
|
||||
WITHDRAW_TYPES = ("release.withdrawn", "variant.withdrawn", "asset.withdrawn")
|
||||
EVENT_TYPES = ("release.published", "release.retired", *WITHDRAW_TYPES)
|
||||
|
||||
_TAG = re.compile(r"<[^>]+>")
|
||||
_MEDIA_TOKEN = re.compile(r"\{\{exerciseMedia:(\d+)\}\}")
|
||||
_DATA_MEDIA = re.compile(r'data-exercise-media-id=["\'](\d+)["\']', re.I)
|
||||
|
||||
LEGAL_HOLD_REASON = {
|
||||
"rights_dispute": "rights",
|
||||
"copyright_complaint": "rights",
|
||||
"consent_withdrawn": "privacy",
|
||||
"privacy_complaint": "privacy",
|
||||
"youth_protection": "safety",
|
||||
"illegal_content": "safety",
|
||||
"other": "safety",
|
||||
}
|
||||
|
||||
OFFICIAL_WRITE_DENIED = "Globale Übungen dürfen nur von Superadmins bearbeitet werden."
|
||||
RATE_LIMIT_PER_MINUTE = 60
|
||||
|
||||
|
||||
def distribution_enabled() -> bool:
|
||||
return os.getenv("DISTRIBUTION_ENABLED", "").strip().lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
def cursor_secret() -> str:
|
||||
secret = os.getenv("DISTRIBUTION_CURSOR_SECRET", "").strip()
|
||||
if secret:
|
||||
return secret
|
||||
if os.getenv("ENVIRONMENT", "development").strip().lower() in ("production", "prod"):
|
||||
raise RuntimeError("DISTRIBUTION_CURSOR_SECRET fehlt")
|
||||
return "shinkan-distribution-dev-cursor"
|
||||
|
||||
|
||||
def format_utc(dt: datetime) -> str:
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def parse_utc(value: str) -> datetime:
|
||||
raw = value.strip()
|
||||
if raw.endswith("Z"):
|
||||
raw = raw[:-1] + "+00:00"
|
||||
parsed = datetime.fromisoformat(raw)
|
||||
if parsed.tzinfo is None:
|
||||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def canonical_json(value: Any) -> bytes:
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _copy_if(source: dict, key: str, required: bool = False, keep_null: bool = False) -> Any:
|
||||
if key not in source:
|
||||
if required:
|
||||
raise ValueError(f"Feld fehlt: {key}")
|
||||
return None
|
||||
value = source[key]
|
||||
if value is None and not keep_null:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def order_manifest(source: dict) -> dict:
|
||||
"""Feldreihenfolge des Übergabevertrags. Optionale leere Felder entfallen, null bleibt bei Fristen."""
|
||||
exercise = source["exercise"]
|
||||
ordered_exercise: dict[str, Any] = {"title": exercise["title"]}
|
||||
if exercise.get("summary") is not None:
|
||||
ordered_exercise["summary"] = exercise["summary"]
|
||||
if exercise.get("audience") is not None:
|
||||
ordered_exercise["audience"] = exercise["audience"]
|
||||
ordered_exercise["rights_id"] = exercise["rights_id"]
|
||||
ordered_exercise["parts"] = [
|
||||
{
|
||||
"id": part["id"],
|
||||
"role": part["role"],
|
||||
"text": part["text"],
|
||||
"rights_id": part["rights_id"],
|
||||
}
|
||||
for part in exercise["parts"]
|
||||
]
|
||||
assets = []
|
||||
for asset in exercise["assets"]:
|
||||
item = {
|
||||
"id": asset["id"],
|
||||
"role": asset["role"],
|
||||
"media_type": asset["media_type"],
|
||||
"size_bytes": asset["size_bytes"],
|
||||
"sha256": asset["sha256"],
|
||||
"rights_id": asset["rights_id"],
|
||||
}
|
||||
if asset.get("label") is not None:
|
||||
item["label"] = asset["label"]
|
||||
assets.append(item)
|
||||
ordered_exercise["assets"] = assets
|
||||
ordered_exercise["common_part_ids"] = list(exercise["common_part_ids"])
|
||||
ordered_exercise["common_asset_ids"] = list(exercise["common_asset_ids"])
|
||||
ordered_exercise["variants"] = [
|
||||
{
|
||||
"id": variant["id"],
|
||||
"label": variant["label"],
|
||||
"part_ids": list(variant["part_ids"]),
|
||||
"asset_ids": list(variant["asset_ids"]),
|
||||
}
|
||||
for variant in exercise["variants"]
|
||||
]
|
||||
rights = []
|
||||
for right in source["rights"]:
|
||||
item = {
|
||||
"id": right["id"],
|
||||
"evidence_ref": right["evidence_ref"],
|
||||
"actions": list(right["actions"]),
|
||||
"territories": right["territories"],
|
||||
"valid_from": right["valid_from"],
|
||||
"valid_until": right["valid_until"],
|
||||
}
|
||||
if right.get("attribution") is not None:
|
||||
item["attribution"] = right["attribution"]
|
||||
rights.append(item)
|
||||
return {
|
||||
"schema_version": source["schema_version"],
|
||||
"resource_type": source["resource_type"],
|
||||
"release_id": source["release_id"],
|
||||
"source_id": source["source_id"],
|
||||
"revision": source["revision"],
|
||||
"publisher_id": source["publisher_id"],
|
||||
"published_at": source["published_at"],
|
||||
"exercise": ordered_exercise,
|
||||
"rights": rights,
|
||||
}
|
||||
|
||||
|
||||
def manifest_bytes(source: dict) -> bytes:
|
||||
return canonical_json(order_manifest(source))
|
||||
|
||||
|
||||
def order_event(event: dict) -> dict:
|
||||
ordered = {
|
||||
"event_id": event["event_id"],
|
||||
"type": event["type"],
|
||||
"release_id": event["release_id"],
|
||||
"occurred_at": event["occurred_at"],
|
||||
}
|
||||
if event["type"] == "release.published":
|
||||
ordered["source_id"] = event["source_id"]
|
||||
ordered["revision"] = event["revision"]
|
||||
ordered["manifest_sha256"] = event["manifest_sha256"]
|
||||
elif event["type"] in WITHDRAW_TYPES:
|
||||
if event["type"] != "release.withdrawn":
|
||||
ordered["target_id"] = event["target_id"]
|
||||
ordered["reason_code"] = event["reason_code"]
|
||||
return ordered
|
||||
|
||||
|
||||
def encode_cursor(secret: str, recipient_id: str, seq: int) -> str:
|
||||
payload = f"{recipient_id}:{int(seq)}".encode("utf-8")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
|
||||
raw = payload + b"." + sig.encode("ascii")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(secret: str, recipient_id: str, token: Optional[str]) -> int:
|
||||
if token is None or token == "":
|
||||
return 0
|
||||
pad = "=" * (-len(token) % 4)
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token + pad)
|
||||
payload, sig = raw.rsplit(b".", 1)
|
||||
expected = hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest().encode("ascii")
|
||||
if not hmac.compare_digest(sig, expected):
|
||||
raise ValueError("sig")
|
||||
rec, seq_raw = payload.decode("utf-8").split(":", 1)
|
||||
if rec != recipient_id:
|
||||
raise ValueError("channel")
|
||||
seq = int(seq_raw)
|
||||
if seq < 0:
|
||||
raise ValueError("seq")
|
||||
return seq
|
||||
except Exception as exc:
|
||||
raise InvalidCursor() from exc
|
||||
|
||||
|
||||
class InvalidCursor(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def official_write_allowed(visibility: Optional[str], role: Optional[str]) -> bool:
|
||||
if (visibility or "").strip().lower() != "official":
|
||||
return True
|
||||
return (role or "").strip().lower() == "superadmin"
|
||||
|
||||
|
||||
def _same_club(left: Any, right: Any) -> bool:
|
||||
try:
|
||||
return left is not None and right is not None and int(left) == int(right)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def release_denial(
|
||||
*,
|
||||
visibility: Optional[str],
|
||||
role: Optional[str],
|
||||
publisher_kind: str,
|
||||
is_owner: bool,
|
||||
is_club_admin: bool,
|
||||
publisher_club_id: Any = None,
|
||||
exercise_club_id: Any = None,
|
||||
) -> Optional[str]:
|
||||
"""Freigabe folgt der Zugehörigkeit der Übung, nicht einer gesonderten Zuordnungsliste."""
|
||||
vis = (visibility or "").strip().lower()
|
||||
role_l = (role or "").strip().lower()
|
||||
kind = (publisher_kind or "").strip().lower()
|
||||
if vis == "official":
|
||||
if role_l != "superadmin":
|
||||
return "Globale Übungen dürfen nur von Superadmins freigegeben werden."
|
||||
if kind != "platform":
|
||||
return "Globale Übungen werden nur über den Plattformbestand freigegeben."
|
||||
return None
|
||||
if kind == "platform":
|
||||
return "Der Plattformbestand gibt nur globale Übungen frei."
|
||||
if vis == "private":
|
||||
if not is_owner:
|
||||
return "Private Übungen gibt nur die Person frei, der sie gehören."
|
||||
if kind != "own":
|
||||
return "Private Übungen werden über den eigenen Bestand freigegeben."
|
||||
return None
|
||||
if vis == "club":
|
||||
if not is_club_admin:
|
||||
return "Vereinsübungen gibt ein Vereinsadmin dieses Vereins frei."
|
||||
if kind != "club" or not _same_club(publisher_club_id, exercise_club_id):
|
||||
return "Vereinsübungen werden über den Bestand dieses Vereins freigegeben."
|
||||
return None
|
||||
return "Diese Übung kann so nicht freigegeben werden."
|
||||
|
||||
|
||||
def can_withdraw(*, role: Optional[str], denial: Optional[str]) -> bool:
|
||||
if (role or "").strip().lower() == "superadmin":
|
||||
return True
|
||||
return denial is None
|
||||
|
||||
|
||||
def package_state(*, fetch_blocked: bool, retired: bool) -> str:
|
||||
if fetch_blocked:
|
||||
return "withdrawn"
|
||||
if retired:
|
||||
return "retired"
|
||||
return "available"
|
||||
|
||||
|
||||
def exercise_offerable(source_status: Optional[str], package_states: Iterable[str]) -> tuple[str, bool]:
|
||||
"""Die eingefrorene Kopie bleibt abrufbar. Neu anbieten darf der Empfänger sie nur, solange die Quelle approved und ein Paket verfügbar ist."""
|
||||
status = "deleted" if not (source_status or "").strip() else str(source_status).strip().lower()
|
||||
states = list(package_states)
|
||||
return status, status == "approved" and any(item == "available" for item in states)
|
||||
|
||||
|
||||
def decide_confirm(stored_release_id: Optional[str], new_release_id: str) -> tuple[str, bool]:
|
||||
"""Technische Wiederholung liefert die gespeicherte Paket-ID. Eine neue Bestätigung legt ein Paket an."""
|
||||
if stored_release_id:
|
||||
return stored_release_id, False
|
||||
return new_release_id, True
|
||||
|
||||
|
||||
def rate_decision(hits: int, window_age_seconds: float, limit: int = RATE_LIMIT_PER_MINUTE) -> tuple[int, bool]:
|
||||
if window_age_seconds >= 60:
|
||||
return 1, False
|
||||
if hits >= limit:
|
||||
return hits, True
|
||||
return hits + 1, False
|
||||
|
||||
|
||||
def plaintext(value: Optional[str]) -> str:
|
||||
text = value or ""
|
||||
text = _MEDIA_TOKEN.sub("", text)
|
||||
text = _DATA_MEDIA.sub("", text)
|
||||
text = _TAG.sub("", text)
|
||||
return unescape(text).strip()
|
||||
|
||||
|
||||
def inline_media_ids(value: Optional[str]) -> set[int]:
|
||||
if not value:
|
||||
return set()
|
||||
ids = {int(item) for item in _MEDIA_TOKEN.findall(value)}
|
||||
ids.update(int(item) for item in _DATA_MEDIA.findall(value))
|
||||
return ids
|
||||
|
||||
|
||||
def snapshot_hash(exercise: dict, variants: list[dict], media: list[dict]) -> str:
|
||||
body = {
|
||||
"title": exercise.get("title") or "",
|
||||
"summary": exercise.get("summary") or "",
|
||||
"goal": exercise.get("goal") or "",
|
||||
"execution": exercise.get("execution") or "",
|
||||
"preparation": exercise.get("preparation") or "",
|
||||
"trainer_notes": exercise.get("trainer_notes") or "",
|
||||
"equipment": exercise.get("equipment"),
|
||||
"duration_min": exercise.get("duration_min"),
|
||||
"duration_max": exercise.get("duration_max"),
|
||||
"status": exercise.get("status"),
|
||||
"exercise_kind": exercise.get("exercise_kind") or "simple",
|
||||
"variants": [
|
||||
{
|
||||
"id": str(item.get("public_id")),
|
||||
"name": item.get("variant_name") or "",
|
||||
"description": item.get("description") or "",
|
||||
"execution_changes": item.get("execution_changes") or "",
|
||||
"duration_min": item.get("duration_min"),
|
||||
"duration_max": item.get("duration_max"),
|
||||
}
|
||||
for item in variants
|
||||
],
|
||||
"media": [
|
||||
{
|
||||
"id": str(item.get("public_id")),
|
||||
"sha256": item.get("sha256") or "",
|
||||
"media_type": item.get("media_type") or "",
|
||||
}
|
||||
for item in media
|
||||
],
|
||||
}
|
||||
return sha256_bytes(canonical_json(body))
|
||||
|
||||
|
||||
def _duration_note(exercise: dict) -> Optional[str]:
|
||||
low = exercise.get("duration_min")
|
||||
high = exercise.get("duration_max")
|
||||
if low and high:
|
||||
return f"{low}–{high} Minuten"
|
||||
if low or high:
|
||||
return f"{low or high} Minuten"
|
||||
return None
|
||||
|
||||
|
||||
def _equipment_text(exercise: dict) -> Optional[str]:
|
||||
raw = exercise.get("equipment")
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
raw = [raw] if raw.strip() else []
|
||||
if isinstance(raw, list):
|
||||
parts = [str(item).strip() for item in raw if str(item).strip()]
|
||||
return ", ".join(parts) or None
|
||||
return None
|
||||
|
||||
|
||||
def default_cut(exercise: dict, variants: list[dict], media: list[dict]) -> dict:
|
||||
parts: list[dict] = []
|
||||
|
||||
def add(key: str, role: str, text: Optional[str]) -> None:
|
||||
cleaned = plaintext(text)
|
||||
if cleaned:
|
||||
parts.append({"key": key, "role": role, "text": cleaned})
|
||||
|
||||
add("field:goal", "goal", exercise.get("goal"))
|
||||
add("field:preparation", "preparation", exercise.get("preparation"))
|
||||
add("field:trainer_notes", "trainer_notes", exercise.get("trainer_notes"))
|
||||
add("field:equipment", "equipment", _equipment_text(exercise))
|
||||
add("field:duration", "duration_note", _duration_note(exercise))
|
||||
common_keys = [part["key"] for part in parts]
|
||||
variant_rows = []
|
||||
if variants:
|
||||
for variant in variants:
|
||||
key = f"variant:{variant['public_id']}:instructions"
|
||||
text = plaintext(exercise.get("execution"))
|
||||
extra = plaintext(variant.get("execution_changes"))
|
||||
combined = "\n".join(piece for piece in (text, extra) if piece)
|
||||
if combined:
|
||||
parts.append({"key": key, "role": "instructions", "text": combined})
|
||||
variant_rows.append(
|
||||
{
|
||||
"key": str(variant["public_id"]),
|
||||
"label": variant.get("variant_name") or "Variante",
|
||||
"part_keys": [key] if combined else [],
|
||||
"media_ids": [],
|
||||
}
|
||||
)
|
||||
else:
|
||||
key = "variant:default:instructions"
|
||||
text = plaintext(exercise.get("execution"))
|
||||
if text:
|
||||
parts.append({"key": key, "role": "instructions", "text": text})
|
||||
variant_rows.append(
|
||||
{
|
||||
"key": "default",
|
||||
"label": "Standard",
|
||||
"part_keys": [key] if text else [],
|
||||
"media_ids": [],
|
||||
}
|
||||
)
|
||||
assets = []
|
||||
for item in media:
|
||||
kind = (item.get("media_type") or "").lower()
|
||||
if kind == "video":
|
||||
role = "demonstration"
|
||||
elif kind in ("document", "pdf"):
|
||||
role = "worksheet"
|
||||
else:
|
||||
role = "illustration"
|
||||
assets.append(
|
||||
{
|
||||
"media_id": str(item["public_id"]),
|
||||
"role": role,
|
||||
"label": item.get("title") or None,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": exercise.get("title") or "",
|
||||
"summary": plaintext(exercise.get("summary")) or None,
|
||||
"audience": None,
|
||||
"rights": [],
|
||||
"parts": parts,
|
||||
"assets": assets,
|
||||
"common_part_keys": common_keys,
|
||||
"common_media_ids": [],
|
||||
"variants": variant_rows,
|
||||
}
|
||||
|
||||
|
||||
def cut_hash(cut: dict) -> str:
|
||||
return sha256_bytes(canonical_json(cut))
|
||||
|
||||
|
||||
def collect_blockers(exercise: dict, variants: list[dict], media: list[dict], cut: dict, now: datetime) -> list[str]:
|
||||
blockers: list[str] = []
|
||||
if (exercise.get("exercise_kind") or "simple") != "simple":
|
||||
blockers.append("Kombinationsübungen können in dieser Fassung nicht herausgegeben werden.")
|
||||
if (exercise.get("status") or "") != "approved":
|
||||
blockers.append("Nur Übungen mit Status approved können freigegeben werden.")
|
||||
texts = " ".join(
|
||||
str(exercise.get(field) or "")
|
||||
for field in ("goal", "execution", "preparation", "trainer_notes", "summary")
|
||||
)
|
||||
selected_media = {str(item.get("media_id")) for item in cut.get("assets") or []}
|
||||
known_media = {str(item.get("public_id")): item for item in media}
|
||||
referenced = inline_media_ids(texts)
|
||||
for media_id in referenced:
|
||||
match = next((item for item in media if int(item.get("id") or 0) == media_id), None)
|
||||
if match is None or str(match.get("public_id")) not in selected_media:
|
||||
blockers.append("Ein Medienanker im Text ist nicht als Medium im Paket enthalten.")
|
||||
break
|
||||
part_keys = [part.get("key") for part in cut.get("parts") or []]
|
||||
if len(part_keys) != len(set(part_keys)):
|
||||
blockers.append("Teilschlüssel sind nicht eindeutig.")
|
||||
if not any(part.get("role") == "goal" and str(part.get("text") or "").strip() for part in cut.get("parts") or []):
|
||||
blockers.append("Das Paket braucht ein Lernziel.")
|
||||
rights = {item.get("id"): item for item in cut.get("rights") or []}
|
||||
if None in rights or "" in rights:
|
||||
blockers.append("Jeder Rechtevermerk braucht eine Kennung.")
|
||||
for right in cut.get("rights") or []:
|
||||
actions = set(right.get("actions") or [])
|
||||
unknown = actions - set(ACTIONS)
|
||||
if unknown:
|
||||
blockers.append("Unbekannte Nutzungsaktion im Rechtevermerk.")
|
||||
if "store" not in actions:
|
||||
blockers.append("Jeder Rechtevermerk muss die Übernahme erlauben.")
|
||||
if not str(right.get("evidence_ref") or "").strip():
|
||||
blockers.append("Jeder Rechtevermerk braucht eine Nachweisreferenz.")
|
||||
try:
|
||||
start = parse_utc(right["valid_from"])
|
||||
except Exception:
|
||||
blockers.append("valid_from ist kein UTC-Zeitpunkt.")
|
||||
continue
|
||||
until_raw = right.get("valid_until")
|
||||
until = None
|
||||
if until_raw is not None:
|
||||
try:
|
||||
until = parse_utc(until_raw)
|
||||
except Exception:
|
||||
blockers.append("valid_until ist kein UTC-Zeitpunkt.")
|
||||
continue
|
||||
if start > now or (until is not None and not (start <= now < until)):
|
||||
blockers.append("Ein Rechtevermerk ist zum Freigabezeitpunkt nicht wirksam.")
|
||||
territories = right.get("territories")
|
||||
if territories is not None:
|
||||
if not isinstance(territories, list) or any(not re.fullmatch(r"[A-Z]{2}", str(code)) for code in territories):
|
||||
blockers.append("territories sind ISO-Ländercodes oder null.")
|
||||
editorial = cut.get("editorial_rights_id")
|
||||
if editorial not in rights:
|
||||
blockers.append("Die redaktionellen Angaben brauchen einen Rechtevermerk.")
|
||||
used_parts: set[str] = set(cut.get("common_part_keys") or [])
|
||||
used_media: set[str] = set(str(item) for item in (cut.get("common_media_ids") or []))
|
||||
variant_keys = []
|
||||
for variant in cut.get("variants") or []:
|
||||
variant_keys.append(variant.get("key"))
|
||||
used_parts.update(variant.get("part_keys") or [])
|
||||
used_media.update(str(item) for item in (variant.get("media_ids") or []))
|
||||
for key in variant.get("part_keys") or []:
|
||||
if key not in part_keys:
|
||||
blockers.append("Eine Variante verweist auf einen unbekannten Teil.")
|
||||
for media_id in variant.get("media_ids") or []:
|
||||
if str(media_id) not in selected_media:
|
||||
blockers.append("Eine Variante verweist auf ein unbekanntes Medium.")
|
||||
for key in cut.get("common_part_keys") or []:
|
||||
if key not in part_keys:
|
||||
blockers.append("Ein gemeinsamer Teil ist unbekannt.")
|
||||
for media_id in cut.get("common_media_ids") or []:
|
||||
if str(media_id) not in selected_media:
|
||||
blockers.append("Ein gemeinsames Medium ist unbekannt.")
|
||||
if len(variant_keys) != len(set(variant_keys)) or not variant_keys:
|
||||
blockers.append("Das Paket braucht mindestens eine Variante.")
|
||||
for part in cut.get("parts") or []:
|
||||
if part.get("role") not in PART_ROLES:
|
||||
blockers.append("Unbekannte Textrolle.")
|
||||
if part.get("key") not in used_parts:
|
||||
blockers.append("Ein Textteil hängt an keiner Variante.")
|
||||
if part.get("rights_id") not in rights:
|
||||
blockers.append("Ein Textteil hat keinen wirksamen Rechtevermerk.")
|
||||
for asset in cut.get("assets") or []:
|
||||
media_id = str(asset.get("media_id"))
|
||||
if media_id not in used_media:
|
||||
blockers.append("Ein Medium hängt an keiner Variante.")
|
||||
if asset.get("role") not in ASSET_ROLES:
|
||||
blockers.append("Unbekannte Medienrolle.")
|
||||
if asset.get("rights_id") not in rights:
|
||||
blockers.append("Ein Medium hat keinen wirksamen Rechtevermerk.")
|
||||
stored = known_media.get(media_id)
|
||||
if stored is None:
|
||||
blockers.append("Ein ausgewähltes Medium gehört nicht zu dieser Übung.")
|
||||
continue
|
||||
if stored.get("legal_hold_active"):
|
||||
blockers.append("Ein ausgewähltes Medium ist gesperrt.")
|
||||
if not stored.get("file_path"):
|
||||
blockers.append("Ein ausgewähltes Medium hat keine gespeicherten Bytes.")
|
||||
if (stored.get("rights_status") or "legacy_unreviewed") in ("legacy_unreviewed", "blocked", ""):
|
||||
blockers.append("Die Upload-Erklärung eines Mediums trägt die Herausgabe nicht.")
|
||||
if variants:
|
||||
known_variant_ids = {str(item.get("public_id")) for item in variants}
|
||||
for variant in cut.get("variants") or []:
|
||||
if variant.get("key") not in known_variant_ids and variant.get("key") != "default":
|
||||
blockers.append("Eine Variante gehört nicht zur Übung.")
|
||||
return list(dict.fromkeys(blockers))
|
||||
|
||||
|
||||
def resolved_asset_ids(manifest: dict, variant_id: str) -> set[str]:
|
||||
exercise = manifest["exercise"]
|
||||
variant = next(item for item in exercise["variants"] if item["id"] == variant_id)
|
||||
return set(exercise["common_asset_ids"]) | set(variant["asset_ids"])
|
||||
|
||||
|
||||
def package_fetch_blocked(events: Iterable[dict], release_id: str) -> bool:
|
||||
return any(
|
||||
event.get("type") in WITHDRAW_TYPES and event.get("release_id") == release_id
|
||||
for event in events
|
||||
)
|
||||
|
||||
|
||||
def retrievable_release_ids(events: Iterable[dict]) -> set[str]:
|
||||
published: set[str] = set()
|
||||
blocked: set[str] = set()
|
||||
for event in events:
|
||||
if event.get("type") == "release.published":
|
||||
published.add(event["release_id"])
|
||||
elif event.get("type") in WITHDRAW_TYPES:
|
||||
blocked.add(event["release_id"])
|
||||
return published - blocked
|
||||
|
||||
|
||||
def plan_available(plan: dict, manifest: dict, events: Iterable[dict]) -> bool:
|
||||
release_id = plan["release_id"]
|
||||
variant_id = plan["variant_id"]
|
||||
relevant = [event for event in events if event.get("release_id") == release_id]
|
||||
if any(event.get("type") == "release.withdrawn" for event in relevant):
|
||||
return False
|
||||
if any(event.get("type") == "variant.withdrawn" and event.get("target_id") == variant_id for event in relevant):
|
||||
return False
|
||||
withdrawn_assets = {
|
||||
event["target_id"] for event in relevant if event.get("type") == "asset.withdrawn"
|
||||
}
|
||||
if withdrawn_assets & resolved_asset_ids(manifest, variant_id):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def actions_cover(actions: Iterable[str], required: Iterable[str]) -> bool:
|
||||
return set(required).issubset(set(actions))
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -243,7 +243,7 @@ def read_root():
|
||||
return out
|
||||
|
||||
# Register routers
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin
|
||||
from routers import auth, profiles, exercises, exercise_progression_graphs, clubs, club_memberships, club_join_requests, club_creation_requests, admin_users, admin_user_content, admin_rights, me_entitlements, platform_media_storage, media_assets, skills, skill_profiles, training_planning, planning_exercise_suggest, dashboard, training_modules, training_framework_programs, catalogs, catalog_prompt_slots, maturity_models, matrix_stack_bundle, matrix_editor, import_wiki, import_wiki_admin, legal_documents, content_reports, ai_prompts_admin, ai_skill_retrieval_admin, exercise_enrichment_admin, openrouter_admin, distribution
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(profiles.router)
|
||||
@@ -281,6 +281,8 @@ app.include_router(ai_prompts_admin.router)
|
||||
app.include_router(openrouter_admin.router)
|
||||
app.include_router(ai_skill_retrieval_admin.router)
|
||||
app.include_router(exercise_enrichment_admin.router)
|
||||
app.include_router(distribution.router)
|
||||
app.include_router(distribution.editorial)
|
||||
|
||||
# Lokale Übungs-Medien: standardmäßig nur über geschützten API-Pfad
|
||||
# GET /api/exercises/{id}/media/{mid}/file (?ssetoken = kurzlebiges Medien-Token, kein Sitzungstoken).
|
||||
|
||||
@@ -134,6 +134,10 @@ def set_legal_hold(
|
||||
updated_row = cur.fetchone()
|
||||
updated = r2d(updated_row)
|
||||
|
||||
from distribution_service import withdraw_assets_for_media_asset
|
||||
|
||||
withdraw_assets_for_media_asset(cur, asset_id, reason_code)
|
||||
|
||||
write_audit_log_entry(
|
||||
cur,
|
||||
asset_id=asset_id,
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
-- Distribution v1: eingefrorene Übungspakete für Empfängerkanäle.
|
||||
-- Produktiver Abruf bleibt über DISTRIBUTION_ENABLED aus, bis die Testinstanz ihn einschaltet.
|
||||
|
||||
ALTER TABLE exercises
|
||||
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||
|
||||
UPDATE exercises SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||
|
||||
ALTER TABLE exercises
|
||||
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||
|
||||
ALTER TABLE exercises
|
||||
ALTER COLUMN public_id SET NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercises_public_id ON exercises (public_id);
|
||||
|
||||
ALTER TABLE exercise_variants
|
||||
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||
|
||||
UPDATE exercise_variants SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||
|
||||
ALTER TABLE exercise_variants
|
||||
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||
|
||||
ALTER TABLE exercise_variants
|
||||
ALTER COLUMN public_id SET NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_variants_public_id ON exercise_variants (public_id);
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ADD COLUMN IF NOT EXISTS public_id UUID;
|
||||
|
||||
UPDATE exercise_media SET public_id = gen_random_uuid() WHERE public_id IS NULL;
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ALTER COLUMN public_id SET DEFAULT gen_random_uuid();
|
||||
|
||||
ALTER TABLE exercise_media
|
||||
ALTER COLUMN public_id SET NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_exercise_media_public_id ON exercise_media (public_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_publishers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('platform', 'own', 'club')),
|
||||
club_id INT REFERENCES clubs (id),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT distribution_publishers_kind_club CHECK (
|
||||
(kind = 'club' AND club_id IS NOT NULL)
|
||||
OR (kind <> 'club' AND club_id IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_distribution_platform_publisher
|
||||
ON distribution_publishers (kind)
|
||||
WHERE kind = 'platform';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_recipients (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_relationships (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
UNIQUE (publisher_id, recipient_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_bindings (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
name TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_keys (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
binding_id UUID NOT NULL REFERENCES distribution_bindings (id),
|
||||
key_prefix TEXT NOT NULL UNIQUE,
|
||||
secret_hash TEXT NOT NULL,
|
||||
expires_at TIMESTAMPTZ,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_releasers (
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
profile_id INT NOT NULL REFERENCES profiles (id),
|
||||
PRIMARY KEY (publisher_id, profile_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_publisher_exercises (
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
exercise_id INT NOT NULL REFERENCES exercises (id),
|
||||
PRIMARY KEY (publisher_id, exercise_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_part_identities (
|
||||
source_id UUID NOT NULL,
|
||||
part_key TEXT NOT NULL,
|
||||
part_id UUID NOT NULL,
|
||||
PRIMARY KEY (source_id, part_key)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_source_revisions (
|
||||
source_id UUID NOT NULL,
|
||||
revision INT NOT NULL CHECK (revision > 0),
|
||||
snapshot_hash TEXT NOT NULL,
|
||||
PRIMARY KEY (source_id, revision),
|
||||
UNIQUE (source_id, snapshot_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_drafts (
|
||||
id UUID PRIMARY KEY,
|
||||
exercise_id INT NOT NULL REFERENCES exercises (id),
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
prepared_by INT NOT NULL REFERENCES profiles (id),
|
||||
cut JSONB NOT NULL,
|
||||
preview_hash TEXT NOT NULL,
|
||||
release_id UUID,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
confirmed_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_releases (
|
||||
release_id UUID PRIMARY KEY,
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
source_id UUID NOT NULL,
|
||||
revision INT NOT NULL,
|
||||
cut_hash TEXT NOT NULL,
|
||||
manifest_text TEXT NOT NULL,
|
||||
manifest_sha256 TEXT NOT NULL,
|
||||
published_at TIMESTAMPTZ NOT NULL,
|
||||
fetch_blocked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
confirmed_by INT REFERENCES profiles (id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_releases_source ON distribution_releases (source_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_releases_recipient ON distribution_releases (recipient_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_release_assets (
|
||||
release_id UUID NOT NULL REFERENCES distribution_releases (release_id),
|
||||
asset_id UUID NOT NULL,
|
||||
sha256 TEXT NOT NULL,
|
||||
size_bytes INT NOT NULL,
|
||||
media_type TEXT NOT NULL,
|
||||
storage_path TEXT NOT NULL,
|
||||
source_media_public_id UUID,
|
||||
source_asset_id INT,
|
||||
PRIMARY KEY (release_id, asset_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_release_assets_source
|
||||
ON distribution_release_assets (source_asset_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_events (
|
||||
event_id UUID PRIMARY KEY,
|
||||
recipient_id UUID NOT NULL REFERENCES distribution_recipients (id),
|
||||
seq BIGINT NOT NULL,
|
||||
event_type TEXT NOT NULL,
|
||||
release_id UUID NOT NULL,
|
||||
occurred_at TIMESTAMPTZ NOT NULL,
|
||||
body JSONB NOT NULL,
|
||||
UNIQUE (recipient_id, seq)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_distribution_events_feed
|
||||
ON distribution_events (recipient_id, seq);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_evidence (
|
||||
id TEXT PRIMARY KEY,
|
||||
publisher_id UUID NOT NULL REFERENCES distribution_publishers (id),
|
||||
note TEXT NOT NULL,
|
||||
created_by INT NOT NULL REFERENCES profiles (id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS distribution_rate_windows (
|
||||
binding_id UUID PRIMARY KEY REFERENCES distribution_bindings (id),
|
||||
window_start TIMESTAMPTZ NOT NULL,
|
||||
hits INT NOT NULL
|
||||
);
|
||||
@@ -0,0 +1,460 @@
|
||||
"""Distributionsfreigabe: Maschinenabruf und Redaktion.
|
||||
|
||||
Maschinenabruf authentifiziert allein über den Distributions-Schlüssel.
|
||||
# ACCESS_LAYER exempt: kein Trainer-Mandant; Kanal kommt aus der Anbindung.
|
||||
Die Redaktions- und Verwaltungsrouten nutzen TenantContext.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from club_tenancy import is_superadmin
|
||||
from db import get_cursor, get_db
|
||||
from distribution_contract import (
|
||||
InvalidCursor,
|
||||
cursor_secret,
|
||||
decode_cursor,
|
||||
distribution_enabled,
|
||||
)
|
||||
from distribution_service import (
|
||||
backlog_count,
|
||||
confirm_draft,
|
||||
create_draft,
|
||||
issue_key,
|
||||
list_changes,
|
||||
load_asset,
|
||||
load_availability,
|
||||
load_manifest,
|
||||
overview,
|
||||
resolve_bearer,
|
||||
retire_release,
|
||||
update_draft,
|
||||
withdraw_release,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
router = APIRouter(prefix="/api/distribution/v1", tags=["distribution"])
|
||||
editorial = APIRouter(tags=["distribution-editorial"])
|
||||
|
||||
NO_STORE = {"Cache-Control": "private, no-store"}
|
||||
|
||||
|
||||
def _machine(authorization: Optional[str]):
|
||||
if not distribution_enabled():
|
||||
raise HTTPException(status_code=404, detail="Nicht gefunden", headers=NO_STORE)
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail={"code": "invalid_key", "message": "Schlüssel ungültig."},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
held: Optional[HTTPException] = None
|
||||
binding = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
binding = resolve_bearer(cur, token)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return binding
|
||||
|
||||
|
||||
def _superadmin(tenant: TenantContext) -> None:
|
||||
if not is_superadmin(tenant.global_role):
|
||||
raise HTTPException(status_code=403, detail="Nur Superadmins dürfen die Distribution verwalten.")
|
||||
|
||||
|
||||
class PublisherBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
kind: str
|
||||
club_id: Optional[int] = None
|
||||
|
||||
|
||||
class RecipientBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class RelationshipBody(BaseModel):
|
||||
publisher_id: str
|
||||
recipient_id: str
|
||||
|
||||
|
||||
class BindingBody(BaseModel):
|
||||
recipient_id: str
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class KeyBody(BaseModel):
|
||||
expires_at: Optional[str] = None
|
||||
|
||||
|
||||
class ProfileBody(BaseModel):
|
||||
profile_id: int
|
||||
|
||||
|
||||
class ExerciseAssignBody(BaseModel):
|
||||
exercise_id: int
|
||||
|
||||
|
||||
class SuspendBody(BaseModel):
|
||||
kind: str
|
||||
id: str
|
||||
|
||||
|
||||
class DraftBody(BaseModel):
|
||||
publisher_id: str
|
||||
recipient_id: str
|
||||
cut: Optional[dict] = None
|
||||
|
||||
|
||||
class CutBody(BaseModel):
|
||||
cut: dict
|
||||
|
||||
|
||||
class ReasonBody(BaseModel):
|
||||
reason_code: str
|
||||
|
||||
|
||||
@router.get("/changes")
|
||||
def get_changes(
|
||||
cursor: Optional[str] = None,
|
||||
limit: Optional[int] = Query(default=None),
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
):
|
||||
binding = _machine(authorization)
|
||||
if limit is None:
|
||||
limit = 50
|
||||
elif limit < 1 or limit > 100:
|
||||
raise HTTPException(status_code=400, detail={"code": "invalid_limit", "message": "limit ist 1 bis 100."}, headers=NO_STORE)
|
||||
try:
|
||||
seq = decode_cursor(cursor_secret(), binding["recipient_id"], cursor)
|
||||
except InvalidCursor:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={"code": "invalid_cursor", "message": "Cursor ungültig."},
|
||||
headers=NO_STORE,
|
||||
)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
payload = list_changes(cur, binding["recipient_id"], seq, limit)
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/exercises/{source_id}/availability")
|
||||
def get_availability(source_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
payload = None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
payload = load_availability(cur, binding["recipient_id"], source_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(
|
||||
content=__import__("json").dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
headers=NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/releases/{release_id}")
|
||||
def get_release(release_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
body = b""
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
body = load_manifest(cur, binding["recipient_id"], release_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return Response(content=body, media_type="application/json", headers=NO_STORE)
|
||||
|
||||
|
||||
@router.get("/releases/{release_id}/assets/{asset_id}")
|
||||
def get_asset(release_id: str, asset_id: str, authorization: Optional[str] = Header(default=None)):
|
||||
binding = _machine(authorization)
|
||||
held: Optional[HTTPException] = None
|
||||
path = None
|
||||
media_type = "application/octet-stream"
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
try:
|
||||
path, media_type = load_asset(cur, binding["recipient_id"], release_id, asset_id)
|
||||
except HTTPException as exc:
|
||||
held = exc
|
||||
if held is not None:
|
||||
held.headers = {**(held.headers or {}), **NO_STORE}
|
||||
raise held
|
||||
return FileResponse(path, media_type=media_type, headers=NO_STORE)
|
||||
|
||||
|
||||
@editorial.get("/api/exercises/{exercise_id}/distribution")
|
||||
def exercise_distribution(exercise_id: int, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return overview(cur, exercise_id, tenant.profile_id, tenant.global_role or "")
|
||||
|
||||
|
||||
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts")
|
||||
def post_draft(exercise_id: int, body: DraftBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
result = create_draft(
|
||||
cur,
|
||||
exercise_id,
|
||||
body.publisher_id,
|
||||
body.recipient_id,
|
||||
tenant.profile_id,
|
||||
tenant.global_role or "",
|
||||
body.cut,
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.put("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}")
|
||||
def put_draft(exercise_id: int, draft_id: str, body: CutBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
result = update_draft(
|
||||
cur, exercise_id, draft_id, body.cut, tenant.profile_id, tenant.global_role or ""
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/exercises/{exercise_id}/distribution/drafts/{draft_id}/confirm")
|
||||
def post_confirm(exercise_id: int, draft_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = confirm_draft(cur, exercise_id, draft_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/retire")
|
||||
def post_retire(release_id: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = retire_release(cur, release_id, tenant.profile_id, tenant.global_role or "")
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/withdraw")
|
||||
def post_withdraw(release_id: str, body: ReasonBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "release", None)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/variants/{variant_id}/withdraw")
|
||||
def post_withdraw_variant(
|
||||
release_id: str,
|
||||
variant_id: str,
|
||||
body: ReasonBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(
|
||||
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "variant", variant_id
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/releases/{release_id}/assets/{asset_id}/withdraw")
|
||||
def post_withdraw_asset(
|
||||
release_id: str,
|
||||
asset_id: str,
|
||||
body: ReasonBody,
|
||||
tenant: TenantContext = Depends(get_tenant_context),
|
||||
):
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = withdraw_release(
|
||||
cur, release_id, body.reason_code, tenant.profile_id, tenant.global_role or "", "asset", asset_id
|
||||
)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers")
|
||||
def post_publisher(body: PublisherBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
if body.kind not in ("platform", "own", "club"):
|
||||
raise HTTPException(status_code=400, detail="kind ist platform, own oder club.")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_publishers (name, kind, club_id)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.name, body.kind, body.club_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/recipients")
|
||||
def post_recipient(body: RecipientBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"INSERT INTO distribution_recipients (name) VALUES (%s) RETURNING id",
|
||||
(body.name,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/relationships")
|
||||
def post_relationship(body: RelationshipBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_relationships (publisher_id, recipient_id)
|
||||
VALUES (%s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.publisher_id, body.recipient_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/bindings")
|
||||
def post_binding(body: BindingBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_bindings (recipient_id, name)
|
||||
VALUES (%s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(body.recipient_id, body.name),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return {"id": str(row["id"])}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/bindings/{binding_id}/keys")
|
||||
def post_key(binding_id: str, body: KeyBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
result = issue_key(cur, binding_id, body.expires_at)
|
||||
conn.commit()
|
||||
return result
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/keys/{key_prefix}/revoke")
|
||||
def post_revoke(key_prefix: str, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"UPDATE distribution_keys SET revoked_at = NOW() WHERE key_prefix = %s AND revoked_at IS NULL",
|
||||
(key_prefix,),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/releasers")
|
||||
def post_releaser(publisher_id: str, body: ProfileBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_releasers (publisher_id, profile_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(publisher_id, body.profile_id),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/publishers/{publisher_id}/exercises")
|
||||
def post_assign(publisher_id: str, body: ExerciseAssignBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO distribution_publisher_exercises (publisher_id, exercise_id)
|
||||
VALUES (%s, %s)
|
||||
ON CONFLICT DO NOTHING
|
||||
""",
|
||||
(publisher_id, body.exercise_id),
|
||||
)
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.post("/api/distribution/admin/suspend")
|
||||
def post_suspend(body: SuspendBody, tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
table = {
|
||||
"publisher": "distribution_publishers",
|
||||
"recipient": "distribution_recipients",
|
||||
"binding": "distribution_bindings",
|
||||
}.get(body.kind)
|
||||
if table is None:
|
||||
raise HTTPException(status_code=400, detail="kind ist publisher, recipient oder binding.")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(f"UPDATE {table} SET status = 'suspended' WHERE id = %s", (body.id,))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@editorial.get("/api/distribution/admin/backlog")
|
||||
def get_backlog(tenant: TenantContext = Depends(get_tenant_context)):
|
||||
_superadmin(tenant)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
return {"count": backlog_count(cur)}
|
||||
@@ -29,6 +29,7 @@ from club_tenancy import (
|
||||
club_admin_shares_club_with_creator,
|
||||
has_club_role,
|
||||
is_platform_admin,
|
||||
is_superadmin,
|
||||
library_content_visible_to_profile,
|
||||
)
|
||||
from tenant_context import TenantContext, get_tenant_context, get_tenant_context_flexible, library_content_visibility_sql
|
||||
@@ -39,6 +40,8 @@ from ai_prompt_context import ExerciseFormAiFocusRow, ExerciseFormAiPromptContex
|
||||
from ai_prompt_job import run_exercise_form_ai_suggestion
|
||||
from account_lifecycle import assert_min_account_state
|
||||
from capabilities import probe_capability
|
||||
from distribution_contract import OFFICIAL_WRITE_DENIED, official_write_allowed
|
||||
from distribution_service import blocks_exercise_delete, blocks_media_delete, blocks_variant_delete
|
||||
from club_features import (
|
||||
consume_club_feature_with_usage,
|
||||
merge_feature_usage_into_response,
|
||||
@@ -563,11 +566,13 @@ def _assert_can_edit_exercise(cur, exercise_id: int, tenant: TenantContext) -> N
|
||||
owner = rd.get("created_by")
|
||||
if owner is not None:
|
||||
owner = int(owner)
|
||||
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
||||
if not official_write_allowed(ex_vis, role):
|
||||
raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
|
||||
if owner == profile_id:
|
||||
return
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
ex_vis = (rd.get("visibility") or "private").strip().lower()
|
||||
ex_cid_raw = rd.get("club_id")
|
||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||
if ex_vis == "club" and ex_cid is not None and can_plan_in_club(cur, profile_id, ex_cid, role):
|
||||
@@ -1458,9 +1463,13 @@ def _exercise_delete_usage_message(counts: dict) -> str:
|
||||
def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||
pid = tenant.profile_id
|
||||
role = tenant.global_role
|
||||
vis = str(row.get("visibility") or "private").strip().lower()
|
||||
if vis == "official":
|
||||
if not is_superadmin(role):
|
||||
raise HTTPException(status_code=403, detail=OFFICIAL_WRITE_DENIED)
|
||||
return
|
||||
if is_platform_admin(role):
|
||||
return
|
||||
vis = str(row.get("visibility") or "private").strip().lower()
|
||||
cid = row.get("club_id")
|
||||
creator = row.get("created_by")
|
||||
try:
|
||||
@@ -1468,11 +1477,6 @@ def _assert_can_delete_exercise(cur, tenant: TenantContext, row: dict) -> None:
|
||||
except (TypeError, ValueError):
|
||||
creator_int = None
|
||||
|
||||
if vis == "official":
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Globale Übungen dürfen nur von Plattform-Admins gelöscht werden.",
|
||||
)
|
||||
if vis == "club":
|
||||
try:
|
||||
ex_club = int(cid) if cid is not None else None
|
||||
@@ -1598,6 +1602,9 @@ def bulk_patch_exercises_metadata(
|
||||
owner = int(owner)
|
||||
|
||||
ex_vis = (rowd.get("visibility") or "private").strip().lower()
|
||||
if not official_write_allowed(ex_vis, role):
|
||||
failed.append({"id": ex_id, "detail": OFFICIAL_WRITE_DENIED})
|
||||
continue
|
||||
ex_cid_raw = rowd.get("club_id")
|
||||
ex_cid = int(ex_cid_raw) if ex_cid_raw is not None else None
|
||||
|
||||
@@ -2833,6 +2840,11 @@ def delete_exercise(
|
||||
usage_msg = _exercise_delete_usage_message(counts)
|
||||
if usage_msg:
|
||||
raise HTTPException(status_code=409, detail=usage_msg)
|
||||
if blocks_exercise_delete(cur, exercise_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Die Übung hat eine externe Freigabe und kann nicht gelöscht werden.",
|
||||
)
|
||||
|
||||
cur.execute("DELETE FROM exercises WHERE id = %s", (exercise_id,))
|
||||
conn.commit()
|
||||
@@ -3040,6 +3052,11 @@ def delete_exercise_variant(
|
||||
cur = get_cursor(conn)
|
||||
_assert_can_edit_exercise(cur, exercise_id, tenant)
|
||||
assert_exercise_not_combination(cur, exercise_id)
|
||||
if blocks_variant_delete(cur, variant_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Die Variante ist Teil einer externen Freigabe und kann nicht gelöscht werden.",
|
||||
)
|
||||
_fetch_variant_row(cur, exercise_id, variant_id)
|
||||
|
||||
cur.execute(
|
||||
@@ -3840,6 +3857,11 @@ def delete_exercise_media(
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="Medium nicht gefunden")
|
||||
if blocks_media_delete(cur, media_id):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Das Medium ist Teil einer externen Freigabe und kann nicht gelöst werden.",
|
||||
)
|
||||
rec = r2d(row)
|
||||
media_asset_id = rec.get("media_asset_id")
|
||||
if media_asset_id:
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
"""Vertrag v1, Referenzfall, Rollen und Bestätigung nach Rückzug."""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||
|
||||
from auth import require_auth
|
||||
from distribution_service import _lock_recipient
|
||||
from distribution_contract import (
|
||||
InvalidCursor,
|
||||
actions_cover,
|
||||
cursor_secret,
|
||||
decide_confirm,
|
||||
decode_cursor,
|
||||
encode_cursor,
|
||||
exercise_offerable,
|
||||
package_state,
|
||||
manifest_bytes,
|
||||
official_write_allowed,
|
||||
plan_available,
|
||||
rate_decision,
|
||||
release_denial,
|
||||
retrievable_release_ids,
|
||||
sha256_bytes,
|
||||
)
|
||||
from main import app
|
||||
from routers.exercises import _assert_can_edit_exercise
|
||||
from tenant_context import TenantContext, get_tenant_context
|
||||
|
||||
FIXTURE = json.loads(
|
||||
(Path(__file__).resolve().parents[2] / "docs" / "architecture" / "distribution" / "Shinkan_Lara_Felix_Referenzfall_v1.json").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_fixture_manifest_hashes_match_contract_order() -> None:
|
||||
for release in FIXTURE["releases"].values():
|
||||
body = manifest_bytes(release["manifest"])
|
||||
assert sha256_bytes(body) == release["manifest_sha256"]
|
||||
assert not body.endswith(b"\n")
|
||||
|
||||
|
||||
def test_reference_case_retrieval_and_plan_effect() -> None:
|
||||
lara_events = FIXTURE["channels"]["lara_felix"]["events"]
|
||||
second_events = FIXTURE["channels"]["zweiter_verein"]["events"]
|
||||
assert retrievable_release_ids(lara_events) == set(FIXTURE["expected"]["lara_felix_can_retrieve_after_withdrawal"])
|
||||
assert retrievable_release_ids(second_events) == set(FIXTURE["expected"]["zweiter_verein_can_retrieve"])
|
||||
manifests = {item["manifest"]["release_id"]: item["manifest"] for item in FIXTURE["releases"].values()}
|
||||
blocked = []
|
||||
available = []
|
||||
for name, plan in FIXTURE["plans"].items():
|
||||
if plan_available(plan, manifests[plan["release_id"]], lara_events):
|
||||
available.append(name)
|
||||
else:
|
||||
blocked.append(name)
|
||||
assert set(blocked) == set(FIXTURE["expected"]["blocked_plans_after_withdrawal"])
|
||||
assert set(available) == set(FIXTURE["expected"]["available_plans_after_withdrawal"])
|
||||
film_actions = FIXTURE["releases"]["vereinsfassung_1"]["manifest"]["rights"][1]["actions"]
|
||||
assert actions_cover(film_actions, ["stream", "course_display", "commercial_course_use"]) is FIXTURE["expected"]["course_film_allowed"]
|
||||
assert ("download" in film_actions) is FIXTURE["expected"]["film_download_allowed"]
|
||||
|
||||
|
||||
def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> None:
|
||||
drafts: dict[str, str] = {}
|
||||
releases: dict[str, dict] = {}
|
||||
events: list[tuple[str, str]] = []
|
||||
|
||||
def confirm(draft_id: str, revision: int, cut: str) -> tuple[str, bool]:
|
||||
release_id, created = decide_confirm(drafts.get(draft_id), f"rel-{len(releases) + 1}")
|
||||
if created:
|
||||
drafts[draft_id] = release_id
|
||||
releases[release_id] = {"withdrawn": False, "revision": revision, "cut": cut}
|
||||
events.append(("published", release_id))
|
||||
return release_id, created
|
||||
|
||||
first, created = confirm("draft-1", 1, "same-cut")
|
||||
again, replayed = confirm("draft-1", 1, "same-cut")
|
||||
assert first == again
|
||||
assert created is True
|
||||
assert replayed is False
|
||||
assert events == [("published", first)]
|
||||
|
||||
releases[first]["withdrawn"] = True
|
||||
second, created_again = confirm("draft-2", 1, "same-cut")
|
||||
assert created_again is True
|
||||
assert second != first
|
||||
assert releases[first]["withdrawn"] is True
|
||||
assert releases[second]["revision"] == 1
|
||||
assert releases[second]["cut"] == "same-cut"
|
||||
assert [kind for kind, _ in events] == ["published", "published"]
|
||||
|
||||
|
||||
def test_availability_keeps_the_copy_and_stops_new_offers() -> None:
|
||||
assert package_state(fetch_blocked=False, retired=False) == "available"
|
||||
assert package_state(fetch_blocked=False, retired=True) == "retired"
|
||||
assert package_state(fetch_blocked=True, retired=True) == "withdrawn"
|
||||
status, offerable = exercise_offerable("approved", ["available"])
|
||||
assert status == "approved" and offerable is True
|
||||
status, offerable = exercise_offerable("archived", ["available"])
|
||||
assert status == "archived" and offerable is False
|
||||
status, offerable = exercise_offerable(None, ["withdrawn"])
|
||||
assert status == "deleted" and offerable is False
|
||||
status, offerable = exercise_offerable("approved", ["retired", "withdrawn"])
|
||||
assert offerable is False
|
||||
|
||||
|
||||
def test_cursor_is_bound_to_recipient() -> None:
|
||||
secret = cursor_secret()
|
||||
token = encode_cursor(secret, "recipient-a", 4)
|
||||
assert decode_cursor(secret, "recipient-a", token) == 4
|
||||
assert decode_cursor(secret, "recipient-a", None) == 0
|
||||
with pytest.raises(InvalidCursor):
|
||||
decode_cursor(secret, "recipient-b", token)
|
||||
|
||||
|
||||
def test_rate_window_blocks_at_sixty() -> None:
|
||||
hits, blocked = rate_decision(59, 10)
|
||||
assert hits == 60 and blocked is False
|
||||
hits, blocked = rate_decision(60, 10)
|
||||
assert blocked is True
|
||||
hits, blocked = rate_decision(60, 61)
|
||||
assert hits == 1 and blocked is False
|
||||
|
||||
|
||||
def test_official_release_and_edit_roles() -> None:
|
||||
assert official_write_allowed("official", "superadmin") is True
|
||||
assert official_write_allowed("official", "admin") is False
|
||||
assert official_write_allowed("official", "club_admin") is False
|
||||
assert official_write_allowed("club", "admin") is True
|
||||
assert release_denial(
|
||||
visibility="official",
|
||||
role="admin",
|
||||
publisher_kind="platform",
|
||||
is_owner=True,
|
||||
is_club_admin=False,
|
||||
)
|
||||
assert release_denial(
|
||||
visibility="official",
|
||||
role="superadmin",
|
||||
publisher_kind="platform",
|
||||
is_owner=False,
|
||||
is_club_admin=False,
|
||||
) is None
|
||||
assert release_denial(
|
||||
visibility="private",
|
||||
role="trainer",
|
||||
publisher_kind="own",
|
||||
is_owner=True,
|
||||
is_club_admin=False,
|
||||
) is None
|
||||
assert release_denial(
|
||||
visibility="private",
|
||||
role="admin",
|
||||
publisher_kind="own",
|
||||
is_owner=False,
|
||||
is_club_admin=False,
|
||||
)
|
||||
assert release_denial(
|
||||
visibility="club",
|
||||
role="trainer",
|
||||
publisher_kind="club",
|
||||
is_owner=True,
|
||||
is_club_admin=False,
|
||||
publisher_club_id=4,
|
||||
exercise_club_id=4,
|
||||
)
|
||||
assert release_denial(
|
||||
visibility="club",
|
||||
role="trainer",
|
||||
publisher_kind="club",
|
||||
is_owner=False,
|
||||
is_club_admin=True,
|
||||
publisher_club_id=4,
|
||||
exercise_club_id=4,
|
||||
) is None
|
||||
assert release_denial(
|
||||
visibility="club",
|
||||
role="trainer",
|
||||
publisher_kind="club",
|
||||
is_owner=False,
|
||||
is_club_admin=True,
|
||||
publisher_club_id=9,
|
||||
exercise_club_id=4,
|
||||
)
|
||||
|
||||
|
||||
def _tenant(role: str, profile_id: int = 7) -> TenantContext:
|
||||
return TenantContext(
|
||||
profile_id=profile_id,
|
||||
global_role=role,
|
||||
effective_club_id=None,
|
||||
club_ids=frozenset(),
|
||||
memberships=[],
|
||||
)
|
||||
|
||||
|
||||
def test_assert_edit_rejects_admin_and_club_role_for_official() -> None:
|
||||
cur = MagicMock()
|
||||
cur.fetchone.return_value = {"created_by": 7, "visibility": "official", "club_id": None}
|
||||
for role in ("admin", "trainer", "club_admin"):
|
||||
with pytest.raises(HTTPException) as caught:
|
||||
_assert_can_edit_exercise(cur, 3, _tenant(role))
|
||||
assert caught.value.status_code == 403
|
||||
_assert_can_edit_exercise(cur, 3, _tenant("superadmin", profile_id=1))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> TestClient:
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("DISTRIBUTION_ENABLED", raising=False)
|
||||
response = client.get("/api/distribution/v1/changes", headers={"Authorization": "Bearer shk.abc.def"})
|
||||
assert response.status_code == 404
|
||||
assert response.headers.get("cache-control") == "private, no-store"
|
||||
|
||||
|
||||
def test_channel_sequence_is_locked() -> None:
|
||||
assert "FOR UPDATE" in inspect.getsource(_lock_recipient)
|
||||
|
||||
|
||||
def test_variant_and_media_routes_reject_admin_on_official(client: TestClient) -> None:
|
||||
app.dependency_overrides[require_auth] = lambda: {"profile_id": 4, "role": "admin"}
|
||||
app.dependency_overrides[get_tenant_context] = lambda: _tenant("admin", 4)
|
||||
mock_cur = MagicMock()
|
||||
mock_cur.fetchone.return_value = {"created_by": 4, "visibility": "official", "club_id": None}
|
||||
mock_cm = MagicMock()
|
||||
mock_cm.__enter__.return_value = MagicMock()
|
||||
mock_cm.__exit__.return_value = False
|
||||
try:
|
||||
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
||||
"routers.exercises.get_cursor", return_value=mock_cur
|
||||
):
|
||||
variant = client.post(
|
||||
"/api/exercises/9/variants",
|
||||
headers={"X-Auth-Token": "t"},
|
||||
json={"variant_name": "Kartenweg"},
|
||||
)
|
||||
media = client.post(
|
||||
"/api/exercises/9/media/from-asset",
|
||||
headers={"X-Auth-Token": "t"},
|
||||
json={"media_asset_id": 3},
|
||||
)
|
||||
assert variant.status_code == 403
|
||||
assert media.status_code == 403
|
||||
finally:
|
||||
app.dependency_overrides.pop(require_auth, None)
|
||||
app.dependency_overrides.pop(get_tenant_context, None)
|
||||
+19
-3
@@ -1,8 +1,8 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.250"
|
||||
APP_VERSION = "0.8.252"
|
||||
BUILD_DATE = "2026-11-23"
|
||||
DB_SCHEMA_VERSION = "20261123098"
|
||||
DB_SCHEMA_VERSION = "20261123099"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
"legal_documents": "1.4.0", # Admin: Live-Vorschau pro Abschnitt + modale Vollvorschau (Editor + Dokumentenliste)
|
||||
@@ -38,7 +38,8 @@ MODULE_VERSIONS = {
|
||||
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.37.2", # Upload-MIME nur aus Magic Bytes; PDF als Anhang; Rich-Text-Allowlist beim Speichern
|
||||
"exercises": "2.38.0", # Globale Übungen schreibt und gibt nur superadmin frei
|
||||
"distribution": "1.1.0", # Freigabe folgt der Übung: Besitzer, Vereinsadmin, Superadmin für global
|
||||
"planning_exercise_suggest": "0.23.8", # Progressionsgraph: Katalog-Kontext (Fokus/Stil/TT/ZG) im Match-Profil
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
@@ -54,6 +55,21 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.252",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Externe Freigabe folgt der Übung: private Übungen gibt der Besitzer frei, Vereinsübungen der Vereinsadmin, globale Übungen nur ein Superadmin.",
|
||||
"Empfänger fragen die Verfügbarkeit einer freigegebenen Übung ab. Archiv und Löschung der Quelle beenden neue Angebote, die eingefrorene Kopie bleibt bis zum Rückzug abrufbar.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.251",
|
||||
"date": "2026-11-23",
|
||||
"changes": [
|
||||
"Eingefrorene Übungsfassungen können für einen Empfängerkanal freigegeben und per Distributions-Schlüssel abgerufen werden. Globale Übungen bearbeitet und gibt nur ein Superadmin frei. Die Distribution bleibt aus, bis DISTRIBUTION_ENABLED gesetzt ist.",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.250",
|
||||
"date": "2026-11-23",
|
||||
|
||||
Reference in new issue
Block a user