library.py 148 KB

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