library.py 107 KB

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