library.py 112 KB

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