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
@@ -12,7 +12,10 @@ from app.ws.hub import hub
|
||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
|
||||
# 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:
|
||||
@@ -38,8 +41,13 @@ def list_clips(
|
||||
db: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
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:
|
||||
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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
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:
|
||||
# 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.execute("PRAGMA journal_mode=WAL")
|
||||
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 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.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -18,6 +18,7 @@ from app.middleware import (
|
||||
SecurityHeadersMiddleware,
|
||||
)
|
||||
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
|
||||
|
||||
@@ -129,12 +130,20 @@ def create_app() -> FastAPI:
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.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.exception_handler(UserError)
|
||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||
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)
|
||||
return app
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from app.models.base import Base, UTCDateTime, utcnow
|
||||
from app.models.clip import Clip, ClipKind
|
||||
from app.models.login_attempt import LoginAttempt
|
||||
from app.models.project import PROJECT_COLORS, Project
|
||||
from app.models.session import UserSession
|
||||
from app.models.user import Role, User
|
||||
|
||||
@@ -9,6 +10,8 @@ __all__ = [
|
||||
"Clip",
|
||||
"ClipKind",
|
||||
"LoginAttempt",
|
||||
"PROJECT_COLORS",
|
||||
"Project",
|
||||
"Role",
|
||||
"UTCDateTime",
|
||||
"User",
|
||||
|
||||
@@ -16,10 +16,16 @@ class ClipKind(enum.StrEnum):
|
||||
|
||||
class Clip(Base):
|
||||
__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)
|
||||
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(
|
||||
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)
|
||||
language: str | None = Field(default=None, max_length=32)
|
||||
pinned: bool = False
|
||||
project_id: int | None = None
|
||||
|
||||
|
||||
class ClipUpdate(BaseModel):
|
||||
@@ -24,6 +25,7 @@ class ClipUpdate(BaseModel):
|
||||
content: str | None = Field(default=None, max_length=_CONTENT_MAX)
|
||||
language: str | None = Field(default=None, max_length=32)
|
||||
pinned: bool | None = None
|
||||
project_id: int | None = None
|
||||
version: int | None = Field(default=None, description="Expected version for conflict check")
|
||||
|
||||
|
||||
@@ -36,6 +38,7 @@ class ClipOut(BaseModel):
|
||||
content: str
|
||||
language: str | None
|
||||
pinned: bool
|
||||
project_id: int | None
|
||||
version: int
|
||||
created_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 sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy import delete, func, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.languages import LANGUAGES
|
||||
from app.models import Clip, ClipKind, utcnow
|
||||
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)
|
||||
_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):
|
||||
@@ -40,15 +45,43 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
|
||||
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(
|
||||
select(Clip)
|
||||
.where(Clip.user_id == user_id)
|
||||
.where(*conditions)
|
||||
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
|
||||
.limit(limit)
|
||||
.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
|
||||
|
||||
|
||||
@@ -65,10 +98,14 @@ def create_clip(
|
||||
title: str | None = None,
|
||||
language: str | None = None,
|
||||
pinned: bool = False,
|
||||
project_id: int | None = None,
|
||||
) -> Clip:
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
if project_id is not None:
|
||||
require_project(db, user_id, project_id)
|
||||
clip = Clip(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
kind=kind,
|
||||
title=title,
|
||||
content=content,
|
||||
@@ -93,8 +130,12 @@ def update_clip(
|
||||
content = changes.get("content", clip.content)
|
||||
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)
|
||||
|
||||
values: dict[str, Any] = {
|
||||
"project_id": project_id,
|
||||
"kind": kind,
|
||||
"title": title,
|
||||
"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
|
||||
Reference in new issue
Block a user