feat: projekte und suche im backend
Projekte pro Benutzer mit Name und Farbe, Clips optional einem Projekt zugeordnet. Löschen eines Projekts verschiebt seine Clips nach "ohne Projekt". Clip-Liste filtert nach Projekt und sucht Teiltexte in Titel und Inhalt, unabhängig von Groß-/Kleinschreibung (auch Umlaute). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
848cff35b3
commit
ff2860f7be
13 files changed
+711
-9
No files matched your search
@@ -0,0 +1,48 @@
|
|||||||
|
"""projects
|
||||||
|
|
||||||
|
Revision ID: 0004
|
||||||
|
Revises: 0003
|
||||||
|
Create Date: 2026-10-25 13:12:18.898120
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "0004"
|
||||||
|
down_revision: str | None = "0003"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"projects",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("name_key", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("color", sa.String(length=16), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("user_id", "name_key", name="uq_projects_user_name"),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table("clips", schema=None) as batch_op:
|
||||||
|
batch_op.add_column(sa.Column("project_id", sa.Integer(), nullable=True))
|
||||||
|
batch_op.create_index("ix_clips_user_project", ["user_id", "project_id"], unique=False)
|
||||||
|
batch_op.create_foreign_key(
|
||||||
|
"fk_clips_project_id", "projects", ["project_id"], ["id"], ondelete="SET NULL"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
with op.batch_alter_table("clips", schema=None) as batch_op:
|
||||||
|
batch_op.drop_constraint("fk_clips_project_id", type_="foreignkey")
|
||||||
|
batch_op.drop_index("ix_clips_user_project")
|
||||||
|
batch_op.drop_column("project_id")
|
||||||
|
|
||||||
|
op.drop_table("projects")
|
||||||
@@ -12,7 +12,10 @@ from app.ws.hub import hub
|
|||||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||||
|
|
||||||
# Fields that may be null on purpose (clearing them); all others are ignored when null
|
# Fields that may be null on purpose (clearing them); all others are ignored when null
|
||||||
_NULLABLE_FIELDS = {"title", "language"}
|
_NULLABLE_FIELDS = {"title", "language", "project_id"}
|
||||||
|
|
||||||
|
# "none" or a project id
|
||||||
|
_PROJECT_FILTER = r"^(none|[1-9][0-9]{0,17})$"
|
||||||
|
|
||||||
|
|
||||||
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||||
@@ -38,8 +41,13 @@ def list_clips(
|
|||||||
db: DbSession,
|
db: DbSession,
|
||||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||||
offset: Annotated[int, Query(ge=0)] = 0,
|
offset: Annotated[int, Query(ge=0)] = 0,
|
||||||
|
project: Annotated[str | None, Query(pattern=_PROJECT_FILTER)] = None,
|
||||||
|
q: Annotated[str | None, Query(max_length=clip_service.SEARCH_MAX_LENGTH)] = None,
|
||||||
) -> ClipList:
|
) -> ClipList:
|
||||||
items, total = clip_service.list_clips(db, user.id, limit, offset)
|
project_filter = project if project in (None, clip_service.NO_PROJECT) else int(project)
|
||||||
|
items, total = clip_service.list_clips(
|
||||||
|
db, user.id, limit, offset, project=project_filter, query=q
|
||||||
|
)
|
||||||
return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total)
|
return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
|
||||||
|
|
||||||
|
from app.api.deps import CurrentUser, DbSession
|
||||||
|
from app.models import Project
|
||||||
|
from app.schemas.projects import ProjectCreate, ProjectOut, ProjectUpdate
|
||||||
|
from app.services import projects as project_service
|
||||||
|
from app.ws.hub import hub
|
||||||
|
|
||||||
|
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(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:
|
||||||
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Projekt nicht gefunden.")
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
@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)]
|
||||||
|
|
||||||
|
|
||||||
|
@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
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{project_id}", response_model=ProjectOut)
|
||||||
|
def update_project(
|
||||||
|
project_id: int,
|
||||||
|
body: ProjectUpdate,
|
||||||
|
user: CurrentUser,
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
@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})
|
||||||
@@ -7,7 +7,13 @@ from sqlalchemy.orm import Session, sessionmaker
|
|||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
def casefold(value: str | None) -> str | None:
|
||||||
|
return None if value is None else value.casefold()
|
||||||
|
|
||||||
|
|
||||||
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
|
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
|
||||||
|
# SQLite's lower() only handles ASCII; this one also folds umlauts and ß for search
|
||||||
|
dbapi_connection.create_function("lc_casefold", 1, casefold, deterministic=True)
|
||||||
cursor = dbapi_connection.cursor()
|
cursor = dbapi_connection.cursor()
|
||||||
cursor.execute("PRAGMA journal_mode=WAL")
|
cursor.execute("PRAGMA journal_mode=WAL")
|
||||||
cursor.execute("PRAGMA foreign_keys=ON")
|
cursor.execute("PRAGMA foreign_keys=ON")
|
||||||
|
|||||||
+10
-1
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
|||||||
from fastapi.responses import FileResponse, JSONResponse
|
from fastapi.responses import FileResponse, JSONResponse
|
||||||
|
|
||||||
from app import __version__
|
from app import __version__
|
||||||
from app.api import admin, auth, clips, health, ws
|
from app.api import admin, auth, clips, health, projects, ws
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.db import _session_factory
|
from app.db import _session_factory
|
||||||
from app.middleware import (
|
from app.middleware import (
|
||||||
@@ -18,6 +18,7 @@ from app.middleware import (
|
|||||||
SecurityHeadersMiddleware,
|
SecurityHeadersMiddleware,
|
||||||
)
|
)
|
||||||
from app.services.auth import delete_old_login_attempts
|
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.sessions import delete_expired_sessions
|
||||||
from app.services.users import UserError, bootstrap_initial_admin
|
from app.services.users import UserError, bootstrap_initial_admin
|
||||||
|
|
||||||
@@ -129,12 +130,20 @@ def create_app() -> FastAPI:
|
|||||||
app.include_router(auth.router, prefix="/api")
|
app.include_router(auth.router, prefix="/api")
|
||||||
app.include_router(admin.router, prefix="/api")
|
app.include_router(admin.router, prefix="/api")
|
||||||
app.include_router(clips.router, prefix="/api")
|
app.include_router(clips.router, prefix="/api")
|
||||||
|
app.include_router(projects.router, prefix="/api")
|
||||||
app.include_router(ws.router, prefix="/api")
|
app.include_router(ws.router, prefix="/api")
|
||||||
|
|
||||||
@app.exception_handler(UserError)
|
@app.exception_handler(UserError)
|
||||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||||
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST)
|
return JSONResponse({"detail": str(exc)}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
@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
|
||||||
|
return JSONResponse(
|
||||||
|
{"detail": "Projekt nicht gefunden."}, status_code=status.HTTP_404_NOT_FOUND
|
||||||
|
)
|
||||||
|
|
||||||
_register_frontend(app, settings.static_dir)
|
_register_frontend(app, settings.static_dir)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from app.models.base import Base, UTCDateTime, utcnow
|
from app.models.base import Base, UTCDateTime, utcnow
|
||||||
from app.models.clip import Clip, ClipKind
|
from app.models.clip import Clip, ClipKind
|
||||||
from app.models.login_attempt import LoginAttempt
|
from app.models.login_attempt import LoginAttempt
|
||||||
|
from app.models.project import PROJECT_COLORS, Project
|
||||||
from app.models.session import UserSession
|
from app.models.session import UserSession
|
||||||
from app.models.user import Role, User
|
from app.models.user import Role, User
|
||||||
|
|
||||||
@@ -9,6 +10,8 @@ __all__ = [
|
|||||||
"Clip",
|
"Clip",
|
||||||
"ClipKind",
|
"ClipKind",
|
||||||
"LoginAttempt",
|
"LoginAttempt",
|
||||||
|
"PROJECT_COLORS",
|
||||||
|
"Project",
|
||||||
"Role",
|
"Role",
|
||||||
"UTCDateTime",
|
"UTCDateTime",
|
||||||
"User",
|
"User",
|
||||||
|
|||||||
@@ -16,10 +16,16 @@ class ClipKind(enum.StrEnum):
|
|||||||
|
|
||||||
class Clip(Base):
|
class Clip(Base):
|
||||||
__tablename__ = "clips"
|
__tablename__ = "clips"
|
||||||
__table_args__ = (Index("ix_clips_user_order", "user_id", "pinned", "updated_at"),)
|
__table_args__ = (
|
||||||
|
Index("ix_clips_user_order", "user_id", "pinned", "updated_at"),
|
||||||
|
Index("ix_clips_user_project", "user_id", "project_id"),
|
||||||
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||||
|
project_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("projects.id", ondelete="SET NULL", name="fk_clips_project_id")
|
||||||
|
)
|
||||||
kind: Mapped[ClipKind] = mapped_column(
|
kind: Mapped[ClipKind] = mapped_column(
|
||||||
Enum(ClipKind, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e])
|
Enum(ClipKind, native_enum=False, length=16, values_callable=lambda e: [m.value for m in e])
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import ForeignKey, String, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.models.base import Base, UTCDateTime, utcnow
|
||||||
|
|
||||||
|
# Fixed palette; the frontend maps these keys to colors that fit the dark theme
|
||||||
|
PROJECT_COLORS = ("blue", "teal", "green", "amber", "orange", "red", "pink", "violet")
|
||||||
|
|
||||||
|
|
||||||
|
class Project(Base):
|
||||||
|
__tablename__ = "projects"
|
||||||
|
__table_args__ = (UniqueConstraint("user_id", "name_key", name="uq_projects_user_name"),)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
|
||||||
|
name: Mapped[str] = mapped_column(String(100))
|
||||||
|
# Case-folded name, so "Work" and "work" count as the same project
|
||||||
|
name_key: Mapped[str] = mapped_column(String(100))
|
||||||
|
color: Mapped[str] = mapped_column(String(16), default="blue")
|
||||||
|
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
|
||||||
@@ -14,6 +14,7 @@ class ClipCreate(BaseModel):
|
|||||||
content: str = Field(max_length=_CONTENT_MAX)
|
content: str = Field(max_length=_CONTENT_MAX)
|
||||||
language: str | None = Field(default=None, max_length=32)
|
language: str | None = Field(default=None, max_length=32)
|
||||||
pinned: bool = False
|
pinned: bool = False
|
||||||
|
project_id: int | None = None
|
||||||
|
|
||||||
|
|
||||||
class ClipUpdate(BaseModel):
|
class ClipUpdate(BaseModel):
|
||||||
@@ -24,6 +25,7 @@ class ClipUpdate(BaseModel):
|
|||||||
content: str | None = Field(default=None, max_length=_CONTENT_MAX)
|
content: str | None = Field(default=None, max_length=_CONTENT_MAX)
|
||||||
language: str | None = Field(default=None, max_length=32)
|
language: str | None = Field(default=None, max_length=32)
|
||||||
pinned: bool | None = None
|
pinned: bool | None = None
|
||||||
|
project_id: int | None = None
|
||||||
version: int | None = Field(default=None, description="Expected version for conflict check")
|
version: int | None = Field(default=None, description="Expected version for conflict check")
|
||||||
|
|
||||||
|
|
||||||
@@ -36,6 +38,7 @@ class ClipOut(BaseModel):
|
|||||||
content: str
|
content: str
|
||||||
language: str | None
|
language: str | None
|
||||||
pinned: bool
|
pinned: bool
|
||||||
|
project_id: int | None
|
||||||
version: int
|
version: int
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
updated_at: datetime
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
from app.models import PROJECT_COLORS
|
||||||
|
|
||||||
|
ProjectColor = Literal[PROJECT_COLORS] # type: ignore[valid-type]
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectCreate(BaseModel):
|
||||||
|
name: str = Field(max_length=1000)
|
||||||
|
color: ProjectColor = "blue"
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectUpdate(BaseModel):
|
||||||
|
name: str | None = Field(default=None, max_length=1000)
|
||||||
|
color: ProjectColor | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectOut(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
name: str
|
||||||
|
color: str
|
||||||
|
clip_count: int = 0
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
@@ -1,15 +1,20 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from sqlalchemy import delete, func, select, update
|
from sqlalchemy import delete, func, or_, select, update
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from app.config import get_settings
|
from app.config import get_settings
|
||||||
from app.languages import LANGUAGES
|
from app.languages import LANGUAGES
|
||||||
from app.models import Clip, ClipKind, utcnow
|
from app.models import Clip, ClipKind, utcnow
|
||||||
|
from app.services.projects import require_project
|
||||||
from app.services.users import UserError
|
from app.services.users import UserError
|
||||||
|
|
||||||
# Changing only these fields does not count as an edit (no new updated_at)
|
# Changing only these fields does not count as an edit (no new updated_at)
|
||||||
_META_FIELDS = frozenset({"pinned"})
|
_META_FIELDS = frozenset({"pinned", "project_id"})
|
||||||
|
|
||||||
|
# Filter value for clips without a project
|
||||||
|
NO_PROJECT = "none"
|
||||||
|
SEARCH_MAX_LENGTH = 200
|
||||||
|
|
||||||
|
|
||||||
class ClipConflict(Exception):
|
class ClipConflict(Exception):
|
||||||
@@ -40,15 +45,43 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
|
|||||||
return title, language
|
return title, language
|
||||||
|
|
||||||
|
|
||||||
def list_clips(db: Session, user_id: int, limit: int, offset: int) -> tuple[list[Clip], int]:
|
def _filters(user_id: int, project: int | str | None, query: str | None) -> list:
|
||||||
|
conditions = [Clip.user_id == user_id]
|
||||||
|
if project == NO_PROJECT:
|
||||||
|
conditions.append(Clip.project_id.is_(None))
|
||||||
|
elif project is not None:
|
||||||
|
conditions.append(Clip.project_id == project)
|
||||||
|
needle = (query or "").strip().casefold()
|
||||||
|
if needle:
|
||||||
|
# Substring match via instr(): no LIKE wildcards to escape, finds "config" in "getConfig"
|
||||||
|
conditions.append(
|
||||||
|
or_(
|
||||||
|
func.instr(func.lc_casefold(Clip.title), needle) > 0,
|
||||||
|
func.instr(func.lc_casefold(Clip.content), needle) > 0,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return conditions
|
||||||
|
|
||||||
|
|
||||||
|
def list_clips(
|
||||||
|
db: Session,
|
||||||
|
user_id: int,
|
||||||
|
limit: int,
|
||||||
|
offset: int,
|
||||||
|
*,
|
||||||
|
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."""
|
||||||
|
conditions = _filters(user_id, project, query)
|
||||||
items = db.scalars(
|
items = db.scalars(
|
||||||
select(Clip)
|
select(Clip)
|
||||||
.where(Clip.user_id == user_id)
|
.where(*conditions)
|
||||||
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
|
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.offset(offset)
|
.offset(offset)
|
||||||
)
|
)
|
||||||
total = db.scalar(select(func.count()).select_from(Clip).where(Clip.user_id == user_id))
|
total = db.scalar(select(func.count()).select_from(Clip).where(*conditions))
|
||||||
return list(items), total or 0
|
return list(items), total or 0
|
||||||
|
|
||||||
|
|
||||||
@@ -65,10 +98,14 @@ def create_clip(
|
|||||||
title: str | None = None,
|
title: str | None = None,
|
||||||
language: str | None = None,
|
language: str | None = None,
|
||||||
pinned: bool = False,
|
pinned: bool = False,
|
||||||
|
project_id: int | None = None,
|
||||||
) -> Clip:
|
) -> Clip:
|
||||||
title, language = _normalize(kind, title, content, language)
|
title, language = _normalize(kind, title, content, language)
|
||||||
|
if project_id is not None:
|
||||||
|
require_project(db, user_id, project_id)
|
||||||
clip = Clip(
|
clip = Clip(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
|
project_id=project_id,
|
||||||
kind=kind,
|
kind=kind,
|
||||||
title=title,
|
title=title,
|
||||||
content=content,
|
content=content,
|
||||||
@@ -93,8 +130,12 @@ def update_clip(
|
|||||||
content = changes.get("content", clip.content)
|
content = changes.get("content", clip.content)
|
||||||
language = changes.get("language", clip.language)
|
language = changes.get("language", clip.language)
|
||||||
title, language = _normalize(kind, title, content, 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)
|
||||||
|
|
||||||
values: dict[str, Any] = {
|
values: dict[str, Any] = {
|
||||||
|
"project_id": project_id,
|
||||||
"kind": kind,
|
"kind": kind,
|
||||||
"title": title,
|
"title": title,
|
||||||
"content": content,
|
"content": content,
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import unicodedata
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
NAME_MAX_LENGTH = 100
|
||||||
|
MAX_PROJECTS_PER_USER = 200
|
||||||
|
|
||||||
|
|
||||||
|
class ProjectNotFound(LookupError):
|
||||||
|
"""The project does not exist or belongs to another user."""
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_name(name: str) -> tuple[str, str]:
|
||||||
|
name = " ".join(name.split())
|
||||||
|
if not name:
|
||||||
|
raise UserError("Der Projektname darf nicht leer sein.")
|
||||||
|
if len(name) > NAME_MAX_LENGTH:
|
||||||
|
raise UserError(f"Der Projektname ist zu lang (höchstens {NAME_MAX_LENGTH} Zeichen).")
|
||||||
|
if any(unicodedata.category(ch).startswith("C") for ch in name):
|
||||||
|
raise UserError("Der Projektname enthält ungültige Zeichen.")
|
||||||
|
return name, name.casefold()
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_color(color: str) -> str:
|
||||||
|
if color not in PROJECT_COLORS:
|
||||||
|
raise UserError("Unbekannte Farbe.")
|
||||||
|
return color
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
.scalar_subquery()
|
||||||
|
)
|
||||||
|
rows = db.execute(
|
||||||
|
select(Project, clip_count)
|
||||||
|
.where(Project.user_id == 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
|
||||||
|
)
|
||||||
|
)
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_project(db: Session, user_id: int, *, name: str, color: str = "blue") -> Project:
|
||||||
|
name, name_key = _validate_name(name)
|
||||||
|
color = _validate_color(color)
|
||||||
|
existing = db.scalar(select(func.count(Project.id)).where(Project.user_id == user_id))
|
||||||
|
if (existing or 0) >= MAX_PROJECTS_PER_USER:
|
||||||
|
raise UserError(f"Höchstens {MAX_PROJECTS_PER_USER} Projekte möglich.")
|
||||||
|
project = Project(user_id=user_id, name=name, name_key=name_key, color=color)
|
||||||
|
db.add(project)
|
||||||
|
try:
|
||||||
|
db.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback()
|
||||||
|
raise _duplicate() from None
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
def update_project(
|
||||||
|
db: Session, project: Project, *, name: str | None = None, color: str | None = None
|
||||||
|
) -> Project:
|
||||||
|
if name is not None:
|
||||||
|
project.name, project.name_key = _validate_name(name)
|
||||||
|
if color is not None:
|
||||||
|
project.color = _validate_color(color)
|
||||||
|
project.updated_at = utcnow()
|
||||||
|
try:
|
||||||
|
db.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback()
|
||||||
|
raise _duplicate() from None
|
||||||
|
db.refresh(project)
|
||||||
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
return False
|
||||||
|
db.commit()
|
||||||
|
return True
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from tests.conftest import login
|
||||||
|
from tests.test_ws import connect
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def anna(client, make_user):
|
||||||
|
make_user("anna")
|
||||||
|
login(client, "anna")
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def bert(client, make_user):
|
||||||
|
"""Second logged-in user with own client, for data separation tests."""
|
||||||
|
make_user("bert")
|
||||||
|
with TestClient(client.app, base_url="https://testserver") as other:
|
||||||
|
login(other, "bert")
|
||||||
|
yield other
|
||||||
|
|
||||||
|
|
||||||
|
def create_project(c, name="Work", **fields):
|
||||||
|
response = c.post("/api/projects", json={"name": name, **fields})
|
||||||
|
assert response.status_code == 201, response.text
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def create_clip(c, **fields):
|
||||||
|
response = c.post("/api/clips", json={"content": "hello", **fields})
|
||||||
|
assert response.status_code == 201, response.text
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def clip_ids(c, **params):
|
||||||
|
response = c.get("/api/clips", params=params)
|
||||||
|
assert response.status_code == 200, response.text
|
||||||
|
body = response.json()
|
||||||
|
assert body["total"] == len(body["items"])
|
||||||
|
return [clip["id"] for clip in body["items"]]
|
||||||
|
|
||||||
|
|
||||||
|
# --- Projects -------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_and_list_projects_sorted_by_name(anna):
|
||||||
|
create_project(anna, "zeta")
|
||||||
|
project = create_project(anna, " Alpha Beta ", color="green")
|
||||||
|
create_project(anna, "Mitte")
|
||||||
|
|
||||||
|
assert project["name"] == "Alpha Beta"
|
||||||
|
assert project["color"] == "green"
|
||||||
|
assert project["clip_count"] == 0
|
||||||
|
names = [p["name"] for p in anna.get("/api/projects").json()]
|
||||||
|
assert names == ["Alpha Beta", "Mitte", "zeta"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_color(anna):
|
||||||
|
assert create_project(anna)["color"] == "blue"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"body",
|
||||||
|
[
|
||||||
|
{"name": " "},
|
||||||
|
{"name": "x" * 101},
|
||||||
|
{"name": "bell\x07"},
|
||||||
|
{"name": "zero\u200bwidth"},
|
||||||
|
{"name": "ok", "color": "black"},
|
||||||
|
{},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_create_validation(anna, body):
|
||||||
|
assert anna.post("/api/projects", json=body).status_code in (400, 422)
|
||||||
|
|
||||||
|
|
||||||
|
def test_name_is_unique_per_user_ignoring_case(anna, bert):
|
||||||
|
create_project(anna, "Straße")
|
||||||
|
|
||||||
|
response = anna.post("/api/projects", json={"name": "STRASSE"})
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "gibt es schon" in response.json()["detail"]
|
||||||
|
# Another user may use the same name
|
||||||
|
create_project(bert, "Straße")
|
||||||
|
|
||||||
|
|
||||||
|
def test_rename_and_recolor(anna):
|
||||||
|
project = create_project(anna, "Old")
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/projects/{project['id']}", json={"name": "New"})
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["name"] == "New"
|
||||||
|
assert response.json()["color"] == "blue"
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/projects/{project['id']}", json={"color": "red"})
|
||||||
|
assert (response.json()["name"], response.json()["color"]) == ("New", "red")
|
||||||
|
|
||||||
|
|
||||||
|
def test_rename_to_existing_name_fails(anna):
|
||||||
|
create_project(anna, "One")
|
||||||
|
two = create_project(anna, "Two")
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/projects/{two['id']}", json={"name": "one"})
|
||||||
|
assert response.status_code == 400
|
||||||
|
# Changing only the case of the own name is allowed
|
||||||
|
assert anna.patch(f"/api/projects/{two['id']}", json={"name": "TWO"}).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_limit(anna, monkeypatch):
|
||||||
|
monkeypatch.setattr("app.services.projects.MAX_PROJECTS_PER_USER", 2)
|
||||||
|
create_project(anna, "a")
|
||||||
|
create_project(anna, "b")
|
||||||
|
|
||||||
|
response = anna.post("/api/projects", json={"name": "c"})
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "Höchstens 2" in response.json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_clip_count(anna):
|
||||||
|
project = create_project(anna)
|
||||||
|
create_clip(anna, project_id=project["id"])
|
||||||
|
create_clip(anna, project_id=project["id"])
|
||||||
|
create_clip(anna)
|
||||||
|
|
||||||
|
assert anna.get("/api/projects").json()[0]["clip_count"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_project_keeps_clips(anna):
|
||||||
|
project = create_project(anna)
|
||||||
|
clip = create_clip(anna, project_id=project["id"])
|
||||||
|
|
||||||
|
assert anna.delete(f"/api/projects/{project['id']}").status_code == 204
|
||||||
|
|
||||||
|
assert anna.get("/api/projects").json() == []
|
||||||
|
current = anna.get(f"/api/clips/{clip['id']}").json()
|
||||||
|
assert current["project_id"] is None
|
||||||
|
assert current["content"] == "hello"
|
||||||
|
# Version is bumped so a stale editor gets a conflict instead of a missing project
|
||||||
|
assert current["version"] == clip["version"] + 1
|
||||||
|
assert current["updated_at"] == clip["updated_at"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_requires_login(client):
|
||||||
|
assert client.get("/api/projects").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
# --- Clips in projects ----------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_assign_clip_to_project(anna):
|
||||||
|
project = create_project(anna)
|
||||||
|
clip = create_clip(anna)
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/clips/{clip['id']}", json={"project_id": project["id"]})
|
||||||
|
assert response.status_code == 200
|
||||||
|
moved = response.json()
|
||||||
|
assert moved["project_id"] == project["id"]
|
||||||
|
# Moving is not an edit, so the clip keeps its place in the list
|
||||||
|
assert moved["updated_at"] == clip["updated_at"]
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/clips/{clip['id']}", json={"project_id": None})
|
||||||
|
assert response.json()["project_id"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_other_fields_keep_project(anna):
|
||||||
|
project = create_project(anna)
|
||||||
|
clip = create_clip(anna, project_id=project["id"])
|
||||||
|
|
||||||
|
response = anna.patch(f"/api/clips/{clip['id']}", json={"content": "changed"})
|
||||||
|
assert response.json()["project_id"] == project["id"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_project_is_rejected(anna):
|
||||||
|
assert anna.post("/api/clips", json={"content": "x", "project_id": 999}).status_code == 404
|
||||||
|
clip = create_clip(anna)
|
||||||
|
response = anna.patch(f"/api/clips/{clip['id']}", json={"project_id": 999})
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.json()["detail"] == "Projekt nicht gefunden."
|
||||||
|
|
||||||
|
|
||||||
|
def test_filter_by_project(anna):
|
||||||
|
work = create_project(anna, "Work")
|
||||||
|
home = create_project(anna, "Home")
|
||||||
|
a = create_clip(anna, project_id=work["id"])
|
||||||
|
b = create_clip(anna, project_id=home["id"])
|
||||||
|
c = create_clip(anna)
|
||||||
|
|
||||||
|
assert clip_ids(anna, project=work["id"]) == [a["id"]]
|
||||||
|
assert clip_ids(anna, project=home["id"]) == [b["id"]]
|
||||||
|
assert clip_ids(anna, project="none") == [c["id"]]
|
||||||
|
assert set(clip_ids(anna)) == {a["id"], b["id"], c["id"]}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", ["abc", "0", "-1", "1; drop", ""])
|
||||||
|
def test_invalid_project_filter(anna, value):
|
||||||
|
assert anna.get("/api/clips", params={"project": value}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
# --- Search ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_finds_substrings_in_content_and_title(anna):
|
||||||
|
code = create_clip(anna, kind="code", language="python", content="cfg = getConfig()")
|
||||||
|
titled = create_clip(anna, title="Server-Config", content="port 8085")
|
||||||
|
create_clip(anna, content="nothing here")
|
||||||
|
|
||||||
|
assert set(clip_ids(anna, q="config")) == {code["id"], titled["id"]}
|
||||||
|
assert clip_ids(anna, q="8085") == [titled["id"]]
|
||||||
|
assert clip_ids(anna, q="missing") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_ignores_case_including_umlauts(anna):
|
||||||
|
clip = create_clip(anna, content="Größe der ÜBERSICHT")
|
||||||
|
|
||||||
|
assert clip_ids(anna, q="größe") == [clip["id"]]
|
||||||
|
assert clip_ids(anna, q="übersicht") == [clip["id"]]
|
||||||
|
assert clip_ids(anna, q="GROESSE") == []
|
||||||
|
assert clip_ids(anna, q="GRÖSSE") == [clip["id"]]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("query", ["%", "_", "100%", "a_b", "\\"])
|
||||||
|
def test_search_treats_wildcards_literally(anna, query):
|
||||||
|
match = create_clip(anna, content="100% done, a_b, back\\slash")
|
||||||
|
create_clip(anna, content="plain text")
|
||||||
|
|
||||||
|
assert clip_ids(anna, q=query) == [match["id"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_blank_search_returns_everything(anna):
|
||||||
|
create_clip(anna)
|
||||||
|
create_clip(anna)
|
||||||
|
|
||||||
|
assert len(clip_ids(anna, q=" ")) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_combined_with_project(anna):
|
||||||
|
project = create_project(anna)
|
||||||
|
inside = create_clip(anna, content="token abc", project_id=project["id"])
|
||||||
|
create_clip(anna, content="token abc")
|
||||||
|
create_clip(anna, content="other", project_id=project["id"])
|
||||||
|
|
||||||
|
assert clip_ids(anna, q="token", project=project["id"]) == [inside["id"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_total_counts_all_matches(anna):
|
||||||
|
for i in range(5):
|
||||||
|
create_clip(anna, content=f"match {i}")
|
||||||
|
create_clip(anna, content="other")
|
||||||
|
|
||||||
|
body = anna.get("/api/clips", params={"q": "match", "limit": 2}).json()
|
||||||
|
assert len(body["items"]) == 2
|
||||||
|
assert body["total"] == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_length_limit(anna):
|
||||||
|
assert anna.get("/api/clips", params={"q": "x" * 201}).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
# --- Data separation ------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_projects_of_other_users_are_invisible(anna, bert):
|
||||||
|
project = create_project(anna, "Secret")
|
||||||
|
url = f"/api/projects/{project['id']}"
|
||||||
|
|
||||||
|
assert bert.get("/api/projects").json() == []
|
||||||
|
assert bert.patch(url, json={"name": "Mine"}).status_code == 404
|
||||||
|
assert bert.delete(url).status_code == 404
|
||||||
|
assert anna.get("/api/projects").json()[0]["name"] == "Secret"
|
||||||
|
|
||||||
|
|
||||||
|
def test_cannot_use_foreign_project_for_clips(anna, bert):
|
||||||
|
project = create_project(anna)
|
||||||
|
|
||||||
|
response = bert.post("/api/clips", json={"content": "x", "project_id": project["id"]})
|
||||||
|
assert response.status_code == 404
|
||||||
|
clip = create_clip(bert)
|
||||||
|
response = bert.patch(f"/api/clips/{clip['id']}", json={"project_id": project["id"]})
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert anna.get("/api/projects").json()[0]["clip_count"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_filters_and_search_never_return_foreign_clips(anna, bert):
|
||||||
|
project = create_project(anna)
|
||||||
|
create_clip(anna, content="secret anna", project_id=project["id"])
|
||||||
|
create_clip(anna, content="secret anna")
|
||||||
|
|
||||||
|
assert clip_ids(bert, q="secret") == []
|
||||||
|
assert clip_ids(bert, project=project["id"]) == []
|
||||||
|
assert clip_ids(bert, project="none") == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_deleting_foreign_project_does_not_touch_its_clips(anna, bert):
|
||||||
|
project = create_project(anna)
|
||||||
|
clip = create_clip(anna, project_id=project["id"])
|
||||||
|
|
||||||
|
assert bert.delete(f"/api/projects/{project['id']}").status_code == 404
|
||||||
|
assert anna.get(f"/api/clips/{clip['id']}").json()["project_id"] == project["id"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_deleting_user_removes_projects(client, anna, db, make_user):
|
||||||
|
from app.models import Project, Role, User
|
||||||
|
|
||||||
|
project_id = create_project(anna)["id"]
|
||||||
|
make_user("root", role=Role.ADMIN)
|
||||||
|
with TestClient(client.app, base_url="https://testserver") as admin:
|
||||||
|
login(admin, "root")
|
||||||
|
anna_id = db.query(User).filter_by(username="anna").one().id
|
||||||
|
assert admin.delete(f"/api/admin/users/{anna_id}").status_code == 204
|
||||||
|
|
||||||
|
db.expire_all()
|
||||||
|
assert db.get(Project, project_id) is None
|
||||||
|
|
||||||
|
|
||||||
|
# --- Live sync ------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_events_reach_all_devices(anna, bert):
|
||||||
|
with connect(anna) as ws, connect(bert) as bert_ws:
|
||||||
|
ws.receive_json()
|
||||||
|
bert_ws.receive_json()
|
||||||
|
|
||||||
|
project = create_project(anna, "Live")
|
||||||
|
event = ws.receive_json()
|
||||||
|
assert event["type"] == "project.created"
|
||||||
|
assert event["data"]["name"] == "Live"
|
||||||
|
|
||||||
|
anna.patch(f"/api/projects/{project['id']}", json={"color": "pink"})
|
||||||
|
event = ws.receive_json()
|
||||||
|
assert event["type"] == "project.updated"
|
||||||
|
assert event["data"]["color"] == "pink"
|
||||||
|
|
||||||
|
anna.delete(f"/api/projects/{project['id']}")
|
||||||
|
assert ws.receive_json() == {"type": "project.deleted", "data": {"id": project["id"]}}
|
||||||
|
|
||||||
|
# Bert gets nothing of this; his first event is his own
|
||||||
|
create_clip(bert)
|
||||||
|
assert bert_ws.receive_json()["type"] == "clip.created"
|
||||||
Reference in new issue
Block a user