"""Daily Report photo service: validate, persist, resolve, delete. Photos are attached to the whole Daily Report (REQ). Files live under the managed document storage root; only metadata is stored in SQLite. Storage key layout (server-generated only, never derived from user input): projects/{project_id}/daily_reports/{daily_report_id}/photos/{uuid}.{ext} Transaction ownership: the service does NOT commit. The caller manages the database transaction. Filesystem writes use compensating cleanup on failure. """ from __future__ import annotations import os import re import tempfile import uuid from pathlib import Path from sqlalchemy import func, select from sqlalchemy.orm import Session from app.config import document_storage_root from app.models.daily_report_photo import DailyReportPhoto # --------------------------------------------------------------------------- # Limits and supported formats # --------------------------------------------------------------------------- # Accepted raster formats. Extension is only a hint — content is validated # against magic bytes so a renamed non-image cannot be stored as a photo. ALLOWED_IMAGE_TYPES: dict[str, str] = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", } ALLOWED_CONTENT_TYPES = frozenset(ALLOWED_IMAGE_TYPES.values()) # Hard limit per file. Larger uploads are rejected with a clear message. MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 10 MB # Hard limit per Daily Report so a report cannot be flooded with uploads. MAX_PHOTOS_PER_REPORT = 20 _SAFE_SEGMENT = re.compile(r"^[A-Za-z0-9._-]+$") class DailyReportPhotoError(ValueError): """Domain error raised by the photo service.""" class PhotoNotFoundError(DailyReportPhotoError): """Photo row or physical file is missing.""" class PhotoPathError(DailyReportPhotoError): """storage_key is unsafe or escapes the storage root.""" class PhotoValidationError(DailyReportPhotoError): """Uploaded file is not an accepted image or exceeds the limits.""" # --------------------------------------------------------------------------- # Content validation # --------------------------------------------------------------------------- def compute_content_hash(content: bytes) -> str: import hashlib return hashlib.sha256(content).hexdigest() def _sniff_extension(content: bytes) -> str | None: """Return the image extension implied by magic bytes, or None.""" if content.startswith(b"\xff\xd8\xff"): return ".jpg" if content.startswith(b"\x89PNG\r\n\x1a\n"): return ".png" if len(content) >= 12 and content[:4] == b"RIFF" and content[8:12] == b"WEBP": return ".webp" return None def _extension_for_name(filename: str | None) -> str: if not filename: return "" return Path(str(filename)).suffix.lower() def validate_upload(content: bytes, original_name: str | None, content_type: str | None) -> tuple[str, str]: """Validate an uploaded photo. Returns (extension, content_type). The original file name is never used as a path — only its extension is consulted as a hint and then cross-checked against the magic bytes. """ if not isinstance(content, (bytes, bytearray)): raise PhotoValidationError("Файл фотографии повреждён") content = bytes(content) if not content: raise PhotoValidationError("Файл фотографии пуст") if len(content) > MAX_PHOTO_BYTES: limit_mb = MAX_PHOTO_BYTES // (1024 * 1024) raise PhotoValidationError( f"Файл слишком большой: {len(content) / (1024 * 1024):.1f} МБ " f"при лимите {limit_mb} МБ" ) sniffed = _sniff_extension(content) if sniffed is None: raise PhotoValidationError( "Неподдерживаемый формат файла: допускаются JPEG, PNG и WebP" ) name_ext = _extension_for_name(original_name) # Declared extension is only a hint; the content decides the real type. if name_ext and name_ext in ALLOWED_IMAGE_TYPES and name_ext != sniffed and not ( sniffed == ".jpg" and name_ext == ".jpeg" ): raise PhotoValidationError( f"Содержимое файла не соответствует расширению {name_ext}: " f"ожидается {ALLOWED_IMAGE_TYPES[sniffed]}" ) declared_type = (content_type or "").split(";")[0].strip().lower() real_type = ALLOWED_IMAGE_TYPES[sniffed] if declared_type and declared_type in ALLOWED_CONTENT_TYPES and declared_type != real_type: raise PhotoValidationError( f"Тип содержимого не соответствует формату файла: {declared_type} ≠ {real_type}" ) return sniffed, real_type # --------------------------------------------------------------------------- # Storage paths # --------------------------------------------------------------------------- def build_photo_storage_key( project_id: int, daily_report_id: int, extension: str, token: str | None = None, ) -> str: """Server-generated relative storage key. Never uses the original file name.""" project_id = int(project_id) daily_report_id = int(daily_report_id) if project_id <= 0 or daily_report_id <= 0: raise PhotoPathError("project_id and daily_report_id must be positive") ext = extension.lstrip(".").lower() if not _SAFE_SEGMENT.match(ext): raise PhotoPathError(f"Invalid extension: {extension!r}") if f".{ext}" not in ALLOWED_IMAGE_TYPES: raise PhotoPathError(f"Unsupported extension: {extension!r}") name = f"{token or uuid.uuid4().hex}.{ext}" return ( f"projects/{project_id}/daily_reports/{daily_report_id}/photos/{name}" ) def resolve_photo_path(storage_key: str) -> Path: """Map a relative storage key to an absolute path inside the storage root.""" if not storage_key or not str(storage_key).strip(): raise PhotoPathError("storage_key is required") key = str(storage_key).replace("\\", "/").strip() if key.startswith("/") or re.match(r"^[A-Za-z]:", key): raise PhotoPathError("storage_key must be relative") if ".." in Path(key).parts: raise PhotoPathError("storage_key must not contain '..'") root = document_storage_root().resolve() candidate = (root / key).resolve() try: candidate.relative_to(root) except ValueError as exc: raise PhotoPathError("storage_key escapes storage root") from exc return candidate # --------------------------------------------------------------------------- # Persist / delete # --------------------------------------------------------------------------- def count_photos(db: Session, daily_report_id: int) -> int: return int( db.execute( select(func.count()).select_from(DailyReportPhoto).where( DailyReportPhoto.daily_report_id == int(daily_report_id) ) ).scalar() or 0 ) def persist_photo( db: Session, *, project_id: int, daily_report_id: int, content: bytes, original_name: str | None = None, content_type: str | None = None, sort_order: int = 0, ) -> DailyReportPhoto: """Validate, store photo bytes on disk and stage a DailyReportPhoto row. Does NOT commit. The caller owns the transaction. On failure the file created by this call is removed (compensating cleanup); existing photos are never touched. """ content = bytes(content) extension, real_type = validate_upload(content, original_name, content_type) existing = count_photos(db, daily_report_id) if existing >= MAX_PHOTOS_PER_REPORT: raise PhotoValidationError( f"К отчёту уже прикреплено максимальное количество фото " f"({MAX_PHOTOS_PER_REPORT})" ) storage_key = build_photo_storage_key(project_id, daily_report_id, extension) path = resolve_photo_path(storage_key) path.parent.mkdir(parents=True, exist_ok=True) tmp_fd, tmp_name = tempfile.mkstemp( dir=str(path.parent), prefix=".tmp-photo-", suffix=extension ) tmp_path = Path(tmp_name) try: with os.fdopen(tmp_fd, "wb") as handle: handle.write(content) handle.flush() os.fsync(handle.fileno()) os.replace(tmp_path, path) except Exception: if tmp_path.exists(): try: tmp_path.unlink() except OSError: pass raise photo = DailyReportPhoto( project_id=int(project_id), daily_report_id=int(daily_report_id), storage_key=storage_key, # Display only. Never used to build a path. original_name=(str(original_name).strip()[:255] or None) if original_name else None, content_type=real_type, file_size=len(content), content_hash=compute_content_hash(content), sort_order=int(sort_order), ) try: db.add(photo) db.flush() except Exception: # Compensating cleanup: the file must not outlive a failed row insert. remove_photo_file(storage_key) raise return photo def persist_photos( db: Session, *, project_id: int, daily_report_id: int, uploads: list[tuple[bytes, str | None, str | None]], ) -> list[DailyReportPhoto]: """Persist a batch of uploads. Rolls back all files of the batch on failure. `uploads` is a list of (content, original_name, content_type). """ created: list[DailyReportPhoto] = [] keys: list[str] = [] try: for index, (content, name, ctype) in enumerate(uploads): photo = persist_photo( db, project_id=project_id, daily_report_id=daily_report_id, content=content, original_name=name, content_type=ctype, sort_order=index, ) created.append(photo) keys.append(photo.storage_key) except Exception: for key in keys: remove_photo_file(key) raise return created def remove_photo_file(storage_key: str) -> None: """Best-effort delete of a photo file. Never raises.""" try: path = resolve_photo_path(storage_key) except PhotoPathError: return try: if path.is_file(): path.unlink() except OSError: pass def delete_photo(db: Session, photo: DailyReportPhoto) -> None: """Delete the photo row and its physical file. Row removal is the caller's transaction; the file is removed after the row is gone so a rollback keeps the file reachable. """ storage_key = photo.storage_key db.delete(photo) db.flush() remove_photo_file(storage_key) def photo_file_bytes(photo: DailyReportPhoto) -> bytes: """Read the photo file. Raises PhotoNotFoundError when missing.""" try: path = resolve_photo_path(photo.storage_key) except PhotoPathError as exc: raise PhotoNotFoundError(f"Файл фотографии недоступен: {exc}") from exc if not path.is_file(): raise PhotoNotFoundError("Файл фотографии не найден в хранилище") return path.read_bytes()