library.py 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786
  1. """API routes for File Manager (Library) functionality."""
  2. import base64
  3. import binascii
  4. import hashlib
  5. import logging
  6. import os
  7. import re
  8. import shutil
  9. import uuid
  10. import zipfile
  11. from pathlib import Path
  12. from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile
  13. from fastapi.responses import FileResponse as FastAPIFileResponse
  14. from sqlalchemy import func, select
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from sqlalchemy.orm import selectinload
  17. from backend.app.core.auth import (
  18. RequireCameraStreamTokenIfAuthEnabled,
  19. require_ownership_permission,
  20. require_permission_if_auth_enabled,
  21. )
  22. from backend.app.core.config import settings as app_settings
  23. from backend.app.core.database import get_db
  24. from backend.app.core.permissions import Permission
  25. from backend.app.models.archive import PrintArchive
  26. from backend.app.models.library import LibraryFile, LibraryFolder
  27. from backend.app.models.print_queue import PrintQueueItem
  28. from backend.app.models.project import Project
  29. from backend.app.models.user import User
  30. from backend.app.schemas.library import (
  31. AddToQueueError,
  32. AddToQueueRequest,
  33. AddToQueueResponse,
  34. AddToQueueResult,
  35. BatchThumbnailRequest,
  36. BatchThumbnailResponse,
  37. BatchThumbnailResult,
  38. BulkDeleteRequest,
  39. BulkDeleteResponse,
  40. ExternalFolderCreate,
  41. FileDuplicate,
  42. FileListResponse,
  43. FileMoveRequest,
  44. FilePrintRequest,
  45. FileResponse as FileResponseSchema,
  46. FileUpdate,
  47. FileUploadResponse,
  48. FolderCreate,
  49. FolderResponse,
  50. FolderTreeItem,
  51. FolderUpdate,
  52. ZipExtractError,
  53. ZipExtractResponse,
  54. ZipExtractResult,
  55. )
  56. from backend.app.services.archive import ThreeMFParser
  57. from backend.app.services.stl_thumbnail import generate_stl_thumbnail
  58. from backend.app.utils.threemf_tools import extract_nozzle_mapping_from_3mf
  59. logger = logging.getLogger(__name__)
  60. router = APIRouter(prefix="/library", tags=["library"])
  61. def get_library_dir() -> Path:
  62. """Get the library storage directory."""
  63. base_dir = Path(app_settings.archive_dir)
  64. library_dir = base_dir / "library"
  65. library_dir.mkdir(parents=True, exist_ok=True)
  66. return library_dir
  67. def get_library_files_dir() -> Path:
  68. """Get the directory for library files."""
  69. files_dir = get_library_dir() / "files"
  70. files_dir.mkdir(parents=True, exist_ok=True)
  71. return files_dir
  72. def get_library_thumbnails_dir() -> Path:
  73. """Get the directory for library thumbnails."""
  74. thumbnails_dir = get_library_dir() / "thumbnails"
  75. thumbnails_dir.mkdir(parents=True, exist_ok=True)
  76. return thumbnails_dir
  77. def to_relative_path(absolute_path: Path | str) -> str:
  78. """Convert an absolute path to a path relative to base_dir for storage."""
  79. if not absolute_path:
  80. return ""
  81. abs_path = Path(absolute_path)
  82. base_dir = Path(app_settings.base_dir)
  83. try:
  84. return str(abs_path.relative_to(base_dir))
  85. except ValueError:
  86. # Path is not under base_dir, return as-is (shouldn't happen normally)
  87. return str(abs_path)
  88. def to_absolute_path(relative_path: str | None) -> Path | None:
  89. """Convert a relative path (from database) to an absolute path for file operations."""
  90. if not relative_path:
  91. return None
  92. path = Path(relative_path)
  93. # Handle already-absolute paths verbatim (backwards compatibility during migration).
  94. # Legacy DB rows may store absolute paths that predate the base_dir layout; the
  95. # traversal guard below only applies to relative paths coming from user input.
  96. if path.is_absolute():
  97. return path.resolve()
  98. base = Path(app_settings.base_dir).resolve()
  99. resolved = (base / relative_path).resolve()
  100. # Guard against path traversal — resolved path must stay inside base_dir.
  101. # Use is_relative_to() to avoid the /data/app vs /data/app_evil prefix confusion
  102. # that a plain startswith(str(base)) check would miss.
  103. if not resolved.is_relative_to(base):
  104. raise ValueError(f"Path escapes base directory: {relative_path!r}")
  105. return resolved
  106. def calculate_file_hash(file_path: Path) -> str:
  107. """Calculate SHA256 hash of a file."""
  108. sha256_hash = hashlib.sha256()
  109. with open(file_path, "rb") as f:
  110. for byte_block in iter(lambda: f.read(4096), b""):
  111. sha256_hash.update(byte_block)
  112. return sha256_hash.hexdigest()
  113. def extract_gcode_thumbnail(file_path: Path) -> bytes | None:
  114. """Extract embedded thumbnail from gcode file.
  115. Supports PrusaSlicer/BambuStudio format:
  116. ; thumbnail begin WxH SIZE
  117. ; base64data...
  118. ; thumbnail end
  119. """
  120. try:
  121. thumbnail_data = None
  122. in_thumbnail = False
  123. thumbnail_lines = []
  124. best_size = 0
  125. with open(file_path, errors="ignore") as f:
  126. # Only read first 50KB for performance (thumbnails are at the start)
  127. content = f.read(50000)
  128. for line in content.split("\n"):
  129. line = line.strip()
  130. # Check for thumbnail start
  131. if line.startswith("; thumbnail begin"):
  132. in_thumbnail = True
  133. thumbnail_lines = []
  134. # Parse dimensions: "; thumbnail begin 300x300 12345"
  135. match = re.search(r"(\d+)x(\d+)", line)
  136. if match:
  137. width = int(match.group(1))
  138. # Prefer larger thumbnails (up to 300px)
  139. if width > best_size and width <= 300:
  140. best_size = width
  141. continue
  142. # Check for thumbnail end
  143. if line.startswith("; thumbnail end"):
  144. if in_thumbnail and thumbnail_lines:
  145. try:
  146. # Decode the base64 data
  147. b64_data = "".join(thumbnail_lines)
  148. decoded = base64.b64decode(b64_data)
  149. # Only keep if this is the best size or first valid thumbnail
  150. if thumbnail_data is None or best_size > 0:
  151. thumbnail_data = decoded
  152. except (binascii.Error, ValueError):
  153. pass # Skip thumbnail with invalid base64 data
  154. in_thumbnail = False
  155. thumbnail_lines = []
  156. continue
  157. # Collect thumbnail data
  158. if in_thumbnail and line.startswith(";"):
  159. # Remove the leading "; " or ";"
  160. data_line = line[1:].strip()
  161. if data_line:
  162. thumbnail_lines.append(data_line)
  163. return thumbnail_data
  164. except Exception as e:
  165. logger.warning("Failed to extract gcode thumbnail: %s", e)
  166. return None
  167. def create_image_thumbnail(file_path: Path, thumbnails_dir: Path, max_size: int = 256) -> str | None:
  168. """Create a thumbnail from an image file.
  169. For small images, copies directly. For larger images, resizes.
  170. Returns the thumbnail path or None on failure.
  171. """
  172. try:
  173. from PIL import Image
  174. thumb_filename = f"{uuid.uuid4().hex}.png"
  175. thumb_path = thumbnails_dir / thumb_filename
  176. with Image.open(file_path) as img:
  177. # Convert to RGB if necessary (for PNG with transparency, etc.)
  178. if img.mode in ("RGBA", "LA", "P"):
  179. # Create white background for transparency
  180. background = Image.new("RGB", img.size, (255, 255, 255))
  181. if img.mode == "P":
  182. img = img.convert("RGBA")
  183. background.paste(img, mask=img.split()[-1] if img.mode == "RGBA" else None)
  184. img = background
  185. elif img.mode != "RGB":
  186. img = img.convert("RGB")
  187. # Resize if larger than max_size
  188. if img.width > max_size or img.height > max_size:
  189. img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
  190. img.save(thumb_path, "PNG", optimize=True)
  191. return str(thumb_path)
  192. except ImportError:
  193. # PIL not installed, just copy the file if it's small enough
  194. logger.warning("PIL not installed, copying image as thumbnail")
  195. try:
  196. file_size = file_path.stat().st_size
  197. if file_size < 500000: # Less than 500KB
  198. thumb_filename = f"{uuid.uuid4().hex}{file_path.suffix}"
  199. thumb_path = thumbnails_dir / thumb_filename
  200. shutil.copy2(file_path, thumb_path)
  201. return str(thumb_path)
  202. except OSError:
  203. pass # File inaccessible; fall through to return None
  204. return None
  205. except Exception as e:
  206. logger.warning("Failed to create image thumbnail: %s", e)
  207. return None
  208. # Supported image extensions for thumbnails
  209. IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
  210. # ============ Folder Endpoints ============
  211. @router.get("/folders", response_model=list[FolderTreeItem])
  212. @router.get("/folders/", response_model=list[FolderTreeItem])
  213. async def list_folders(
  214. response: Response,
  215. db: AsyncSession = Depends(get_db),
  216. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  217. ):
  218. """Get all folders as a tree structure."""
  219. # Prevent browser caching of folder list
  220. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  221. # Get all folders with project and archive joins
  222. result = await db.execute(
  223. select(LibraryFolder, Project.name, PrintArchive.print_name)
  224. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  225. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  226. .order_by(LibraryFolder.name)
  227. )
  228. rows = result.all()
  229. # Get file counts per folder
  230. file_counts_result = await db.execute(
  231. select(LibraryFile.folder_id, func.count(LibraryFile.id))
  232. .where(LibraryFile.folder_id.isnot(None))
  233. .group_by(LibraryFile.folder_id)
  234. )
  235. file_counts = dict(file_counts_result.all())
  236. # Build tree structure
  237. folder_map = {}
  238. root_folders = []
  239. for folder, project_name, archive_name in rows:
  240. folder_item = FolderTreeItem(
  241. id=folder.id,
  242. name=folder.name,
  243. parent_id=folder.parent_id,
  244. project_id=folder.project_id,
  245. archive_id=folder.archive_id,
  246. project_name=project_name,
  247. archive_name=archive_name,
  248. is_external=folder.is_external,
  249. external_path=folder.external_path,
  250. external_readonly=folder.external_readonly,
  251. file_count=file_counts.get(folder.id, 0),
  252. children=[],
  253. )
  254. folder_map[folder.id] = folder_item
  255. # Link children to parents
  256. for folder, _, _ in rows:
  257. folder_item = folder_map[folder.id]
  258. if folder.parent_id is None:
  259. root_folders.append(folder_item)
  260. elif folder.parent_id in folder_map:
  261. folder_map[folder.parent_id].children.append(folder_item)
  262. return root_folders
  263. @router.get("/folders/by-project/{project_id}", response_model=list[FolderResponse])
  264. async def get_folders_by_project(
  265. project_id: int,
  266. db: AsyncSession = Depends(get_db),
  267. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  268. ):
  269. """Get all folders linked to a specific project."""
  270. result = await db.execute(
  271. select(LibraryFolder, Project.name)
  272. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  273. .where(LibraryFolder.project_id == project_id)
  274. .order_by(LibraryFolder.name)
  275. )
  276. rows = result.all()
  277. folders = []
  278. for folder, project_name in rows:
  279. # Get file count
  280. file_count_result = await db.execute(
  281. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder.id)
  282. )
  283. file_count = file_count_result.scalar() or 0
  284. folders.append(
  285. FolderResponse(
  286. id=folder.id,
  287. name=folder.name,
  288. parent_id=folder.parent_id,
  289. project_id=folder.project_id,
  290. archive_id=folder.archive_id,
  291. project_name=project_name,
  292. archive_name=None,
  293. is_external=folder.is_external,
  294. external_path=folder.external_path,
  295. external_readonly=folder.external_readonly,
  296. external_show_hidden=folder.external_show_hidden,
  297. file_count=file_count,
  298. created_at=folder.created_at,
  299. updated_at=folder.updated_at,
  300. )
  301. )
  302. return folders
  303. @router.get("/folders/by-archive/{archive_id}", response_model=list[FolderResponse])
  304. async def get_folders_by_archive(
  305. archive_id: int,
  306. db: AsyncSession = Depends(get_db),
  307. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  308. ):
  309. """Get all folders linked to a specific archive."""
  310. result = await db.execute(
  311. select(LibraryFolder, PrintArchive.print_name)
  312. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  313. .where(LibraryFolder.archive_id == archive_id)
  314. .order_by(LibraryFolder.name)
  315. )
  316. rows = result.all()
  317. folders = []
  318. for folder, archive_name in rows:
  319. # Get file count
  320. file_count_result = await db.execute(
  321. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder.id)
  322. )
  323. file_count = file_count_result.scalar() or 0
  324. folders.append(
  325. FolderResponse(
  326. id=folder.id,
  327. name=folder.name,
  328. parent_id=folder.parent_id,
  329. project_id=folder.project_id,
  330. archive_id=folder.archive_id,
  331. project_name=None,
  332. archive_name=archive_name,
  333. is_external=folder.is_external,
  334. external_path=folder.external_path,
  335. external_readonly=folder.external_readonly,
  336. external_show_hidden=folder.external_show_hidden,
  337. file_count=file_count,
  338. created_at=folder.created_at,
  339. updated_at=folder.updated_at,
  340. )
  341. )
  342. return folders
  343. @router.post("/folders", response_model=FolderResponse)
  344. @router.post("/folders/", response_model=FolderResponse)
  345. async def create_folder(
  346. data: FolderCreate,
  347. db: AsyncSession = Depends(get_db),
  348. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  349. ):
  350. """Create a new folder."""
  351. # Verify parent exists if specified
  352. if data.parent_id is not None:
  353. parent_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.parent_id))
  354. if not parent_result.scalar_one_or_none():
  355. raise HTTPException(status_code=404, detail="Parent folder not found")
  356. # Verify project exists if specified
  357. project_name = None
  358. if data.project_id is not None:
  359. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  360. project = project_result.scalar_one_or_none()
  361. if not project:
  362. raise HTTPException(status_code=404, detail="Project not found")
  363. project_name = project.name
  364. # Verify archive exists if specified
  365. archive_name = None
  366. if data.archive_id is not None:
  367. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  368. archive = archive_result.scalar_one_or_none()
  369. if not archive:
  370. raise HTTPException(status_code=404, detail="Archive not found")
  371. archive_name = archive.print_name
  372. folder = LibraryFolder(
  373. name=data.name,
  374. parent_id=data.parent_id,
  375. project_id=data.project_id,
  376. archive_id=data.archive_id,
  377. )
  378. db.add(folder)
  379. await db.commit()
  380. await db.refresh(folder)
  381. return FolderResponse(
  382. id=folder.id,
  383. name=folder.name,
  384. parent_id=folder.parent_id,
  385. project_id=folder.project_id,
  386. archive_id=folder.archive_id,
  387. project_name=project_name,
  388. archive_name=archive_name,
  389. is_external=folder.is_external,
  390. external_path=folder.external_path,
  391. external_readonly=folder.external_readonly,
  392. external_show_hidden=folder.external_show_hidden,
  393. file_count=0,
  394. created_at=folder.created_at,
  395. updated_at=folder.updated_at,
  396. )
  397. @router.get("/folders/{folder_id}", response_model=FolderResponse)
  398. async def get_folder(
  399. folder_id: int,
  400. db: AsyncSession = Depends(get_db),
  401. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  402. ):
  403. """Get a folder by ID."""
  404. result = await db.execute(
  405. select(LibraryFolder, Project.name, PrintArchive.print_name)
  406. .outerjoin(Project, LibraryFolder.project_id == Project.id)
  407. .outerjoin(PrintArchive, LibraryFolder.archive_id == PrintArchive.id)
  408. .where(LibraryFolder.id == folder_id)
  409. )
  410. row = result.one_or_none()
  411. if not row:
  412. raise HTTPException(status_code=404, detail="Folder not found")
  413. folder, project_name, archive_name = row
  414. # Get file count
  415. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id))
  416. file_count = file_count_result.scalar() or 0
  417. return FolderResponse(
  418. id=folder.id,
  419. name=folder.name,
  420. parent_id=folder.parent_id,
  421. project_id=folder.project_id,
  422. archive_id=folder.archive_id,
  423. project_name=project_name,
  424. archive_name=archive_name,
  425. is_external=folder.is_external,
  426. external_path=folder.external_path,
  427. external_readonly=folder.external_readonly,
  428. external_show_hidden=folder.external_show_hidden,
  429. file_count=file_count,
  430. created_at=folder.created_at,
  431. updated_at=folder.updated_at,
  432. )
  433. @router.put("/folders/{folder_id}", response_model=FolderResponse)
  434. async def update_folder(
  435. folder_id: int,
  436. data: FolderUpdate,
  437. db: AsyncSession = Depends(get_db),
  438. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPDATE_ALL)),
  439. ):
  440. """Update a folder.
  441. Note: Folders require library:update_all permission since they don't have
  442. ownership tracking.
  443. """
  444. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  445. folder = result.scalar_one_or_none()
  446. if not folder:
  447. raise HTTPException(status_code=404, detail="Folder not found")
  448. if data.name is not None:
  449. folder.name = data.name
  450. if data.parent_id is not None:
  451. # Prevent circular reference
  452. if data.parent_id == folder_id:
  453. raise HTTPException(status_code=400, detail="Folder cannot be its own parent")
  454. # Check for circular reference in ancestors
  455. if data.parent_id != 0: # 0 means move to root
  456. current_id = data.parent_id
  457. while current_id is not None:
  458. if current_id == folder_id:
  459. raise HTTPException(status_code=400, detail="Cannot move folder into its own subtree")
  460. parent_result = await db.execute(select(LibraryFolder.parent_id).where(LibraryFolder.id == current_id))
  461. current_id = parent_result.scalar()
  462. folder.parent_id = data.parent_id
  463. else:
  464. folder.parent_id = None
  465. # Update project_id (0 to unlink)
  466. if data.project_id is not None:
  467. if data.project_id == 0:
  468. folder.project_id = None
  469. else:
  470. # Verify project exists
  471. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  472. if not project_result.scalar_one_or_none():
  473. raise HTTPException(status_code=404, detail="Project not found")
  474. folder.project_id = data.project_id
  475. # Update archive_id (0 to unlink)
  476. if data.archive_id is not None:
  477. if data.archive_id == 0:
  478. folder.archive_id = None
  479. else:
  480. # Verify archive exists
  481. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  482. if not archive_result.scalar_one_or_none():
  483. raise HTTPException(status_code=404, detail="Archive not found")
  484. folder.archive_id = data.archive_id
  485. await db.commit()
  486. await db.refresh(folder)
  487. # Get file count and names
  488. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id))
  489. file_count = file_count_result.scalar() or 0
  490. # Get project and archive names
  491. project_name = None
  492. archive_name = None
  493. if folder.project_id:
  494. project_result = await db.execute(select(Project.name).where(Project.id == folder.project_id))
  495. project_name = project_result.scalar()
  496. if folder.archive_id:
  497. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == folder.archive_id))
  498. archive_name = archive_result.scalar()
  499. return FolderResponse(
  500. id=folder.id,
  501. name=folder.name,
  502. parent_id=folder.parent_id,
  503. project_id=folder.project_id,
  504. archive_id=folder.archive_id,
  505. project_name=project_name,
  506. archive_name=archive_name,
  507. is_external=folder.is_external,
  508. external_path=folder.external_path,
  509. external_readonly=folder.external_readonly,
  510. external_show_hidden=folder.external_show_hidden,
  511. file_count=file_count,
  512. created_at=folder.created_at,
  513. updated_at=folder.updated_at,
  514. )
  515. @router.delete("/folders/{folder_id}")
  516. async def delete_folder(
  517. folder_id: int,
  518. db: AsyncSession = Depends(get_db),
  519. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_DELETE_ALL)),
  520. ):
  521. """Delete a folder and all its contents (cascade).
  522. Note: Folders require library:delete_all permission since they don't have
  523. ownership tracking.
  524. """
  525. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  526. folder = result.scalar_one_or_none()
  527. if not folder:
  528. raise HTTPException(status_code=404, detail="Folder not found")
  529. # External folders: only remove DB records, never delete files from external path
  530. is_ext = folder.is_external
  531. # Get all files in this folder and subfolders to delete from disk
  532. async def get_all_file_ids(fid: int) -> list[int]:
  533. """Recursively get all file IDs in a folder tree."""
  534. file_ids = []
  535. # Get files in this folder
  536. files_result = await db.execute(
  537. select(LibraryFile.id, LibraryFile.file_path, LibraryFile.thumbnail_path, LibraryFile.is_external).where(
  538. LibraryFile.folder_id == fid
  539. )
  540. )
  541. for fid_val, file_path, thumb_path, file_is_ext in files_result.all():
  542. file_ids.append(fid_val)
  543. # Only delete non-external files from disk
  544. if not is_ext and not file_is_ext:
  545. try:
  546. if file_path and os.path.exists(file_path):
  547. os.remove(file_path)
  548. if thumb_path and os.path.exists(thumb_path):
  549. os.remove(thumb_path)
  550. except OSError as e:
  551. logger.warning("Failed to delete file: %s", e)
  552. # Get child folders and recurse
  553. children_result = await db.execute(select(LibraryFolder.id).where(LibraryFolder.parent_id == fid))
  554. for (child_id,) in children_result.all():
  555. file_ids.extend(await get_all_file_ids(child_id))
  556. return file_ids
  557. await get_all_file_ids(folder_id)
  558. # Delete folder (cascade will handle files and subfolders)
  559. await db.delete(folder)
  560. await db.commit()
  561. return {"status": "success", "message": "Folder deleted"}
  562. # ============ External Folder Endpoints ============
  563. # Blocked system directories that cannot be mounted
  564. _BLOCKED_PREFIXES = (
  565. "/proc",
  566. "/sys",
  567. "/dev",
  568. "/run",
  569. "/boot",
  570. "/sbin",
  571. "/bin",
  572. "/usr/sbin",
  573. "/usr/bin",
  574. "/lib",
  575. "/etc",
  576. )
  577. # Supported file extensions for external folder scanning
  578. _SCANNABLE_EXTENSIONS = {
  579. ".3mf",
  580. ".gcode",
  581. ".gcode.3mf",
  582. ".stl",
  583. ".obj",
  584. ".step",
  585. ".stp",
  586. ".png",
  587. ".jpg",
  588. ".jpeg",
  589. ".gif",
  590. ".webp",
  591. ".svg",
  592. }
  593. def _validate_external_path(path_str: str) -> Path:
  594. """Validate an external path is safe to mount."""
  595. path = Path(path_str).resolve()
  596. if not path.is_absolute():
  597. raise HTTPException(status_code=400, detail="Path must be absolute")
  598. for prefix in _BLOCKED_PREFIXES:
  599. if str(path).startswith(prefix):
  600. raise HTTPException(status_code=400, detail=f"Cannot mount system directory: {prefix}")
  601. if not path.exists():
  602. raise HTTPException(status_code=400, detail=f"Path does not exist: {path}")
  603. if not path.is_dir():
  604. raise HTTPException(status_code=400, detail=f"Path is not a directory: {path}")
  605. # Check readability
  606. if not os.access(path, os.R_OK):
  607. raise HTTPException(status_code=400, detail=f"Path is not readable: {path}")
  608. return path
  609. @router.post("/folders/external", response_model=FolderResponse)
  610. async def create_external_folder(
  611. data: ExternalFolderCreate,
  612. db: AsyncSession = Depends(get_db),
  613. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  614. ):
  615. """Create an external folder that points to a host directory."""
  616. resolved = _validate_external_path(data.external_path)
  617. # Check no other external folder already points to this path
  618. existing = await db.execute(
  619. select(LibraryFolder).where(
  620. LibraryFolder.is_external.is_(True),
  621. LibraryFolder.external_path == str(resolved),
  622. )
  623. )
  624. if existing.scalar_one_or_none():
  625. raise HTTPException(status_code=409, detail="An external folder already exists for this path")
  626. # Verify parent exists if specified
  627. if data.parent_id is not None:
  628. parent_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.parent_id))
  629. if not parent_result.scalar_one_or_none():
  630. raise HTTPException(status_code=404, detail="Parent folder not found")
  631. folder = LibraryFolder(
  632. name=data.name,
  633. parent_id=data.parent_id,
  634. is_external=True,
  635. external_path=str(resolved),
  636. external_readonly=data.readonly,
  637. external_show_hidden=data.show_hidden,
  638. )
  639. db.add(folder)
  640. await db.commit()
  641. await db.refresh(folder)
  642. return FolderResponse(
  643. id=folder.id,
  644. name=folder.name,
  645. parent_id=folder.parent_id,
  646. project_id=None,
  647. archive_id=None,
  648. is_external=True,
  649. external_path=folder.external_path,
  650. external_readonly=folder.external_readonly,
  651. external_show_hidden=folder.external_show_hidden,
  652. file_count=0,
  653. created_at=folder.created_at,
  654. updated_at=folder.updated_at,
  655. )
  656. @router.post("/folders/{folder_id}/scan")
  657. async def scan_external_folder(
  658. folder_id: int,
  659. db: AsyncSession = Depends(get_db),
  660. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  661. ):
  662. """Scan an external folder and sync files to the database.
  663. Discovers new files, removes DB entries for deleted files.
  664. Does not copy files — stores the external path directly.
  665. """
  666. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  667. folder = result.scalar_one_or_none()
  668. if not folder:
  669. raise HTTPException(status_code=404, detail="Folder not found")
  670. if not folder.is_external or not folder.external_path:
  671. raise HTTPException(status_code=400, detail="Not an external folder")
  672. ext_path = Path(folder.external_path)
  673. if not ext_path.exists() or not ext_path.is_dir():
  674. raise HTTPException(status_code=400, detail=f"External path is not accessible: {folder.external_path}")
  675. # Collect all existing child external subfolder IDs (single query)
  676. all_folder_ids = [folder_id]
  677. child_result = await db.execute(
  678. select(LibraryFolder).where(
  679. LibraryFolder.is_external.is_(True),
  680. LibraryFolder.parent_id.isnot(None),
  681. )
  682. )
  683. all_child_folders = child_result.scalars().all()
  684. # Walk the parent chain to find all descendants of folder_id
  685. parent_to_children: dict[int, list] = {}
  686. for cf in all_child_folders:
  687. parent_to_children.setdefault(cf.parent_id, []).append(cf)
  688. queue = [folder_id]
  689. while queue:
  690. pid = queue.pop()
  691. for child in parent_to_children.get(pid, []):
  692. all_folder_ids.append(child.id)
  693. queue.append(child.id)
  694. # Get existing DB files across root and all subfolders
  695. existing_result = await db.execute(
  696. select(LibraryFile).where(
  697. LibraryFile.folder_id.in_(all_folder_ids),
  698. LibraryFile.is_external.is_(True),
  699. )
  700. )
  701. existing_files = {f.file_path: f for f in existing_result.scalars().all()}
  702. # Build folder cache: relative path -> folder_id (for resolving subfolders)
  703. # Pre-populate with existing child folders keyed by their external_path
  704. folder_cache: dict[str, int] = {"": folder_id}
  705. for fid in all_folder_ids:
  706. if fid == folder_id:
  707. continue
  708. # Find the child folder object
  709. for cf in all_child_folders:
  710. if cf.id == fid and cf.external_path:
  711. try:
  712. rel = str(Path(cf.external_path).relative_to(ext_path))
  713. if rel != ".":
  714. folder_cache[rel] = cf.id
  715. except ValueError:
  716. pass
  717. # Scan the directory
  718. added = 0
  719. removed = 0
  720. found_paths: set[str] = set()
  721. seen_rel_dirs: set[str] = set()
  722. for dirpath, dirnames, filenames in os.walk(ext_path):
  723. # Filter hidden directories unless configured
  724. if not folder.external_show_hidden:
  725. dirnames[:] = [d for d in dirnames if not d.startswith(".")]
  726. rel_dir = str(Path(dirpath).relative_to(ext_path))
  727. if rel_dir == ".":
  728. rel_dir = ""
  729. seen_rel_dirs.add(rel_dir)
  730. # Resolve or create subfolder chain for this directory
  731. if rel_dir and rel_dir not in folder_cache:
  732. parts = Path(rel_dir).parts
  733. current_path = ""
  734. current_parent = folder_id
  735. for part in parts:
  736. current_path = f"{current_path}/{part}".lstrip("/")
  737. if current_path in folder_cache:
  738. current_parent = folder_cache[current_path]
  739. else:
  740. existing_sub = await db.execute(
  741. select(LibraryFolder).where(
  742. LibraryFolder.name == part,
  743. LibraryFolder.parent_id == current_parent,
  744. LibraryFolder.is_external.is_(True),
  745. )
  746. )
  747. existing_folder = existing_sub.scalar_one_or_none()
  748. if existing_folder:
  749. current_parent = existing_folder.id
  750. else:
  751. new_folder = LibraryFolder(
  752. name=part,
  753. parent_id=current_parent,
  754. is_external=True,
  755. external_path=str(ext_path / current_path),
  756. external_readonly=folder.external_readonly,
  757. external_show_hidden=folder.external_show_hidden,
  758. )
  759. db.add(new_folder)
  760. await db.flush()
  761. current_parent = new_folder.id
  762. folder_cache[current_path] = current_parent
  763. target_folder_id = folder_cache.get(rel_dir, folder_id)
  764. for filename in filenames:
  765. # Skip hidden files unless configured
  766. if not folder.external_show_hidden and filename.startswith("."):
  767. continue
  768. filepath = Path(dirpath) / filename
  769. ext = filepath.suffix.lower()
  770. # Check for compound extensions like .gcode.3mf
  771. if ext not in _SCANNABLE_EXTENSIONS:
  772. # Check compound
  773. compound = "".join(filepath.suffixes[-2:]).lower() if len(filepath.suffixes) >= 2 else ""
  774. if compound not in _SCANNABLE_EXTENSIONS:
  775. continue
  776. # Resolve symlinks and ensure still under external_path
  777. try:
  778. real_path = filepath.resolve()
  779. real_path.relative_to(ext_path.resolve())
  780. except (ValueError, OSError):
  781. continue # Symlink escapes the external dir
  782. file_path_str = str(filepath)
  783. found_paths.add(file_path_str)
  784. if file_path_str in existing_files:
  785. continue # Already tracked
  786. # Get file info
  787. try:
  788. stat = filepath.stat()
  789. except OSError:
  790. continue
  791. file_type = ext[1:] if ext else "unknown"
  792. # For compound extensions, use the meaningful part
  793. if file_type in ("3mf",) and len(filepath.suffixes) >= 2:
  794. inner = filepath.suffixes[-2].lower()
  795. if inner == ".gcode":
  796. file_type = "gcode.3mf"
  797. # Extract thumbnail for 3mf files
  798. thumbnail_path = None
  799. file_metadata = None
  800. if file_type == "3mf":
  801. try:
  802. parser = ThreeMFParser(str(filepath))
  803. raw_metadata = parser.parse()
  804. if raw_metadata:
  805. # Extract thumbnail before cleaning metadata
  806. thumb_data = raw_metadata.get("_thumbnail_data")
  807. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  808. if thumb_data:
  809. thumb_dir = get_library_thumbnails_dir()
  810. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  811. thumb_full = thumb_dir / thumb_filename
  812. thumb_full.write_bytes(thumb_data)
  813. thumbnail_path = to_relative_path(thumb_full)
  814. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  815. def clean_metadata(obj):
  816. if isinstance(obj, dict):
  817. return {
  818. k: clean_metadata(v)
  819. for k, v in obj.items()
  820. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  821. }
  822. elif isinstance(obj, list):
  823. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  824. elif isinstance(obj, bytes):
  825. return None
  826. return obj
  827. file_metadata = clean_metadata(raw_metadata)
  828. except Exception as e:
  829. logger.debug("Failed to extract metadata from external 3mf %s: %s", filepath, e)
  830. # Generate thumbnail for STL files
  831. if file_type == "stl" and thumbnail_path is None:
  832. try:
  833. thumb_dir = get_library_thumbnails_dir()
  834. thumb_result = generate_stl_thumbnail(str(filepath), str(thumb_dir))
  835. if thumb_result:
  836. thumbnail_path = to_relative_path(Path(thumb_result))
  837. except Exception as e:
  838. logger.debug("Failed to generate STL thumbnail for external %s: %s", filepath, e)
  839. # Extract gcode thumbnail
  840. if file_type == "gcode" and thumbnail_path is None:
  841. thumb_data = extract_gcode_thumbnail(filepath)
  842. if thumb_data:
  843. thumb_dir = get_library_thumbnails_dir()
  844. thumb_filename = f"{uuid.uuid4().hex}.png"
  845. thumb_full = thumb_dir / thumb_filename
  846. thumb_full.write_bytes(thumb_data)
  847. thumbnail_path = to_relative_path(thumb_full)
  848. # Create thumbnail for image files
  849. if ext.lower() in IMAGE_EXTENSIONS and thumbnail_path is None:
  850. thumbnail_path_str = create_image_thumbnail(filepath, get_library_thumbnails_dir())
  851. if thumbnail_path_str:
  852. thumbnail_path = to_relative_path(Path(thumbnail_path_str))
  853. db_file = LibraryFile(
  854. folder_id=target_folder_id,
  855. is_external=True,
  856. filename=filename,
  857. file_path=file_path_str,
  858. file_type=file_type,
  859. file_size=stat.st_size,
  860. file_hash=None, # Skip hashing external files for performance
  861. thumbnail_path=thumbnail_path,
  862. file_metadata=file_metadata,
  863. )
  864. db.add(db_file)
  865. added += 1
  866. # Remove DB entries for files that no longer exist on disk
  867. for path_str, db_file in existing_files.items():
  868. if path_str not in found_paths:
  869. # Clean up thumbnail if we generated one
  870. if db_file.thumbnail_path:
  871. try:
  872. abs_thumb = to_absolute_path(db_file.thumbnail_path)
  873. if abs_thumb and abs_thumb.exists():
  874. abs_thumb.unlink()
  875. except OSError:
  876. pass
  877. await db.delete(db_file)
  878. removed += 1
  879. # Remove empty subfolders whose directories no longer exist on disk
  880. # Process deepest-first by sorting on path depth (descending)
  881. subfolder_entries = [(rel, fid) for rel, fid in folder_cache.items() if rel and fid != folder_id]
  882. subfolder_entries.sort(key=lambda x: x[0].count("/"), reverse=True)
  883. for rel_path, sub_fid in subfolder_entries:
  884. if rel_path in seen_rel_dirs:
  885. continue # Directory still exists on disk
  886. # Check if subfolder has any remaining files
  887. file_count_result = await db.execute(select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == sub_fid))
  888. if (file_count_result.scalar() or 0) == 0:
  889. # Check if it has any remaining child folders
  890. child_count_result = await db.execute(
  891. select(func.count(LibraryFolder.id)).where(LibraryFolder.parent_id == sub_fid)
  892. )
  893. if (child_count_result.scalar() or 0) == 0:
  894. sub_folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == sub_fid))
  895. sub_folder_obj = sub_folder_result.scalar_one_or_none()
  896. if sub_folder_obj:
  897. await db.delete(sub_folder_obj)
  898. await db.commit()
  899. return {"status": "success", "added": added, "removed": removed}
  900. # ============ File Endpoints ============
  901. @router.get("/files", response_model=list[FileListResponse])
  902. @router.get("/files/", response_model=list[FileListResponse])
  903. async def list_files(
  904. response: Response,
  905. folder_id: int | None = None,
  906. project_id: int | None = None,
  907. include_root: bool = True,
  908. db: AsyncSession = Depends(get_db),
  909. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  910. ):
  911. """List files, optionally filtered by folder or project.
  912. Args:
  913. folder_id: Filter by folder ID. If None and include_root=True, returns root files.
  914. project_id: Return all files across folders linked to this project (bulk fetch, avoids N+1).
  915. include_root: If True and folder_id is None, returns files at root level.
  916. If False and folder_id is None, returns all files.
  917. """
  918. query = select(LibraryFile).options(selectinload(LibraryFile.created_by))
  919. if folder_id is not None:
  920. query = query.where(LibraryFile.folder_id == folder_id)
  921. elif project_id is not None:
  922. # Single join instead of one query per folder (avoids N+1 pattern)
  923. query = query.join(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  924. query = query.where(LibraryFolder.project_id == project_id)
  925. elif include_root:
  926. query = query.where(LibraryFile.folder_id.is_(None))
  927. query = query.order_by(LibraryFile.filename)
  928. result = await db.execute(query)
  929. files = result.scalars().all()
  930. # Get duplicate counts
  931. hash_counts = {}
  932. if files:
  933. hashes = [f.file_hash for f in files if f.file_hash]
  934. if hashes:
  935. dup_result = await db.execute(
  936. select(LibraryFile.file_hash, func.count(LibraryFile.id))
  937. .where(LibraryFile.file_hash.in_(hashes))
  938. .group_by(LibraryFile.file_hash)
  939. )
  940. hash_counts = {h: c - 1 for h, c in dup_result.all()} # -1 to exclude self
  941. # Prevent browser caching of file list
  942. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  943. file_list = []
  944. for f in files:
  945. # Extract key metadata for display
  946. print_name = None
  947. print_time = None
  948. filament_grams = None
  949. sliced_for_model = None
  950. if f.file_metadata:
  951. print_name = f.file_metadata.get("print_name")
  952. print_time = f.file_metadata.get("print_time_seconds")
  953. filament_grams = f.file_metadata.get("filament_used_grams")
  954. sliced_for_model = f.file_metadata.get("sliced_for_model")
  955. file_list.append(
  956. FileListResponse(
  957. id=f.id,
  958. folder_id=f.folder_id,
  959. is_external=f.is_external,
  960. filename=f.filename,
  961. file_type=f.file_type,
  962. file_size=f.file_size,
  963. thumbnail_path=f.thumbnail_path,
  964. print_count=f.print_count,
  965. duplicate_count=hash_counts.get(f.file_hash, 0) if f.file_hash else 0,
  966. created_by_id=f.created_by_id,
  967. created_by_username=f.created_by.username if f.created_by else None,
  968. created_at=f.created_at,
  969. print_name=print_name,
  970. print_time_seconds=print_time,
  971. filament_used_grams=filament_grams,
  972. sliced_for_model=sliced_for_model,
  973. )
  974. )
  975. return file_list
  976. @router.post("/files", response_model=FileUploadResponse)
  977. @router.post("/files/", response_model=FileUploadResponse)
  978. async def upload_file(
  979. file: UploadFile = File(...),
  980. folder_id: int | None = None,
  981. generate_stl_thumbnails: bool = Query(default=True),
  982. db: AsyncSession = Depends(get_db),
  983. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  984. ):
  985. """Upload a file to the library."""
  986. try:
  987. if not file.filename:
  988. raise HTTPException(status_code=400, detail="Filename is required")
  989. filename = file.filename
  990. ext = os.path.splitext(filename)[1].lower()
  991. # Handle files without extension
  992. file_type = ext[1:] if ext else "unknown"
  993. # Verify folder exists if specified
  994. if folder_id is not None:
  995. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  996. target_folder = folder_result.scalar_one_or_none()
  997. if not target_folder:
  998. raise HTTPException(status_code=404, detail="Folder not found")
  999. if target_folder.is_external and target_folder.external_readonly:
  1000. raise HTTPException(status_code=403, detail="Cannot upload to a read-only external folder")
  1001. # Generate unique filename for storage
  1002. unique_filename = f"{uuid.uuid4().hex}{ext}"
  1003. file_path = get_library_files_dir() / unique_filename
  1004. # Save file
  1005. content = await file.read()
  1006. with open(file_path, "wb") as f:
  1007. f.write(content)
  1008. # Calculate hash
  1009. file_hash = calculate_file_hash(file_path)
  1010. # Check for duplicates
  1011. dup_result = await db.execute(select(LibraryFile.id).where(LibraryFile.file_hash == file_hash).limit(1))
  1012. duplicate_of = dup_result.scalar()
  1013. # Extract metadata and thumbnail
  1014. metadata = {}
  1015. thumbnail_path = None
  1016. thumbnails_dir = get_library_thumbnails_dir()
  1017. if ext == ".3mf":
  1018. try:
  1019. parser = ThreeMFParser(str(file_path))
  1020. raw_metadata = parser.parse()
  1021. # Extract thumbnail before cleaning metadata
  1022. thumbnail_data = raw_metadata.get("_thumbnail_data")
  1023. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  1024. # Save thumbnail if extracted
  1025. if thumbnail_data:
  1026. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  1027. thumb_path = thumbnails_dir / thumb_filename
  1028. with open(thumb_path, "wb") as f:
  1029. f.write(thumbnail_data)
  1030. thumbnail_path = str(thumb_path)
  1031. # Clean metadata - remove non-JSON-serializable data (bytes, etc.)
  1032. def clean_metadata(obj):
  1033. if isinstance(obj, dict):
  1034. return {
  1035. k: clean_metadata(v)
  1036. for k, v in obj.items()
  1037. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  1038. }
  1039. elif isinstance(obj, list):
  1040. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  1041. elif isinstance(obj, bytes):
  1042. return None
  1043. return obj
  1044. metadata = clean_metadata(raw_metadata)
  1045. except Exception as e:
  1046. logger.warning("Failed to parse 3MF: %s", e)
  1047. elif ext == ".gcode":
  1048. # Extract embedded thumbnail from gcode
  1049. try:
  1050. thumbnail_data = extract_gcode_thumbnail(file_path)
  1051. if thumbnail_data:
  1052. thumb_filename = f"{uuid.uuid4().hex}.png"
  1053. thumb_path = thumbnails_dir / thumb_filename
  1054. with open(thumb_path, "wb") as f:
  1055. f.write(thumbnail_data)
  1056. thumbnail_path = str(thumb_path)
  1057. except Exception as e:
  1058. logger.warning("Failed to extract gcode thumbnail: %s", e)
  1059. elif ext.lower() in IMAGE_EXTENSIONS:
  1060. # For image files, create a thumbnail from the image itself
  1061. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  1062. elif ext == ".stl":
  1063. # Generate STL thumbnail if enabled
  1064. if generate_stl_thumbnails:
  1065. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  1066. # Create database entry (store relative paths for portability)
  1067. library_file = LibraryFile(
  1068. folder_id=folder_id,
  1069. filename=filename,
  1070. file_path=to_relative_path(file_path),
  1071. file_type=file_type,
  1072. file_size=len(content),
  1073. file_hash=file_hash,
  1074. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  1075. file_metadata=metadata if metadata else None,
  1076. created_by_id=current_user.id if current_user else None,
  1077. )
  1078. db.add(library_file)
  1079. await db.commit()
  1080. await db.refresh(library_file)
  1081. return FileUploadResponse(
  1082. id=library_file.id,
  1083. filename=library_file.filename,
  1084. file_type=library_file.file_type,
  1085. file_size=library_file.file_size,
  1086. thumbnail_path=library_file.thumbnail_path,
  1087. duplicate_of=duplicate_of,
  1088. metadata=library_file.file_metadata,
  1089. )
  1090. except HTTPException:
  1091. raise
  1092. except Exception as e:
  1093. logger.error("Upload failed for %s: %s", file.filename, e, exc_info=True)
  1094. raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
  1095. @router.post("/files/extract-zip", response_model=ZipExtractResponse)
  1096. async def extract_zip_file(
  1097. file: UploadFile = File(...),
  1098. folder_id: int | None = Query(default=None),
  1099. preserve_structure: bool = Query(default=True),
  1100. create_folder_from_zip: bool = Query(default=False),
  1101. generate_stl_thumbnails: bool = Query(default=True),
  1102. db: AsyncSession = Depends(get_db),
  1103. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPLOAD)),
  1104. ):
  1105. """Upload and extract a ZIP file to the library.
  1106. Args:
  1107. file: The ZIP file to extract
  1108. folder_id: Target folder ID (None = root)
  1109. preserve_structure: If True, recreate folder structure from ZIP; if False, extract all files flat
  1110. create_folder_from_zip: If True, create a folder named after the ZIP file and extract into it
  1111. generate_stl_thumbnails: If True, generate thumbnails for STL files
  1112. """
  1113. import tempfile
  1114. if not file.filename or not file.filename.lower().endswith(".zip"):
  1115. raise HTTPException(status_code=400, detail="Only ZIP files are supported")
  1116. # Verify target folder exists if specified
  1117. if folder_id is not None:
  1118. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  1119. target_folder = folder_result.scalar_one_or_none()
  1120. if not target_folder:
  1121. raise HTTPException(status_code=404, detail="Target folder not found")
  1122. if target_folder.is_external and target_folder.external_readonly:
  1123. raise HTTPException(status_code=403, detail="Cannot extract ZIP to a read-only external folder")
  1124. # Save ZIP to temp file
  1125. try:
  1126. with tempfile.NamedTemporaryFile(delete=False, suffix=".zip") as tmp:
  1127. content = await file.read()
  1128. tmp.write(content)
  1129. tmp_path = tmp.name
  1130. except Exception as e:
  1131. raise HTTPException(status_code=500, detail=f"Failed to save ZIP file: {str(e)}")
  1132. extracted_files: list[ZipExtractResult] = []
  1133. errors: list[ZipExtractError] = []
  1134. folders_created = 0
  1135. folder_cache: dict[str, int] = {} # path -> folder_id
  1136. # If create_folder_from_zip is True, create a folder named after the ZIP file
  1137. zip_folder_id = folder_id
  1138. logger.info(
  1139. f"ZIP extraction: create_folder_from_zip={create_folder_from_zip}, folder_id={folder_id}, filename={file.filename}"
  1140. )
  1141. if create_folder_from_zip and file.filename:
  1142. # Remove .zip extension to get folder name
  1143. zip_folder_name = file.filename[:-4] if file.filename.lower().endswith(".zip") else file.filename
  1144. # Check if folder already exists
  1145. existing = await db.execute(
  1146. select(LibraryFolder).where(
  1147. LibraryFolder.name == zip_folder_name,
  1148. LibraryFolder.parent_id == folder_id if folder_id else LibraryFolder.parent_id.is_(None),
  1149. )
  1150. )
  1151. existing_folder = existing.scalar_one_or_none()
  1152. if existing_folder:
  1153. zip_folder_id = existing_folder.id
  1154. logger.info("Reusing existing folder '%s' with id=%s", zip_folder_name, zip_folder_id)
  1155. else:
  1156. # Create folder
  1157. new_folder = LibraryFolder(name=zip_folder_name, parent_id=folder_id)
  1158. db.add(new_folder)
  1159. await db.flush()
  1160. await db.commit() # Commit folder creation immediately
  1161. zip_folder_id = new_folder.id
  1162. folders_created += 1
  1163. logger.info("Created new folder '%s' with id=%s", zip_folder_name, zip_folder_id)
  1164. try:
  1165. with zipfile.ZipFile(tmp_path, "r") as zf:
  1166. # Filter out directories and hidden/system files
  1167. file_list = [
  1168. name
  1169. for name in zf.namelist()
  1170. if not name.endswith("/")
  1171. and not name.startswith("__MACOSX")
  1172. and not os.path.basename(name).startswith(".")
  1173. ]
  1174. for zip_path in file_list:
  1175. try:
  1176. # Determine target folder (use zip_folder_id as base if create_folder_from_zip was used)
  1177. target_folder_id = zip_folder_id
  1178. if preserve_structure:
  1179. # Get directory path from ZIP
  1180. dir_path = os.path.dirname(zip_path)
  1181. if dir_path:
  1182. # Create folder structure
  1183. parts = dir_path.split("/")
  1184. current_parent = zip_folder_id
  1185. current_path = ""
  1186. for part in parts:
  1187. if not part:
  1188. continue
  1189. current_path = f"{current_path}/{part}" if current_path else part
  1190. if current_path in folder_cache:
  1191. current_parent = folder_cache[current_path]
  1192. else:
  1193. # Check if folder exists
  1194. existing = await db.execute(
  1195. select(LibraryFolder).where(
  1196. LibraryFolder.name == part,
  1197. LibraryFolder.parent_id == current_parent
  1198. if current_parent
  1199. else LibraryFolder.parent_id.is_(None),
  1200. )
  1201. )
  1202. existing_folder = existing.scalar_one_or_none()
  1203. if existing_folder:
  1204. current_parent = existing_folder.id
  1205. else:
  1206. # Create folder
  1207. new_folder = LibraryFolder(name=part, parent_id=current_parent)
  1208. db.add(new_folder)
  1209. await db.flush()
  1210. current_parent = new_folder.id
  1211. folders_created += 1
  1212. folder_cache[current_path] = current_parent
  1213. target_folder_id = current_parent
  1214. # Extract file
  1215. filename = os.path.basename(zip_path)
  1216. ext = os.path.splitext(filename)[1].lower()
  1217. file_type = ext[1:] if ext else "unknown"
  1218. # Generate unique filename for storage
  1219. unique_filename = f"{uuid.uuid4().hex}{ext}"
  1220. file_path = get_library_files_dir() / unique_filename
  1221. # Extract and save file
  1222. file_content = zf.read(zip_path)
  1223. with open(file_path, "wb") as f:
  1224. f.write(file_content)
  1225. # Calculate hash
  1226. file_hash = calculate_file_hash(file_path)
  1227. # Extract metadata and thumbnail for 3MF files
  1228. metadata = {}
  1229. thumbnail_path = None
  1230. thumbnails_dir = get_library_thumbnails_dir()
  1231. if ext == ".3mf":
  1232. try:
  1233. parser = ThreeMFParser(str(file_path))
  1234. raw_metadata = parser.parse()
  1235. thumbnail_data = raw_metadata.get("_thumbnail_data")
  1236. thumbnail_ext = raw_metadata.get("_thumbnail_ext", ".png")
  1237. if thumbnail_data:
  1238. thumb_filename = f"{uuid.uuid4().hex}{thumbnail_ext}"
  1239. thumb_path = thumbnails_dir / thumb_filename
  1240. with open(thumb_path, "wb") as f:
  1241. f.write(thumbnail_data)
  1242. thumbnail_path = str(thumb_path)
  1243. def clean_metadata(obj):
  1244. if isinstance(obj, dict):
  1245. return {
  1246. k: clean_metadata(v)
  1247. for k, v in obj.items()
  1248. if not isinstance(v, bytes) and k not in ("_thumbnail_data", "_thumbnail_ext")
  1249. }
  1250. elif isinstance(obj, list):
  1251. return [clean_metadata(i) for i in obj if not isinstance(i, bytes)]
  1252. elif isinstance(obj, bytes):
  1253. return None
  1254. return obj
  1255. metadata = clean_metadata(raw_metadata)
  1256. except Exception as e:
  1257. logger.warning("Failed to parse 3MF from ZIP: %s", e)
  1258. elif ext == ".gcode":
  1259. try:
  1260. thumbnail_data = extract_gcode_thumbnail(file_path)
  1261. if thumbnail_data:
  1262. thumb_filename = f"{uuid.uuid4().hex}.png"
  1263. thumb_path = thumbnails_dir / thumb_filename
  1264. with open(thumb_path, "wb") as f:
  1265. f.write(thumbnail_data)
  1266. thumbnail_path = str(thumb_path)
  1267. except Exception as e:
  1268. logger.warning("Failed to extract gcode thumbnail from ZIP: %s", e)
  1269. elif ext.lower() in IMAGE_EXTENSIONS:
  1270. thumbnail_path = create_image_thumbnail(file_path, thumbnails_dir)
  1271. elif ext == ".stl":
  1272. # Generate STL thumbnail if enabled
  1273. if generate_stl_thumbnails:
  1274. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  1275. # Create database entry (store relative paths for portability)
  1276. library_file = LibraryFile(
  1277. folder_id=target_folder_id,
  1278. filename=filename,
  1279. file_path=to_relative_path(file_path),
  1280. file_type=file_type,
  1281. file_size=len(file_content),
  1282. file_hash=file_hash,
  1283. thumbnail_path=to_relative_path(thumbnail_path) if thumbnail_path else None,
  1284. file_metadata=metadata if metadata else None,
  1285. created_by_id=current_user.id if current_user else None,
  1286. )
  1287. db.add(library_file)
  1288. await db.flush()
  1289. await db.refresh(library_file)
  1290. extracted_files.append(
  1291. ZipExtractResult(
  1292. filename=filename,
  1293. file_id=library_file.id,
  1294. folder_id=target_folder_id,
  1295. )
  1296. )
  1297. # Commit after each file to release database lock
  1298. # This prevents long-running transactions from blocking other requests
  1299. await db.commit()
  1300. except Exception as e:
  1301. logger.error("Failed to extract %s: %s", zip_path, e)
  1302. errors.append(ZipExtractError(filename=os.path.basename(zip_path), error=str(e)))
  1303. # Rollback the failed file but continue with others
  1304. await db.rollback()
  1305. return ZipExtractResponse(
  1306. extracted=len(extracted_files),
  1307. folders_created=folders_created,
  1308. files=extracted_files,
  1309. errors=errors,
  1310. )
  1311. except zipfile.BadZipFile:
  1312. raise HTTPException(status_code=400, detail="Invalid or corrupted ZIP file")
  1313. except Exception as e:
  1314. logger.error("ZIP extraction failed: %s", e, exc_info=True)
  1315. raise HTTPException(status_code=500, detail=f"ZIP extraction failed: {str(e)}")
  1316. finally:
  1317. # Clean up temp file
  1318. try:
  1319. os.unlink(tmp_path)
  1320. except OSError:
  1321. pass # Best-effort temp file cleanup; ignore if already removed
  1322. # ============ STL Thumbnail Batch Generation ============
  1323. @router.post("/generate-stl-thumbnails", response_model=BatchThumbnailResponse)
  1324. async def batch_generate_stl_thumbnails(
  1325. request: BatchThumbnailRequest,
  1326. db: AsyncSession = Depends(get_db),
  1327. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_UPDATE_ALL)),
  1328. ):
  1329. """Generate thumbnails for STL files in batch.
  1330. Note: Requires library:update_all permission since this is a batch operation
  1331. that may affect files owned by different users.
  1332. Can generate thumbnails for:
  1333. - Specific file IDs (file_ids)
  1334. - All STL files in a folder (folder_id)
  1335. - All STL files missing thumbnails (all_missing=True)
  1336. """
  1337. thumbnails_dir = get_library_thumbnails_dir()
  1338. results: list[BatchThumbnailResult] = []
  1339. # Build query based on request
  1340. query = select(LibraryFile).where(LibraryFile.file_type == "stl")
  1341. if request.file_ids:
  1342. # Specific files
  1343. query = query.where(LibraryFile.id.in_(request.file_ids))
  1344. elif request.folder_id is not None:
  1345. # All STL files in a specific folder
  1346. query = query.where(LibraryFile.folder_id == request.folder_id)
  1347. if not request.all_missing:
  1348. # If not specifically asking for missing thumbnails, get all
  1349. pass
  1350. else:
  1351. query = query.where(LibraryFile.thumbnail_path.is_(None))
  1352. elif request.all_missing:
  1353. # All STL files without thumbnails
  1354. query = query.where(LibraryFile.thumbnail_path.is_(None))
  1355. else:
  1356. # No criteria specified - return empty
  1357. return BatchThumbnailResponse(
  1358. processed=0,
  1359. succeeded=0,
  1360. failed=0,
  1361. results=[],
  1362. )
  1363. result = await db.execute(query)
  1364. stl_files = result.scalars().all()
  1365. succeeded = 0
  1366. failed = 0
  1367. for stl_file in stl_files:
  1368. file_path = to_absolute_path(stl_file.file_path)
  1369. if not file_path or not file_path.exists():
  1370. results.append(
  1371. BatchThumbnailResult(
  1372. file_id=stl_file.id,
  1373. filename=stl_file.filename,
  1374. success=False,
  1375. error="File not found on disk",
  1376. )
  1377. )
  1378. failed += 1
  1379. continue
  1380. try:
  1381. thumbnail_path = generate_stl_thumbnail(file_path, thumbnails_dir)
  1382. if thumbnail_path:
  1383. # Update database with relative path
  1384. stl_file.thumbnail_path = to_relative_path(thumbnail_path)
  1385. await db.flush()
  1386. results.append(
  1387. BatchThumbnailResult(
  1388. file_id=stl_file.id,
  1389. filename=stl_file.filename,
  1390. success=True,
  1391. )
  1392. )
  1393. succeeded += 1
  1394. else:
  1395. results.append(
  1396. BatchThumbnailResult(
  1397. file_id=stl_file.id,
  1398. filename=stl_file.filename,
  1399. success=False,
  1400. error="Thumbnail generation failed",
  1401. )
  1402. )
  1403. failed += 1
  1404. except Exception as e:
  1405. logger.error("Failed to generate thumbnail for %s: %s", stl_file.filename, e)
  1406. results.append(
  1407. BatchThumbnailResult(
  1408. file_id=stl_file.id,
  1409. filename=stl_file.filename,
  1410. success=False,
  1411. error=str(e),
  1412. )
  1413. )
  1414. failed += 1
  1415. await db.commit()
  1416. return BatchThumbnailResponse(
  1417. processed=len(stl_files),
  1418. succeeded=succeeded,
  1419. failed=failed,
  1420. results=results,
  1421. )
  1422. # ============ Queue Operations ============
  1423. # NOTE: These routes must be defined BEFORE /files/{file_id} to avoid path parameter conflicts
  1424. def is_sliced_file(filename: str) -> bool:
  1425. """Check if a file is a sliced (printable) file.
  1426. Sliced files are:
  1427. - .gcode files
  1428. - .3mf files that contain '.gcode.' in the name (e.g., filename.gcode.3mf)
  1429. """
  1430. lower = filename.lower()
  1431. return lower.endswith(".gcode") or ".gcode." in lower
  1432. @router.post("/files/add-to-queue", response_model=AddToQueueResponse)
  1433. async def add_files_to_queue(
  1434. request: AddToQueueRequest,
  1435. db: AsyncSession = Depends(get_db),
  1436. _: User | None = Depends(require_permission_if_auth_enabled(Permission.QUEUE_CREATE)),
  1437. ):
  1438. """Add library files to the print queue.
  1439. Only sliced files (.gcode or .gcode.3mf) can be added to the queue.
  1440. The archive will be created automatically when the print starts.
  1441. """
  1442. added: list[AddToQueueResult] = []
  1443. errors: list[AddToQueueError] = []
  1444. # Get all requested files
  1445. result = await db.execute(select(LibraryFile).where(LibraryFile.id.in_(request.file_ids)))
  1446. files = {f.id: f for f in result.scalars().all()}
  1447. # Get max position for queue ordering
  1448. pos_result = await db.execute(select(func.coalesce(func.max(PrintQueueItem.position), 0)))
  1449. max_position = pos_result.scalar() or 0
  1450. for file_id in request.file_ids:
  1451. lib_file = files.get(file_id)
  1452. if not lib_file:
  1453. errors.append(AddToQueueError(file_id=file_id, filename="(not found)", error="File not found"))
  1454. continue
  1455. # Validate file is sliced
  1456. if not is_sliced_file(lib_file.filename):
  1457. errors.append(
  1458. AddToQueueError(
  1459. file_id=file_id,
  1460. filename=lib_file.filename,
  1461. error="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1462. )
  1463. )
  1464. continue
  1465. try:
  1466. # Verify file exists on disk
  1467. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1468. if not file_path.exists():
  1469. errors.append(
  1470. AddToQueueError(file_id=file_id, filename=lib_file.filename, error="File not found on disk")
  1471. )
  1472. continue
  1473. # Create queue item referencing library file (archive created at print start)
  1474. max_position += 1
  1475. queue_item = PrintQueueItem(
  1476. printer_id=None, # Unassigned
  1477. library_file_id=file_id,
  1478. position=max_position,
  1479. status="pending",
  1480. )
  1481. db.add(queue_item)
  1482. await db.flush() # Get queue_item.id
  1483. added.append(
  1484. AddToQueueResult(
  1485. file_id=file_id,
  1486. filename=lib_file.filename,
  1487. queue_item_id=queue_item.id,
  1488. )
  1489. )
  1490. except Exception as e:
  1491. logger.exception("Error adding file %s to queue", file_id)
  1492. errors.append(AddToQueueError(file_id=file_id, filename=lib_file.filename, error=str(e)))
  1493. await db.commit()
  1494. return AddToQueueResponse(added=added, errors=errors)
  1495. @router.get("/files/{file_id}/plates")
  1496. async def get_library_file_plates(
  1497. file_id: int,
  1498. db: AsyncSession = Depends(get_db),
  1499. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1500. ):
  1501. """Get available plates from a multi-plate 3MF library file.
  1502. Returns a list of plates with their index, name, thumbnail availability,
  1503. and filament requirements. For single-plate exports, returns a single plate.
  1504. """
  1505. import json
  1506. import defusedxml.ElementTree as ET
  1507. # Get the library file
  1508. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1509. lib_file = result.scalar_one_or_none()
  1510. if not lib_file:
  1511. raise HTTPException(status_code=404, detail="File not found")
  1512. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1513. if not file_path.exists():
  1514. raise HTTPException(status_code=404, detail="File not found on disk")
  1515. # Only 3MF files have plates
  1516. if not lib_file.filename.lower().endswith(".3mf"):
  1517. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1518. plates = []
  1519. try:
  1520. with zipfile.ZipFile(file_path, "r") as zf:
  1521. namelist = zf.namelist()
  1522. # Find all plate gcode files to determine available plates
  1523. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1524. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1525. plate_indices: list[int] = []
  1526. if gcode_files:
  1527. # Extract plate indices from gcode filenames
  1528. for gf in gcode_files:
  1529. try:
  1530. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1531. plate_indices.append(int(plate_str))
  1532. except ValueError:
  1533. pass # Skip gcode file with non-numeric plate index
  1534. else:
  1535. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1536. plate_png_files = [
  1537. n
  1538. for n in namelist
  1539. if n.startswith("Metadata/plate_")
  1540. and n.endswith(".png")
  1541. and "_small" not in n
  1542. and "no_light" not in n
  1543. ]
  1544. plate_name_candidates = plate_json_files + plate_png_files
  1545. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1546. seen_indices: set[int] = set()
  1547. for name in plate_name_candidates:
  1548. match = plate_re.match(name)
  1549. if match:
  1550. try:
  1551. index = int(match.group(1))
  1552. except ValueError:
  1553. continue
  1554. if index in seen_indices:
  1555. continue
  1556. seen_indices.add(index)
  1557. plate_indices.append(index)
  1558. if not plate_indices:
  1559. # No plate metadata found
  1560. return {"file_id": file_id, "filename": lib_file.filename, "plates": [], "is_multi_plate": False}
  1561. plate_indices.sort()
  1562. # Parse model_settings.config for plate names + object assignments
  1563. plate_names = {}
  1564. plate_object_ids: dict[int, list[str]] = {}
  1565. object_names_by_id: dict[str, str] = {}
  1566. if "Metadata/model_settings.config" in namelist:
  1567. try:
  1568. model_content = zf.read("Metadata/model_settings.config").decode()
  1569. model_root = ET.fromstring(model_content)
  1570. for obj_elem in model_root.findall(".//object"):
  1571. obj_id = obj_elem.get("id")
  1572. if not obj_id:
  1573. continue
  1574. name_meta = obj_elem.find("metadata[@key='name']")
  1575. obj_name = name_meta.get("value") if name_meta is not None else None
  1576. if obj_name:
  1577. object_names_by_id[obj_id] = obj_name
  1578. for plate_elem in model_root.findall(".//plate"):
  1579. plater_id = None
  1580. plater_name = None
  1581. for meta in plate_elem.findall("metadata"):
  1582. key = meta.get("key")
  1583. value = meta.get("value")
  1584. if key == "plater_id" and value:
  1585. try:
  1586. plater_id = int(value)
  1587. except ValueError:
  1588. pass # Ignore plate with non-numeric plater_id
  1589. elif key == "plater_name" and value:
  1590. plater_name = value.strip()
  1591. if plater_id is not None and plater_name:
  1592. plate_names[plater_id] = plater_name
  1593. if plater_id is not None:
  1594. for instance_elem in plate_elem.findall("model_instance"):
  1595. for inst_meta in instance_elem.findall("metadata"):
  1596. if inst_meta.get("key") == "object_id":
  1597. obj_id = inst_meta.get("value")
  1598. if not obj_id:
  1599. continue
  1600. plate_object_ids.setdefault(plater_id, [])
  1601. if obj_id not in plate_object_ids[plater_id]:
  1602. plate_object_ids[plater_id].append(obj_id)
  1603. except Exception:
  1604. pass # model_settings.config is optional; skip if missing or malformed
  1605. # Parse slice_info.config for plate metadata
  1606. plate_metadata = {}
  1607. if "Metadata/slice_info.config" in namelist:
  1608. content = zf.read("Metadata/slice_info.config").decode()
  1609. root = ET.fromstring(content)
  1610. for plate_elem in root.findall(".//plate"):
  1611. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1612. plate_index = None
  1613. for meta in plate_elem.findall("metadata"):
  1614. key = meta.get("key")
  1615. value = meta.get("value")
  1616. if key == "index" and value:
  1617. try:
  1618. plate_index = int(value)
  1619. except ValueError:
  1620. pass # Ignore plate with non-numeric index
  1621. elif key == "prediction" and value:
  1622. try:
  1623. plate_info["prediction"] = int(value)
  1624. except ValueError:
  1625. pass # Leave prediction as None if not a valid integer
  1626. elif key == "weight" and value:
  1627. try:
  1628. plate_info["weight"] = float(value)
  1629. except ValueError:
  1630. pass # Leave weight as None if not a valid number
  1631. # Get filaments used in this plate
  1632. for filament_elem in plate_elem.findall("filament"):
  1633. filament_id = filament_elem.get("id")
  1634. filament_type = filament_elem.get("type", "")
  1635. filament_color = filament_elem.get("color", "")
  1636. used_g = filament_elem.get("used_g", "0")
  1637. used_m = filament_elem.get("used_m", "0")
  1638. try:
  1639. used_grams = float(used_g)
  1640. except (ValueError, TypeError):
  1641. used_grams = 0
  1642. if used_grams > 0 and filament_id:
  1643. plate_info["filaments"].append(
  1644. {
  1645. "slot_id": int(filament_id),
  1646. "type": filament_type,
  1647. "color": filament_color,
  1648. "used_grams": round(used_grams, 1),
  1649. "used_meters": float(used_m) if used_m else 0,
  1650. }
  1651. )
  1652. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1653. # Collect object names
  1654. for obj_elem in plate_elem.findall("object"):
  1655. obj_name = obj_elem.get("name")
  1656. if obj_name and obj_name not in plate_info["objects"]:
  1657. plate_info["objects"].append(obj_name)
  1658. # Set plate name
  1659. if plate_index is not None:
  1660. custom_name = plate_names.get(plate_index)
  1661. if custom_name:
  1662. plate_info["name"] = custom_name
  1663. elif plate_info["objects"]:
  1664. plate_info["name"] = plate_info["objects"][0]
  1665. plate_metadata[plate_index] = plate_info
  1666. # Parse plate_*.json for object lists when slice_info is missing
  1667. plate_json_objects: dict[int, list[str]] = {}
  1668. for name in namelist:
  1669. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  1670. if not match:
  1671. continue
  1672. try:
  1673. plate_index = int(match.group(1))
  1674. except ValueError:
  1675. continue
  1676. try:
  1677. payload = json.loads(zf.read(name).decode())
  1678. bbox_objects = payload.get("bbox_objects", [])
  1679. names: list[str] = []
  1680. for obj in bbox_objects:
  1681. obj_name = obj.get("name") if isinstance(obj, dict) else None
  1682. if obj_name and obj_name not in names:
  1683. names.append(obj_name)
  1684. if names:
  1685. plate_json_objects[plate_index] = names
  1686. except Exception:
  1687. continue
  1688. # Build plate list
  1689. for idx in plate_indices:
  1690. meta = plate_metadata.get(idx, {})
  1691. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1692. objects = meta.get("objects", [])
  1693. if not objects:
  1694. objects = plate_json_objects.get(idx, [])
  1695. if not objects and plate_object_ids.get(idx):
  1696. objects = [
  1697. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  1698. ]
  1699. plate_name = meta.get("name")
  1700. if not plate_name:
  1701. plate_name = plate_names.get(idx)
  1702. if not plate_name and objects:
  1703. plate_name = objects[0]
  1704. plates.append(
  1705. {
  1706. "index": idx,
  1707. "name": plate_name,
  1708. "objects": objects,
  1709. "object_count": len(objects),
  1710. "has_thumbnail": has_thumbnail,
  1711. "thumbnail_url": f"/api/v1/library/files/{file_id}/plate-thumbnail/{idx}"
  1712. if has_thumbnail
  1713. else None,
  1714. "print_time_seconds": meta.get("prediction"),
  1715. "filament_used_grams": meta.get("weight"),
  1716. "filaments": meta.get("filaments", []),
  1717. }
  1718. )
  1719. except Exception as e:
  1720. logger.warning("Failed to parse plates from library file %s: %s", file_id, e)
  1721. return {
  1722. "file_id": file_id,
  1723. "filename": lib_file.filename,
  1724. "plates": plates,
  1725. "is_multi_plate": len(plates) > 1,
  1726. }
  1727. @router.get("/files/{file_id}/plate-thumbnail/{plate_index}")
  1728. async def get_library_file_plate_thumbnail(
  1729. file_id: int,
  1730. plate_index: int,
  1731. db: AsyncSession = Depends(get_db),
  1732. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1733. ):
  1734. """Get the thumbnail image for a specific plate from a library file."""
  1735. from starlette.responses import Response
  1736. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1737. lib_file = result.scalar_one_or_none()
  1738. if not lib_file:
  1739. raise HTTPException(status_code=404, detail="File not found")
  1740. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1741. if not file_path.exists():
  1742. raise HTTPException(status_code=404, detail="File not found on disk")
  1743. try:
  1744. with zipfile.ZipFile(file_path, "r") as zf:
  1745. thumb_path = f"Metadata/plate_{plate_index}.png"
  1746. if thumb_path in zf.namelist():
  1747. data = zf.read(thumb_path)
  1748. return Response(content=data, media_type="image/png")
  1749. except Exception:
  1750. pass # Archive unreadable or thumbnail missing; fall through to 404
  1751. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1752. @router.get("/files/{file_id}/filament-requirements")
  1753. async def get_library_file_filament_requirements(
  1754. file_id: int,
  1755. plate_id: int | None = None,
  1756. db: AsyncSession = Depends(get_db),
  1757. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1758. ):
  1759. """Get filament requirements from a library file.
  1760. Parses the 3MF file to extract filament slot IDs, types, colors, and usage.
  1761. This enables AMS slot assignment when printing from the file manager.
  1762. Args:
  1763. file_id: The library file ID
  1764. plate_id: Optional plate index to get filaments for a specific plate
  1765. """
  1766. import defusedxml.ElementTree as ET
  1767. # Get the library file
  1768. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1769. lib_file = result.scalar_one_or_none()
  1770. if not lib_file:
  1771. raise HTTPException(status_code=404, detail="File not found")
  1772. # Get the full file path
  1773. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1774. if not file_path.exists():
  1775. raise HTTPException(status_code=404, detail="File not found on disk")
  1776. # Only 3MF files have parseable filament info
  1777. if not lib_file.filename.lower().endswith(".3mf"):
  1778. return {"file_id": file_id, "filename": lib_file.filename, "plate_id": plate_id, "filaments": []}
  1779. filaments = []
  1780. try:
  1781. with zipfile.ZipFile(file_path, "r") as zf:
  1782. # Parse slice_info.config for filament requirements
  1783. if "Metadata/slice_info.config" in zf.namelist():
  1784. content = zf.read("Metadata/slice_info.config").decode()
  1785. root = ET.fromstring(content)
  1786. if plate_id is not None:
  1787. # Find filaments for specific plate
  1788. for plate_elem in root.findall(".//plate"):
  1789. # Check if this is the requested plate
  1790. plate_index = None
  1791. for meta in plate_elem.findall("metadata"):
  1792. if meta.get("key") == "index":
  1793. try:
  1794. plate_index = int(meta.get("value", ""))
  1795. except ValueError:
  1796. pass # Skip plate with non-numeric index value
  1797. break
  1798. if plate_index == plate_id:
  1799. # Extract filaments from this plate
  1800. for filament_elem in plate_elem.findall("filament"):
  1801. filament_id = filament_elem.get("id")
  1802. filament_type = filament_elem.get("type", "")
  1803. filament_color = filament_elem.get("color", "")
  1804. used_g = filament_elem.get("used_g", "0")
  1805. used_m = filament_elem.get("used_m", "0")
  1806. tray_info_idx = filament_elem.get("tray_info_idx", "")
  1807. try:
  1808. used_grams = float(used_g)
  1809. except (ValueError, TypeError):
  1810. used_grams = 0
  1811. if used_grams > 0 and filament_id:
  1812. filaments.append(
  1813. {
  1814. "slot_id": int(filament_id),
  1815. "type": filament_type,
  1816. "color": filament_color,
  1817. "used_grams": round(used_grams, 1),
  1818. "used_meters": float(used_m) if used_m else 0,
  1819. "tray_info_idx": tray_info_idx,
  1820. }
  1821. )
  1822. break
  1823. else:
  1824. # Extract all filaments with used_g > 0 (for single-plate or overview)
  1825. for filament_elem in root.findall(".//filament"):
  1826. filament_id = filament_elem.get("id")
  1827. filament_type = filament_elem.get("type", "")
  1828. filament_color = filament_elem.get("color", "")
  1829. used_g = filament_elem.get("used_g", "0")
  1830. used_m = filament_elem.get("used_m", "0")
  1831. tray_info_idx = filament_elem.get("tray_info_idx", "")
  1832. try:
  1833. used_grams = float(used_g)
  1834. except (ValueError, TypeError):
  1835. used_grams = 0
  1836. if used_grams > 0 and filament_id:
  1837. filaments.append(
  1838. {
  1839. "slot_id": int(filament_id),
  1840. "type": filament_type,
  1841. "color": filament_color,
  1842. "used_grams": round(used_grams, 1),
  1843. "used_meters": float(used_m) if used_m else 0,
  1844. "tray_info_idx": tray_info_idx,
  1845. }
  1846. )
  1847. # Sort by slot ID
  1848. filaments.sort(key=lambda x: x["slot_id"])
  1849. # Enrich with nozzle mapping for dual-nozzle printers
  1850. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  1851. if nozzle_mapping:
  1852. for filament in filaments:
  1853. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  1854. except Exception as e:
  1855. logger.warning("Failed to parse filament requirements from library file %s: %s", file_id, e)
  1856. return {
  1857. "file_id": file_id,
  1858. "filename": lib_file.filename,
  1859. "plate_id": plate_id,
  1860. "filaments": filaments,
  1861. }
  1862. @router.post("/files/{file_id}/print")
  1863. async def print_library_file(
  1864. file_id: int,
  1865. printer_id: int,
  1866. body: FilePrintRequest | None = None,
  1867. db: AsyncSession = Depends(get_db),
  1868. current_user: User | None = Depends(require_permission_if_auth_enabled(Permission.PRINTERS_CONTROL)),
  1869. ):
  1870. """Dispatch a library file for send/start on a printer.
  1871. The actual send/start work is handled asynchronously by background
  1872. dispatch so the UI can continue immediately.
  1873. Only sliced files (.gcode or .gcode.3mf) can be printed.
  1874. """
  1875. from backend.app.models.printer import Printer
  1876. from backend.app.services.background_dispatch import DispatchEnqueueRejected, background_dispatch
  1877. from backend.app.services.printer_manager import printer_manager
  1878. # Use defaults if no body provided
  1879. if body is None:
  1880. body = FilePrintRequest()
  1881. # Get the library file
  1882. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  1883. lib_file = result.scalar_one_or_none()
  1884. if not lib_file:
  1885. raise HTTPException(status_code=404, detail="File not found")
  1886. # Validate file is sliced
  1887. if not is_sliced_file(lib_file.filename):
  1888. raise HTTPException(
  1889. status_code=400,
  1890. detail="Not a sliced file. Only .gcode or .gcode.3mf files can be printed.",
  1891. )
  1892. # Get the full file path
  1893. file_path = Path(app_settings.base_dir) / lib_file.file_path
  1894. if not file_path.exists():
  1895. raise HTTPException(status_code=404, detail="File not found on disk")
  1896. # Get printer
  1897. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1898. printer = result.scalar_one_or_none()
  1899. if not printer:
  1900. raise HTTPException(status_code=404, detail="Printer not found")
  1901. # Check printer is connected
  1902. if not printer_manager.is_connected(printer_id):
  1903. raise HTTPException(status_code=400, detail="Printer is not connected")
  1904. # Validate project exists before dispatching so a bogus ID yields 404, not a FK-constraint 500
  1905. if body.project_id is not None:
  1906. project_result = await db.execute(select(Project).where(Project.id == body.project_id))
  1907. if not project_result.scalar_one_or_none():
  1908. raise HTTPException(status_code=404, detail="Project not found")
  1909. plate_name = body.plate_name
  1910. if not plate_name and body.plate_id is not None:
  1911. plate_name = f"Plate {body.plate_id}"
  1912. dispatch_source_name = lib_file.filename
  1913. if plate_name:
  1914. dispatch_source_name = f"{lib_file.filename} • {plate_name}"
  1915. try:
  1916. dispatch_result = await background_dispatch.dispatch_print_library_file(
  1917. file_id=file_id,
  1918. filename=dispatch_source_name,
  1919. printer_id=printer_id,
  1920. printer_name=printer.name,
  1921. options=body.model_dump(exclude_none=True, exclude={"cleanup_library_after_dispatch"}),
  1922. project_id=body.project_id,
  1923. requested_by_user_id=current_user.id if current_user else None,
  1924. requested_by_username=current_user.username if current_user else None,
  1925. cleanup_library_after_dispatch=body.cleanup_library_after_dispatch,
  1926. )
  1927. except DispatchEnqueueRejected as e:
  1928. raise HTTPException(status_code=409, detail=str(e)) from e
  1929. return {
  1930. "status": "dispatched",
  1931. "printer_id": printer_id,
  1932. "archive_id": None,
  1933. "filename": lib_file.filename,
  1934. "dispatch_job_id": dispatch_result["dispatch_job_id"],
  1935. "dispatch_position": dispatch_result["dispatch_position"],
  1936. }
  1937. # ============ File Detail Endpoints ============
  1938. @router.get("/files/{file_id}", response_model=FileResponseSchema)
  1939. async def get_file(
  1940. file_id: int,
  1941. db: AsyncSession = Depends(get_db),
  1942. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  1943. ):
  1944. """Get a file by ID with full details."""
  1945. result = await db.execute(
  1946. select(LibraryFile).options(selectinload(LibraryFile.created_by)).where(LibraryFile.id == file_id)
  1947. )
  1948. file = result.scalar_one_or_none()
  1949. if not file:
  1950. raise HTTPException(status_code=404, detail="File not found")
  1951. # Get folder name
  1952. folder_name = None
  1953. if file.folder_id:
  1954. folder_result = await db.execute(select(LibraryFolder.name).where(LibraryFolder.id == file.folder_id))
  1955. folder_name = folder_result.scalar()
  1956. # Get project name
  1957. project_name = None
  1958. if file.project_id:
  1959. project_result = await db.execute(select(Project.name).where(Project.id == file.project_id))
  1960. project_name = project_result.scalar()
  1961. # Get duplicates
  1962. duplicates = []
  1963. duplicate_count = 0
  1964. if file.file_hash:
  1965. dup_result = await db.execute(
  1966. select(LibraryFile, LibraryFolder.name)
  1967. .outerjoin(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  1968. .where(LibraryFile.file_hash == file.file_hash, LibraryFile.id != file.id)
  1969. )
  1970. for dup_file, dup_folder_name in dup_result.all():
  1971. duplicates.append(
  1972. FileDuplicate(
  1973. id=dup_file.id,
  1974. filename=dup_file.filename,
  1975. folder_id=dup_file.folder_id,
  1976. folder_name=dup_folder_name,
  1977. created_at=dup_file.created_at,
  1978. )
  1979. )
  1980. duplicate_count = len(duplicates)
  1981. # Extract key metadata fields
  1982. print_name = None
  1983. print_time = None
  1984. filament_grams = None
  1985. sliced_for_model = None
  1986. if file.file_metadata:
  1987. print_name = file.file_metadata.get("print_name")
  1988. print_time = file.file_metadata.get("print_time_seconds")
  1989. filament_grams = file.file_metadata.get("filament_used_grams")
  1990. sliced_for_model = file.file_metadata.get("sliced_for_model")
  1991. return FileResponseSchema(
  1992. id=file.id,
  1993. folder_id=file.folder_id,
  1994. folder_name=folder_name,
  1995. project_id=file.project_id,
  1996. project_name=project_name,
  1997. filename=file.filename,
  1998. file_path=file.file_path,
  1999. file_type=file.file_type,
  2000. file_size=file.file_size,
  2001. file_hash=file.file_hash,
  2002. thumbnail_path=file.thumbnail_path,
  2003. metadata=file.file_metadata,
  2004. print_count=file.print_count,
  2005. last_printed_at=file.last_printed_at,
  2006. notes=file.notes,
  2007. duplicates=duplicates if duplicates else None,
  2008. duplicate_count=duplicate_count,
  2009. created_by_id=file.created_by_id,
  2010. created_by_username=file.created_by.username if file.created_by else None,
  2011. created_at=file.created_at,
  2012. updated_at=file.updated_at,
  2013. print_name=print_name,
  2014. print_time_seconds=print_time,
  2015. filament_used_grams=filament_grams,
  2016. sliced_for_model=sliced_for_model,
  2017. )
  2018. @router.put("/files/{file_id}", response_model=FileResponseSchema)
  2019. async def update_file(
  2020. file_id: int,
  2021. data: FileUpdate,
  2022. db: AsyncSession = Depends(get_db),
  2023. auth_result: tuple[User | None, bool] = Depends(
  2024. require_ownership_permission(
  2025. Permission.LIBRARY_UPDATE_ALL,
  2026. Permission.LIBRARY_UPDATE_OWN,
  2027. )
  2028. ),
  2029. ):
  2030. """Update a file's metadata."""
  2031. user, can_modify_all = auth_result
  2032. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2033. file = result.scalar_one_or_none()
  2034. if not file:
  2035. raise HTTPException(status_code=404, detail="File not found")
  2036. # Ownership check
  2037. if not can_modify_all:
  2038. if file.created_by_id != user.id:
  2039. raise HTTPException(status_code=403, detail="You can only update your own files")
  2040. if data.filename is not None:
  2041. # Validate filename doesn't contain path separators
  2042. if "/" in data.filename or "\\" in data.filename:
  2043. raise HTTPException(status_code=400, detail="Filename cannot contain path separators")
  2044. file.filename = data.filename
  2045. # Also update print_name in file_metadata so the display name matches
  2046. if file.file_metadata and "print_name" in file.file_metadata:
  2047. file.file_metadata = {**file.file_metadata, "print_name": data.filename}
  2048. if data.folder_id is not None:
  2049. if data.folder_id == 0:
  2050. file.folder_id = None
  2051. else:
  2052. # Verify folder exists
  2053. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  2054. if not folder_result.scalar_one_or_none():
  2055. raise HTTPException(status_code=404, detail="Folder not found")
  2056. file.folder_id = data.folder_id
  2057. if data.project_id is not None:
  2058. if data.project_id == 0:
  2059. file.project_id = None
  2060. else:
  2061. # Verify project exists
  2062. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  2063. if not project_result.scalar_one_or_none():
  2064. raise HTTPException(status_code=404, detail="Project not found")
  2065. file.project_id = data.project_id
  2066. if data.notes is not None:
  2067. file.notes = data.notes if data.notes else None
  2068. await db.commit()
  2069. await db.refresh(file)
  2070. # Return full response (reuse get_file logic)
  2071. return await get_file(file_id, db)
  2072. @router.delete("/files/{file_id}")
  2073. async def delete_file(
  2074. file_id: int,
  2075. db: AsyncSession = Depends(get_db),
  2076. auth_result: tuple[User | None, bool] = Depends(
  2077. require_ownership_permission(
  2078. Permission.LIBRARY_DELETE_ALL,
  2079. Permission.LIBRARY_DELETE_OWN,
  2080. )
  2081. ),
  2082. ):
  2083. """Delete a file."""
  2084. user, can_modify_all = auth_result
  2085. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2086. file = result.scalar_one_or_none()
  2087. if not file:
  2088. raise HTTPException(status_code=404, detail="File not found")
  2089. # Ownership check
  2090. if not can_modify_all:
  2091. if file.created_by_id != user.id:
  2092. raise HTTPException(status_code=403, detail="You can only delete your own files")
  2093. # External files: only remove DB entry and thumbnail, never delete the actual file
  2094. try:
  2095. if not file.is_external:
  2096. abs_file_path = to_absolute_path(file.file_path)
  2097. if abs_file_path and abs_file_path.exists():
  2098. abs_file_path.unlink()
  2099. # Always clean up thumbnails we generated
  2100. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  2101. if abs_thumb_path and abs_thumb_path.exists():
  2102. abs_thumb_path.unlink()
  2103. except OSError as e:
  2104. logger.warning("Failed to delete file from disk: %s", e)
  2105. await db.delete(file)
  2106. await db.commit()
  2107. return {"status": "success", "message": "File deleted"}
  2108. # ============ File Content Endpoints ============
  2109. @router.get("/files/{file_id}/download")
  2110. async def download_file(
  2111. file_id: int,
  2112. db: AsyncSession = Depends(get_db),
  2113. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2114. ):
  2115. """Download a file."""
  2116. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2117. file = result.scalar_one_or_none()
  2118. if not file:
  2119. raise HTTPException(status_code=404, detail="File not found")
  2120. abs_path = to_absolute_path(file.file_path)
  2121. if not abs_path or not abs_path.exists():
  2122. raise HTTPException(status_code=404, detail="File not found on disk")
  2123. return FastAPIFileResponse(
  2124. str(abs_path),
  2125. filename=file.filename,
  2126. media_type="application/octet-stream",
  2127. )
  2128. @router.post("/files/{file_id}/slicer-token")
  2129. async def create_library_slicer_token(
  2130. file_id: int,
  2131. db: AsyncSession = Depends(get_db),
  2132. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2133. ):
  2134. """Create a short-lived download token for opening files in slicer applications.
  2135. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  2136. auth headers, so they use this token in the URL path instead.
  2137. """
  2138. from backend.app.core.auth import create_slicer_download_token
  2139. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2140. file = result.scalar_one_or_none()
  2141. if not file:
  2142. raise HTTPException(status_code=404, detail="File not found")
  2143. token = await create_slicer_download_token("library", file_id)
  2144. return {"token": token}
  2145. @router.get("/files/{file_id}/dl/{token}/{filename}")
  2146. async def download_library_file_for_slicer(
  2147. file_id: int,
  2148. token: str,
  2149. filename: str,
  2150. db: AsyncSession = Depends(get_db),
  2151. ):
  2152. """Download a library file using a slicer download token.
  2153. Token-authenticated (no auth headers needed). The token is short-lived
  2154. and single-use, created by POST /files/{file_id}/slicer-token.
  2155. Filename is at the end of the URL so slicers can detect the file format.
  2156. """
  2157. from backend.app.core.auth import verify_slicer_download_token
  2158. if not await verify_slicer_download_token(token, "library", file_id):
  2159. raise HTTPException(status_code=403, detail="Invalid or expired download token")
  2160. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2161. file = result.scalar_one_or_none()
  2162. if not file:
  2163. raise HTTPException(status_code=404, detail="File not found")
  2164. abs_path = to_absolute_path(file.file_path)
  2165. if not abs_path or not abs_path.exists():
  2166. raise HTTPException(status_code=404, detail="File not found on disk")
  2167. return FastAPIFileResponse(
  2168. str(abs_path),
  2169. filename=file.filename,
  2170. media_type="application/octet-stream",
  2171. )
  2172. @router.get("/files/{file_id}/thumbnail")
  2173. async def get_thumbnail(
  2174. file_id: int,
  2175. db: AsyncSession = Depends(get_db),
  2176. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2177. ):
  2178. """Get a file's thumbnail."""
  2179. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2180. file = result.scalar_one_or_none()
  2181. if not file:
  2182. raise HTTPException(status_code=404, detail="File not found")
  2183. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  2184. if not abs_thumb_path or not abs_thumb_path.exists():
  2185. raise HTTPException(status_code=404, detail="Thumbnail not found")
  2186. # Detect media type from extension
  2187. thumb_ext = abs_thumb_path.suffix.lower()
  2188. media_types = {
  2189. ".png": "image/png",
  2190. ".jpg": "image/jpeg",
  2191. ".jpeg": "image/jpeg",
  2192. ".gif": "image/gif",
  2193. ".webp": "image/webp",
  2194. }
  2195. media_type = media_types.get(thumb_ext, "image/png")
  2196. return FastAPIFileResponse(str(abs_thumb_path), media_type=media_type)
  2197. @router.get("/files/{file_id}/gcode")
  2198. async def get_gcode(
  2199. file_id: int,
  2200. db: AsyncSession = Depends(get_db),
  2201. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2202. ):
  2203. """Get gcode for a file (for preview)."""
  2204. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2205. file = result.scalar_one_or_none()
  2206. if not file:
  2207. raise HTTPException(status_code=404, detail="File not found")
  2208. abs_path = to_absolute_path(file.file_path)
  2209. if not abs_path or not abs_path.exists():
  2210. raise HTTPException(status_code=404, detail="File not found on disk")
  2211. if file.file_type == "gcode":
  2212. return FastAPIFileResponse(str(abs_path), media_type="text/plain")
  2213. elif file.file_type == "3mf":
  2214. # Extract gcode from 3mf
  2215. try:
  2216. with zipfile.ZipFile(str(abs_path), "r") as zf:
  2217. # Find gcode file
  2218. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  2219. if not gcode_files:
  2220. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  2221. gcode_content = zf.read(gcode_files[0])
  2222. from fastapi.responses import Response
  2223. return Response(content=gcode_content, media_type="text/plain")
  2224. except zipfile.BadZipFile:
  2225. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  2226. else:
  2227. raise HTTPException(status_code=400, detail="Unsupported file type")
  2228. # ============ Bulk Operations ============
  2229. @router.post("/files/move")
  2230. async def move_files(
  2231. data: FileMoveRequest,
  2232. db: AsyncSession = Depends(get_db),
  2233. auth_result: tuple[User | None, bool] = Depends(
  2234. require_ownership_permission(
  2235. Permission.LIBRARY_UPDATE_ALL,
  2236. Permission.LIBRARY_UPDATE_OWN,
  2237. )
  2238. ),
  2239. ):
  2240. """Move multiple files to a folder.
  2241. Files not owned by the user are skipped (unless user has *_all permission).
  2242. """
  2243. user, can_modify_all = auth_result
  2244. # Verify folder exists if specified
  2245. if data.folder_id is not None:
  2246. folder_result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == data.folder_id))
  2247. target_folder = folder_result.scalar_one_or_none()
  2248. if not target_folder:
  2249. raise HTTPException(status_code=404, detail="Folder not found")
  2250. if target_folder.is_external and target_folder.external_readonly:
  2251. raise HTTPException(status_code=403, detail="Cannot move files to a read-only external folder")
  2252. # Update files
  2253. moved = 0
  2254. skipped = 0
  2255. for file_id in data.file_ids:
  2256. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2257. file = result.scalar_one_or_none()
  2258. if file:
  2259. # Ownership check
  2260. if not can_modify_all and file.created_by_id != user.id:
  2261. skipped += 1
  2262. continue
  2263. # Cannot move external files out of their folder
  2264. if file.is_external:
  2265. skipped += 1
  2266. continue
  2267. file.folder_id = data.folder_id
  2268. moved += 1
  2269. return {"status": "success", "moved": moved, "skipped": skipped}
  2270. @router.post("/bulk-delete", response_model=BulkDeleteResponse)
  2271. async def bulk_delete(
  2272. data: BulkDeleteRequest,
  2273. db: AsyncSession = Depends(get_db),
  2274. auth_result: tuple[User | None, bool] = Depends(
  2275. require_ownership_permission(
  2276. Permission.LIBRARY_DELETE_ALL,
  2277. Permission.LIBRARY_DELETE_OWN,
  2278. )
  2279. ),
  2280. ):
  2281. """Delete multiple files and/or folders.
  2282. Files not owned by the user are skipped (unless user has *_all permission).
  2283. """
  2284. user, can_modify_all = auth_result
  2285. deleted_files = 0
  2286. deleted_folders = 0
  2287. skipped_files = 0
  2288. # Delete files first
  2289. for file_id in data.file_ids:
  2290. result = await db.execute(select(LibraryFile).where(LibraryFile.id == file_id))
  2291. file = result.scalar_one_or_none()
  2292. if file:
  2293. # Ownership check
  2294. if not can_modify_all and file.created_by_id != user.id:
  2295. skipped_files += 1
  2296. continue
  2297. try:
  2298. if not file.is_external:
  2299. abs_file_path = to_absolute_path(file.file_path)
  2300. if abs_file_path and abs_file_path.exists():
  2301. abs_file_path.unlink()
  2302. abs_thumb_path = to_absolute_path(file.thumbnail_path)
  2303. if abs_thumb_path and abs_thumb_path.exists():
  2304. abs_thumb_path.unlink()
  2305. except OSError as e:
  2306. logger.warning("Failed to delete file from disk: %s", e)
  2307. await db.delete(file)
  2308. deleted_files += 1
  2309. # Delete folders (cascade will handle contents)
  2310. # Note: Folders don't have ownership tracking currently, require *_all permission
  2311. for folder_id in data.folder_ids:
  2312. if not can_modify_all:
  2313. # Users without *_all permission cannot delete folders
  2314. continue
  2315. result = await db.execute(select(LibraryFolder).where(LibraryFolder.id == folder_id))
  2316. folder = result.scalar_one_or_none()
  2317. if folder:
  2318. # Count files that will be deleted
  2319. file_count_result = await db.execute(
  2320. select(func.count(LibraryFile.id)).where(LibraryFile.folder_id == folder_id)
  2321. )
  2322. deleted_files += file_count_result.scalar() or 0
  2323. await db.delete(folder)
  2324. deleted_folders += 1
  2325. await db.commit()
  2326. return BulkDeleteResponse(deleted_files=deleted_files, deleted_folders=deleted_folders)
  2327. # ============ Stats Endpoint ============
  2328. @router.get("/stats")
  2329. async def get_library_stats(
  2330. db: AsyncSession = Depends(get_db),
  2331. _: User | None = Depends(require_permission_if_auth_enabled(Permission.LIBRARY_READ)),
  2332. ):
  2333. """Get library statistics."""
  2334. # Total files
  2335. total_files_result = await db.execute(select(func.count(LibraryFile.id)))
  2336. total_files = total_files_result.scalar() or 0
  2337. # Total folders
  2338. total_folders_result = await db.execute(select(func.count(LibraryFolder.id)))
  2339. total_folders = total_folders_result.scalar() or 0
  2340. # Total size
  2341. total_size_result = await db.execute(select(func.sum(LibraryFile.file_size)))
  2342. total_size = total_size_result.scalar() or 0
  2343. # Files by type
  2344. type_result = await db.execute(
  2345. select(LibraryFile.file_type, func.count(LibraryFile.id)).group_by(LibraryFile.file_type)
  2346. )
  2347. files_by_type = dict(type_result.all())
  2348. # Total prints
  2349. total_prints_result = await db.execute(select(func.sum(LibraryFile.print_count)))
  2350. total_prints = total_prints_result.scalar() or 0
  2351. # Disk space info
  2352. library_dir = get_library_dir()
  2353. try:
  2354. disk_stat = shutil.disk_usage(library_dir)
  2355. disk_free_bytes = disk_stat.free
  2356. disk_total_bytes = disk_stat.total
  2357. disk_used_bytes = disk_stat.used
  2358. except OSError:
  2359. disk_free_bytes = 0
  2360. disk_total_bytes = 0
  2361. disk_used_bytes = 0
  2362. return {
  2363. "total_files": total_files,
  2364. "total_folders": total_folders,
  2365. "total_size_bytes": total_size,
  2366. "files_by_type": files_by_type,
  2367. "total_prints": total_prints,
  2368. "disk_free_bytes": disk_free_bytes,
  2369. "disk_total_bytes": disk_total_bytes,
  2370. "disk_used_bytes": disk_used_bytes,
  2371. }