feat: projekte mit anderen benutzern teilen (backend)
Mitglieder mit Rolle "bearbeiten" oder "lesen"; nur der Besitzer verwaltet das Projekt. Sichtbar sind eigene Clips und alle Clips in eigenen oder geteilten Projekten, zentral in services/access.py. Beim Entfernen oder Verlassen landen die eigenen Clips wieder bei "ohne Projekt". Live-Ereignisse gehen an alle, die einen Clip sehen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cfa2a1d0ab
commit
d3a52c25a7
18 files changed
+1043
-133
No files matched your search
+21
-15
@@ -4,10 +4,11 @@ from fastapi import APIRouter, BackgroundTasks, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Clip
|
||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||
from app.services import clips as clip_service
|
||||
from app.ws.hub import hub
|
||||
from app.services.access import clip_audience
|
||||
|
||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
|
||||
@@ -18,17 +19,12 @@ _NULLABLE_FIELDS = {"title", "language", "project_id"}
|
||||
_PROJECT_FILTER = r"^(none|[1-9][0-9]{0,17})$"
|
||||
|
||||
|
||||
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||
"""Tell all devices of the user about a change, after the response is sent."""
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
|
||||
|
||||
def _clip_data(clip: Clip) -> dict:
|
||||
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||
|
||||
|
||||
def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
# Foreign and missing clips look the same, so ids of other users are not revealed
|
||||
def _get_visible_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
# Invisible and missing clips look the same, so ids of other users are not revealed
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
if clip is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
@@ -54,13 +50,18 @@ def list_clips(
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks):
|
||||
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
_notify(background, user.id, "clip.created", _clip_data(clip))
|
||||
notify(
|
||||
background,
|
||||
clip_audience(db, clip.user_id, clip.project_id),
|
||||
"clip.created",
|
||||
_clip_data(clip),
|
||||
)
|
||||
return clip
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
return _get_own_clip(db, user, clip_id)
|
||||
return _get_visible_clip(db, user, clip_id)
|
||||
|
||||
|
||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||
@@ -71,12 +72,13 @@ def update_clip(
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
clip = _get_own_clip(db, user, clip_id)
|
||||
clip = _get_visible_clip(db, user, clip_id)
|
||||
changes = {
|
||||
field: getattr(body, field)
|
||||
for field in body.model_fields_set - {"version"}
|
||||
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
||||
}
|
||||
before = clip_audience(db, clip.user_id, clip.project_id)
|
||||
try:
|
||||
clip = clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||
except clip_service.ClipConflict as exc:
|
||||
@@ -87,7 +89,10 @@ def update_clip(
|
||||
"current": _clip_data(exc.current),
|
||||
},
|
||||
)
|
||||
_notify(background, user.id, "clip.updated", _clip_data(clip))
|
||||
after = clip_audience(db, clip.user_id, clip.project_id)
|
||||
notify(background, after, "clip.updated", _clip_data(clip))
|
||||
# Moved out of a shared project: the others no longer see it
|
||||
notify(background, before - after, "clip.deleted", {"id": clip.id})
|
||||
return clip
|
||||
|
||||
|
||||
@@ -95,6 +100,7 @@ def update_clip(
|
||||
def delete_clip(
|
||||
clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
_notify(background, user.id, "clip.deleted", {"id": clip_id})
|
||||
clip = _get_visible_clip(db, user, clip_id)
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
clip_service.delete_clip(db, user.id, clip)
|
||||
notify(background, audience, "clip.deleted", {"id": clip_id})
|
||||
@@ -5,11 +5,12 @@ from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.config import get_settings
|
||||
from app.schemas.clips import ClipOut
|
||||
from app.services import clips as clip_service
|
||||
from app.services import files as file_service
|
||||
from app.ws.hub import hub
|
||||
from app.services.access import clip_audience
|
||||
|
||||
router = APIRouter(prefix="/files", tags=["files"])
|
||||
|
||||
@@ -28,10 +29,6 @@ class ExpiryUpdate(BaseModel):
|
||||
expires_days: int
|
||||
|
||||
|
||||
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
async def upload(
|
||||
request: Request,
|
||||
@@ -59,7 +56,8 @@ async def upload(
|
||||
title=title,
|
||||
)
|
||||
out = ClipOut.model_validate(clip)
|
||||
_notify(background, user.id, "clip.created", out.model_dump(mode="json"))
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
notify(background, audience, "clip.created", out.model_dump(mode="json"))
|
||||
return out
|
||||
|
||||
|
||||
@@ -76,7 +74,8 @@ def usage(user: CurrentUser, db: DbSession) -> Usage:
|
||||
@router.get("/{clip_id}")
|
||||
def download(clip_id: int, user: CurrentUser, db: DbSession, inline: bool = False):
|
||||
stored = file_service.get_file(db, user.id, clip_id)
|
||||
path = None if stored is None else file_service.file_path(user.id, stored.storage_name)
|
||||
# Stored under the uploader, who may be another member of a shared project
|
||||
path = None if stored is None else file_service.file_path(stored.user_id, stored.storage_name)
|
||||
if stored is None or path is None or not path.is_file():
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Datei nicht gefunden.")
|
||||
# Only verified images may be shown in the browser; everything else is a download
|
||||
@@ -105,5 +104,6 @@ def update_expiry(
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
clip = file_service.set_expiry(db, user.id, clip, body.expires_days)
|
||||
out = ClipOut.model_validate(clip)
|
||||
_notify(background, user.id, "clip.updated", out.model_dump(mode="json"))
|
||||
audience = clip_audience(db, clip.user_id, clip.project_id)
|
||||
notify(background, audience, "clip.updated", out.model_dump(mode="json"))
|
||||
return out
|
||||
@@ -0,0 +1,11 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import BackgroundTasks
|
||||
|
||||
from app.ws.hub import hub
|
||||
|
||||
|
||||
def notify(background: BackgroundTasks, user_ids: Iterable[int], event: str, data: dict) -> None:
|
||||
"""Tell all devices of these users about a change, after the response is sent."""
|
||||
for user_id in set(user_ids):
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
+141
-24
@@ -1,41 +1,82 @@
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.api.notify import notify
|
||||
from app.models import Project
|
||||
from app.schemas.projects import ProjectCreate, ProjectOut, ProjectUpdate
|
||||
from app.schemas.projects import (
|
||||
MemberAdd,
|
||||
MemberOut,
|
||||
MemberUpdate,
|
||||
ProjectCreate,
|
||||
ProjectOut,
|
||||
ProjectUpdate,
|
||||
)
|
||||
from app.services import projects as project_service
|
||||
from app.ws.hub import hub
|
||||
from app.services.access import project_audience
|
||||
from app.services.projects import ProjectView
|
||||
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
|
||||
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
def _out(view: ProjectView) -> ProjectOut:
|
||||
p = view.project
|
||||
return ProjectOut(
|
||||
id=p.id,
|
||||
name=p.name,
|
||||
color=p.color,
|
||||
role=view.role.value,
|
||||
owner_name=view.owner_name,
|
||||
clip_count=view.clip_count,
|
||||
member_count=view.member_count,
|
||||
created_at=p.created_at,
|
||||
updated_at=p.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _out(project: Project, clip_count: int) -> ProjectOut:
|
||||
return ProjectOut.model_validate(project).model_copy(update={"clip_count": clip_count})
|
||||
|
||||
|
||||
def _get_own_project(db: DbSession, user: CurrentUser, project_id: int) -> Project:
|
||||
project = project_service.get_project(db, user.id, project_id)
|
||||
if project is None:
|
||||
def _view(db: DbSession, user: CurrentUser, project_id: int) -> ProjectView:
|
||||
view = project_service.view_project(db, user.id, project_id)
|
||||
if view is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Projekt nicht gefunden.")
|
||||
return project
|
||||
return view
|
||||
|
||||
|
||||
def _owned(db: DbSession, user: CurrentUser, project_id: int) -> Project:
|
||||
"""Only the owner manages a project; members get 403, everyone else 404."""
|
||||
view = _view(db, user, project_id)
|
||||
if view.project.user_id != user.id:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Nur der Besitzer kann das ändern.")
|
||||
return view.project
|
||||
|
||||
|
||||
def _notify_project(
|
||||
background: BackgroundTasks,
|
||||
db: DbSession,
|
||||
project_id: int,
|
||||
event: str,
|
||||
user_ids: Iterable[int],
|
||||
) -> None:
|
||||
"""Send each user the project as they see it (role and owner differ per viewer)."""
|
||||
for user_id in set(user_ids):
|
||||
view = project_service.view_project(db, user_id, project_id)
|
||||
if view is not None:
|
||||
notify(background, [user_id], event, _out(view).model_dump(mode="json"))
|
||||
|
||||
|
||||
@router.get("", response_model=list[ProjectOut])
|
||||
def list_projects(user: CurrentUser, db: DbSession) -> list[ProjectOut]:
|
||||
return [_out(p, count) for p, count in project_service.list_projects(db, user.id)]
|
||||
return [_out(view) for view in project_service.list_projects(db, user.id)]
|
||||
|
||||
|
||||
@router.post("", response_model=ProjectOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_project(
|
||||
body: ProjectCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> ProjectOut:
|
||||
project = _out(project_service.create_project(db, user.id, **body.model_dump()), 0)
|
||||
_notify(background, user.id, "project.created", project.model_dump(mode="json"))
|
||||
return project
|
||||
project = project_service.create_project(db, user.id, **body.model_dump())
|
||||
out = _out(_view(db, user, project.id))
|
||||
notify(background, [user.id], "project.created", out.model_dump(mode="json"))
|
||||
return out
|
||||
|
||||
|
||||
@router.patch("/{project_id}", response_model=ProjectOut)
|
||||
@@ -46,17 +87,93 @@ def update_project(
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> ProjectOut:
|
||||
project = _get_own_project(db, user, project_id)
|
||||
project = project_service.update_project(db, project, name=body.name, color=body.color)
|
||||
out = _out(project, project_service.count_clips(db, user.id, project.id))
|
||||
_notify(background, user.id, "project.updated", out.model_dump(mode="json"))
|
||||
return out
|
||||
project = _owned(db, user, project_id)
|
||||
project_service.update_project(db, project, name=body.name, color=body.color)
|
||||
_notify_project(background, db, project_id, "project.updated", project_audience(db, project_id))
|
||||
return _out(_view(db, user, project_id))
|
||||
|
||||
|
||||
@router.delete("/{project_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_project(
|
||||
project_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not project_service.delete_project(db, user.id, project_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Projekt nicht gefunden.")
|
||||
_notify(background, user.id, "project.deleted", {"id": project_id})
|
||||
_owned(db, user, project_id)
|
||||
audience = project_audience(db, project_id)
|
||||
project_service.delete_project(db, user.id, project_id)
|
||||
# Clients detach: own clips move to "no project", clips of others disappear
|
||||
notify(background, audience, "project.deleted", {"id": project_id})
|
||||
|
||||
|
||||
# --- Members --------------------------------------------------------------------
|
||||
|
||||
|
||||
def _members_out(db: DbSession, project: Project) -> list[MemberOut]:
|
||||
return [
|
||||
MemberOut(user_id=m.user_id, username=m.username, role=m.role.value)
|
||||
for m in project_service.list_members(db, project)
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{project_id}/members", response_model=list[MemberOut])
|
||||
def list_members(project_id: int, user: CurrentUser, db: DbSession) -> list[MemberOut]:
|
||||
return _members_out(db, _view(db, user, project_id).project)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{project_id}/members", response_model=list[MemberOut], status_code=status.HTTP_201_CREATED
|
||||
)
|
||||
def add_member(
|
||||
project_id: int,
|
||||
body: MemberAdd,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> list[MemberOut]:
|
||||
project = _owned(db, user, project_id)
|
||||
added = project_service.add_member(db, project, body.username, body.role)
|
||||
# The new member's clients reload their clips when the project appears
|
||||
_notify_project(background, db, project_id, "project.created", [added.id])
|
||||
others = project_audience(db, project_id) - {added.id}
|
||||
_notify_project(background, db, project_id, "project.updated", others)
|
||||
return _members_out(db, project)
|
||||
|
||||
|
||||
@router.patch("/{project_id}/members/{member_id}", response_model=list[MemberOut])
|
||||
def update_member(
|
||||
project_id: int,
|
||||
member_id: int,
|
||||
body: MemberUpdate,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> list[MemberOut]:
|
||||
project = _owned(db, user, project_id)
|
||||
if not project_service.set_member_role(db, project, member_id, body.role):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Mitglied nicht gefunden.")
|
||||
_notify_project(background, db, project_id, "project.updated", [member_id])
|
||||
return _members_out(db, project)
|
||||
|
||||
|
||||
@router.delete("/{project_id}/members/{member_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def remove_member(
|
||||
project_id: int,
|
||||
member_id: int,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
) -> None:
|
||||
"""The owner removes a member, or a member leaves (member_id = own id)."""
|
||||
if member_id != user.id:
|
||||
_owned(db, user, project_id)
|
||||
else:
|
||||
_view(db, user, project_id)
|
||||
moved = project_service.remove_member(db, project_id, member_id)
|
||||
if moved is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Mitglied nicht gefunden.")
|
||||
remaining = project_audience(db, project_id)
|
||||
# For the former member the project is gone; their clips are back in "no project"
|
||||
notify(background, [member_id], "project.deleted", {"id": project_id})
|
||||
# The others no longer see the former member's clips
|
||||
for clip_id in moved:
|
||||
notify(background, remaining, "clip.deleted", {"id": clip_id})
|
||||
_notify_project(background, db, project_id, "project.updated", remaining)
|
||||
@@ -0,0 +1,24 @@
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.models import User
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class UserName(BaseModel):
|
||||
id: int
|
||||
username: str
|
||||
|
||||
|
||||
@router.get("", response_model=list[UserName])
|
||||
def list_user_names(user: CurrentUser, db: DbSession) -> list[UserName]:
|
||||
"""Names of the other active users, for sharing projects; nothing else is revealed."""
|
||||
rows = db.execute(
|
||||
select(User.id, User.username)
|
||||
.where(User.is_active, User.id != user.id)
|
||||
.order_by(User.username)
|
||||
)
|
||||
return [UserName(id=uid, username=name) for uid, name in rows]
|
||||
+12
-6
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import admin, auth, clips, files, health, projects, ws
|
||||
from app.api import admin, auth, clips, files, health, projects, users, ws
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -18,8 +18,8 @@ from app.middleware import (
|
||||
SecurityHeadersMiddleware,
|
||||
)
|
||||
from app.services import files as file_service
|
||||
from app.services.access import ProjectNotFound, ReadOnly
|
||||
from app.services.auth import delete_old_login_attempts
|
||||
from app.services.projects import ProjectNotFound
|
||||
from app.services.sessions import delete_expired_sessions
|
||||
from app.services.users import UserError, bootstrap_initial_admin
|
||||
from app.ws.hub import hub
|
||||
@@ -29,8 +29,8 @@ logger = logging.getLogger(__name__)
|
||||
CLEANUP_INTERVAL_SECONDS = 3600
|
||||
|
||||
|
||||
def _cleanup() -> list[tuple[int, int]]:
|
||||
"""Hourly housekeeping; returns (user_id, clip_id) of expired file clips."""
|
||||
def _cleanup() -> list[tuple[int, set[int]]]:
|
||||
"""Hourly housekeeping; returns (clip_id, audience) of expired file clips."""
|
||||
with _session_factory()() as db:
|
||||
sessions = delete_expired_sessions(db)
|
||||
attempts = delete_old_login_attempts(db)
|
||||
@@ -50,8 +50,9 @@ def _cleanup() -> list[tuple[int, int]]:
|
||||
async def _cleanup_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
for user_id, clip_id in await run_in_threadpool(_cleanup):
|
||||
await hub.broadcast(user_id, {"type": "clip.deleted", "data": {"id": clip_id}})
|
||||
for clip_id, audience in await run_in_threadpool(_cleanup):
|
||||
for user_id in audience:
|
||||
await hub.broadcast(user_id, {"type": "clip.deleted", "data": {"id": clip_id}})
|
||||
except Exception:
|
||||
logger.exception("Cleanup failed")
|
||||
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
|
||||
@@ -149,6 +150,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(clips.router, prefix="/api")
|
||||
app.include_router(projects.router, prefix="/api")
|
||||
app.include_router(files.router, prefix="/api")
|
||||
app.include_router(users.router, prefix="/api")
|
||||
app.include_router(ws.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
@@ -159,6 +161,10 @@ def create_app() -> FastAPI:
|
||||
def file_rejected_handler(_request: Request, exc: file_service.FileRejected) -> JSONResponse:
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
|
||||
|
||||
@app.exception_handler(ReadOnly)
|
||||
def read_only_handler(_request: Request, exc: ReadOnly) -> JSONResponse:
|
||||
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
@app.exception_handler(ProjectNotFound)
|
||||
def project_not_found_handler(_request: Request, _exc: ProjectNotFound) -> JSONResponse:
|
||||
# Same answer for foreign and missing projects, so ids of other users are not revealed
|
||||
|
||||
@@ -2,6 +2,7 @@ from app.models.base import Base, UTCDateTime, utcnow
|
||||
from app.models.clip import Clip, ClipKind
|
||||
from app.models.file import StoredFile
|
||||
from app.models.login_attempt import LoginAttempt
|
||||
from app.models.member import MemberRole, ProjectMember
|
||||
from app.models.project import PROJECT_COLORS, Project
|
||||
from app.models.session import UserSession
|
||||
from app.models.user import Role, User
|
||||
@@ -11,8 +12,10 @@ __all__ = [
|
||||
"Clip",
|
||||
"ClipKind",
|
||||
"LoginAttempt",
|
||||
"MemberRole",
|
||||
"PROJECT_COLORS",
|
||||
"Project",
|
||||
"ProjectMember",
|
||||
"Role",
|
||||
"StoredFile",
|
||||
"UTCDateTime",
|
||||
|
||||
@@ -11,6 +11,7 @@ from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.file import StoredFile
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class ClipKind(enum.StrEnum):
|
||||
@@ -44,6 +45,13 @@ class Clip(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
|
||||
# Shown on clips in shared projects ("von anna")
|
||||
owner: Mapped[User] = relationship(lazy="selectin")
|
||||
|
||||
@property
|
||||
def owner_name(self) -> str:
|
||||
return self.owner.username
|
||||
|
||||
file: Mapped[StoredFile | None] = relationship(
|
||||
back_populates="clip", lazy="selectin", passive_deletes=True
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Enum, ForeignKey, Index, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
|
||||
|
||||
class MemberRole(enum.StrEnum):
|
||||
EDIT = "edit"
|
||||
READ = "read"
|
||||
|
||||
|
||||
class ProjectMember(Base):
|
||||
"""A user a project is shared with; the owner is not stored here (projects.user_id)."""
|
||||
|
||||
__tablename__ = "project_members"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("project_id", "user_id", name="uq_project_members"),
|
||||
Index("ix_project_members_user", "user_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
project_id: Mapped[int] = mapped_column(ForeignKey("projects.id", ondelete="CASCADE"))
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||
role: Mapped[MemberRole] = mapped_column(
|
||||
Enum(
|
||||
MemberRole, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e]
|
||||
)
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||
@@ -43,6 +43,8 @@ class ClipOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
user_id: int
|
||||
owner_name: str
|
||||
kind: ClipKind
|
||||
title: str | None
|
||||
content: str
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.models import PROJECT_COLORS
|
||||
|
||||
@@ -19,11 +19,29 @@ class ProjectUpdate(BaseModel):
|
||||
|
||||
|
||||
class ProjectOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
"""A project as seen by one user (role and owner differ per viewer)."""
|
||||
|
||||
id: int
|
||||
name: str
|
||||
color: str
|
||||
clip_count: int = 0
|
||||
role: Literal["owner", "edit", "read"]
|
||||
owner_name: str
|
||||
clip_count: int
|
||||
member_count: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class MemberOut(BaseModel):
|
||||
user_id: int
|
||||
username: str
|
||||
role: Literal["owner", "edit", "read"]
|
||||
|
||||
|
||||
class MemberAdd(BaseModel):
|
||||
username: str = Field(max_length=100)
|
||||
role: Literal["edit", "read"] = "edit"
|
||||
|
||||
|
||||
class MemberUpdate(BaseModel):
|
||||
role: Literal["edit", "read"]
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Who may see and change what.
|
||||
|
||||
A user sees their own clips plus every clip in a project they own or are a member of.
|
||||
Clips outside projects are private. All visibility checks go through this module.
|
||||
"""
|
||||
|
||||
import enum
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import Clip, MemberRole, Project, ProjectMember
|
||||
|
||||
|
||||
class ProjectRole(enum.StrEnum):
|
||||
OWNER = "owner"
|
||||
EDIT = "edit"
|
||||
READ = "read"
|
||||
|
||||
|
||||
WRITE_ROLES = frozenset({ProjectRole.OWNER, ProjectRole.EDIT})
|
||||
|
||||
|
||||
class ProjectNotFound(LookupError):
|
||||
"""The project does not exist or is not visible to the user."""
|
||||
|
||||
|
||||
class ReadOnly(PermissionError):
|
||||
"""The user may see, but not change this."""
|
||||
|
||||
|
||||
def accessible_project_ids(user_id: int):
|
||||
"""Subquery of the ids of all projects the user owns or is a member of."""
|
||||
return (
|
||||
select(Project.id)
|
||||
.where(Project.user_id == user_id)
|
||||
.union(select(ProjectMember.project_id).where(ProjectMember.user_id == user_id))
|
||||
)
|
||||
|
||||
|
||||
def visible_clip(user_id: int):
|
||||
"""SQL condition for clips the user may see."""
|
||||
return or_(Clip.user_id == user_id, Clip.project_id.in_(accessible_project_ids(user_id)))
|
||||
|
||||
|
||||
def project_role(db: Session, user_id: int, project_id: int) -> ProjectRole | None:
|
||||
owner_id = db.scalar(select(Project.user_id).where(Project.id == project_id))
|
||||
if owner_id is None:
|
||||
return None
|
||||
if owner_id == user_id:
|
||||
return ProjectRole.OWNER
|
||||
role = db.scalar(
|
||||
select(ProjectMember.role).where(
|
||||
ProjectMember.project_id == project_id, ProjectMember.user_id == user_id
|
||||
)
|
||||
)
|
||||
return None if role is None else ProjectRole(MemberRole(role).value)
|
||||
|
||||
|
||||
def require_project_write(db: Session, user_id: int, project_id: int) -> ProjectRole:
|
||||
"""For putting clips into a project: owner or editor."""
|
||||
role = project_role(db, user_id, project_id)
|
||||
if role is None:
|
||||
raise ProjectNotFound(project_id)
|
||||
if role not in WRITE_ROLES:
|
||||
raise ReadOnly("Nur Lesezugriff auf dieses Projekt.")
|
||||
return role
|
||||
|
||||
|
||||
def can_write_clip(db: Session, user_id: int, clip: Clip) -> bool:
|
||||
"""Own clips always; others' clips only in projects where the user may edit."""
|
||||
if clip.user_id == user_id:
|
||||
return True
|
||||
if clip.project_id is None:
|
||||
return False
|
||||
return project_role(db, user_id, clip.project_id) in WRITE_ROLES
|
||||
|
||||
|
||||
def require_clip_write(db: Session, user_id: int, clip: Clip) -> None:
|
||||
if not can_write_clip(db, user_id, clip):
|
||||
raise ReadOnly("Nur Lesezugriff auf dieses Projekt.")
|
||||
|
||||
|
||||
def project_audience(db: Session, project_id: int) -> set[int]:
|
||||
"""Owner and members: everyone who sees the project."""
|
||||
owner_id = db.scalar(select(Project.user_id).where(Project.id == project_id))
|
||||
members = db.scalars(
|
||||
select(ProjectMember.user_id).where(ProjectMember.project_id == project_id)
|
||||
)
|
||||
return ({owner_id} if owner_id is not None else set()) | set(members)
|
||||
|
||||
|
||||
def clip_audience(db: Session, owner_id: int, project_id: int | None) -> set[int]:
|
||||
"""Everyone who sees a clip: its owner, plus the project's audience."""
|
||||
audience = {owner_id}
|
||||
if project_id is not None:
|
||||
audience |= project_audience(db, project_id)
|
||||
return audience
|
||||
@@ -6,8 +6,8 @@ from sqlalchemy.orm import Session
|
||||
from app.config import get_settings
|
||||
from app.languages import LANGUAGES
|
||||
from app.models import Clip, ClipKind, StoredFile, utcnow
|
||||
from app.services.access import require_clip_write, require_project_write, visible_clip
|
||||
from app.services.files import remove_from_disk
|
||||
from app.services.projects import require_project
|
||||
from app.services.users import UserError
|
||||
|
||||
# Changing only these fields does not count as an edit (no new updated_at)
|
||||
@@ -50,9 +50,10 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
|
||||
|
||||
|
||||
def _filters(user_id: int, project: int | str | None, query: str | None) -> list:
|
||||
conditions = [Clip.user_id == user_id]
|
||||
conditions = [visible_clip(user_id)]
|
||||
if project == NO_PROJECT:
|
||||
conditions.append(Clip.project_id.is_(None))
|
||||
# Clips without project are always private
|
||||
conditions += [Clip.user_id == user_id, Clip.project_id.is_(None)]
|
||||
elif project is not None:
|
||||
conditions.append(Clip.project_id == project)
|
||||
needle = (query or "").strip().casefold()
|
||||
@@ -76,7 +77,7 @@ def list_clips(
|
||||
project: int | str | None = None,
|
||||
query: str | None = None,
|
||||
) -> tuple[list[Clip], int]:
|
||||
"""Clips of the user, optionally only those of a project (or NO_PROJECT) matching a query."""
|
||||
"""Visible clips, optionally only those of a project (or NO_PROJECT) matching a query."""
|
||||
conditions = _filters(user_id, project, query)
|
||||
items = db.scalars(
|
||||
select(Clip)
|
||||
@@ -90,7 +91,8 @@ def list_clips(
|
||||
|
||||
|
||||
def get_clip(db: Session, user_id: int, clip_id: int) -> Clip | None:
|
||||
return db.scalar(select(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
"""A clip the user may see (own or in a shared project), else None."""
|
||||
return db.scalar(select(Clip).where(Clip.id == clip_id, visible_clip(user_id)))
|
||||
|
||||
|
||||
def create_clip(
|
||||
@@ -108,7 +110,7 @@ def create_clip(
|
||||
raise UserError("Dateien werden über den Upload angelegt.")
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
if project_id is not None:
|
||||
require_project(db, user_id, project_id)
|
||||
require_project_write(db, user_id, project_id)
|
||||
clip = Clip(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
@@ -130,7 +132,11 @@ def update_clip(
|
||||
changes: dict[str, Any],
|
||||
expected_version: int | None = None,
|
||||
) -> Clip:
|
||||
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict."""
|
||||
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict.
|
||||
|
||||
The clip must be visible to the user (get_clip); write access is checked here.
|
||||
"""
|
||||
require_clip_write(db, user_id, clip)
|
||||
# Early check so a stale client gets the conflict, not a follow-up validation error
|
||||
if expected_version is not None and clip.version != expected_version:
|
||||
raise ClipConflict(clip)
|
||||
@@ -144,8 +150,8 @@ def update_clip(
|
||||
language = changes.get("language", clip.language)
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
project_id = changes.get("project_id", clip.project_id)
|
||||
if "project_id" in changes and project_id is not None:
|
||||
require_project(db, user_id, project_id)
|
||||
if "project_id" in changes and project_id not in (None, clip.project_id):
|
||||
require_project_write(db, user_id, project_id)
|
||||
|
||||
values: dict[str, Any] = {
|
||||
"project_id": project_id,
|
||||
@@ -160,7 +166,7 @@ def update_clip(
|
||||
values["updated_at"] = utcnow()
|
||||
|
||||
# Conditional UPDATE keeps the version check atomic across concurrent requests
|
||||
stmt = update(Clip).where(Clip.id == clip.id, Clip.user_id == user_id)
|
||||
stmt = update(Clip).where(Clip.id == clip.id)
|
||||
if expected_version is not None:
|
||||
stmt = stmt.where(Clip.version == expected_version)
|
||||
result = db.execute(stmt.values(**values).execution_options(synchronize_session=False))
|
||||
@@ -173,14 +179,14 @@ def update_clip(
|
||||
return clip
|
||||
|
||||
|
||||
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
|
||||
storage_name = db.scalar(
|
||||
select(StoredFile.storage_name).where(
|
||||
StoredFile.clip_id == clip_id, StoredFile.user_id == user_id
|
||||
)
|
||||
)
|
||||
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
def delete_clip(db: Session, user_id: int, clip: Clip) -> None:
|
||||
"""Delete a visible clip; write access is checked here. Its file goes with it."""
|
||||
require_clip_write(db, user_id, clip)
|
||||
stored = db.execute(
|
||||
select(StoredFile.user_id, StoredFile.storage_name).where(StoredFile.clip_id == clip.id)
|
||||
).first()
|
||||
db.execute(delete(Clip).where(Clip.id == clip.id))
|
||||
db.commit()
|
||||
if storage_name is not None:
|
||||
remove_from_disk(user_id, storage_name)
|
||||
return result.rowcount > 0
|
||||
if stored is not None:
|
||||
# Stored under the uploader, who may be another member of a shared project
|
||||
remove_from_disk(stored.user_id, stored.storage_name)
|
||||
@@ -16,7 +16,12 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import Clip, ClipKind, StoredFile, utcnow
|
||||
from app.services.projects import require_project
|
||||
from app.services.access import (
|
||||
clip_audience,
|
||||
require_clip_write,
|
||||
require_project_write,
|
||||
visible_clip,
|
||||
)
|
||||
from app.services.users import UserError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -158,7 +163,7 @@ async def store_upload(
|
||||
if title is not None and len(title) > 200:
|
||||
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||
if project_id is not None:
|
||||
require_project(db, user_id, project_id)
|
||||
require_project_write(db, user_id, project_id)
|
||||
_check_limits(db, user_id, size)
|
||||
|
||||
settings = get_settings()
|
||||
@@ -215,9 +220,11 @@ async def store_upload(
|
||||
|
||||
|
||||
def get_file(db: Session, user_id: int, clip_id: int) -> StoredFile | None:
|
||||
"""The file of a clip of this user, unless it has expired."""
|
||||
"""The file of a clip the user may see, unless it has expired."""
|
||||
stored = db.scalar(
|
||||
select(StoredFile).where(StoredFile.clip_id == clip_id, StoredFile.user_id == user_id)
|
||||
select(StoredFile)
|
||||
.join(Clip, Clip.id == StoredFile.clip_id)
|
||||
.where(StoredFile.clip_id == clip_id, visible_clip(user_id))
|
||||
)
|
||||
if stored is None or (stored.expires_at is not None and stored.expires_at <= utcnow()):
|
||||
return None
|
||||
@@ -228,10 +235,11 @@ def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip
|
||||
"""Change how long a file is kept; counts as a change of the clip, not as an edit."""
|
||||
if clip.file is None:
|
||||
raise UserError("Dieser Clip ist keine Datei.")
|
||||
require_clip_write(db, user_id, clip)
|
||||
clip.file.expires_at = _expires_at(expires_days)
|
||||
db.execute(
|
||||
update(Clip)
|
||||
.where(Clip.id == clip.id, Clip.user_id == user_id)
|
||||
.where(Clip.id == clip.id)
|
||||
.values(version=Clip.version + 1)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
@@ -240,20 +248,27 @@ def set_expiry(db: Session, user_id: int, clip: Clip, expires_days: int) -> Clip
|
||||
return clip
|
||||
|
||||
|
||||
def delete_expired(db: Session) -> list[tuple[int, int]]:
|
||||
"""Delete clips whose file has expired; returns (user_id, clip_id) for notifications."""
|
||||
def delete_expired(db: Session) -> list[tuple[int, set[int]]]:
|
||||
"""Delete clips whose file has expired; returns (clip_id, audience) for notifications."""
|
||||
rows = db.execute(
|
||||
select(StoredFile.user_id, StoredFile.clip_id, StoredFile.storage_name).where(
|
||||
StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow()
|
||||
select(
|
||||
StoredFile.user_id.label("uploader_id"),
|
||||
StoredFile.storage_name,
|
||||
Clip.id,
|
||||
Clip.user_id.label("owner_id"),
|
||||
Clip.project_id,
|
||||
)
|
||||
.join(Clip, Clip.id == StoredFile.clip_id)
|
||||
.where(StoredFile.expires_at.is_not(None), StoredFile.expires_at <= utcnow())
|
||||
).all()
|
||||
if not rows:
|
||||
return []
|
||||
db.execute(delete(Clip).where(Clip.id.in_([row.clip_id for row in rows])))
|
||||
audiences = [(row.id, clip_audience(db, row.owner_id, row.project_id)) for row in rows]
|
||||
db.execute(delete(Clip).where(Clip.id.in_([row.id for row in rows])))
|
||||
db.commit()
|
||||
for row in rows:
|
||||
remove_from_disk(row.user_id, row.storage_name)
|
||||
return [(row.user_id, row.clip_id) for row in rows]
|
||||
remove_from_disk(row.uploader_id, row.storage_name)
|
||||
return audiences
|
||||
|
||||
|
||||
def remove_orphans(db: Session) -> int:
|
||||
|
||||
@@ -1,18 +1,42 @@
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models import PROJECT_COLORS, Clip, Project, utcnow
|
||||
from app.services.users import UserError
|
||||
from app.models import PROJECT_COLORS, Clip, MemberRole, Project, ProjectMember, User, utcnow
|
||||
from app.services.access import (
|
||||
ProjectNotFound,
|
||||
ProjectRole,
|
||||
accessible_project_ids,
|
||||
project_role,
|
||||
)
|
||||
from app.services.users import UserError, normalize_username
|
||||
|
||||
NAME_MAX_LENGTH = 100
|
||||
MAX_PROJECTS_PER_USER = 200
|
||||
MAX_MEMBERS_PER_PROJECT = 50
|
||||
|
||||
__all__ = ["ProjectNotFound"]
|
||||
|
||||
|
||||
class ProjectNotFound(LookupError):
|
||||
"""The project does not exist or belongs to another user."""
|
||||
@dataclass
|
||||
class ProjectView:
|
||||
"""A project as one particular user sees it."""
|
||||
|
||||
project: Project
|
||||
role: ProjectRole
|
||||
owner_name: str
|
||||
clip_count: int
|
||||
member_count: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class Member:
|
||||
user_id: int
|
||||
username: str
|
||||
role: ProjectRole
|
||||
|
||||
|
||||
def _validate_name(name: str) -> tuple[str, str]:
|
||||
@@ -36,41 +60,59 @@ def _duplicate() -> UserError:
|
||||
return UserError("Ein Projekt mit diesem Namen gibt es schon.")
|
||||
|
||||
|
||||
def list_projects(db: Session, user_id: int) -> list[tuple[Project, int]]:
|
||||
"""Projects of the user, sorted by name, each with its number of clips."""
|
||||
clip_count = (
|
||||
select(func.count(Clip.id))
|
||||
.where(Clip.project_id == Project.id, Clip.user_id == user_id)
|
||||
def _clip_count():
|
||||
return select(func.count(Clip.id)).where(Clip.project_id == Project.id).scalar_subquery()
|
||||
|
||||
|
||||
def _member_count():
|
||||
return (
|
||||
select(func.count(ProjectMember.id))
|
||||
.where(ProjectMember.project_id == Project.id)
|
||||
# Only Project comes from the outer query; ProjectMember is counted here
|
||||
.correlate(Project)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
|
||||
def list_projects(db: Session, user_id: int) -> list[ProjectView]:
|
||||
"""Own and shared projects, sorted by name, with clip counts of all members."""
|
||||
rows = db.execute(
|
||||
select(Project, clip_count)
|
||||
.where(Project.user_id == user_id)
|
||||
select(Project, User.username, _clip_count(), _member_count(), ProjectMember.role)
|
||||
.join(User, User.id == Project.user_id)
|
||||
.outerjoin(
|
||||
ProjectMember,
|
||||
(ProjectMember.project_id == Project.id) & (ProjectMember.user_id == user_id),
|
||||
)
|
||||
.where(Project.id.in_(accessible_project_ids(user_id)))
|
||||
.order_by(Project.name_key, Project.id)
|
||||
)
|
||||
return [(project, count) for project, count in rows]
|
||||
|
||||
|
||||
def get_project(db: Session, user_id: int, project_id: int) -> Project | None:
|
||||
return db.scalar(select(Project).where(Project.id == project_id, Project.user_id == user_id))
|
||||
|
||||
|
||||
def require_project(db: Session, user_id: int, project_id: int) -> Project:
|
||||
project = get_project(db, user_id, project_id)
|
||||
if project is None:
|
||||
raise ProjectNotFound(project_id)
|
||||
return project
|
||||
|
||||
|
||||
def count_clips(db: Session, user_id: int, project_id: int) -> int:
|
||||
return (
|
||||
db.scalar(
|
||||
select(func.count(Clip.id)).where(
|
||||
Clip.user_id == user_id, Clip.project_id == project_id
|
||||
)
|
||||
return [
|
||||
ProjectView(
|
||||
project=project,
|
||||
role=ProjectRole.OWNER if project.user_id == user_id else ProjectRole(role),
|
||||
owner_name=owner_name,
|
||||
clip_count=clips,
|
||||
member_count=members,
|
||||
)
|
||||
or 0
|
||||
)
|
||||
for project, owner_name, clips, members, role in rows
|
||||
]
|
||||
|
||||
|
||||
def view_project(db: Session, user_id: int, project_id: int) -> ProjectView | None:
|
||||
"""One project as the user sees it, or None if it is not visible to them."""
|
||||
role = project_role(db, user_id, project_id)
|
||||
if role is None:
|
||||
return None
|
||||
project, owner_name, clips, members = db.execute(
|
||||
select(Project, User.username, _clip_count(), _member_count())
|
||||
.join(User, User.id == Project.user_id)
|
||||
.where(Project.id == project_id)
|
||||
).one()
|
||||
return ProjectView(project, role, owner_name, clips, members)
|
||||
|
||||
|
||||
def get_owned_project(db: Session, user_id: int, project_id: int) -> Project | None:
|
||||
return db.scalar(select(Project).where(Project.id == project_id, Project.user_id == user_id))
|
||||
|
||||
|
||||
def create_project(db: Session, user_id: int, *, name: str, color: str = "blue") -> Project:
|
||||
@@ -106,18 +148,102 @@ def update_project(
|
||||
return project
|
||||
|
||||
|
||||
def _detach_clips(db: Session, project_id: int, owner_id: int | None = None) -> list[int]:
|
||||
"""Move clips out of a project (all, or those of one user); returns their ids.
|
||||
|
||||
Versions are bumped so open editors holding the old project notice the change.
|
||||
"""
|
||||
conditions = [Clip.project_id == project_id]
|
||||
if owner_id is not None:
|
||||
conditions.append(Clip.user_id == owner_id)
|
||||
ids = list(db.scalars(select(Clip.id).where(*conditions)))
|
||||
if ids:
|
||||
db.execute(
|
||||
update(Clip)
|
||||
.where(Clip.id.in_(ids))
|
||||
.values(project_id=None, version=Clip.version + 1)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
return ids
|
||||
|
||||
|
||||
def delete_project(db: Session, user_id: int, project_id: int) -> bool:
|
||||
"""Delete a project; its clips stay and move to "no project"."""
|
||||
# Bump versions so open editors holding the old project notice the change
|
||||
db.execute(
|
||||
update(Clip)
|
||||
.where(Clip.user_id == user_id, Clip.project_id == project_id)
|
||||
.values(project_id=None, version=Clip.version + 1)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
result = db.execute(delete(Project).where(Project.id == project_id, Project.user_id == user_id))
|
||||
if result.rowcount == 0:
|
||||
db.rollback()
|
||||
"""Delete an own project; all clips in it stay and move to their owners' "no project"."""
|
||||
if get_owned_project(db, user_id, project_id) is None:
|
||||
return False
|
||||
_detach_clips(db, project_id)
|
||||
db.execute(delete(Project).where(Project.id == project_id))
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
# --- Members --------------------------------------------------------------------
|
||||
|
||||
|
||||
def list_members(db: Session, project: Project) -> list[Member]:
|
||||
"""Owner first, then members by name."""
|
||||
owner = db.get(User, project.user_id)
|
||||
rows = db.execute(
|
||||
select(User.id, User.username, ProjectMember.role)
|
||||
.join(ProjectMember, ProjectMember.user_id == User.id)
|
||||
.where(ProjectMember.project_id == project.id)
|
||||
.order_by(User.username)
|
||||
)
|
||||
members = [Member(uid, name, ProjectRole(MemberRole(role).value)) for uid, name, role in rows]
|
||||
return [Member(owner.id, owner.username, ProjectRole.OWNER), *members]
|
||||
|
||||
|
||||
def _member_role(role: str) -> MemberRole:
|
||||
try:
|
||||
return MemberRole(role)
|
||||
except ValueError:
|
||||
raise UserError("Unbekannte Rolle.") from None
|
||||
|
||||
|
||||
def add_member(db: Session, project: Project, username: str, role: str) -> User:
|
||||
member_role = _member_role(role)
|
||||
user = db.scalar(
|
||||
select(User).where(User.username == normalize_username(username), User.is_active)
|
||||
)
|
||||
if user is None:
|
||||
raise UserError("Diesen Benutzer gibt es nicht.")
|
||||
if user.id == project.user_id:
|
||||
raise UserError("Das Projekt gehört dir bereits.")
|
||||
count = db.scalar(
|
||||
select(func.count(ProjectMember.id)).where(ProjectMember.project_id == project.id)
|
||||
)
|
||||
if (count or 0) >= MAX_MEMBERS_PER_PROJECT:
|
||||
raise UserError(f"Höchstens {MAX_MEMBERS_PER_PROJECT} Mitglieder pro Projekt.")
|
||||
db.add(ProjectMember(project_id=project.id, user_id=user.id, role=member_role))
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise UserError(f"{user.username} ist schon Mitglied.") from None
|
||||
return user
|
||||
|
||||
|
||||
def set_member_role(db: Session, project: Project, user_id: int, role: str) -> bool:
|
||||
result = db.execute(
|
||||
update(ProjectMember)
|
||||
.where(ProjectMember.project_id == project.id, ProjectMember.user_id == user_id)
|
||||
.values(role=_member_role(role))
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
def remove_member(db: Session, project_id: int, user_id: int) -> list[int] | None:
|
||||
"""Remove a member (or let them leave). Their clips in the project go back to their
|
||||
own "no project". Returns the ids of those clips, or None if they were no member."""
|
||||
result = db.execute(
|
||||
delete(ProjectMember).where(
|
||||
ProjectMember.project_id == project_id, ProjectMember.user_id == user_id
|
||||
)
|
||||
)
|
||||
if result.rowcount == 0:
|
||||
db.rollback()
|
||||
return None
|
||||
moved = _detach_clips(db, project_id, owner_id=user_id)
|
||||
db.commit()
|
||||
return moved
|
||||
Reference in new issue
Block a user