library.py 124 KB

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