library.py 174 KB

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