print_log.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import logging
  2. from datetime import datetime
  3. from fastapi import APIRouter, Depends, HTTPException, Query
  4. from fastapi.responses import FileResponse
  5. from sqlalchemy import delete, func, select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.core.auth import (
  8. RequireCameraStreamTokenIfAuthEnabled,
  9. RequirePermissionIfAuthEnabled,
  10. require_ownership_permission,
  11. )
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.models.print_log import PrintLogEntry
  16. from backend.app.models.user import User
  17. from backend.app.schemas.print_log import PrintLogEntrySchema, PrintLogResponse
  18. logger = logging.getLogger(__name__)
  19. router = APIRouter(prefix="/print-log", tags=["print-log"])
  20. @router.get("/", response_model=PrintLogResponse)
  21. async def get_print_log(
  22. search: str | None = None,
  23. printer_id: int | None = None,
  24. created_by_username: str | None = None,
  25. status: str | None = None,
  26. date_from: datetime | None = None,
  27. date_to: datetime | None = None,
  28. limit: int = Query(default=50, ge=1, le=500),
  29. offset: int = Query(default=0, ge=0),
  30. db: AsyncSession = Depends(get_db),
  31. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  32. ):
  33. """Get the print log."""
  34. query = select(PrintLogEntry)
  35. count_query = select(func.count(PrintLogEntry.id))
  36. if printer_id is not None:
  37. query = query.where(PrintLogEntry.printer_id == printer_id)
  38. count_query = count_query.where(PrintLogEntry.printer_id == printer_id)
  39. if created_by_username:
  40. query = query.where(PrintLogEntry.created_by_username == created_by_username)
  41. count_query = count_query.where(PrintLogEntry.created_by_username == created_by_username)
  42. if status:
  43. query = query.where(PrintLogEntry.status == status)
  44. count_query = count_query.where(PrintLogEntry.status == status)
  45. if search:
  46. query = query.where(PrintLogEntry.print_name.ilike(f"%{search}%"))
  47. count_query = count_query.where(PrintLogEntry.print_name.ilike(f"%{search}%"))
  48. if date_from:
  49. query = query.where(PrintLogEntry.created_at >= date_from)
  50. count_query = count_query.where(PrintLogEntry.created_at >= date_from)
  51. if date_to:
  52. query = query.where(PrintLogEntry.created_at <= date_to)
  53. count_query = count_query.where(PrintLogEntry.created_at <= date_to)
  54. # Get total count
  55. total_result = await db.execute(count_query)
  56. total = total_result.scalar() or 0
  57. # Get paginated results
  58. query = query.order_by(PrintLogEntry.created_at.desc()).offset(offset).limit(limit)
  59. result = await db.execute(query)
  60. entries = result.scalars().all()
  61. return PrintLogResponse(
  62. items=[
  63. PrintLogEntrySchema(
  64. id=e.id,
  65. print_name=e.print_name,
  66. printer_name=e.printer_name,
  67. printer_id=e.printer_id,
  68. status=e.status,
  69. started_at=e.started_at,
  70. completed_at=e.completed_at,
  71. duration_seconds=e.duration_seconds,
  72. filament_type=e.filament_type,
  73. filament_color=e.filament_color,
  74. filament_used_grams=e.filament_used_grams,
  75. thumbnail_path=e.thumbnail_path,
  76. created_by_username=e.created_by_username,
  77. created_at=e.created_at,
  78. )
  79. for e in entries
  80. ],
  81. total=total,
  82. )
  83. @router.get("/{entry_id}/thumbnail")
  84. async def get_print_log_thumbnail(
  85. entry_id: int,
  86. db: AsyncSession = Depends(get_db),
  87. _: None = RequireCameraStreamTokenIfAuthEnabled,
  88. ):
  89. """Get the thumbnail for a print log entry.
  90. Requires a stream token query param (?token=xxx) when auth is enabled.
  91. Self-heals stale entries: when thumbnail_path points to a file that no
  92. longer exists on disk (archive was deleted, or print failed before the
  93. thumbnail was ever written), NULL the path on the entry so subsequent
  94. page renders skip the request entirely. The frontend's <img> tag is
  95. gated on entry.thumbnail_path being truthy, so the next fetch of the
  96. log list will simply not request this thumbnail again.
  97. """
  98. entry = await db.get(PrintLogEntry, entry_id)
  99. if not entry or not entry.thumbnail_path:
  100. raise HTTPException(404, "Thumbnail not found")
  101. thumb_path = settings.base_dir / entry.thumbnail_path
  102. if not thumb_path.exists():
  103. entry.thumbnail_path = None
  104. await db.commit()
  105. raise HTTPException(404, "Thumbnail file not found")
  106. return FileResponse(
  107. path=thumb_path,
  108. media_type="image/png",
  109. headers={"Cache-Control": "public, max-age=86400"},
  110. )
  111. @router.delete("/")
  112. async def clear_print_log(
  113. db: AsyncSession = Depends(get_db),
  114. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_ALL),
  115. ):
  116. """Clear the print log.
  117. Only deletes log entries. Archives and queue items are never touched.
  118. """
  119. result = await db.execute(delete(PrintLogEntry))
  120. deleted = result.rowcount
  121. await db.commit()
  122. logger.info("Print log cleared: %d entries deleted", deleted)
  123. return {"deleted": deleted}
  124. @router.delete("/{entry_id}")
  125. async def delete_print_log_entry(
  126. entry_id: int,
  127. db: AsyncSession = Depends(get_db),
  128. auth_result: tuple[User | None, bool] = Depends(
  129. require_ownership_permission(
  130. Permission.ARCHIVES_DELETE_ALL,
  131. Permission.ARCHIVES_DELETE_OWN,
  132. )
  133. ),
  134. ):
  135. """Delete a single print-log entry (#1687).
  136. Removes the row entirely. Because /archives/stats aggregates over
  137. PrintLogEntry, the deleted row's filament / cost / duration / count
  138. contributions drop out of the totals in the same response cycle.
  139. The linked archive (if any) is untouched — the FK on the archive row
  140. is from PrintLogEntry, not the other way around.
  141. """
  142. user, can_modify_all = auth_result
  143. entry = await db.get(PrintLogEntry, entry_id)
  144. if not entry:
  145. raise HTTPException(404, "Print log entry not found")
  146. if not can_modify_all:
  147. if entry.created_by_id is None or (user is not None and entry.created_by_id != user.id):
  148. raise HTTPException(403, "You can only delete your own print log entries")
  149. await db.delete(entry)
  150. await db.commit()
  151. logger.info("Print log entry %d deleted", entry_id)
  152. return {"status": "deleted", "id": entry_id}