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>
1094 lines
38 KiB
Python
1094 lines
38 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
|
|
from db import r2d
|
|
from distribution_contract import (
|
|
LEGAL_HOLD_REASON,
|
|
REASON_CODES,
|
|
can_withdraw,
|
|
canonical_json,
|
|
collect_blockers,
|
|
cut_hash,
|
|
decide_confirm,
|
|
exercise_offerable,
|
|
package_state,
|
|
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
|
|
"""
|
|
)
|
|
publishers = []
|
|
for row in _rows(cur):
|
|
item = r2d(row)
|
|
if _denial_for(cur, exercise, item, profile_id, role):
|
|
continue
|
|
publishers.append(
|
|
{"id": str(item["id"]), "name": item["name"], "kind": item["kind"], "club_id": item["club_id"]}
|
|
)
|
|
release_block = None
|
|
if not publishers:
|
|
release_block = _denial_for(
|
|
cur,
|
|
exercise,
|
|
{
|
|
"kind": {"official": "platform", "club": "club"}.get(
|
|
(exercise.get("visibility") or "").strip().lower(), "own"
|
|
),
|
|
"club_id": exercise.get("club_id"),
|
|
},
|
|
profile_id,
|
|
role,
|
|
) or "Für diesen Bestand ist noch kein Herausgeber eingerichtet."
|
|
return {
|
|
"enabled": distribution_enabled(),
|
|
"visibility": exercise.get("visibility"),
|
|
"may_release": release_block is None,
|
|
"release_block": release_block,
|
|
"releases": releases,
|
|
"publishers": publishers,
|
|
"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, 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}
|
|
|
|
|
|
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 list_changes(cur, recipient_id: str, cursor_seq: int, limit: int) -> 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"])
|
|
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 load_availability(cur, recipient_id: str, source_id: str) -> 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 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],
|
|
)
|
|
return {
|
|
"source_id": str(source_id),
|
|
"source_status": status,
|
|
"offerable": offerable,
|
|
"releases": releases,
|
|
}
|
|
|
|
|
|
def load_manifest(cur, recipient_id: str, release_id: str) -> bytes:
|
|
cur.execute(
|
|
"""
|
|
SELECT release_id, recipient_id, publisher_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."})
|
|
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) -> tuple[Path, str]:
|
|
cur.execute(
|
|
"""
|
|
SELECT r.recipient_id, r.fetch_blocked, r.manifest_text, r.release_id, r.publisher_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."})
|
|
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"]
|