Files
lan-clipboard/backend/app/services/clips.py
T
dbildhauerandClaude Opus 5.5 52a8fd019f feat: dateiaustausch im backend
Dateien als Clip-Art "file": gestreamter Upload mit Größengrenze, Kontingent
pro Benutzer und Mindestreserve an freiem Speicher. Download immer als
Anhang mit sandbox-CSP, Vorschau nur für geprüfte JPEG/PNG/GIF/WebP.
Ablauf nach 1/7/30 Tagen oder nie; der Aufräumjob löscht abgelaufene und
verwaiste Dateien.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:01:10 +01:00

187 lines
6.3 KiB
Python

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, StoredFile, utcnow
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)
_META_FIELDS = frozenset({"pinned", "project_id"})
# Fixed for file clips: content is the file name
_CONTENT_FIELDS = frozenset({"kind", "content", "language"})
# 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.CODE:
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:
if kind == ClipKind.FILE:
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)
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)
if clip.kind == ClipKind.FILE and set(changes) & _CONTENT_FIELDS:
raise UserError("Bei Dateien lassen sich nur Titel, Projekt und Anheften ändern.")
if changes.get("kind") == ClipKind.FILE and clip.kind != ClipKind.FILE:
raise UserError("Ein Clip lässt sich nicht in eine Datei umwandeln.")
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:
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))
db.commit()
if storage_name is not None:
remove_from_disk(user_id, storage_name)
return result.rowcount > 0