library.py 113 KB

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