from typing import Any 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", "project_id"}) # Filter value for clips without a project NO_PROJECT = "none" SEARCH_MAX_LENGTH = 200 class ClipConflict(Exception): """The clip was changed elsewhere since the client loaded it.""" def __init__(self, current: Clip) -> None: super().__init__("clip version conflict") self.current = current def _normalize(kind: ClipKind, title: str | None, content: str, language: str | None): max_chars = get_settings().clip_max_chars if not content.strip(): raise UserError("Der Inhalt darf nicht leer sein.") if len(content) > max_chars: raise UserError( f"Der Inhalt ist zu lang (höchstens {max_chars:,} Zeichen).".replace(",", ".") ) title = (title or "").strip() or None if title is not None and len(title) > 200: raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).") if kind == ClipKind.TEXT: language = None else: language = language or "plaintext" if language not in LANGUAGES: raise UserError("Unbekannte Sprache.") return title, language 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(*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(*conditions)) return list(items), total or 0 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)) def create_clip( db: Session, user_id: int, *, content: str, kind: ClipKind = ClipKind.TEXT, 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, language=language, pinned=pinned, ) db.add(clip) db.commit() return clip def update_clip( db: Session, user_id: int, clip: Clip, changes: dict[str, Any], expected_version: int | None = None, ) -> Clip: """Apply a partial update. With expected_version, a concurrent change raises ClipConflict.""" # 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) kind = changes.get("kind", clip.kind) title = changes.get("title", clip.title) 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, "language": language, "pinned": changes.get("pinned", clip.pinned), "version": Clip.version + 1, } if set(changes) - _META_FIELDS: 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) if expected_version is not None: stmt = stmt.where(Clip.version == expected_version) result = db.execute(stmt.values(**values).execution_options(synchronize_session=False)) if result.rowcount == 0: db.rollback() db.refresh(clip) raise ClipConflict(clip) db.commit() db.refresh(clip) return clip def delete_clip(db: Session, user_id: int, clip_id: int) -> bool: result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id)) db.commit() return result.rowcount > 0