archives.py 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671
  1. import io
  2. import json
  3. import logging
  4. import re as _re
  5. import zipfile
  6. from collections import defaultdict
  7. from datetime import date, datetime, time, timedelta, timezone
  8. from decimal import ROUND_HALF_UP, Decimal
  9. from pathlib import Path
  10. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  11. from fastapi.responses import FileResponse, Response
  12. from sqlalchemy import and_, case, func, or_, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.auth import (
  15. RequireCameraStreamTokenIfAuthEnabled,
  16. RequirePermissionIfAuthEnabled,
  17. require_ownership_permission,
  18. )
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import get_db
  21. from backend.app.core.permissions import Permission
  22. from backend.app.models.archive import PrintArchive
  23. from backend.app.models.filament import Filament
  24. from backend.app.models.spool_usage_history import SpoolUsageHistory
  25. from backend.app.models.user import User
  26. from backend.app.schemas.archive import ArchiveResponse, ArchiveSlim, ArchiveStats, ArchiveUpdate
  27. from backend.app.schemas.print_log import PrintLogResponse
  28. from backend.app.schemas.slicer import SliceRequest
  29. from backend.app.services.archive import ArchiveService
  30. from backend.app.utils.http import build_content_disposition
  31. from backend.app.utils.safe_path import safe_join_under
  32. from backend.app.utils.threemf_tools import (
  33. extract_embedded_presets_from_3mf,
  34. extract_nozzle_mapping_from_3mf,
  35. extract_project_filaments_from_3mf,
  36. )
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/archives", tags=["archives"])
  39. def _safe_filename(filename: str) -> str:
  40. """Extract basename from a client-supplied filename, preventing path traversal.
  41. Normalizes backslashes (Windows paths) before extracting so that
  42. '..\\\\..\\\\evil.3mf' is correctly stripped to 'evil.3mf' on Linux.
  43. """
  44. return Path(filename.replace("\\", "/")).name
  45. _TIMELAPSE_FILENAME_TS_RE = _re.compile(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})")
  46. _DEFAULT_TIMELAPSE_OFFSETS_HOURS: tuple[int, ...] = (0, 8, -8, 7, -7, 1, -1)
  47. _DEFAULT_TIMELAPSE_TOLERANCE = timedelta(hours=4)
  48. _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN = timedelta(minutes=15)
  49. def _match_timelapse_by_timestamp(
  50. video_files: list[dict],
  51. archive_start: datetime | None,
  52. *,
  53. tolerance: timedelta = _DEFAULT_TIMELAPSE_TOLERANCE,
  54. ambiguity_margin: timedelta = _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN,
  55. offsets_hours: tuple[int, ...] = _DEFAULT_TIMELAPSE_OFFSETS_HOURS,
  56. ) -> tuple[dict | None, timedelta | None]:
  57. """Pick the timelapse whose filename timestamp best matches the print start time.
  58. Bambu timelapse filenames embed the printer-local START time (e.g.
  59. "video_2026-05-08_09-41-29.mp4"). The printer's clock may be offset from the
  60. server's — especially in LAN-Only mode where NTP is unreachable — so we try a
  61. small set of common UTC offsets and keep the (video, offset) pair with the
  62. smallest absolute distance from archive_start. We deliberately do NOT consider
  63. archive_end here: the filename is start time, not end time, so comparing it to
  64. completion is not a real signal (Strategy 3 handles end via file mtime).
  65. Because the offset list densely covers a wide span, an unrelated video's
  66. filename can coincidentally land near a later print's start at some offset.
  67. To avoid that false positive, we require the best (video, offset) pair to
  68. beat the next-best pair *from a different video* by at least `ambiguity_margin`.
  69. When the top two candidates from different videos are too close to call,
  70. we return None and let the caller fall back to manual selection.
  71. """
  72. if archive_start is None:
  73. return None, None
  74. # (diff, video) for every (video, offset) pair within tolerance.
  75. candidates: list[tuple[timedelta, dict]] = []
  76. for f in video_files:
  77. fname = f.get("name", "")
  78. m = _TIMELAPSE_FILENAME_TS_RE.search(fname)
  79. if not m:
  80. continue
  81. try:
  82. file_time = datetime.strptime(m.group(1), "%Y-%m-%d_%H-%M-%S")
  83. except ValueError:
  84. continue
  85. for hour_offset in offsets_hours:
  86. adjusted = file_time - timedelta(hours=hour_offset)
  87. diff = abs(adjusted - archive_start)
  88. if diff <= tolerance:
  89. candidates.append((diff, f))
  90. if not candidates:
  91. return None, None
  92. candidates.sort(key=lambda c: c[0])
  93. best_diff, best_video = candidates[0]
  94. best_name = best_video.get("name")
  95. for diff, video in candidates[1:]:
  96. if video.get("name") != best_name and (diff - best_diff) < ambiguity_margin:
  97. # Another video matches almost as well — refuse to auto-pick.
  98. return None, None
  99. return best_video, best_diff
  100. def _ensure_archive_visible(
  101. archive: PrintArchive | None,
  102. user: User | None,
  103. can_read_all: bool,
  104. ) -> PrintArchive:
  105. """Per-archive visibility gate for ownership-scoped reads (#1726-adjacent).
  106. Returns ``archive`` if the caller is allowed to see it; raises 404 otherwise.
  107. Single enforcement point used by every detail / download / sub-resource
  108. route so we can't accidentally leak a row through a less-guarded sibling.
  109. Rules:
  110. - Missing archive or soft-deleted (``deleted_at != None``) → 404.
  111. - Caller with ARCHIVES_READ_ALL or auth disabled (``can_read_all=True``,
  112. ``user`` may be None) → archive returned.
  113. - Caller without ARCHIVES_READ_ALL and ``archive.created_by_id != user.id``
  114. → 404, deliberately NOT 403. 403 leaks "this id exists but you can't
  115. see it" — enumeration-friendly. 404 is indistinguishable from a
  116. nonexistent id. Pre-GHSA fix the caller saw 200 here (the PoC vector).
  117. - Ownerless rows (``created_by_id is None``) require ALL — fail-closed
  118. per ``feedback_no_fail_open_in_auth``.
  119. """
  120. if not archive or archive.deleted_at is not None:
  121. raise HTTPException(404, "Archive not found")
  122. if can_read_all:
  123. return archive
  124. # Auth enabled, caller has _OWN only.
  125. if user is None:
  126. # Defensive: should be unreachable (RequirePermissionIfAuthEnabled
  127. # would have 401'd already), but never trust user identity to be
  128. # non-None when can_read_all is False.
  129. raise HTTPException(404, "Archive not found")
  130. if archive.created_by_id is None or archive.created_by_id != user.id:
  131. raise HTTPException(404, "Archive not found")
  132. return archive
  133. def _validate_user_filter_permission(current_user: User | None, created_by_id: int | None):
  134. """Raise 403 if created_by_id filter is used without stats:filter_by_user permission."""
  135. if created_by_id is None or current_user is None:
  136. return
  137. if current_user.is_admin:
  138. return
  139. if not current_user.has_permission(Permission.STATS_FILTER_BY_USER.value):
  140. raise HTTPException(status_code=403, detail="Permission stats:filter_by_user required")
  141. def _apply_user_filter(conditions: list, created_by_id: int | None):
  142. """Append created_by_id filter to conditions list if specified."""
  143. if created_by_id is not None:
  144. if created_by_id == -1:
  145. conditions.append(PrintArchive.created_by_id.is_(None))
  146. else:
  147. conditions.append(PrintArchive.created_by_id == created_by_id)
  148. def _apply_run_user_filter(conditions: list, created_by_id: int | None):
  149. """Append created_by_id filter scoped to PrintLogEntry rows."""
  150. from backend.app.models.print_log import PrintLogEntry
  151. if created_by_id is not None:
  152. if created_by_id == -1:
  153. conditions.append(PrintLogEntry.created_by_id.is_(None))
  154. else:
  155. conditions.append(PrintLogEntry.created_by_id == created_by_id)
  156. def compute_time_accuracy(archive: PrintArchive, run_aggregate: dict | None = None) -> dict:
  157. """Compute actual print time and accuracy for an archive.
  158. Returns dict with actual_time_seconds and time_accuracy.
  159. time_accuracy = (estimated / actual) * 100
  160. - 100% = perfect estimate
  161. - >100% = print was faster than estimated
  162. - <100% = print took longer than estimated
  163. When ``run_aggregate`` indicates the archive has more than one logged
  164. run (multi-plate file printed plate-by-plate, or reprints), both
  165. fields are suppressed: ``archive.started_at / completed_at`` reflect
  166. the LATEST run only, while ``archive.print_time_seconds`` is the
  167. whole-file estimate (post-#1593 the parser sums across plates), so
  168. comparing the two describes different scopes. The card-rendering
  169. frontend falls through to ``archive.print_time_seconds`` for the
  170. time display and hides the badge when ``time_accuracy`` is null —
  171. that's the desired "show estimate, no badge" presentation for
  172. multi-run archives (#1608). Single-run archives keep the original
  173. badge behaviour verbatim.
  174. """
  175. result: dict[str, int | float | None] = {"actual_time_seconds": None, "time_accuracy": None}
  176. # Multi-run archives: the per-run actual (started_at..completed_at on
  177. # the archive row) is incommensurable with the whole-file estimate.
  178. # Both fields are cleared so the card shows estimate + no badge.
  179. if run_aggregate and (run_aggregate.get("run_count") or 0) > 1:
  180. return result
  181. if archive.started_at and archive.completed_at and archive.status == "completed":
  182. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  183. if actual_seconds > 0:
  184. result["actual_time_seconds"] = actual_seconds
  185. if archive.print_time_seconds and archive.print_time_seconds > 0:
  186. # Calculate accuracy as percentage
  187. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  188. # Sanity check: skip unreasonable values (e.g., manually changed status)
  189. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  190. if 5 <= accuracy <= 500:
  191. result["time_accuracy"] = round(accuracy, 1)
  192. return result
  193. async def _load_run_aggregates(db: AsyncSession, archive_ids: list[int]) -> dict[int, dict]:
  194. """Batch-load per-archive run aggregates from PrintLogEntry.
  195. Returns ``{archive_id: {run_count, last_run_at, total_filament_actual_grams,
  196. successful_run_count, failed_run_count}}``. Archives with no logged runs are
  197. absent from the map; callers should treat that as zero/none.
  198. """
  199. from backend.app.models.print_log import PrintLogEntry
  200. if not archive_ids:
  201. return {}
  202. rows = await db.execute(
  203. select(
  204. PrintLogEntry.archive_id,
  205. func.count(PrintLogEntry.id).label("run_count"),
  206. func.max(PrintLogEntry.started_at).label("last_run_at"),
  207. func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0).label("total_filament"),
  208. func.sum(case((PrintLogEntry.status == "completed", 1), else_=0)).label("successful"),
  209. func.sum(case((PrintLogEntry.status == "failed", 1), else_=0)).label("failed"),
  210. )
  211. .where(PrintLogEntry.archive_id.in_(archive_ids))
  212. .group_by(PrintLogEntry.archive_id)
  213. )
  214. aggregates: dict[int, dict] = {}
  215. for archive_id, run_count, last_run_at, total_filament, successful, failed in rows.all():
  216. aggregates[archive_id] = {
  217. "run_count": int(run_count or 0),
  218. "last_run_at": last_run_at,
  219. "total_filament_actual_grams": float(total_filament) if total_filament else None,
  220. "successful_run_count": int(successful or 0),
  221. "failed_run_count": int(failed or 0),
  222. }
  223. return aggregates
  224. def archive_to_response(
  225. archive: PrintArchive,
  226. duplicates: list[dict] | None = None,
  227. duplicate_count: int = 0,
  228. duplicate_sequence: int = 0,
  229. original_archive_id: int | None = None,
  230. run_aggregate: dict | None = None,
  231. ) -> dict:
  232. """Convert archive model to response dict with computed fields."""
  233. data = {
  234. "id": archive.id,
  235. "printer_id": archive.printer_id,
  236. "project_id": archive.project_id,
  237. "project_name": archive.project.name if archive.project else None,
  238. "filename": archive.filename,
  239. "file_path": archive.file_path,
  240. "file_size": archive.file_size,
  241. "content_hash": archive.content_hash,
  242. "thumbnail_path": archive.thumbnail_path,
  243. "timelapse_path": archive.timelapse_path,
  244. "source_3mf_path": archive.source_3mf_path,
  245. "f3d_path": archive.f3d_path,
  246. "duplicates": duplicates,
  247. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  248. "duplicate_sequence": duplicate_sequence,
  249. "original_archive_id": original_archive_id,
  250. "print_name": archive.print_name,
  251. "print_time_seconds": archive.print_time_seconds,
  252. "filament_used_grams": archive.filament_used_grams,
  253. "filament_type": archive.filament_type,
  254. "filament_color": archive.filament_color,
  255. "layer_height": archive.layer_height,
  256. "total_layers": archive.total_layers,
  257. "nozzle_diameter": archive.nozzle_diameter,
  258. "bed_temperature": archive.bed_temperature,
  259. "bed_type": archive.bed_type,
  260. "nozzle_temperature": archive.nozzle_temperature,
  261. "sliced_for_model": archive.sliced_for_model,
  262. "status": archive.status,
  263. "started_at": archive.started_at,
  264. "completed_at": archive.completed_at,
  265. "extra_data": archive.extra_data,
  266. "makerworld_url": archive.makerworld_url,
  267. "designer": archive.designer,
  268. "external_url": archive.external_url,
  269. "is_favorite": archive.is_favorite,
  270. "tags": archive.tags,
  271. "notes": archive.notes,
  272. "cost": archive.cost,
  273. "photos": archive.photos,
  274. "failure_reason": archive.failure_reason,
  275. "quantity": archive.quantity,
  276. "energy_kwh": archive.energy_kwh,
  277. "energy_cost": archive.energy_cost,
  278. "created_at": archive.created_at,
  279. # User tracking (Issue #206)
  280. "created_by_id": archive.created_by_id,
  281. "created_by_username": archive.created_by.username if archive.created_by else None,
  282. }
  283. # Add computed time accuracy fields. ``run_aggregate`` lets
  284. # ``compute_time_accuracy`` suppress the badge for multi-run archives
  285. # where the per-run actual / whole-file estimate scopes don't match
  286. # (#1608).
  287. accuracy_data = compute_time_accuracy(archive, run_aggregate)
  288. data.update(accuracy_data)
  289. if run_aggregate:
  290. data["run_count"] = run_aggregate.get("run_count", 0)
  291. data["last_run_at"] = run_aggregate.get("last_run_at")
  292. data["total_filament_actual_grams"] = run_aggregate.get("total_filament_actual_grams")
  293. data["successful_run_count"] = run_aggregate.get("successful_run_count", 0)
  294. data["failed_run_count"] = run_aggregate.get("failed_run_count", 0)
  295. return data
  296. @router.get("/", response_model=list[ArchiveResponse])
  297. async def list_archives(
  298. printer_id: int | None = None,
  299. project_id: int | None = None,
  300. date_from: date | None = Query(None),
  301. date_to: date | None = Query(None),
  302. limit: int = 50,
  303. offset: int = 0,
  304. db: AsyncSession = Depends(get_db),
  305. auth_result: tuple[User | None, bool] = Depends(
  306. require_ownership_permission(
  307. Permission.ARCHIVES_READ_ALL,
  308. Permission.ARCHIVES_READ_OWN,
  309. )
  310. ),
  311. ):
  312. """List archived prints."""
  313. user, can_read_all = auth_result
  314. visible_to_user_id = user.id if (user is not None and not can_read_all) else None
  315. service = ArchiveService(db)
  316. archives = await service.list_archives(
  317. printer_id=printer_id,
  318. project_id=project_id,
  319. date_from=date_from,
  320. date_to=date_to,
  321. limit=limit,
  322. offset=offset,
  323. visible_to_user_id=visible_to_user_id,
  324. )
  325. # Get sets of duplicate hashes and duplicate (name, hash) pairs (efficient single queries)
  326. duplicate_hashes, duplicate_name_hash_pairs = await service.get_duplicate_hashes_and_names()
  327. # Batch-load duplicate groups once for the current page keys.
  328. duplicate_hashes_in_page = {
  329. a.content_hash for a in archives if a.content_hash and a.content_hash in duplicate_hashes
  330. }
  331. duplicate_name_hash_keys_in_page = {
  332. (a.print_name.lower(), a.content_hash)
  333. for a in archives
  334. if a.print_name and a.content_hash and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  335. }
  336. duplicate_meta_by_archive_id: dict[int, tuple[int, int, int]] = {}
  337. if duplicate_hashes_in_page or duplicate_name_hash_keys_in_page:
  338. duplicate_group_conditions = []
  339. if duplicate_hashes_in_page:
  340. duplicate_group_conditions.append(PrintArchive.content_hash.in_(duplicate_hashes_in_page))
  341. if duplicate_name_hash_keys_in_page:
  342. name_hash_conditions = [
  343. and_(func.lower(PrintArchive.print_name) == name, PrintArchive.content_hash == hash_)
  344. for name, hash_ in duplicate_name_hash_keys_in_page
  345. ]
  346. duplicate_group_conditions.extend(name_hash_conditions)
  347. duplicate_group_rows = await db.execute(
  348. select(
  349. PrintArchive.id,
  350. PrintArchive.created_at,
  351. PrintArchive.content_hash,
  352. func.lower(PrintArchive.print_name).label("print_name_lower"),
  353. ).where(or_(*duplicate_group_conditions), PrintArchive.deleted_at.is_(None))
  354. )
  355. duplicate_groups_by_hash: dict[str, list[tuple[int, datetime]]] = defaultdict(list)
  356. duplicate_groups_by_name_hash: dict[tuple[str, str], list[tuple[int, datetime]]] = defaultdict(list)
  357. for archive_id, created_at, content_hash, print_name_lower in duplicate_group_rows.all():
  358. if content_hash and content_hash in duplicate_hashes_in_page:
  359. duplicate_groups_by_hash[content_hash].append((archive_id, created_at))
  360. if (
  361. print_name_lower
  362. and content_hash
  363. and (print_name_lower, content_hash) in duplicate_name_hash_keys_in_page
  364. ):
  365. duplicate_groups_by_name_hash[(print_name_lower, content_hash)].append((archive_id, created_at))
  366. for group in duplicate_groups_by_hash.values():
  367. if len(group) < 2:
  368. continue
  369. group.sort(key=lambda x: x[1])
  370. original_id = group[0][0]
  371. duplicate_count = len(group) - 1
  372. for sequence, (archive_id, _) in enumerate(group):
  373. duplicate_meta_by_archive_id[archive_id] = (sequence, original_id, duplicate_count)
  374. # Keep hash-based grouping precedence; name/hash groups only fill missing items.
  375. for group in duplicate_groups_by_name_hash.values():
  376. if len(group) < 2:
  377. continue
  378. group.sort(key=lambda x: x[1])
  379. original_id = group[0][0]
  380. duplicate_count = len(group) - 1
  381. for sequence, (archive_id, _) in enumerate(group):
  382. duplicate_meta_by_archive_id.setdefault(archive_id, (sequence, original_id, duplicate_count))
  383. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  384. # Build response with duplicate sequence and original archive ID pre-computed
  385. result = []
  386. for a in archives:
  387. has_hash_dup = a.content_hash in duplicate_hashes if a.content_hash else False
  388. has_name_dup = (
  389. bool(a.print_name and a.content_hash)
  390. and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  391. )
  392. has_duplicate = has_hash_dup or has_name_dup
  393. # Pre-compute duplicate sequence and original archive ID
  394. duplicate_sequence = 0
  395. original_archive_id: int | None = None
  396. duplicate_count = 1 if has_duplicate else 0
  397. if has_duplicate and a.id in duplicate_meta_by_archive_id:
  398. duplicate_sequence, original_archive_id, duplicate_count = duplicate_meta_by_archive_id[a.id]
  399. result.append(
  400. archive_to_response(
  401. a,
  402. duplicate_count=duplicate_count,
  403. duplicate_sequence=duplicate_sequence,
  404. original_archive_id=original_archive_id,
  405. run_aggregate=run_aggregates.get(a.id),
  406. )
  407. )
  408. return result
  409. @router.get("/no-3mf-warning")
  410. async def no_3mf_warning(
  411. db: AsyncSession = Depends(get_db),
  412. auth_result: tuple[User | None, bool] = Depends(
  413. require_ownership_permission(
  414. Permission.ARCHIVES_READ_ALL,
  415. Permission.ARCHIVES_READ_OWN,
  416. )
  417. ),
  418. ):
  419. """Whether to nudge the user about install step 4 ("Store sent files on
  420. external storage"). True iff any archive in the last 30 days was created
  421. via the no-3MF fallback path — that's the deterministic symptom of the
  422. slicer-side variant of the setting being off.
  423. Complements the connection-diagnostic ``external_storage`` check, which
  424. only catches the printer-side variant of the setting. On older slicers
  425. where the toggle lives only in BambuStudio, the printer never reports it
  426. and the diagnostic passes — this endpoint surfaces the symptom instead.
  427. Dismissal is handled client-side via localStorage (one-shot): once the
  428. user has been told, no further nudge until they clear browser storage.
  429. The backend stays stateless.
  430. """
  431. user, can_read_all = auth_result
  432. cutoff = datetime.now(timezone.utc) - timedelta(days=30)
  433. conditions = [
  434. PrintArchive.created_at >= cutoff,
  435. PrintArchive.deleted_at.is_(None),
  436. PrintArchive.extra_data.isnot(None),
  437. ]
  438. if user is not None and not can_read_all:
  439. conditions.append(PrintArchive.created_by_id == user.id)
  440. result = await db.execute(select(PrintArchive.extra_data).where(*conditions))
  441. for (extra_data,) in result.all():
  442. if extra_data and extra_data.get("no_3mf_available"):
  443. return {"has_fallback": True}
  444. return {"has_fallback": False}
  445. @router.get("/slim", response_model=list[ArchiveSlim])
  446. async def list_archives_slim(
  447. date_from: date | None = Query(None),
  448. date_to: date | None = Query(None),
  449. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  450. limit: int = Query(default=10000, le=50000),
  451. offset: int = 0,
  452. db: AsyncSession = Depends(get_db),
  453. auth_result: tuple[User | None, bool] = Depends(
  454. require_ownership_permission(
  455. Permission.ARCHIVES_READ_ALL,
  456. Permission.ARCHIVES_READ_OWN,
  457. )
  458. ),
  459. ):
  460. """Per-event listing for stats/dashboard widgets.
  461. Reads from print_log_entries so reprints contribute each run and
  462. orphaned events (archive deleted, log row survived via ON DELETE
  463. SET NULL) still aggregate consistently with Quick Stats. The sliced
  464. print_time_seconds is joined from the archive when available; for
  465. orphan events it is null and downstream widgets fall back to the
  466. measured duration_seconds.
  467. """
  468. from backend.app.models.print_log import PrintLogEntry
  469. current_user, can_read_all = auth_result
  470. _validate_user_filter_permission(current_user, created_by_id)
  471. # Callers without ARCHIVES_READ_ALL can only see their own runs — pin
  472. # the filter unconditionally so a caller-supplied ?created_by_id=
  473. # can't widen the listing past their own scope. The existing
  474. # _validate_user_filter_permission rejects ?created_by_id= without
  475. # STATS_FILTER_BY_USER, so the only way to reach this is owner-self
  476. # filtering anyway, but pinning here is the fail-closed default.
  477. if current_user is not None and not can_read_all:
  478. created_by_id = current_user.id
  479. filters = []
  480. if date_from:
  481. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  482. filters.append(PrintLogEntry.created_at >= dt_from)
  483. if date_to:
  484. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  485. filters.append(PrintLogEntry.created_at <= dt_to)
  486. _apply_run_user_filter(filters, created_by_id)
  487. query = (
  488. select(
  489. PrintLogEntry.printer_id,
  490. PrintLogEntry.print_name,
  491. PrintArchive.print_time_seconds,
  492. PrintLogEntry.started_at,
  493. PrintLogEntry.completed_at,
  494. PrintLogEntry.duration_seconds,
  495. PrintLogEntry.filament_used_grams,
  496. PrintLogEntry.filament_type,
  497. PrintLogEntry.filament_color,
  498. PrintLogEntry.status,
  499. PrintLogEntry.cost,
  500. PrintLogEntry.energy_kwh,
  501. PrintLogEntry.energy_cost,
  502. PrintLogEntry.created_at,
  503. )
  504. .outerjoin(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  505. .where(*filters)
  506. .order_by(PrintLogEntry.created_at.desc())
  507. .limit(limit)
  508. .offset(offset)
  509. )
  510. result = await db.execute(query)
  511. rows = result.all()
  512. return [
  513. {
  514. "printer_id": r.printer_id,
  515. "print_name": r.print_name,
  516. "print_time_seconds": r.print_time_seconds,
  517. "actual_time_seconds": (
  518. # Measured elapsed time for every status (#1390): failed /
  519. # cancelled prints still ran for some duration, and Quick
  520. # Stats already counts that. Widgets that fall back to
  521. # print_time_seconds (slicer estimate) for non-completed
  522. # events would diverge from Quick Stats — so expose the
  523. # measured value here unconditionally.
  524. #
  525. # Trust an explicit 0 (reconciled aborts store it deliberately;
  526. # their real end time is unknown) instead of recomputing the
  527. # multi-day disconnect gap from the timestamps (#2592).
  528. r.duration_seconds
  529. if r.duration_seconds is not None
  530. else (
  531. int((r.completed_at - r.started_at).total_seconds())
  532. if r.started_at and r.completed_at and (r.completed_at - r.started_at).total_seconds() > 0
  533. else None
  534. )
  535. ),
  536. "filament_used_grams": r.filament_used_grams,
  537. "filament_type": r.filament_type,
  538. "filament_color": r.filament_color,
  539. "status": r.status,
  540. "started_at": r.started_at,
  541. "completed_at": r.completed_at,
  542. "cost": r.cost,
  543. "energy_kwh": r.energy_kwh,
  544. "energy_cost": r.energy_cost,
  545. "quantity": 1,
  546. "created_at": r.created_at,
  547. }
  548. for r in rows
  549. ]
  550. @router.get("/search", response_model=list[ArchiveResponse])
  551. async def search_archives(
  552. q: str = Query(..., min_length=2, description="Search query"),
  553. printer_id: int | None = None,
  554. project_id: int | None = None,
  555. status: str | None = None,
  556. limit: int = 50,
  557. offset: int = 0,
  558. db: AsyncSession = Depends(get_db),
  559. auth_result: tuple[User | None, bool] = Depends(
  560. require_ownership_permission(
  561. Permission.ARCHIVES_READ_ALL,
  562. Permission.ARCHIVES_READ_OWN,
  563. )
  564. ),
  565. ):
  566. """Full-text search across archives.
  567. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  568. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  569. """
  570. from sqlalchemy import text
  571. from sqlalchemy.orm import selectinload
  572. from backend.app.core.db_dialect import is_sqlite
  573. user, can_read_all = auth_result
  574. own_only = user is not None and not can_read_all
  575. search_term = q.strip()
  576. # Build dialect-specific full-text search query
  577. if is_sqlite():
  578. # SQLite FTS5: wildcard suffix for partial matches
  579. if not search_term.endswith("*"):
  580. search_term = f"{search_term}*"
  581. fts_query = text("""
  582. SELECT rowid FROM archive_fts
  583. WHERE archive_fts MATCH :search_term
  584. ORDER BY rank
  585. LIMIT :limit OFFSET :offset
  586. """)
  587. else:
  588. # PostgreSQL: tsvector + plainto_tsquery with prefix matching
  589. fts_query = text("""
  590. SELECT id FROM print_archives
  591. WHERE to_tsvector('simple',
  592. COALESCE(print_name, '') || ' ' ||
  593. COALESCE(filename, '') || ' ' ||
  594. COALESCE(tags, '') || ' ' ||
  595. COALESCE(notes, '') || ' ' ||
  596. COALESCE(designer, '') || ' ' ||
  597. COALESCE(filament_type, '')
  598. ) @@ to_tsquery('simple', :search_term)
  599. LIMIT :limit OFFSET :offset
  600. """)
  601. # Convert "benchy" to "benchy:*" for prefix matching in tsquery
  602. search_term = " & ".join(f"{word}:*" for word in search_term.split() if word)
  603. try:
  604. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  605. matched_ids = [row[0] for row in result.fetchall()]
  606. except Exception as e:
  607. logger.warning("FTS search failed, falling back to LIKE search: %s", e)
  608. # Fallback to LIKE search if FTS fails
  609. like_pattern = f"%{q}%"
  610. query = (
  611. select(PrintArchive)
  612. .options(selectinload(PrintArchive.project))
  613. .where(
  614. (
  615. (PrintArchive.print_name.ilike(like_pattern))
  616. | (PrintArchive.filename.ilike(like_pattern))
  617. | (PrintArchive.tags.ilike(like_pattern))
  618. | (PrintArchive.notes.ilike(like_pattern))
  619. | (PrintArchive.designer.ilike(like_pattern))
  620. | (PrintArchive.filament_type.ilike(like_pattern))
  621. ),
  622. PrintArchive.deleted_at.is_(None),
  623. )
  624. .order_by(PrintArchive.created_at.desc())
  625. )
  626. if printer_id:
  627. query = query.where(PrintArchive.printer_id == printer_id)
  628. if project_id:
  629. query = query.where(PrintArchive.project_id == project_id)
  630. if status:
  631. query = query.where(PrintArchive.status == status)
  632. if own_only:
  633. query = query.where(PrintArchive.created_by_id == user.id)
  634. query = query.limit(limit).offset(offset)
  635. result = await db.execute(query)
  636. archives = result.scalars().all()
  637. # Load run aggregates so multi-run archives' time/accuracy badge is
  638. # suppressed consistently with the main list endpoint (#1608).
  639. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  640. return [archive_to_response(a, run_aggregate=run_aggregates.get(a.id)) for a in archives]
  641. if not matched_ids:
  642. return []
  643. # Fetch full archive records for matched IDs (excluding soft-deleted, #1343)
  644. query = (
  645. select(PrintArchive)
  646. .options(selectinload(PrintArchive.project))
  647. .where(PrintArchive.id.in_(matched_ids), PrintArchive.deleted_at.is_(None))
  648. )
  649. if own_only:
  650. query = query.where(PrintArchive.created_by_id == user.id)
  651. # Apply additional filters
  652. if printer_id:
  653. query = query.where(PrintArchive.printer_id == printer_id)
  654. if project_id:
  655. query = query.where(PrintArchive.project_id == project_id)
  656. if status:
  657. query = query.where(PrintArchive.status == status)
  658. result = await db.execute(query)
  659. archives_dict = {a.id: a for a in result.scalars().all()}
  660. # Preserve FTS ranking order and apply pagination
  661. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  662. paginated = ordered_archives[offset : offset + limit]
  663. # Load run aggregates so multi-run archives' time/accuracy badge is
  664. # suppressed consistently with the main list endpoint (#1608).
  665. run_aggregates = await _load_run_aggregates(db, [a.id for a in paginated])
  666. return [archive_to_response(a, run_aggregate=run_aggregates.get(a.id)) for a in paginated]
  667. @router.post("/search/rebuild-index")
  668. async def rebuild_search_index(
  669. db: AsyncSession = Depends(get_db),
  670. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  671. ):
  672. """Rebuild the full-text search index from existing archives.
  673. Use this if search results seem incomplete or incorrect.
  674. """
  675. from sqlalchemy import text
  676. from backend.app.core.db_dialect import is_sqlite
  677. try:
  678. if is_sqlite():
  679. # SQLite: rebuild FTS5 virtual table
  680. await db.execute(text("DELETE FROM archive_fts"))
  681. await db.execute(
  682. text("""
  683. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  684. SELECT id, print_name, filename, tags, notes, designer, filament_type
  685. FROM print_archives
  686. """)
  687. )
  688. await db.commit()
  689. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  690. count = result.scalar() or 0
  691. else:
  692. # PostgreSQL: GIN index is auto-maintained, just reindex
  693. await db.execute(text("REINDEX INDEX idx_archives_fulltext"))
  694. await db.commit()
  695. result = await db.execute(text("SELECT COUNT(*) FROM print_archives"))
  696. count = result.scalar() or 0
  697. return {"message": f"Search index rebuilt with {count} entries"}
  698. except Exception as e:
  699. logger.error("Failed to rebuild search index: %s", e)
  700. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  701. @router.get("/analysis/failures")
  702. async def analyze_failures(
  703. days: int | None = None,
  704. date_from: date | None = Query(None),
  705. date_to: date | None = Query(None),
  706. printer_id: int | None = None,
  707. project_id: int | None = None,
  708. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  709. db: AsyncSession = Depends(get_db),
  710. auth_result: tuple[User | None, bool] = Depends(
  711. require_ownership_permission(
  712. Permission.ARCHIVES_READ_ALL,
  713. Permission.ARCHIVES_READ_OWN,
  714. )
  715. ),
  716. ):
  717. """Analyze failure patterns across prints.
  718. Returns failure statistics including:
  719. - Overall failure rate
  720. - Failures by reason, filament type, printer
  721. - Time of day distribution
  722. - Recent failures
  723. - Weekly trend
  724. """
  725. current_user, can_read_all = auth_result
  726. _validate_user_filter_permission(current_user, created_by_id)
  727. # Callers without ARCHIVES_READ_ALL are scoped to their own runs (#2).
  728. if current_user is not None and not can_read_all:
  729. created_by_id = current_user.id
  730. from backend.app.services.failure_analysis import FailureAnalysisService
  731. service = FailureAnalysisService(db)
  732. return await service.analyze_failures(
  733. days=days,
  734. date_from=date_from,
  735. date_to=date_to,
  736. printer_id=printer_id,
  737. project_id=project_id,
  738. created_by_id=created_by_id,
  739. )
  740. @router.get("/compare")
  741. async def compare_archives(
  742. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  743. db: AsyncSession = Depends(get_db),
  744. auth_result: tuple[User | None, bool] = Depends(
  745. require_ownership_permission(
  746. Permission.ARCHIVES_READ_ALL,
  747. Permission.ARCHIVES_READ_OWN,
  748. )
  749. ),
  750. ):
  751. """Compare multiple archives side by side.
  752. Compares print settings, filament usage, and print times.
  753. Also analyzes correlation between settings and success/failure.
  754. Args:
  755. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  756. """
  757. from backend.app.services.archive_comparison import ArchiveComparisonService
  758. user, can_read_all = auth_result
  759. # Parse and validate archive IDs
  760. try:
  761. ids = [int(id.strip()) for id in archive_ids.split(",")]
  762. except ValueError:
  763. raise HTTPException(400, "Invalid archive IDs format")
  764. if len(ids) < 2:
  765. raise HTTPException(400, "At least 2 archives required for comparison")
  766. if len(ids) > 5:
  767. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  768. # Verify the caller is allowed to see every archive in the comparison —
  769. # one not-owned id in the list would otherwise leak its full detail block.
  770. # _ensure_archive_visible raises 404 on the first miss (same 404 the
  771. # single-archive endpoint would return).
  772. if user is not None and not can_read_all:
  773. existing = await db.execute(
  774. select(PrintArchive.id, PrintArchive.created_by_id, PrintArchive.deleted_at).where(PrintArchive.id.in_(ids))
  775. )
  776. owners_by_id = {row.id: row for row in existing.all()}
  777. for archive_id in ids:
  778. row = owners_by_id.get(archive_id)
  779. if row is None or row.deleted_at is not None or row.created_by_id != user.id:
  780. raise HTTPException(404, "Archive not found")
  781. service = ArchiveComparisonService(db)
  782. try:
  783. return await service.compare_archives(ids)
  784. except ValueError as e:
  785. raise HTTPException(400, str(e))
  786. @router.get("/export")
  787. async def export_archives(
  788. format: str = Query("csv", description="Export format: csv or xlsx"),
  789. fields: str | None = Query(None, description="Comma-separated field names"),
  790. printer_id: int | None = None,
  791. project_id: int | None = None,
  792. status: str | None = None,
  793. date_from: str | None = Query(None, description="Start date (ISO format)"),
  794. date_to: str | None = Query(None, description="End date (ISO format)"),
  795. search: str | None = None,
  796. db: AsyncSession = Depends(get_db),
  797. auth_result: tuple[User | None, bool] = Depends(
  798. require_ownership_permission(
  799. Permission.ARCHIVES_READ_ALL,
  800. Permission.ARCHIVES_READ_OWN,
  801. )
  802. ),
  803. ):
  804. """Export archives to CSV or Excel format.
  805. Returns a downloadable file with archive data.
  806. """
  807. from datetime import datetime
  808. from fastapi.responses import StreamingResponse
  809. from backend.app.services.export import ExportService
  810. user, can_read_all = auth_result
  811. visible_to_user_id = user.id if (user is not None and not can_read_all) else None
  812. if format not in ("csv", "xlsx"):
  813. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  814. # Parse fields
  815. field_list = None
  816. if fields:
  817. field_list = [f.strip() for f in fields.split(",")]
  818. # Parse dates
  819. date_from_dt = None
  820. date_to_dt = None
  821. if date_from:
  822. try:
  823. date_from_dt = datetime.fromisoformat(date_from)
  824. except ValueError:
  825. raise HTTPException(400, "Invalid date_from format")
  826. if date_to:
  827. try:
  828. date_to_dt = datetime.fromisoformat(date_to)
  829. except ValueError:
  830. raise HTTPException(400, "Invalid date_to format")
  831. service = ExportService(db)
  832. try:
  833. file_bytes, filename, content_type = await service.export_archives(
  834. format=format,
  835. fields=field_list,
  836. printer_id=printer_id,
  837. project_id=project_id,
  838. status=status,
  839. date_from=date_from_dt,
  840. date_to=date_to_dt,
  841. search=search,
  842. visible_to_user_id=visible_to_user_id,
  843. )
  844. except ImportError as e:
  845. raise HTTPException(500, str(e))
  846. return StreamingResponse(
  847. io.BytesIO(file_bytes),
  848. media_type=content_type,
  849. headers={"Content-Disposition": build_content_disposition(filename)},
  850. )
  851. @router.get("/stats/export")
  852. async def export_stats(
  853. format: str = Query("csv", description="Export format: csv or xlsx"),
  854. days: int = 30,
  855. printer_id: int | None = None,
  856. project_id: int | None = None,
  857. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  858. db: AsyncSession = Depends(get_db),
  859. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  860. ):
  861. """Export statistics summary to CSV or Excel format."""
  862. _validate_user_filter_permission(current_user, created_by_id)
  863. from fastapi.responses import StreamingResponse
  864. from backend.app.services.export import ExportService
  865. if format not in ("csv", "xlsx"):
  866. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  867. service = ExportService(db)
  868. try:
  869. file_bytes, filename, content_type = await service.export_stats(
  870. format=format,
  871. days=days,
  872. printer_id=printer_id,
  873. project_id=project_id,
  874. created_by_id=created_by_id,
  875. )
  876. except ImportError as e:
  877. raise HTTPException(500, str(e))
  878. return StreamingResponse(
  879. io.BytesIO(file_bytes),
  880. media_type=content_type,
  881. headers={"Content-Disposition": build_content_disposition(filename)},
  882. )
  883. @router.get("/stats", response_model=ArchiveStats)
  884. async def get_archive_stats(
  885. date_from: date | None = Query(None, description="Start date (inclusive), YYYY-MM-DD"),
  886. date_to: date | None = Query(None, description="End date (inclusive), YYYY-MM-DD"),
  887. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  888. db: AsyncSession = Depends(get_db),
  889. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  890. ):
  891. """Get statistics across all archives.
  892. Stats aggregate over PrintLogEntry (one row per print event), not over
  893. PrintArchive (one row per file). A reprint contributes a new PrintLogEntry
  894. so its filament/cost/time/energy add to the totals instead of overwriting
  895. the source archive's first-run values (#1378).
  896. """
  897. from backend.app.models.print_log import PrintLogEntry
  898. _validate_user_filter_permission(current_user, created_by_id)
  899. # Build date filter conditions scoped to PrintLogEntry (event-time).
  900. base_conditions = []
  901. if date_from:
  902. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  903. base_conditions.append(PrintLogEntry.created_at >= dt_from)
  904. if date_to:
  905. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  906. base_conditions.append(PrintLogEntry.created_at <= dt_to)
  907. _apply_run_user_filter(base_conditions, created_by_id)
  908. # Total counts (one row per print event).
  909. total_result = await db.execute(select(func.count(PrintLogEntry.id)).where(*base_conditions))
  910. total_prints = total_result.scalar() or 0
  911. successful_result = await db.execute(
  912. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status == "completed", *base_conditions)
  913. )
  914. successful_prints = successful_result.scalar() or 0
  915. failed_result = await db.execute(
  916. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status.in_(("failed", "aborted")), *base_conditions)
  917. )
  918. failed_prints = failed_result.scalar() or 0
  919. # User/system-stopped prints — stopped/cancelled/skipped are distinct from
  920. # quality failures: the user (or the queue) interrupted them, the printer
  921. # didn't detect a fault. Bucketed separately so the Success Rate gauge
  922. # divides by completed + failed only (a cancelled print shouldn't drag
  923. # the gauge down), while still being visible in the breakdown so they
  924. # don't silently vanish from Total Prints (#1390).
  925. cancelled_result = await db.execute(
  926. select(func.count(PrintLogEntry.id)).where(
  927. PrintLogEntry.status.in_(("stopped", "cancelled", "skipped")), *base_conditions
  928. )
  929. )
  930. cancelled_prints = cancelled_result.scalar() or 0
  931. # Total elapsed time — PrintLogEntry stores duration_seconds directly so we
  932. # can sum it server-side. Rows missing duration fall back to the slicer
  933. # estimate from the archive (joined for that case only).
  934. time_rows = await db.execute(
  935. select(
  936. PrintLogEntry.duration_seconds,
  937. PrintLogEntry.started_at,
  938. PrintLogEntry.completed_at,
  939. ).where(*base_conditions)
  940. )
  941. total_seconds = 0
  942. for duration_seconds, started_at, completed_at in time_rows.all():
  943. # Trust an explicitly stored duration, INCLUDING 0: a reconciled abort
  944. # stores 0 on purpose because its real end time is unknown, and the
  945. # started_at→completed_at fallback would otherwise bank the whole
  946. # multi-day disconnect gap as print time (#2592). Only rows with a NULL
  947. # duration (legacy entries that never recorded one) fall back.
  948. if duration_seconds is not None:
  949. total_seconds += duration_seconds
  950. elif started_at and completed_at:
  951. elapsed = (completed_at - started_at).total_seconds()
  952. if elapsed > 0:
  953. total_seconds += int(elapsed)
  954. total_time = total_seconds / 3600 # Convert to hours
  955. filament_result = await db.execute(
  956. select(func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0)).where(*base_conditions)
  957. )
  958. total_filament = filament_result.scalar() or 0
  959. cost_result = await db.execute(select(func.sum(PrintLogEntry.cost)).where(*base_conditions))
  960. total_cost = cost_result.scalar() or 0
  961. # By filament type (split comma-separated values for multi-material prints)
  962. filament_type_result = await db.execute(
  963. select(PrintLogEntry.filament_type).where(PrintLogEntry.filament_type.isnot(None), *base_conditions)
  964. )
  965. prints_by_filament: dict[str, int] = {}
  966. for (filament_types,) in filament_type_result.all():
  967. for ftype in filament_types.split(","):
  968. ftype = ftype.strip()
  969. if ftype:
  970. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  971. # By printer
  972. printer_result = await db.execute(
  973. select(PrintLogEntry.printer_id, func.count(PrintLogEntry.id))
  974. .where(*base_conditions)
  975. .group_by(PrintLogEntry.printer_id)
  976. )
  977. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  978. # Time accuracy — compare each completed run's actual duration to the
  979. # slicer's estimate on the linked archive. Runs without a linked archive
  980. # (NULL archive_id) or without an estimate are excluded.
  981. accuracy_rows = await db.execute(
  982. select(
  983. PrintLogEntry.duration_seconds,
  984. PrintLogEntry.started_at,
  985. PrintLogEntry.completed_at,
  986. PrintLogEntry.printer_id,
  987. PrintArchive.print_time_seconds,
  988. )
  989. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  990. .where(
  991. PrintLogEntry.status == "completed",
  992. PrintArchive.print_time_seconds.isnot(None),
  993. *base_conditions,
  994. )
  995. )
  996. # Accuracy is meaningful only when the estimate roughly describes the
  997. # work the run actually performed. Two shapes produce wildly-off ratios
  998. # that are pure noise:
  999. # - multi-plate ``.gcode.3mf`` printed plate-by-plate: each run's
  1000. # actual is one plate, the archive's estimate is the sum across
  1001. # plates (post-#1593 parser fix), so the ratio is roughly N×100%
  1002. # for an N-plate file. Pre-fix this shape was also broken, just
  1003. # less dramatically — the estimate was plate-1-only so the ratio
  1004. # was meaningless rather than N×.
  1005. # - manual interventions / purge waste blowing the actual far past
  1006. # the estimate.
  1007. # Clamp to the [50%, 200%] band so the printer-level average reflects
  1008. # real slicer-vs-reality drift, not multi-plate accounting or one-off
  1009. # outliers. Single-plate archives — the case the metric is actually
  1010. # designed for — stay fully included.
  1011. _ACCURACY_BAND_LO = 50.0
  1012. _ACCURACY_BAND_HI = 200.0
  1013. average_accuracy = None
  1014. accuracy_by_printer: dict[str, float] = {}
  1015. accuracies: list[float] = []
  1016. printer_accuracies: dict[str, list[float]] = {}
  1017. for duration_seconds, started_at, completed_at, run_printer_id, estimate_seconds in accuracy_rows.all():
  1018. actual_seconds = duration_seconds
  1019. if not actual_seconds and started_at and completed_at:
  1020. elapsed = (completed_at - started_at).total_seconds()
  1021. actual_seconds = int(elapsed) if elapsed > 0 else None
  1022. if not actual_seconds or not estimate_seconds:
  1023. continue
  1024. accuracy = (estimate_seconds / actual_seconds) * 100
  1025. if accuracy < _ACCURACY_BAND_LO or accuracy > _ACCURACY_BAND_HI:
  1026. continue
  1027. accuracies.append(accuracy)
  1028. printer_key = str(run_printer_id) if run_printer_id else "unknown"
  1029. printer_accuracies.setdefault(printer_key, []).append(accuracy)
  1030. if accuracies:
  1031. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  1032. for printer_key, accs in printer_accuracies.items():
  1033. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  1034. # Energy totals - check which mode to use
  1035. from backend.app.api.routes.settings import get_setting
  1036. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  1037. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  1038. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  1039. total_energy_kwh: float = 0.0
  1040. total_energy_cost: float = 0.0
  1041. energy_data_warming_up = False
  1042. if energy_tracking_mode == "total" and not date_from and not date_to:
  1043. # All-time total consumption — read live lifetime counters.
  1044. total_energy_kwh = await _sum_live_plug_totals(db)
  1045. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  1046. elif energy_tracking_mode == "total":
  1047. # Total consumption mode with a date filter (#941): use hourly snapshots
  1048. # to compute per-plug (endpoint - baseline) deltas.
  1049. total_energy_kwh, energy_data_warming_up = await _sum_snapshot_deltas(
  1050. db,
  1051. dt_from=(datetime.combine(date_from, time.min, tzinfo=timezone.utc) if date_from else None),
  1052. dt_to=(datetime.combine(date_to, time.max, tzinfo=timezone.utc) if date_to else None),
  1053. )
  1054. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  1055. else:
  1056. # Per-print mode: sum the per-run energy column from PrintLogEntry.
  1057. energy_kwh_result = await db.execute(select(func.sum(PrintLogEntry.energy_kwh)).where(*base_conditions))
  1058. total_energy_kwh = energy_kwh_result.scalar() or 0
  1059. energy_cost_result = await db.execute(select(func.sum(PrintLogEntry.energy_cost)).where(*base_conditions))
  1060. total_energy_cost = energy_cost_result.scalar() or 0
  1061. return ArchiveStats(
  1062. total_prints=total_prints,
  1063. successful_prints=successful_prints,
  1064. failed_prints=failed_prints,
  1065. cancelled_prints=cancelled_prints,
  1066. total_print_time_hours=round(total_time, 1),
  1067. total_filament_grams=round(total_filament, 1),
  1068. total_cost=round(total_cost, 2),
  1069. prints_by_filament_type=prints_by_filament,
  1070. prints_by_printer=prints_by_printer,
  1071. average_time_accuracy=average_accuracy,
  1072. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  1073. total_energy_kwh=round(total_energy_kwh, 3),
  1074. total_energy_cost=round(total_energy_cost, 3),
  1075. energy_data_warming_up=energy_data_warming_up,
  1076. )
  1077. async def _sum_live_plug_totals(db: AsyncSession) -> float:
  1078. """Sum the live lifetime counter from every smart plug.
  1079. Used for all-time "total consumption" mode. Only the current value is
  1080. available so this can't be date-filtered — use `_sum_snapshot_deltas` for
  1081. that case.
  1082. """
  1083. from backend.app.api.routes.settings import get_setting
  1084. from backend.app.models.smart_plug import SmartPlug
  1085. from backend.app.services.homeassistant import homeassistant_service
  1086. from backend.app.services.mqtt_relay import mqtt_relay
  1087. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  1088. from backend.app.services.tasmota import tasmota_service
  1089. plugs_result = await db.execute(select(SmartPlug))
  1090. plugs = list(plugs_result.scalars().all())
  1091. ha_url = await get_setting(db, "ha_url") or ""
  1092. ha_token = await get_setting(db, "ha_token") or ""
  1093. homeassistant_service.configure(ha_url, ha_token)
  1094. total = 0.0
  1095. for plug in plugs:
  1096. if plug.plug_type == "tasmota":
  1097. energy = await tasmota_service.get_energy(plug)
  1098. if energy and energy.get("total") is not None:
  1099. total += energy["total"]
  1100. elif plug.plug_type == "homeassistant":
  1101. energy = await homeassistant_service.get_energy(plug)
  1102. if energy and energy.get("total") is not None:
  1103. total += energy["total"]
  1104. elif plug.plug_type == "mqtt":
  1105. # MQTT plugs only expose today's counter, not lifetime.
  1106. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  1107. if mqtt_data and mqtt_data.energy is not None:
  1108. total += mqtt_data.energy
  1109. elif plug.plug_type == "rest":
  1110. energy = await rest_smart_plug_service.get_energy(plug)
  1111. if energy and energy.get("today") is not None:
  1112. total += energy["today"]
  1113. return total
  1114. async def _sum_snapshot_deltas(
  1115. db: AsyncSession,
  1116. *,
  1117. dt_from: datetime | None,
  1118. dt_to: datetime | None,
  1119. ) -> tuple[float, bool]:
  1120. """Sum per-plug energy consumption over a date range using hourly snapshots.
  1121. For each plug:
  1122. * baseline = last snapshot at or before `dt_from` (ideal)
  1123. — if missing, fall back to the earliest snapshot ever
  1124. recorded for the plug and flag the result as warming up.
  1125. * endpoint = last snapshot at or before `dt_to` (or most recent overall)
  1126. * delta = max(0, endpoint - baseline) — clamp counter resets to 0.
  1127. Returns (total_kwh, warming_up). `warming_up = True` means at least one plug
  1128. had no baseline before `dt_from` (fresh install or fresh upgrade), so the
  1129. result undercounts the beginning of the range.
  1130. """
  1131. from backend.app.models.smart_plug import SmartPlug
  1132. from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
  1133. from backend.app.utils.local_time import to_naive_utc
  1134. # ``recorded_at`` is a naive column holding UTC. Binding an aware datetime
  1135. # against it raises DataError on asyncpg (SQLite silently drops the offset),
  1136. # which took the whole date-filtered energy figure down on Postgres.
  1137. dt_from = to_naive_utc(dt_from)
  1138. dt_to = to_naive_utc(dt_to)
  1139. plug_ids_result = await db.execute(select(SmartPlug.id))
  1140. plug_ids = [row[0] for row in plug_ids_result.all()]
  1141. if not plug_ids:
  1142. return 0.0, False
  1143. total = 0.0
  1144. warming_up = False
  1145. for plug_id in plug_ids:
  1146. baseline: float | None = None
  1147. if dt_from is not None:
  1148. baseline_q = await db.execute(
  1149. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1150. .where(
  1151. SmartPlugEnergySnapshot.plug_id == plug_id,
  1152. SmartPlugEnergySnapshot.recorded_at <= dt_from,
  1153. )
  1154. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  1155. .limit(1)
  1156. )
  1157. baseline = baseline_q.scalar()
  1158. if baseline is None:
  1159. # No snapshot before range start — fall back to the earliest
  1160. # snapshot ever recorded. Result undercounts the pre-first-snapshot
  1161. # portion of the range; signal that to the frontend.
  1162. earliest_q = await db.execute(
  1163. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1164. .where(SmartPlugEnergySnapshot.plug_id == plug_id)
  1165. .order_by(SmartPlugEnergySnapshot.recorded_at.asc())
  1166. .limit(1)
  1167. )
  1168. baseline = earliest_q.scalar()
  1169. if baseline is None:
  1170. # No snapshots at all for this plug yet.
  1171. warming_up = True
  1172. continue
  1173. warming_up = True
  1174. endpoint_conditions = [SmartPlugEnergySnapshot.plug_id == plug_id]
  1175. if dt_to is not None:
  1176. endpoint_conditions.append(SmartPlugEnergySnapshot.recorded_at <= dt_to)
  1177. endpoint_q = await db.execute(
  1178. select(SmartPlugEnergySnapshot.lifetime_kwh)
  1179. .where(*endpoint_conditions)
  1180. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  1181. .limit(1)
  1182. )
  1183. endpoint = endpoint_q.scalar()
  1184. if endpoint is None:
  1185. continue
  1186. total += max(0.0, endpoint - baseline)
  1187. return total, warming_up
  1188. @router.get("/tags")
  1189. async def get_all_tags(
  1190. db: AsyncSession = Depends(get_db),
  1191. auth_result: tuple[User | None, bool] = Depends(
  1192. require_ownership_permission(
  1193. Permission.ARCHIVES_READ_ALL,
  1194. Permission.ARCHIVES_READ_OWN,
  1195. )
  1196. ),
  1197. ):
  1198. """List all unique tags with usage counts.
  1199. Returns a list of tags sorted by count (descending), then by name.
  1200. """
  1201. user, can_read_all = auth_result
  1202. # Query all archives with non-null tags
  1203. tag_conditions = [PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None)]
  1204. if user is not None and not can_read_all:
  1205. tag_conditions.append(PrintArchive.created_by_id == user.id)
  1206. result = await db.execute(select(PrintArchive.tags).where(*tag_conditions))
  1207. all_tags_rows = result.all()
  1208. # Count occurrences of each tag
  1209. tag_counts: dict[str, int] = {}
  1210. for (tags_str,) in all_tags_rows:
  1211. if tags_str:
  1212. for tag in tags_str.split(","):
  1213. tag = tag.strip()
  1214. if tag:
  1215. tag_counts[tag] = tag_counts.get(tag, 0) + 1
  1216. # Convert to list and sort by count (desc), then name (asc)
  1217. tags_list = [{"name": name, "count": count} for name, count in tag_counts.items()]
  1218. tags_list.sort(key=lambda x: (-x["count"], x["name"].lower()))
  1219. return tags_list
  1220. @router.put("/tags/{tag_name}")
  1221. async def rename_tag(
  1222. tag_name: str,
  1223. request: Request,
  1224. db: AsyncSession = Depends(get_db),
  1225. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1226. ):
  1227. """Rename a tag across all archives.
  1228. Request body should contain {"new_name": "new tag name"}.
  1229. Returns the count of affected archives.
  1230. """
  1231. body = await request.json()
  1232. new_name = body.get("new_name", "").strip()
  1233. if not new_name:
  1234. raise HTTPException(400, "new_name is required")
  1235. if new_name == tag_name:
  1236. return {"affected": 0}
  1237. # Find all archives containing the old tag
  1238. result = await db.execute(
  1239. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1240. )
  1241. archives = list(result.scalars().all())
  1242. affected = 0
  1243. for archive in archives:
  1244. if not archive.tags:
  1245. continue
  1246. tags = [t.strip() for t in archive.tags.split(",")]
  1247. if tag_name in tags:
  1248. # Replace old tag with new tag
  1249. new_tags = [new_name if t == tag_name else t for t in tags]
  1250. # Remove duplicates while preserving order
  1251. seen = set()
  1252. unique_tags = []
  1253. for t in new_tags:
  1254. if t not in seen:
  1255. seen.add(t)
  1256. unique_tags.append(t)
  1257. archive.tags = ", ".join(unique_tags)
  1258. affected += 1
  1259. await db.commit()
  1260. return {"affected": affected}
  1261. @router.delete("/tags/{tag_name}")
  1262. async def delete_tag(
  1263. tag_name: str,
  1264. db: AsyncSession = Depends(get_db),
  1265. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1266. ):
  1267. """Delete a tag from all archives.
  1268. Returns the count of affected archives.
  1269. """
  1270. # Find all archives containing the tag
  1271. result = await db.execute(
  1272. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1273. )
  1274. archives = list(result.scalars().all())
  1275. affected = 0
  1276. for archive in archives:
  1277. if not archive.tags:
  1278. continue
  1279. tags = [t.strip() for t in archive.tags.split(",")]
  1280. if tag_name in tags:
  1281. # Remove the tag
  1282. new_tags = [t for t in tags if t != tag_name]
  1283. archive.tags = ", ".join(new_tags) if new_tags else None
  1284. affected += 1
  1285. await db.commit()
  1286. return {"affected": affected}
  1287. @router.get("/{archive_id}", response_model=ArchiveResponse)
  1288. async def get_archive(
  1289. archive_id: int,
  1290. db: AsyncSession = Depends(get_db),
  1291. auth_result: tuple[User | None, bool] = Depends(
  1292. require_ownership_permission(
  1293. Permission.ARCHIVES_READ_ALL,
  1294. Permission.ARCHIVES_READ_OWN,
  1295. )
  1296. ),
  1297. ):
  1298. """Get a specific archive."""
  1299. user, can_read_all = auth_result
  1300. service = ArchiveService(db)
  1301. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1302. # Find duplicates
  1303. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1304. duplicates = await service.find_duplicates(
  1305. archive_id=archive.id,
  1306. content_hash=archive.content_hash,
  1307. print_name=archive.print_name,
  1308. makerworld_model_id=makerworld_id,
  1309. )
  1310. run_aggregates = await _load_run_aggregates(db, [archive.id])
  1311. return archive_to_response(archive, duplicates, run_aggregate=run_aggregates.get(archive.id))
  1312. @router.get("/{archive_id}/delete-impact")
  1313. async def get_archive_delete_impact(
  1314. archive_id: int,
  1315. db: AsyncSession = Depends(get_db),
  1316. auth_result: tuple[User | None, bool] = Depends(
  1317. require_ownership_permission(
  1318. Permission.ARCHIVES_READ_ALL,
  1319. Permission.ARCHIVES_READ_OWN,
  1320. )
  1321. ),
  1322. ):
  1323. """Pre-flight for the delete-confirm modal (#1734).
  1324. Returns the number of related queue items the user is about to remove
  1325. AND whether any of them are currently printing (which would block the
  1326. delete with a 409 — surfaced to the modal so it can disable the
  1327. confirm button instead of failing on submit). Cheap, single endpoint —
  1328. not folded into the archive GET response so the much larger list
  1329. endpoint isn't forced to run the same query per row.
  1330. """
  1331. user, can_read_all = auth_result
  1332. service = ArchiveService(db)
  1333. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1334. from backend.app.services.archive import _count_related_queue_items
  1335. total, printing = await _count_related_queue_items(db, archive.id)
  1336. return {"related_queue_items": total, "currently_printing": printing}
  1337. @router.get("/{archive_id}/runs", response_model=PrintLogResponse)
  1338. async def list_archive_runs(
  1339. archive_id: int,
  1340. db: AsyncSession = Depends(get_db),
  1341. auth_result: tuple[User | None, bool] = Depends(
  1342. require_ownership_permission(
  1343. Permission.ARCHIVES_READ_ALL,
  1344. Permission.ARCHIVES_READ_OWN,
  1345. )
  1346. ),
  1347. ):
  1348. """List PrintLogEntry rows for this archive — one per print event.
  1349. Newest first. Drives the per-archive "Print Log" view (#1378).
  1350. """
  1351. from backend.app.models.print_log import PrintLogEntry
  1352. from backend.app.schemas.print_log import PrintLogEntrySchema
  1353. user, can_read_all = auth_result
  1354. _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all)
  1355. rows = await db.execute(
  1356. select(PrintLogEntry)
  1357. .where(PrintLogEntry.archive_id == archive_id)
  1358. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  1359. )
  1360. entries = list(rows.scalars().all())
  1361. items = [PrintLogEntrySchema.model_validate(e, from_attributes=True) for e in entries]
  1362. return PrintLogResponse(items=items, total=len(items))
  1363. @router.get("/{archive_id}/similar")
  1364. async def find_similar_archives(
  1365. archive_id: int,
  1366. limit: int = 10,
  1367. db: AsyncSession = Depends(get_db),
  1368. auth_result: tuple[User | None, bool] = Depends(
  1369. require_ownership_permission(
  1370. Permission.ARCHIVES_READ_ALL,
  1371. Permission.ARCHIVES_READ_OWN,
  1372. )
  1373. ),
  1374. ):
  1375. """Find archives with similar settings for comparison.
  1376. Returns archives that match by:
  1377. - Same print name (highest priority)
  1378. - Same file content hash
  1379. - Same filament type
  1380. """
  1381. from backend.app.services.archive_comparison import ArchiveComparisonService
  1382. user, can_read_all = auth_result
  1383. _ensure_archive_visible(await db.get(PrintArchive, archive_id), user, can_read_all)
  1384. service = ArchiveComparisonService(db)
  1385. try:
  1386. return await service.find_similar_archives(archive_id, limit=limit)
  1387. except ValueError as e:
  1388. raise HTTPException(404, str(e))
  1389. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  1390. async def update_archive(
  1391. archive_id: int,
  1392. update_data: ArchiveUpdate,
  1393. db: AsyncSession = Depends(get_db),
  1394. auth_result: tuple[User | None, bool] = Depends(
  1395. require_ownership_permission(
  1396. Permission.ARCHIVES_UPDATE_ALL,
  1397. Permission.ARCHIVES_UPDATE_OWN,
  1398. )
  1399. ),
  1400. ):
  1401. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  1402. from sqlalchemy.orm import selectinload
  1403. user, can_modify_all = auth_result
  1404. result = await db.execute(
  1405. select(PrintArchive)
  1406. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1407. .where(PrintArchive.id == archive_id)
  1408. )
  1409. archive = result.scalar_one_or_none()
  1410. if not archive:
  1411. raise HTTPException(404, "Archive not found")
  1412. # Ownership check
  1413. if not can_modify_all:
  1414. if archive.created_by_id != user.id:
  1415. raise HTTPException(403, "You can only update your own archives")
  1416. update_payload = update_data.model_dump(exclude_unset=True)
  1417. for field, value in update_payload.items():
  1418. setattr(archive, field, value)
  1419. # #1444: Mirror per-run classification fields to the most recent
  1420. # PrintLogEntry for this archive. PrintLogEntry.failure_reason is captured
  1421. # once at print-completion time from archive.failure_reason — which is
  1422. # NULL until the user classifies the failure via the Edit Archive modal.
  1423. # Without this mirror the Failure Analysis widget (which groups by
  1424. # print_log_entries.failure_reason) keeps showing "Unknown" forever.
  1425. # Same desync hits status: flipping it in the modal wouldn't update the
  1426. # entry either. Only the latest entry is touched because that's the run
  1427. # the modal is implicitly showing (archive.failure_reason / status are
  1428. # overwritten on each reprint to reflect the latest run's outcome).
  1429. mirror_fields = {"failure_reason", "status"}
  1430. to_mirror = {k: v for k, v in update_payload.items() if k in mirror_fields}
  1431. if to_mirror:
  1432. from backend.app.models.print_log import PrintLogEntry
  1433. latest_entry = await db.scalar(
  1434. select(PrintLogEntry)
  1435. .where(PrintLogEntry.archive_id == archive_id)
  1436. .order_by(PrintLogEntry.id.desc())
  1437. .limit(1)
  1438. )
  1439. if latest_entry is not None:
  1440. for field, value in to_mirror.items():
  1441. setattr(latest_entry, field, value)
  1442. await db.commit()
  1443. # Re-fetch with relationships loaded after commit
  1444. result = await db.execute(
  1445. select(PrintArchive)
  1446. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1447. .where(PrintArchive.id == archive_id)
  1448. )
  1449. archive = result.scalar_one_or_none()
  1450. # Load run aggregate so the time/accuracy badge stays consistent with
  1451. # the list / detail endpoints when the frontend re-renders the card
  1452. # after a PATCH (#1608).
  1453. run_aggregates = await _load_run_aggregates(db, [archive.id]) if archive else {}
  1454. return archive_to_response(archive, run_aggregate=run_aggregates.get(archive.id) if archive else None)
  1455. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  1456. async def toggle_favorite(
  1457. archive_id: int,
  1458. db: AsyncSession = Depends(get_db),
  1459. auth_result: tuple[User | None, bool] = Depends(
  1460. require_ownership_permission(
  1461. Permission.ARCHIVES_UPDATE_ALL,
  1462. Permission.ARCHIVES_UPDATE_OWN,
  1463. )
  1464. ),
  1465. ):
  1466. """Toggle favorite status for an archive."""
  1467. user, can_modify_all = auth_result
  1468. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1469. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  1470. archive.is_favorite = not archive.is_favorite
  1471. await db.commit()
  1472. await db.refresh(archive)
  1473. return archive
  1474. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  1475. async def rescan_archive(
  1476. archive_id: int,
  1477. db: AsyncSession = Depends(get_db),
  1478. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1479. ):
  1480. """Rescan the 3MF file and update metadata."""
  1481. from backend.app.api.routes.settings import get_setting
  1482. from backend.app.services.archive import ThreeMFParser
  1483. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1484. archive = result.scalar_one_or_none()
  1485. if not archive:
  1486. raise HTTPException(404, "Archive not found")
  1487. file_path = settings.base_dir / archive.file_path
  1488. if not file_path.is_file():
  1489. raise HTTPException(404, "Archive file not found")
  1490. # Parse the 3MF file
  1491. parser = ThreeMFParser(file_path)
  1492. metadata = parser.parse()
  1493. # Update fields from metadata
  1494. if metadata.get("filament_type"):
  1495. archive.filament_type = metadata["filament_type"]
  1496. if metadata.get("filament_color"):
  1497. archive.filament_color = metadata["filament_color"]
  1498. if metadata.get("print_time_seconds"):
  1499. archive.print_time_seconds = metadata["print_time_seconds"]
  1500. if metadata.get("filament_used_grams"):
  1501. archive.filament_used_grams = metadata["filament_used_grams"]
  1502. if metadata.get("layer_height"):
  1503. archive.layer_height = metadata["layer_height"]
  1504. if metadata.get("nozzle_diameter"):
  1505. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1506. if metadata.get("bed_temperature"):
  1507. archive.bed_temperature = metadata["bed_temperature"]
  1508. if metadata.get("bed_type"):
  1509. archive.bed_type = metadata["bed_type"]
  1510. if metadata.get("nozzle_temperature"):
  1511. archive.nozzle_temperature = metadata["nozzle_temperature"]
  1512. if metadata.get("makerworld_url"):
  1513. archive.makerworld_url = metadata["makerworld_url"]
  1514. if metadata.get("designer"):
  1515. archive.designer = metadata["designer"]
  1516. # Calculate cost: prefer spool-based cost if available, else catalog-based.
  1517. # When spool-based costs exist but don't cover every filament gram used
  1518. # (#1344), fall back to the global default rate for the untracked weight
  1519. # so the displayed cost still reflects the whole print.
  1520. if archive.filament_used_grams and archive.filament_type:
  1521. default_cost_setting = await get_setting(db, "default_filament_cost")
  1522. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1523. usage_result = await db.execute(
  1524. select(
  1525. func.sum(SpoolUsageHistory.cost),
  1526. func.sum(SpoolUsageHistory.weight_used),
  1527. ).where(SpoolUsageHistory.archive_id == archive.id)
  1528. )
  1529. usage_cost_row = usage_result.one()
  1530. usage_cost = usage_cost_row[0]
  1531. tracked_grams = float(usage_cost_row[1] or 0)
  1532. if usage_cost is not None and usage_cost > 0:
  1533. total_cost = float(usage_cost)
  1534. untracked_grams = max(0.0, archive.filament_used_grams - tracked_grams)
  1535. if untracked_grams > 0 and default_cost_per_kg > 0:
  1536. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1537. archive.cost = float(Decimal(str(total_cost)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
  1538. else:
  1539. primary_type = archive.filament_type.split(",")[0].strip()
  1540. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1541. filament = filament_result.scalar_one_or_none()
  1542. if filament:
  1543. archive.cost = float(
  1544. Decimal(str((archive.filament_used_grams / 1000) * filament.cost_per_kg)).quantize(
  1545. Decimal("0.01"), rounding=ROUND_HALF_UP
  1546. )
  1547. )
  1548. else:
  1549. archive.cost = float(
  1550. Decimal(str((archive.filament_used_grams / 1000) * default_cost_per_kg)).quantize(
  1551. Decimal("0.01"), rounding=ROUND_HALF_UP
  1552. )
  1553. )
  1554. await db.commit()
  1555. await db.refresh(archive)
  1556. return archive
  1557. @router.post("/recalculate-costs")
  1558. async def recalculate_all_costs(
  1559. db: AsyncSession = Depends(get_db),
  1560. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1561. ):
  1562. """Recalculate costs for all archives based on filament usage and prices."""
  1563. from backend.app.api.routes.settings import get_setting
  1564. result = await db.execute(select(PrintArchive))
  1565. archives = list(result.scalars().all())
  1566. # Load all filaments for lookup
  1567. filament_result = await db.execute(select(Filament))
  1568. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  1569. # Get default filament cost from settings
  1570. default_cost_setting = await get_setting(db, "default_filament_cost")
  1571. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1572. # Pre-fetch all usage costs and tracked weight by archive_id.
  1573. # Tracked weight is used to top-up the cost at the default rate for any
  1574. # filament grams not covered by an inventory spool (#1344).
  1575. usage_costs_result = await db.execute(
  1576. select(
  1577. SpoolUsageHistory.archive_id,
  1578. func.sum(SpoolUsageHistory.cost),
  1579. func.sum(SpoolUsageHistory.weight_used),
  1580. ).group_by(SpoolUsageHistory.archive_id)
  1581. )
  1582. usage_costs = usage_costs_result.fetchall()
  1583. cost_map = {
  1584. row[0]: (row[1], float(row[2] or 0))
  1585. for row in usage_costs
  1586. if row[0] is not None and row[1] is not None and row[1] > 0
  1587. }
  1588. updated = 0
  1589. for archive in archives:
  1590. usage = cost_map.get(archive.id)
  1591. if usage is not None:
  1592. usage_cost, tracked_grams = usage
  1593. total_cost = float(usage_cost)
  1594. archive_grams = float(archive.filament_used_grams or 0)
  1595. untracked_grams = max(0.0, archive_grams - tracked_grams)
  1596. if untracked_grams > 0 and default_cost_per_kg > 0:
  1597. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1598. new_cost = round(total_cost, 2)
  1599. else:
  1600. # Fallback: sum costs for old records by print_name
  1601. usage_result = await db.execute(
  1602. select(func.sum(SpoolUsageHistory.cost)).where(
  1603. SpoolUsageHistory.print_name == archive.print_name,
  1604. SpoolUsageHistory.archive_id.is_(None),
  1605. )
  1606. )
  1607. fallback_cost = usage_result.scalar()
  1608. if fallback_cost is not None and fallback_cost > 0:
  1609. new_cost = round(fallback_cost, 2)
  1610. elif archive.filament_used_grams and archive.filament_type:
  1611. primary_type = archive.filament_type.split(",")[0].strip()
  1612. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  1613. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  1614. else:
  1615. new_cost = None
  1616. if new_cost is not None and archive.cost != new_cost:
  1617. archive.cost = new_cost
  1618. updated += 1
  1619. await db.commit()
  1620. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  1621. @router.post("/rescan-all")
  1622. async def rescan_all_archives(
  1623. db: AsyncSession = Depends(get_db),
  1624. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1625. ):
  1626. """Rescan all archives and update their metadata."""
  1627. from backend.app.services.archive import ThreeMFParser
  1628. result = await db.execute(select(PrintArchive))
  1629. archives = list(result.scalars().all())
  1630. updated = 0
  1631. errors = []
  1632. for archive in archives:
  1633. try:
  1634. file_path = settings.base_dir / archive.file_path
  1635. if not file_path.is_file():
  1636. errors.append({"id": archive.id, "error": "File not found"})
  1637. continue
  1638. parser = ThreeMFParser(file_path)
  1639. metadata = parser.parse()
  1640. if metadata.get("filament_type"):
  1641. archive.filament_type = metadata["filament_type"]
  1642. if metadata.get("filament_color"):
  1643. archive.filament_color = metadata["filament_color"]
  1644. if metadata.get("print_time_seconds"):
  1645. archive.print_time_seconds = metadata["print_time_seconds"]
  1646. if metadata.get("filament_used_grams"):
  1647. archive.filament_used_grams = metadata["filament_used_grams"]
  1648. if metadata.get("layer_height"):
  1649. archive.layer_height = metadata["layer_height"]
  1650. if metadata.get("nozzle_diameter"):
  1651. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1652. if metadata.get("makerworld_url"):
  1653. archive.makerworld_url = metadata["makerworld_url"]
  1654. if metadata.get("designer"):
  1655. archive.designer = metadata["designer"]
  1656. updated += 1
  1657. except Exception as e:
  1658. logger.exception("Failed to rescan archive %s: %s", archive.id, e)
  1659. errors.append({"id": archive.id, "error": "Failed to parse 3MF file"})
  1660. await db.commit()
  1661. return {"updated": updated, "errors": errors}
  1662. @router.get("/{archive_id}/duplicates")
  1663. async def get_archive_duplicates(
  1664. archive_id: int,
  1665. db: AsyncSession = Depends(get_db),
  1666. auth_result: tuple[User | None, bool] = Depends(
  1667. require_ownership_permission(
  1668. Permission.ARCHIVES_READ_ALL,
  1669. Permission.ARCHIVES_READ_OWN,
  1670. )
  1671. ),
  1672. ):
  1673. """Get duplicates for a specific archive."""
  1674. user, can_read_all = auth_result
  1675. service = ArchiveService(db)
  1676. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1677. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1678. duplicates = await service.find_duplicates(
  1679. archive_id=archive.id,
  1680. content_hash=archive.content_hash,
  1681. print_name=archive.print_name,
  1682. makerworld_model_id=makerworld_id,
  1683. )
  1684. return {"duplicates": duplicates, "count": len(duplicates)}
  1685. @router.post("/backfill-hashes")
  1686. async def backfill_content_hashes(
  1687. db: AsyncSession = Depends(get_db),
  1688. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1689. ):
  1690. """Compute and store content hashes for all archives missing them."""
  1691. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  1692. archives = list(result.scalars().all())
  1693. updated = 0
  1694. errors = []
  1695. for archive in archives:
  1696. try:
  1697. file_path = settings.base_dir / archive.file_path
  1698. if not file_path.is_file():
  1699. errors.append({"id": archive.id, "error": "File not found"})
  1700. continue
  1701. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  1702. updated += 1
  1703. except Exception as e:
  1704. logger.exception("Failed to compute hash for archive %s: %s", archive.id, e)
  1705. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  1706. await db.commit()
  1707. return {"updated": updated, "errors": errors}
  1708. @router.delete("/{archive_id}")
  1709. async def delete_archive(
  1710. archive_id: int,
  1711. purge_stats: bool = Query(
  1712. False,
  1713. description=(
  1714. "When false (default) the archive is soft-deleted — files removed "
  1715. "from disk, row hidden from listings, but its filament / energy / "
  1716. "time / cost contribution stays in Quick Stats. Set true to also "
  1717. "drop the row from statistics (#1343)."
  1718. ),
  1719. ),
  1720. db: AsyncSession = Depends(get_db),
  1721. auth_result: tuple[User | None, bool] = Depends(
  1722. require_ownership_permission(
  1723. Permission.ARCHIVES_DELETE_ALL,
  1724. Permission.ARCHIVES_DELETE_OWN,
  1725. )
  1726. ),
  1727. ):
  1728. """Delete an archive (soft by default; ``?purge_stats=true`` to hard-delete).
  1729. Both delete paths now cascade to related ``print_queue`` rows (#1734) —
  1730. hard delete via the ``ON DELETE CASCADE`` FK, soft delete via the
  1731. ``_delete_related_queue_items`` helper. A 409 guard blocks the delete
  1732. when any related queue item is currently mid-print so the dispatcher
  1733. doesn't lose its metadata trail under the running print.
  1734. """
  1735. user, can_modify_all = auth_result
  1736. # Get archive first to check ownership
  1737. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1738. archive = result.scalar_one_or_none()
  1739. if not archive:
  1740. raise HTTPException(404, "Archive not found")
  1741. # Ownership check
  1742. if not can_modify_all:
  1743. if archive.created_by_id != user.id:
  1744. raise HTTPException(403, "You can only delete your own archives")
  1745. # #1734: block delete when any related queue item is currently printing.
  1746. # Both soft and hard delete are gated — an in-flight print needs its
  1747. # backing archive to stay around for the metadata trail (filament,
  1748. # plate, ams_mapping). The user can stop the print first, then retry.
  1749. from backend.app.services.archive import _count_related_queue_items
  1750. _related_total, related_printing = await _count_related_queue_items(db, archive_id)
  1751. if related_printing > 0:
  1752. raise HTTPException(
  1753. 409,
  1754. f"Cannot delete archive — {related_printing} related queue item(s) are "
  1755. f"currently printing. Stop the print first, then retry.",
  1756. )
  1757. service = ArchiveService(db)
  1758. if purge_stats:
  1759. # Hard-delete the linked PrintLogEntry rows first so their filament /
  1760. # cost / count contributions disappear from /archives/stats. The FK is
  1761. # ON DELETE SET NULL, so without this delete the runs would survive
  1762. # the archive row and keep showing up in totals (#1343 / #1378).
  1763. from sqlalchemy import delete as sa_delete
  1764. from backend.app.models.print_log import PrintLogEntry
  1765. await db.execute(sa_delete(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id))
  1766. await db.commit()
  1767. if not await service.delete_archive(archive_id):
  1768. raise HTTPException(404, "Archive not found")
  1769. return {"status": "deleted", "purged_from_stats": True}
  1770. if not await service.soft_delete_archive(archive_id):
  1771. raise HTTPException(404, "Archive not found")
  1772. return {"status": "deleted", "purged_from_stats": False}
  1773. @router.get("/{archive_id}/download")
  1774. async def download_archive(
  1775. archive_id: int,
  1776. inline: bool = False,
  1777. db: AsyncSession = Depends(get_db),
  1778. auth_result: tuple[User | None, bool] = Depends(
  1779. require_ownership_permission(
  1780. Permission.ARCHIVES_READ_ALL,
  1781. Permission.ARCHIVES_READ_OWN,
  1782. )
  1783. ),
  1784. ):
  1785. """Download the 3MF file."""
  1786. user, can_read_all = auth_result
  1787. service = ArchiveService(db)
  1788. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1789. file_path = settings.base_dir / archive.file_path
  1790. if not file_path.is_file():
  1791. raise HTTPException(404, "File not found")
  1792. # Use inline disposition to let browser/OS handle file association
  1793. content_disposition = "inline" if inline else "attachment"
  1794. return FileResponse(
  1795. path=file_path,
  1796. filename=archive.filename,
  1797. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1798. content_disposition_type=content_disposition,
  1799. )
  1800. @router.get("/{archive_id}/file/{filename}")
  1801. async def download_archive_with_filename(
  1802. archive_id: int,
  1803. filename: str,
  1804. db: AsyncSession = Depends(get_db),
  1805. auth_result: tuple[User | None, bool] = Depends(
  1806. require_ownership_permission(
  1807. Permission.ARCHIVES_READ_ALL,
  1808. Permission.ARCHIVES_READ_OWN,
  1809. )
  1810. ),
  1811. ):
  1812. """Download the 3MF file with filename in URL."""
  1813. user, can_read_all = auth_result
  1814. service = ArchiveService(db)
  1815. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1816. file_path = settings.base_dir / archive.file_path
  1817. if not file_path.is_file():
  1818. raise HTTPException(404, "File not found")
  1819. return FileResponse(
  1820. path=file_path,
  1821. filename=archive.filename,
  1822. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1823. )
  1824. @router.post("/{archive_id}/slicer-token")
  1825. async def create_archive_slicer_token(
  1826. archive_id: int,
  1827. db: AsyncSession = Depends(get_db),
  1828. auth_result: tuple[User | None, bool] = Depends(
  1829. require_ownership_permission(
  1830. Permission.ARCHIVES_READ_ALL,
  1831. Permission.ARCHIVES_READ_OWN,
  1832. )
  1833. ),
  1834. ):
  1835. """Create a short-lived download token for opening files in slicer applications.
  1836. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  1837. auth headers, so they use this token in the URL path instead.
  1838. """
  1839. from backend.app.core.auth import create_slicer_download_token
  1840. user, can_read_all = auth_result
  1841. service = ArchiveService(db)
  1842. _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  1843. token = await create_slicer_download_token("archive", archive_id)
  1844. return {"token": token}
  1845. @router.get("/{archive_id}/dl/{token}/{filename}")
  1846. async def download_archive_for_slicer(
  1847. archive_id: int,
  1848. token: str,
  1849. filename: str,
  1850. db: AsyncSession = Depends(get_db),
  1851. ):
  1852. """Download 3MF file using a slicer download token.
  1853. Token-authenticated (no auth headers needed). The token is short-lived
  1854. and single-use, created by POST /{archive_id}/slicer-token.
  1855. Filename is at the end of the URL so slicers can detect the file format.
  1856. """
  1857. from backend.app.core.auth import verify_slicer_download_token
  1858. if not await verify_slicer_download_token(token, "archive", archive_id):
  1859. raise HTTPException(403, "Invalid or expired download token")
  1860. service = ArchiveService(db)
  1861. archive = await service.get_archive(archive_id)
  1862. if not archive:
  1863. raise HTTPException(404, "Archive not found")
  1864. file_path = settings.base_dir / archive.file_path
  1865. if not file_path.is_file():
  1866. raise HTTPException(404, "File not found")
  1867. return FileResponse(
  1868. path=file_path,
  1869. filename=archive.filename,
  1870. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1871. )
  1872. @router.get("/{archive_id}/thumbnail")
  1873. async def get_thumbnail(
  1874. archive_id: int,
  1875. db: AsyncSession = Depends(get_db),
  1876. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1877. ):
  1878. """Get the thumbnail image.
  1879. Requires a stream token query param (?token=xxx) when auth is enabled.
  1880. """
  1881. service = ArchiveService(db)
  1882. archive = await service.get_archive(archive_id)
  1883. if not archive or not archive.thumbnail_path:
  1884. raise HTTPException(404, "Thumbnail not found")
  1885. thumb_path = settings.base_dir / archive.thumbnail_path
  1886. if not thumb_path.exists():
  1887. raise HTTPException(404, "Thumbnail file not found")
  1888. # Use file modification time as ETag to bust cache
  1889. mtime = int(thumb_path.stat().st_mtime)
  1890. return FileResponse(
  1891. path=thumb_path,
  1892. media_type="image/png",
  1893. headers={
  1894. "Cache-Control": "no-cache, must-revalidate",
  1895. "ETag": f'"{mtime}"',
  1896. },
  1897. )
  1898. @router.get("/{archive_id}/timelapse")
  1899. async def get_timelapse(
  1900. archive_id: int,
  1901. db: AsyncSession = Depends(get_db),
  1902. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1903. ):
  1904. """Get the timelapse video.
  1905. Requires a stream token query param (?token=xxx) when auth is enabled.
  1906. """
  1907. service = ArchiveService(db)
  1908. archive = await service.get_archive(archive_id)
  1909. if not archive or not archive.timelapse_path:
  1910. raise HTTPException(404, "Timelapse not found")
  1911. timelapse_path = settings.base_dir / archive.timelapse_path
  1912. if not timelapse_path.exists():
  1913. raise HTTPException(404, "Timelapse file not found")
  1914. # Use file modification time as ETag to bust cache after processing
  1915. mtime = int(timelapse_path.stat().st_mtime)
  1916. # Detect media type from file extension (AVI from P1S before background conversion)
  1917. suffix = timelapse_path.suffix.lower()
  1918. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  1919. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  1920. return FileResponse(
  1921. path=timelapse_path,
  1922. media_type=media_type,
  1923. filename=f"{archive.print_name or 'timelapse'}{ext}",
  1924. headers={
  1925. "Cache-Control": "no-cache, must-revalidate",
  1926. "ETag": f'"{mtime}"',
  1927. },
  1928. )
  1929. @router.delete("/{archive_id}/timelapse")
  1930. async def delete_timelapse(
  1931. archive_id: int,
  1932. db: AsyncSession = Depends(get_db),
  1933. auth_result: tuple[User | None, bool] = Depends(
  1934. require_ownership_permission(
  1935. Permission.ARCHIVES_DELETE_ALL,
  1936. Permission.ARCHIVES_DELETE_OWN,
  1937. )
  1938. ),
  1939. ):
  1940. """Remove the timelapse video from an archive."""
  1941. user, can_modify_all = auth_result
  1942. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1943. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  1944. if not archive.timelapse_path:
  1945. raise HTTPException(404, "No timelapse attached to this archive")
  1946. # Delete the file
  1947. timelapse_path = settings.base_dir / archive.timelapse_path
  1948. if timelapse_path.exists():
  1949. timelapse_path.unlink()
  1950. # Clear the path in database
  1951. archive.timelapse_path = None
  1952. await db.commit()
  1953. return {"status": "deleted"}
  1954. @router.post("/{archive_id}/timelapse/scan")
  1955. async def scan_timelapse(
  1956. archive_id: int,
  1957. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1958. ):
  1959. """Scan printer for timelapse matching this archive and attach it."""
  1960. from backend.app.core.database import async_session
  1961. from backend.app.models.printer import Printer
  1962. from backend.app.services.bambu_ftp import (
  1963. download_file_bytes_async,
  1964. get_ftp_retry_settings,
  1965. list_files_async,
  1966. with_ftp_retry,
  1967. )
  1968. # Read the archive + printer in a short session and release the pooled DB
  1969. # connection BEFORE the FTP scan/download below — a timelapse pull walks
  1970. # several directories and fetches a 100MB+ video, so holding Depends(get_db)
  1971. # across it pinned one connection idle-in-transaction for minutes (#2572).
  1972. # Scalar columns stay readable on the detached rows (expire_on_commit=False);
  1973. # the attach at the end runs in its own fresh short session.
  1974. async with async_session() as db:
  1975. archive = await ArchiveService(db).get_archive(archive_id)
  1976. if not archive:
  1977. raise HTTPException(404, "Archive not found")
  1978. if archive.timelapse_path:
  1979. return {"status": "exists", "message": "Timelapse already attached"}
  1980. if not archive.printer_id:
  1981. raise HTTPException(400, "Archive has no associated printer")
  1982. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1983. printer = result.scalar_one_or_none()
  1984. if not printer:
  1985. raise HTTPException(404, "Printer not found")
  1986. # Get base name from archive filename (without .3mf extension)
  1987. base_name = Path(archive.filename).stem
  1988. # Scan timelapse directory on printer
  1989. # Different printer models use different paths
  1990. files = []
  1991. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1992. try:
  1993. files = await list_files_async(
  1994. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1995. )
  1996. if files:
  1997. break
  1998. except Exception:
  1999. continue
  2000. if not files:
  2001. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  2002. # Look for matching timelapse
  2003. matching_file = None
  2004. video_files = [
  2005. f for f in files if not f.get("is_directory") and f.get("name", "").lower().endswith((".mp4", ".avi"))
  2006. ]
  2007. # Strategy 1: Match by print name in filename
  2008. for f in video_files:
  2009. fname = f.get("name", "")
  2010. if base_name.lower() in fname.lower():
  2011. matching_file = f
  2012. break
  2013. # Strategy 2: Match by timestamp proximity against print START time.
  2014. # Bambu timelapse filename embeds the print start time in printer-local clock.
  2015. # See _match_timelapse_by_timestamp for the offset-search rationale and why we
  2016. # intentionally don't try to match filename against end time here.
  2017. if not matching_file and archive.started_at:
  2018. candidate, diff = _match_timelapse_by_timestamp(video_files, archive.started_at)
  2019. if candidate is not None:
  2020. matching_file = candidate
  2021. logger.info("Matched timelapse by timestamp: %s (diff: %s)", candidate.get("name"), diff)
  2022. # Strategy 3: Use file modification time from FTP listing
  2023. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  2024. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  2025. from datetime import datetime, timedelta
  2026. _archive_start = archive.started_at
  2027. archive_end = archive.completed_at or archive.created_at
  2028. best_match = None
  2029. best_diff = timedelta(hours=24)
  2030. for f in video_files:
  2031. mtime = f.get("mtime")
  2032. if mtime:
  2033. # Timelapse file should be modified during or shortly after the print
  2034. # The mtime should be close to completion time (video finishes when print ends)
  2035. if archive_end:
  2036. diff = abs(mtime - archive_end)
  2037. if diff < best_diff:
  2038. best_diff = diff
  2039. best_match = f
  2040. logger.debug(
  2041. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  2042. )
  2043. if best_match and best_diff < timedelta(hours=2):
  2044. matching_file = best_match
  2045. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  2046. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  2047. # This handles cases where printer clock is wrong or timezone issues exist
  2048. if not matching_file and len(video_files) == 1:
  2049. from datetime import datetime, timedelta, timezone
  2050. archive_completed = archive.completed_at or archive.created_at
  2051. if archive_completed:
  2052. if archive_completed.tzinfo is None:
  2053. archive_completed = archive_completed.replace(tzinfo=timezone.utc)
  2054. time_since_completion = datetime.now(timezone.utc) - archive_completed
  2055. # If archive was completed within the last hour, assume the single timelapse is for it
  2056. if time_since_completion < timedelta(hours=1):
  2057. matching_file = video_files[0]
  2058. logger.info("Using single timelapse file as fallback: %s", video_files[0].get("name"))
  2059. # Note: We intentionally don't use a "most recent file" fallback because
  2060. # we can't verify if timelapse was actually enabled for this print.
  2061. # Instead, return the list of available files for manual selection.
  2062. if not matching_file:
  2063. # Return available files for manual selection
  2064. available_files = [
  2065. {
  2066. "name": f.get("name"),
  2067. "path": f.get("path"),
  2068. "size": f.get("size"),
  2069. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  2070. }
  2071. for f in video_files
  2072. ]
  2073. # Sort by mtime descending (most recent first)
  2074. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  2075. return {
  2076. "status": "not_found",
  2077. "message": "No matching timelapse found - please select manually",
  2078. "available_files": available_files,
  2079. }
  2080. # Download the timelapse - use the full path from the file listing
  2081. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  2082. # Get FTP retry settings
  2083. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2084. if ftp_retry_enabled:
  2085. timelapse_data = await with_ftp_retry(
  2086. download_file_bytes_async,
  2087. printer.ip_address,
  2088. printer.access_code,
  2089. remote_path,
  2090. socket_timeout=ftp_timeout,
  2091. printer_model=printer.model,
  2092. max_retries=ftp_retry_count,
  2093. retry_delay=ftp_retry_delay,
  2094. operation_name=f"Download timelapse {matching_file['name']}",
  2095. )
  2096. else:
  2097. timelapse_data = await download_file_bytes_async(
  2098. printer.ip_address,
  2099. printer.access_code,
  2100. remote_path,
  2101. socket_timeout=ftp_timeout,
  2102. printer_model=printer.model,
  2103. )
  2104. if not timelapse_data:
  2105. raise HTTPException(500, "Failed to download timelapse")
  2106. # Attach in a fresh short session (the read session was released before FTP).
  2107. async with async_session() as db:
  2108. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  2109. if not success:
  2110. raise HTTPException(500, "Failed to attach timelapse")
  2111. return {
  2112. "status": "attached",
  2113. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  2114. "filename": matching_file["name"],
  2115. }
  2116. @router.post("/{archive_id}/timelapse/select")
  2117. async def select_timelapse(
  2118. archive_id: int,
  2119. filename: str = Query(..., description="Timelapse filename to attach"),
  2120. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2121. ):
  2122. """Manually select a timelapse from the printer to attach."""
  2123. from backend.app.core.database import async_session
  2124. from backend.app.models.printer import Printer
  2125. from backend.app.services.bambu_ftp import (
  2126. download_file_bytes_async,
  2127. get_ftp_retry_settings,
  2128. list_files_async,
  2129. with_ftp_retry,
  2130. )
  2131. # Read the archive + printer in a short session and release the pooled DB
  2132. # connection BEFORE the FTP scan/download below (#2572); scalars stay
  2133. # readable after close (expire_on_commit=False), the attach reopens one.
  2134. async with async_session() as db:
  2135. archive = await ArchiveService(db).get_archive(archive_id)
  2136. if not archive:
  2137. raise HTTPException(404, "Archive not found")
  2138. if not archive.printer_id:
  2139. raise HTTPException(400, "Archive has no associated printer")
  2140. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2141. printer = result.scalar_one_or_none()
  2142. if not printer:
  2143. raise HTTPException(404, "Printer not found")
  2144. # Find the file on the printer
  2145. files = []
  2146. remote_path = None
  2147. for timelapse_dir in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  2148. try:
  2149. files = await list_files_async(
  2150. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  2151. )
  2152. for f in files:
  2153. if f.get("name") == filename:
  2154. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  2155. break
  2156. if remote_path:
  2157. break
  2158. except Exception:
  2159. continue
  2160. if not remote_path:
  2161. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  2162. # Download and attach
  2163. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2164. if ftp_retry_enabled:
  2165. timelapse_data = await with_ftp_retry(
  2166. download_file_bytes_async,
  2167. printer.ip_address,
  2168. printer.access_code,
  2169. remote_path,
  2170. socket_timeout=ftp_timeout,
  2171. printer_model=printer.model,
  2172. max_retries=ftp_retry_count,
  2173. retry_delay=ftp_retry_delay,
  2174. operation_name=f"Download timelapse {filename}",
  2175. )
  2176. else:
  2177. timelapse_data = await download_file_bytes_async(
  2178. printer.ip_address,
  2179. printer.access_code,
  2180. remote_path,
  2181. socket_timeout=ftp_timeout,
  2182. printer_model=printer.model,
  2183. )
  2184. if not timelapse_data:
  2185. raise HTTPException(500, "Failed to download timelapse")
  2186. # Attach in a fresh short session (the read session was released before FTP).
  2187. async with async_session() as db:
  2188. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, filename)
  2189. if not success:
  2190. raise HTTPException(500, "Failed to attach timelapse")
  2191. return {
  2192. "status": "attached",
  2193. "message": f"Timelapse '{filename}' attached successfully",
  2194. "filename": filename,
  2195. }
  2196. @router.post("/{archive_id}/timelapse/upload")
  2197. async def upload_timelapse(
  2198. archive_id: int,
  2199. file: UploadFile = File(...),
  2200. db: AsyncSession = Depends(get_db),
  2201. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2202. ):
  2203. """Manually upload a timelapse video to an archive."""
  2204. service = ArchiveService(db)
  2205. archive = await service.get_archive(archive_id)
  2206. if not archive:
  2207. raise HTTPException(404, "Archive not found")
  2208. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  2209. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  2210. content = await file.read()
  2211. safe_filename = _safe_filename(file.filename)
  2212. success = await service.attach_timelapse(archive_id, content, safe_filename)
  2213. if not success:
  2214. raise HTTPException(500, "Failed to attach timelapse")
  2215. return {"status": "attached", "filename": safe_filename}
  2216. @router.get("/{archive_id}/timelapse/info")
  2217. async def get_timelapse_info(
  2218. archive_id: int,
  2219. db: AsyncSession = Depends(get_db),
  2220. auth_result: tuple[User | None, bool] = Depends(
  2221. require_ownership_permission(
  2222. Permission.ARCHIVES_READ_ALL,
  2223. Permission.ARCHIVES_READ_OWN,
  2224. )
  2225. ),
  2226. ):
  2227. """Get timelapse video metadata for editor."""
  2228. from backend.app.schemas.timelapse import TimelapseInfoResponse
  2229. from backend.app.services.timelapse_processor import TimelapseProcessor
  2230. user, can_read_all = auth_result
  2231. service = ArchiveService(db)
  2232. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2233. if not archive.timelapse_path:
  2234. raise HTTPException(404, "Timelapse not found")
  2235. timelapse_path = settings.base_dir / archive.timelapse_path
  2236. if not timelapse_path.exists():
  2237. raise HTTPException(404, "Timelapse file not found")
  2238. try:
  2239. processor = TimelapseProcessor(timelapse_path)
  2240. info = await processor.get_info()
  2241. return TimelapseInfoResponse(**info)
  2242. except Exception as e:
  2243. logger.error("Failed to get timelapse info: %s", e)
  2244. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  2245. @router.get("/{archive_id}/timelapse/thumbnails")
  2246. async def get_timelapse_thumbnails(
  2247. archive_id: int,
  2248. count: int = Query(10, ge=1, le=30),
  2249. width: int = Query(160, ge=80, le=320),
  2250. db: AsyncSession = Depends(get_db),
  2251. auth_result: tuple[User | None, bool] = Depends(
  2252. require_ownership_permission(
  2253. Permission.ARCHIVES_READ_ALL,
  2254. Permission.ARCHIVES_READ_OWN,
  2255. )
  2256. ),
  2257. ):
  2258. """Generate timeline thumbnail frames for visual scrubbing."""
  2259. import base64
  2260. from backend.app.schemas.timelapse import ThumbnailResponse
  2261. from backend.app.services.timelapse_processor import TimelapseProcessor
  2262. user, can_read_all = auth_result
  2263. service = ArchiveService(db)
  2264. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2265. if not archive.timelapse_path:
  2266. raise HTTPException(404, "Timelapse not found")
  2267. timelapse_path = settings.base_dir / archive.timelapse_path
  2268. if not timelapse_path.exists():
  2269. raise HTTPException(404, "Timelapse file not found")
  2270. try:
  2271. processor = TimelapseProcessor(timelapse_path)
  2272. thumbnails = await processor.generate_thumbnails(count, width)
  2273. return ThumbnailResponse(
  2274. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  2275. timestamps=[ts for ts, _ in thumbnails],
  2276. )
  2277. except Exception as e:
  2278. logger.error("Failed to generate thumbnails: %s", e)
  2279. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  2280. @router.post("/{archive_id}/timelapse/process")
  2281. async def process_timelapse(
  2282. archive_id: int,
  2283. trim_start: float = Form(0),
  2284. trim_end: float = Form(None),
  2285. speed: float = Form(1.0),
  2286. save_mode: str = Form("new"),
  2287. output_filename: str = Form(None),
  2288. audio: UploadFile = File(None),
  2289. db: AsyncSession = Depends(get_db),
  2290. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2291. ):
  2292. """Process timelapse with trim, speed, and optional audio overlay."""
  2293. import shutil
  2294. import tempfile
  2295. from backend.app.schemas.timelapse import ProcessResponse
  2296. from backend.app.services.timelapse_processor import TimelapseProcessor
  2297. # Validate speed
  2298. if not 0.25 <= speed <= 4.0:
  2299. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  2300. if save_mode not in ("replace", "new"):
  2301. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  2302. service = ArchiveService(db)
  2303. archive = await service.get_archive(archive_id)
  2304. if not archive or not archive.timelapse_path:
  2305. raise HTTPException(404, "Timelapse not found")
  2306. timelapse_path = settings.base_dir / archive.timelapse_path
  2307. if not timelapse_path.exists():
  2308. raise HTTPException(404, "Timelapse file not found")
  2309. archive_dir = timelapse_path.parent
  2310. # Handle audio file
  2311. audio_temp_path = None
  2312. if audio and audio.filename:
  2313. # Validate audio file extension
  2314. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  2315. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  2316. audio_content = await audio.read()
  2317. # Extract and validate suffix to prevent path injection
  2318. suffix = Path(audio.filename).suffix.lower()
  2319. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  2320. raise HTTPException(400, "Invalid audio file extension")
  2321. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  2322. audio_temp_path.write_bytes(audio_content)
  2323. try:
  2324. processor = TimelapseProcessor(timelapse_path)
  2325. # Determine output path
  2326. if save_mode == "replace":
  2327. # Process to temp file first, then replace
  2328. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  2329. output_path = temp_output
  2330. else:
  2331. # Save as new file alongside original
  2332. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  2333. # Sanitize filename - remove path separators and traversal sequences
  2334. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  2335. # Prevent path traversal
  2336. if ".." in filename or not filename or filename.startswith("."):
  2337. filename = f"timelapse_{archive_id}_edited"
  2338. if not filename.endswith(".mp4"):
  2339. filename += ".mp4"
  2340. output_path = archive_dir / filename # SEC-PATH-OK: filename alnum-filtered + .. rejected above
  2341. success = await processor.process(
  2342. output_path=output_path,
  2343. trim_start=trim_start,
  2344. trim_end=trim_end,
  2345. speed=speed,
  2346. audio_path=audio_temp_path,
  2347. )
  2348. if not success:
  2349. raise HTTPException(500, "Video processing failed")
  2350. # Handle save mode
  2351. if save_mode == "replace":
  2352. # Replace original file
  2353. shutil.move(str(output_path), str(timelapse_path))
  2354. final_path = archive.timelapse_path
  2355. message = "Timelapse replaced successfully"
  2356. else:
  2357. final_path = str(output_path.relative_to(settings.base_dir))
  2358. message = f"Saved as {output_path.name}"
  2359. return ProcessResponse(
  2360. status="completed",
  2361. output_path=final_path,
  2362. message=message,
  2363. )
  2364. except HTTPException:
  2365. raise
  2366. except Exception as e:
  2367. logger.error("Timelapse processing failed: %s", e)
  2368. raise HTTPException(500, f"Processing failed: {str(e)}")
  2369. finally:
  2370. # Cleanup temp audio file
  2371. if audio_temp_path and audio_temp_path.exists():
  2372. audio_temp_path.unlink()
  2373. # ============================================
  2374. # Photo Endpoints
  2375. # ============================================
  2376. @router.post("/{archive_id}/photos")
  2377. async def upload_photo(
  2378. archive_id: int,
  2379. file: UploadFile = File(...),
  2380. db: AsyncSession = Depends(get_db),
  2381. auth_result: tuple[User | None, bool] = Depends(
  2382. require_ownership_permission(
  2383. Permission.ARCHIVES_UPDATE_ALL,
  2384. Permission.ARCHIVES_UPDATE_OWN,
  2385. )
  2386. ),
  2387. ):
  2388. """Upload a photo of the printed result."""
  2389. user, can_modify_all = auth_result
  2390. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2391. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  2392. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  2393. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  2394. # Get archive directory
  2395. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2396. photos_dir = archive_dir / "photos"
  2397. photos_dir.mkdir(exist_ok=True)
  2398. # Generate unique filename
  2399. import uuid
  2400. ext = Path(file.filename).suffix.lower()
  2401. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  2402. photo_path = photos_dir / photo_filename # SEC-PATH-OK: photo_filename = uuid.uuid4().hex[:8] + ext
  2403. # Save file
  2404. content = await file.read()
  2405. photo_path.write_bytes(content)
  2406. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  2407. photos = list(archive.photos or [])
  2408. photos.append(photo_filename)
  2409. archive.photos = photos
  2410. await db.commit()
  2411. await db.refresh(archive)
  2412. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  2413. @router.get("/{archive_id}/photos/{filename}")
  2414. async def get_photo(
  2415. archive_id: int,
  2416. filename: str,
  2417. db: AsyncSession = Depends(get_db),
  2418. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2419. ):
  2420. """Get a specific photo.
  2421. Requires a stream token query param (?token=xxx) when auth is enabled.
  2422. """
  2423. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2424. archive = result.scalar_one_or_none()
  2425. if not archive:
  2426. raise HTTPException(404, "Archive not found")
  2427. # Membership check first — UUID-generated names on upload mean any URL
  2428. # filename that doesn't appear here is by definition not a real photo.
  2429. # Mirrors the delete handler below; previously this endpoint had no
  2430. # membership check at all and joined `filename` straight to disk.
  2431. if not archive.photos or filename not in archive.photos:
  2432. raise HTTPException(404, "Photo not found")
  2433. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2434. photos_dir = archive_dir / "photos"
  2435. # Defence-in-depth: even though the membership check above already
  2436. # constrains `filename` to UUID-generated names from upload, the
  2437. # resolve + containment check guards against future code paths that
  2438. # might populate `archive.photos` from a less-trusted source.
  2439. photo_path = safe_join_under(photos_dir, filename)
  2440. if not photo_path.exists():
  2441. raise HTTPException(404, "Photo not found")
  2442. # Determine media type
  2443. ext = Path(filename).suffix.lower()
  2444. media_types = {
  2445. ".jpg": "image/jpeg",
  2446. ".jpeg": "image/jpeg",
  2447. ".png": "image/png",
  2448. ".webp": "image/webp",
  2449. }
  2450. media_type = media_types.get(ext, "image/jpeg")
  2451. return FileResponse(path=photo_path, media_type=media_type)
  2452. @router.delete("/{archive_id}/photos/{filename}")
  2453. async def delete_photo(
  2454. archive_id: int,
  2455. filename: str,
  2456. db: AsyncSession = Depends(get_db),
  2457. auth_result: tuple[User | None, bool] = Depends(
  2458. require_ownership_permission(
  2459. Permission.ARCHIVES_DELETE_ALL,
  2460. Permission.ARCHIVES_DELETE_OWN,
  2461. )
  2462. ),
  2463. ):
  2464. """Delete a photo."""
  2465. user, can_modify_all = auth_result
  2466. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2467. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  2468. if not archive.photos or filename not in archive.photos:
  2469. raise HTTPException(404, "Photo not found")
  2470. # Delete file — same defence-in-depth as get_photo above.
  2471. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2472. photos_dir = archive_dir / "photos"
  2473. photo_path = safe_join_under(photos_dir, filename)
  2474. if photo_path.exists():
  2475. photo_path.unlink()
  2476. # Update archive photos list
  2477. photos = [p for p in archive.photos if p != filename]
  2478. archive.photos = photos if photos else None
  2479. await db.commit()
  2480. return {"status": "deleted", "photos": archive.photos}
  2481. # ============================================
  2482. # QR Code Endpoint
  2483. # ============================================
  2484. @router.get("/{archive_id}/qrcode")
  2485. async def get_qrcode(
  2486. archive_id: int,
  2487. request: Request,
  2488. size: int = 200,
  2489. db: AsyncSession = Depends(get_db),
  2490. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2491. ):
  2492. """Generate a QR code that links to this archive.
  2493. Requires a stream token query param (?token=xxx) when auth is enabled.
  2494. """
  2495. try:
  2496. import qrcode
  2497. from PIL import Image as PILImage
  2498. except ImportError:
  2499. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  2500. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2501. archive = result.scalar_one_or_none()
  2502. if not archive:
  2503. raise HTTPException(404, "Archive not found")
  2504. # Build URL to archive download
  2505. base_url = str(request.base_url).rstrip("/")
  2506. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  2507. # Generate QR code
  2508. qr = qrcode.QRCode(
  2509. version=1,
  2510. error_correction=qrcode.constants.ERROR_CORRECT_M,
  2511. box_size=10,
  2512. border=2,
  2513. )
  2514. qr.add_data(archive_url)
  2515. qr.make(fit=True)
  2516. img = qr.make_image(fill_color="black", back_color="white")
  2517. # Convert to PIL Image for resizing
  2518. pil_img = img.get_image()
  2519. # Resize if needed
  2520. if size != 200:
  2521. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  2522. # Convert to bytes
  2523. buffer = io.BytesIO()
  2524. pil_img.save(buffer, format="PNG")
  2525. buffer.seek(0)
  2526. qr_filename = f"qr_{archive.print_name or archive_id}.png"
  2527. return Response(
  2528. content=buffer.getvalue(),
  2529. media_type="image/png",
  2530. headers={"Content-Disposition": build_content_disposition(qr_filename, disposition="inline")},
  2531. )
  2532. @router.get("/{archive_id}/capabilities")
  2533. async def get_archive_capabilities(
  2534. archive_id: int,
  2535. db: AsyncSession = Depends(get_db),
  2536. auth_result: tuple[User | None, bool] = Depends(
  2537. require_ownership_permission(
  2538. Permission.ARCHIVES_READ_ALL,
  2539. Permission.ARCHIVES_READ_OWN,
  2540. )
  2541. ),
  2542. ):
  2543. """Check what viewing capabilities are available for this 3MF file."""
  2544. import defusedxml.ElementTree as ET
  2545. user, can_read_all = auth_result
  2546. service = ArchiveService(db)
  2547. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2548. file_path = settings.base_dir / archive.file_path
  2549. if not file_path.is_file():
  2550. raise HTTPException(404, "File not found")
  2551. has_model = False
  2552. has_gcode = False
  2553. has_source = False
  2554. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  2555. filament_colors: list[str] = []
  2556. # Check if source 3MF exists - this is where actual mesh data typically lives
  2557. source_path = None
  2558. if archive.source_3mf_path:
  2559. source_path = settings.base_dir / archive.source_3mf_path
  2560. if source_path.exists():
  2561. has_source = True
  2562. # Helper function to check for mesh data and extract colors from a 3MF file
  2563. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  2564. """Extract mesh presence, colors, and build volume from a 3MF file."""
  2565. found_mesh = False
  2566. colors: list[str] = []
  2567. volume = {"x": 256, "y": 256, "z": 256}
  2568. try:
  2569. with zipfile.ZipFile(zf_path, "r") as zf:
  2570. names = zf.namelist()
  2571. # Check for 3D model - look for actual mesh data
  2572. for name in names:
  2573. if name.endswith(".model"):
  2574. try:
  2575. content = zf.read(name).decode("utf-8")
  2576. if "<vertex" in content or "<mesh" in content:
  2577. found_mesh = True
  2578. break
  2579. except Exception:
  2580. pass # Skip unreadable .model entries in archive
  2581. # Extract filament colors from project_settings.config
  2582. if "Metadata/project_settings.config" in names:
  2583. try:
  2584. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2585. config_data = json.loads(config_content)
  2586. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  2587. printable_area = config_data.get("printable_area", [])
  2588. if printable_area and len(printable_area) >= 3:
  2589. max_x = 0
  2590. max_y = 0
  2591. for coord in printable_area:
  2592. if "x" in coord:
  2593. parts = coord.split("x")
  2594. if len(parts) == 2:
  2595. try:
  2596. x, y = int(parts[0]), int(parts[1])
  2597. max_x = max(max_x, x)
  2598. max_y = max(max_y, y)
  2599. except ValueError:
  2600. pass # Skip non-numeric printable_area coordinate
  2601. if max_x > 0 and max_y > 0:
  2602. volume["x"] = max_x
  2603. volume["y"] = max_y
  2604. # Parse printable_height
  2605. printable_height = config_data.get("printable_height")
  2606. if printable_height:
  2607. try:
  2608. volume["z"] = int(printable_height)
  2609. except (ValueError, TypeError):
  2610. pass # Skip unparseable printable_height value
  2611. # Extract filament colors
  2612. raw_colors = config_data.get("filament_colour", [])
  2613. if raw_colors:
  2614. for color in raw_colors:
  2615. if color and isinstance(color, str):
  2616. colors.append(color)
  2617. except Exception:
  2618. pass # Skip malformed project_settings.config
  2619. except zipfile.BadZipFile:
  2620. pass # File is not a valid zip/3MF archive
  2621. return found_mesh, colors, volume
  2622. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  2623. if has_source and source_path:
  2624. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  2625. if source_has_mesh:
  2626. has_model = True
  2627. if source_colors:
  2628. filament_colors = source_colors
  2629. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  2630. build_volume = source_volume
  2631. try:
  2632. with zipfile.ZipFile(file_path, "r") as zf:
  2633. names = zf.namelist()
  2634. # Check for G-code in the sliced file
  2635. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  2636. # Check for 3D model in sliced file (fallback if no source)
  2637. if not has_model:
  2638. for name in names:
  2639. if name.endswith(".model"):
  2640. try:
  2641. content = zf.read(name).decode("utf-8")
  2642. if "<vertex" in content or "<mesh" in content:
  2643. has_model = True
  2644. break
  2645. except Exception:
  2646. pass # Skip unreadable .model entries in archive
  2647. # Extract filament colors from slice_info.config (for gcode preview)
  2648. # These are the actual filaments used in the print, indexed by tool/extruder
  2649. slice_colors: list[str] = []
  2650. if "Metadata/slice_info.config" in names:
  2651. try:
  2652. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2653. root = ET.fromstring(slice_content)
  2654. filaments = root.findall(".//filament")
  2655. filament_map: dict[int, str] = {}
  2656. for f in filaments:
  2657. fid = f.get("id")
  2658. fcolor = f.get("color")
  2659. used_g = f.get("used_g", "0")
  2660. try:
  2661. used_amount = float(used_g)
  2662. except (ValueError, TypeError):
  2663. used_amount = 0
  2664. if fid is not None and fcolor:
  2665. try:
  2666. tool_id = int(fid) - 1
  2667. if tool_id >= 0 and used_amount > 0:
  2668. filament_map[tool_id] = fcolor
  2669. except ValueError:
  2670. pass # Skip filament entry with non-numeric ID
  2671. if filament_map:
  2672. max_tool = max(filament_map.keys())
  2673. for i in range(max_tool + 1):
  2674. slice_colors.append(filament_map.get(i, "#00AE42"))
  2675. except Exception:
  2676. pass # Skip malformed slice_info.config XML
  2677. # Use slice_info colors if we don't have colors from source yet
  2678. if not filament_colors and slice_colors:
  2679. filament_colors = slice_colors
  2680. # Extract build volume from sliced file if not already set from source
  2681. if build_volume["x"] == 256 and build_volume["y"] == 256:
  2682. if "Metadata/project_settings.config" in names:
  2683. try:
  2684. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2685. config_data = json.loads(config_content)
  2686. printable_area = config_data.get("printable_area", [])
  2687. if printable_area and len(printable_area) >= 3:
  2688. max_x = 0
  2689. max_y = 0
  2690. for coord in printable_area:
  2691. if "x" in coord:
  2692. parts = coord.split("x")
  2693. if len(parts) == 2:
  2694. try:
  2695. x, y = int(parts[0]), int(parts[1])
  2696. max_x = max(max_x, x)
  2697. max_y = max(max_y, y)
  2698. except ValueError:
  2699. pass # Skip non-numeric printable_area coordinate
  2700. if max_x > 0 and max_y > 0:
  2701. build_volume["x"] = max_x
  2702. build_volume["y"] = max_y
  2703. printable_height = config_data.get("printable_height")
  2704. if printable_height:
  2705. try:
  2706. build_volume["z"] = int(printable_height)
  2707. except (ValueError, TypeError):
  2708. pass # Skip unparseable printable_height value
  2709. # Fallback colors from project_settings if still empty
  2710. if not filament_colors:
  2711. raw_colors = config_data.get("filament_colour", [])
  2712. if raw_colors:
  2713. for color in raw_colors:
  2714. if color and isinstance(color, str):
  2715. filament_colors.append(color)
  2716. except Exception:
  2717. pass # Skip malformed project_settings.config
  2718. except zipfile.BadZipFile:
  2719. raise HTTPException(400, "Invalid 3MF file")
  2720. return {
  2721. "has_model": has_model,
  2722. "has_gcode": has_gcode,
  2723. "has_source": has_source,
  2724. "build_volume": build_volume,
  2725. "filament_colors": filament_colors,
  2726. }
  2727. @router.get("/{archive_id}/gcode")
  2728. async def get_gcode(
  2729. archive_id: int,
  2730. plate: int | None = None,
  2731. db: AsyncSession = Depends(get_db),
  2732. auth_result: tuple[User | None, bool] = Depends(
  2733. require_ownership_permission(
  2734. Permission.ARCHIVES_READ_ALL,
  2735. Permission.ARCHIVES_READ_OWN,
  2736. )
  2737. ),
  2738. ):
  2739. """Extract and return G-code from the 3MF file.
  2740. When *plate* is provided, returns the G-code for that specific plate
  2741. (e.g. ``?plate=2`` returns ``Metadata/plate_2.gcode``). If omitted, falls
  2742. back to the first plate found in the archive (preserving the original
  2743. behaviour for callers that predate the multi-plate viewer).
  2744. """
  2745. user, can_read_all = auth_result
  2746. service = ArchiveService(db)
  2747. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2748. file_path = settings.base_dir / archive.file_path
  2749. if not file_path.is_file():
  2750. raise HTTPException(404, "File not found")
  2751. if plate is not None and plate < 1:
  2752. raise HTTPException(400, "Plate index must be >= 1")
  2753. try:
  2754. with zipfile.ZipFile(file_path, "r") as zf:
  2755. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  2756. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  2757. if not gcode_files:
  2758. raise HTTPException(
  2759. 404,
  2760. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  2761. )
  2762. if plate is not None:
  2763. # Resolve plate → filename via the same parsing the plates
  2764. # endpoint uses (int() on the suffix), so zero-padded names
  2765. # like plate_01.gcode are found when the plates endpoint
  2766. # reported index 1.
  2767. selected = None
  2768. for gf in gcode_files:
  2769. if not gf.startswith("Metadata/plate_"):
  2770. continue
  2771. suffix = gf[len("Metadata/plate_") : -len(".gcode")]
  2772. try:
  2773. if int(suffix) == plate:
  2774. selected = gf
  2775. break
  2776. except ValueError:
  2777. continue
  2778. if selected is None:
  2779. raise HTTPException(404, f"Plate {plate} not found in this archive")
  2780. else:
  2781. selected = gcode_files[0]
  2782. gcode_content = zf.read(selected).decode("utf-8")
  2783. return Response(content=gcode_content, media_type="text/plain")
  2784. except zipfile.BadZipFile:
  2785. raise HTTPException(400, "Invalid 3MF file")
  2786. except HTTPException:
  2787. raise
  2788. except Exception as e:
  2789. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  2790. @router.get("/{archive_id}/plate-preview")
  2791. async def get_plate_preview(
  2792. archive_id: int,
  2793. db: AsyncSession = Depends(get_db),
  2794. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2795. ):
  2796. """Get the plate preview image from the 3MF file.
  2797. Returns the slicer-generated plate thumbnail which shows the model
  2798. with correct colors and positioning.
  2799. Requires a stream token query param (?token=xxx) when auth is enabled.
  2800. """
  2801. service = ArchiveService(db)
  2802. archive = await service.get_archive(archive_id)
  2803. if not archive:
  2804. raise HTTPException(404, "Archive not found")
  2805. file_path = settings.base_dir / archive.file_path
  2806. if not file_path.is_file():
  2807. raise HTTPException(404, "File not found")
  2808. try:
  2809. with zipfile.ZipFile(file_path, "r") as zf:
  2810. names = zf.namelist()
  2811. # Try to find plate preview images in order of preference
  2812. # First look for the specific plate being printed (check slice_info for plate index)
  2813. plate_num = 1
  2814. if "Metadata/slice_info.config" in names:
  2815. try:
  2816. import defusedxml.ElementTree as ET
  2817. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2818. root = ET.fromstring(slice_content)
  2819. plate_elem = root.find(".//plate/metadata[@key='index']")
  2820. if plate_elem is not None:
  2821. plate_num = int(plate_elem.get("value", "1"))
  2822. except Exception:
  2823. pass # Default plate_num=1 if slice_info is missing or malformed
  2824. # Try plate-specific image first, then fall back to plate_1
  2825. preview_paths = [
  2826. f"Metadata/plate_{plate_num}.png",
  2827. "Metadata/plate_1.png",
  2828. "Metadata/thumbnail.png",
  2829. ]
  2830. for preview_path in preview_paths:
  2831. if preview_path in names:
  2832. image_data = zf.read(preview_path)
  2833. return Response(content=image_data, media_type="image/png")
  2834. # If no plate image, try any PNG in Metadata
  2835. for name in names:
  2836. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  2837. image_data = zf.read(name)
  2838. return Response(content=image_data, media_type="image/png")
  2839. raise HTTPException(404, "No plate preview found in 3MF file")
  2840. except zipfile.BadZipFile:
  2841. raise HTTPException(400, "Invalid 3MF file")
  2842. except HTTPException:
  2843. raise
  2844. except Exception as e:
  2845. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  2846. @router.post("/upload")
  2847. async def upload_archive(
  2848. file: UploadFile = File(...),
  2849. printer_id: int | None = None,
  2850. db: AsyncSession = Depends(get_db),
  2851. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2852. ):
  2853. """Manually upload a 3MF file to archive."""
  2854. if not file.filename or not file.filename.endswith(".3mf"):
  2855. raise HTTPException(400, "File must be a .3mf file")
  2856. # Save uploaded file temporarily — strip directory components to prevent path traversal
  2857. safe_filename = _safe_filename(file.filename)
  2858. temp_path = (
  2859. settings.archive_dir / "temp" / safe_filename
  2860. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  2861. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2862. try:
  2863. content = await file.read()
  2864. # #1401: same content validation as library upload — catches
  2865. # raw-gcode-renamed-to-.3mf and other unprintable shapes before
  2866. # archiving them and offering them up for print.
  2867. from backend.app.api.routes.library import validate_print_file_upload
  2868. validate_print_file_upload(file.filename, content)
  2869. temp_path.write_bytes(content)
  2870. service = ArchiveService(db)
  2871. archive = await service.archive_print(
  2872. printer_id=printer_id,
  2873. source_file=temp_path,
  2874. created_by_id=current_user.id if current_user else None,
  2875. )
  2876. if not archive:
  2877. raise HTTPException(400, "Failed to archive file")
  2878. return ArchiveResponse.model_validate(archive)
  2879. finally:
  2880. if temp_path.exists():
  2881. temp_path.unlink()
  2882. @router.post("/upload-bulk")
  2883. async def upload_archives_bulk(
  2884. files: list[UploadFile] = File(...),
  2885. printer_id: int | None = None,
  2886. db: AsyncSession = Depends(get_db),
  2887. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2888. ):
  2889. """Bulk upload multiple 3MF files to archive."""
  2890. from backend.app.api.routes.library import validate_print_file_upload
  2891. results = []
  2892. errors = []
  2893. for file in files:
  2894. if not file.filename or not file.filename.endswith(".3mf"):
  2895. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  2896. continue
  2897. safe_filename = _safe_filename(file.filename)
  2898. temp_path = (
  2899. settings.archive_dir / "temp" / safe_filename
  2900. ) # SEC-PATH-OK: safe_filename = _safe_filename(...) basename-stripped above
  2901. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2902. try:
  2903. content = await file.read()
  2904. # #1401: bulk-upload variant of the library validation. Collect
  2905. # the rejection per-file rather than aborting the whole batch
  2906. # so one bad file in a 10-file drag-drop doesn't lose the
  2907. # other nine.
  2908. try:
  2909. validate_print_file_upload(file.filename, content)
  2910. except HTTPException as exc:
  2911. errors.append({"filename": file.filename, "error": exc.detail})
  2912. continue
  2913. temp_path.write_bytes(content)
  2914. service = ArchiveService(db)
  2915. archive = await service.archive_print(
  2916. printer_id=printer_id,
  2917. source_file=temp_path,
  2918. created_by_id=current_user.id if current_user else None,
  2919. )
  2920. if archive:
  2921. results.append(
  2922. {
  2923. "filename": file.filename,
  2924. "id": archive.id,
  2925. "status": "success",
  2926. }
  2927. )
  2928. else:
  2929. errors.append({"filename": file.filename, "error": "Failed to process"})
  2930. except Exception as e:
  2931. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  2932. errors.append({"filename": file.filename, "error": "Failed to process file"})
  2933. finally:
  2934. if temp_path.exists():
  2935. temp_path.unlink()
  2936. return {
  2937. "uploaded": len(results),
  2938. "failed": len(errors),
  2939. "results": results,
  2940. "errors": errors,
  2941. }
  2942. @router.get("/{archive_id}/plates")
  2943. async def get_archive_plates(
  2944. archive_id: int,
  2945. db: AsyncSession = Depends(get_db),
  2946. auth_result: tuple[User | None, bool] = Depends(
  2947. require_ownership_permission(
  2948. Permission.ARCHIVES_READ_ALL,
  2949. Permission.ARCHIVES_READ_OWN,
  2950. )
  2951. ),
  2952. ):
  2953. """Get available plates from a multi-plate 3MF archive.
  2954. Returns a list of plates with their index, name, thumbnail availability,
  2955. and filament requirements. For single-plate exports, returns a single plate.
  2956. """
  2957. import re
  2958. import defusedxml.ElementTree as ET
  2959. user, can_read_all = auth_result
  2960. service = ArchiveService(db)
  2961. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  2962. file_path = settings.base_dir / archive.file_path
  2963. if not file_path.is_file():
  2964. raise HTTPException(404, "Archive file not found")
  2965. plates = []
  2966. # Initialize so the `has_gcode = bool(gcode_files)` after the try/except
  2967. # never raises NameError when the archive isn't a valid zip (e.g. plain
  2968. # .gcode file from a sliced-archive flow that didn't request 3MF output).
  2969. gcode_files: list[str] = []
  2970. # Printer / process preset names the 3MF was prepared with — used by the
  2971. # SliceModal to default its dropdowns (#1325).
  2972. embedded_presets: dict[str, str | None] = {"printer": None, "process": None}
  2973. try:
  2974. with zipfile.ZipFile(file_path, "r") as zf:
  2975. namelist = zf.namelist()
  2976. embedded_presets = extract_embedded_presets_from_3mf(zf)
  2977. # Find all plate gcode files to determine available plates
  2978. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  2979. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  2980. plate_indices: list[int] = []
  2981. if gcode_files:
  2982. # Extract plate indices from gcode filenames
  2983. for gf in gcode_files:
  2984. # "Metadata/plate_5.gcode" -> 5
  2985. try:
  2986. # Remove "Metadata/plate_" and ".gcode"
  2987. plate_str = gf[15:-6]
  2988. plate_indices.append(int(plate_str))
  2989. except ValueError:
  2990. pass # Skip gcode file with non-numeric plate index
  2991. else:
  2992. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  2993. plate_png_files = [
  2994. n
  2995. for n in namelist
  2996. if n.startswith("Metadata/plate_")
  2997. and n.endswith(".png")
  2998. and "_small" not in n
  2999. and "no_light" not in n
  3000. ]
  3001. plate_name_candidates = plate_json_files + plate_png_files
  3002. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  3003. seen_indices: set[int] = set()
  3004. for name in plate_name_candidates:
  3005. match = plate_re.match(name)
  3006. if match:
  3007. try:
  3008. index = int(match.group(1))
  3009. except ValueError:
  3010. continue
  3011. if index in seen_indices:
  3012. continue
  3013. seen_indices.add(index)
  3014. plate_indices.append(index)
  3015. if not plate_indices:
  3016. # No plate metadata found
  3017. return {
  3018. "archive_id": archive_id,
  3019. "filename": archive.filename,
  3020. "plates": [],
  3021. "is_multi_plate": False,
  3022. }
  3023. plate_indices.sort()
  3024. # Parse model_settings.config for plate names + object assignments
  3025. # Plate names are stored with plater_id and plater_name keys
  3026. plate_names = {} # plater_id -> name
  3027. plate_object_ids: dict[int, list[str]] = {}
  3028. object_names_by_id: dict[str, str] = {}
  3029. if "Metadata/model_settings.config" in namelist:
  3030. try:
  3031. model_content = zf.read("Metadata/model_settings.config").decode()
  3032. model_root = ET.fromstring(model_content)
  3033. # Build object ID -> name map
  3034. for obj_elem in model_root.findall(".//object"):
  3035. obj_id = obj_elem.get("id")
  3036. if not obj_id:
  3037. continue
  3038. name_meta = obj_elem.find("metadata[@key='name']")
  3039. obj_name = name_meta.get("value") if name_meta is not None else None
  3040. if obj_name:
  3041. object_names_by_id[obj_id] = obj_name
  3042. for plate_elem in model_root.findall(".//plate"):
  3043. plater_id = None
  3044. plater_name = None
  3045. for meta in plate_elem.findall("metadata"):
  3046. key = meta.get("key")
  3047. value = meta.get("value")
  3048. if key == "plater_id" and value:
  3049. try:
  3050. plater_id = int(value)
  3051. except ValueError:
  3052. pass # Skip plate with non-numeric plater_id
  3053. elif key == "plater_name" and value:
  3054. plater_name = value.strip()
  3055. if plater_id is not None and plater_name:
  3056. plate_names[plater_id] = plater_name
  3057. if plater_id is not None:
  3058. for instance_elem in plate_elem.findall("model_instance"):
  3059. for inst_meta in instance_elem.findall("metadata"):
  3060. if inst_meta.get("key") == "object_id":
  3061. obj_id = inst_meta.get("value")
  3062. if not obj_id:
  3063. continue
  3064. plate_object_ids.setdefault(plater_id, [])
  3065. if obj_id not in plate_object_ids[plater_id]:
  3066. plate_object_ids[plater_id].append(obj_id)
  3067. except Exception:
  3068. pass # model_settings.config parsing is optional
  3069. # Parse slice_info.config for plate metadata
  3070. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  3071. if "Metadata/slice_info.config" in namelist:
  3072. content = zf.read("Metadata/slice_info.config").decode()
  3073. root = ET.fromstring(content)
  3074. for plate_elem in root.findall(".//plate"):
  3075. plate_info = {
  3076. "filaments": [],
  3077. "prediction": None,
  3078. "weight": None,
  3079. "name": None,
  3080. "objects": [],
  3081. "bed_type": None,
  3082. }
  3083. # Get plate index from metadata
  3084. plate_index = None
  3085. for meta in plate_elem.findall("metadata"):
  3086. key = meta.get("key")
  3087. value = meta.get("value")
  3088. if key == "index" and value:
  3089. try:
  3090. plate_index = int(value)
  3091. except ValueError:
  3092. pass # Skip plate with non-numeric index
  3093. elif key == "prediction" and value:
  3094. try:
  3095. plate_info["prediction"] = int(value)
  3096. except ValueError:
  3097. pass # Skip non-numeric print time prediction
  3098. elif key == "weight" and value:
  3099. try:
  3100. plate_info["weight"] = float(value)
  3101. except ValueError:
  3102. pass # Skip non-numeric filament weight
  3103. elif key == "curr_bed_type" and value:
  3104. # Per-plate bed type so the PrintModal can show the
  3105. # right plate alongside each option (#1281).
  3106. plate_info["bed_type"] = value.strip()
  3107. # Get filaments used in this plate
  3108. for filament_elem in plate_elem.findall("filament"):
  3109. filament_id = filament_elem.get("id")
  3110. filament_type = filament_elem.get("type", "")
  3111. filament_color = filament_elem.get("color", "")
  3112. used_g = filament_elem.get("used_g", "0")
  3113. used_m = filament_elem.get("used_m", "0")
  3114. try:
  3115. used_grams = float(used_g)
  3116. except (ValueError, TypeError):
  3117. used_grams = 0
  3118. if used_grams > 0 and filament_id:
  3119. plate_info["filaments"].append(
  3120. {
  3121. "slot_id": int(filament_id),
  3122. "type": filament_type,
  3123. "color": filament_color,
  3124. "used_grams": round(used_grams, 1),
  3125. "used_meters": float(used_m) if used_m else 0,
  3126. }
  3127. )
  3128. # Sort filaments by slot ID
  3129. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  3130. # Collect all object names on this plate
  3131. for obj_elem in plate_elem.findall("object"):
  3132. obj_name = obj_elem.get("name")
  3133. if obj_name and obj_name not in plate_info["objects"]:
  3134. plate_info["objects"].append(obj_name)
  3135. # Set plate name: prefer custom name from model_settings.config,
  3136. # fall back to first object name if no custom name was set
  3137. if plate_index is not None:
  3138. custom_name = plate_names.get(plate_index)
  3139. if custom_name:
  3140. plate_info["name"] = custom_name
  3141. else:
  3142. # Fall back to first object name as hint
  3143. if plate_info["objects"]:
  3144. plate_info["name"] = plate_info["objects"][0]
  3145. plate_metadata[plate_index] = plate_info
  3146. # Parse plate_*.json for object lists when slice_info is missing
  3147. plate_json_objects: dict[int, list[str]] = {}
  3148. for name in namelist:
  3149. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  3150. if not match:
  3151. continue
  3152. try:
  3153. plate_index = int(match.group(1))
  3154. except ValueError:
  3155. continue
  3156. try:
  3157. payload = json.loads(zf.read(name).decode())
  3158. bbox_objects = payload.get("bbox_objects", [])
  3159. names = []
  3160. for obj in bbox_objects:
  3161. obj_name = obj.get("name") if isinstance(obj, dict) else None
  3162. if obj_name and obj_name not in names:
  3163. names.append(obj_name)
  3164. if names:
  3165. plate_json_objects[plate_index] = names
  3166. except Exception:
  3167. continue
  3168. # Build plate list
  3169. for idx in plate_indices:
  3170. meta = plate_metadata.get(idx, {})
  3171. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  3172. objects = meta.get("objects", [])
  3173. if not objects:
  3174. objects = plate_json_objects.get(idx, [])
  3175. if not objects and plate_object_ids.get(idx):
  3176. objects = [
  3177. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  3178. ]
  3179. plate_name = meta.get("name")
  3180. if not plate_name:
  3181. plate_name = plate_names.get(idx)
  3182. if not plate_name and objects:
  3183. plate_name = objects[0]
  3184. plates.append(
  3185. {
  3186. "index": idx,
  3187. "name": plate_name,
  3188. "objects": objects,
  3189. "object_count": len(objects),
  3190. "has_thumbnail": has_thumbnail,
  3191. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  3192. if has_thumbnail
  3193. else None,
  3194. "print_time_seconds": meta.get("prediction"),
  3195. "filament_used_grams": meta.get("weight"),
  3196. "filaments": meta.get("filaments", []),
  3197. "bed_type": meta.get("bed_type"),
  3198. }
  3199. )
  3200. except Exception as e:
  3201. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  3202. # Has gcode iff the plate list was built from .gcode filenames (as opposed
  3203. # to the JSON/PNG fallback for source-only 3MF projects). Callers that need
  3204. # to preview gcode — the viewer, skip-objects — can gate on this instead of
  3205. # 404-ing on every plate request.
  3206. has_gcode = bool(gcode_files)
  3207. return {
  3208. "archive_id": archive_id,
  3209. "filename": archive.filename,
  3210. "plates": plates,
  3211. "is_multi_plate": len(plates) > 1,
  3212. "has_gcode": has_gcode,
  3213. "embedded_printer": embedded_presets["printer"],
  3214. "embedded_process": embedded_presets["process"],
  3215. }
  3216. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  3217. async def get_plate_thumbnail(
  3218. archive_id: int,
  3219. plate_index: int,
  3220. db: AsyncSession = Depends(get_db),
  3221. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3222. ):
  3223. """Get the thumbnail image for a specific plate.
  3224. Requires a stream token query param (?token=xxx) when auth is enabled.
  3225. """
  3226. service = ArchiveService(db)
  3227. archive = await service.get_archive(archive_id)
  3228. if not archive:
  3229. raise HTTPException(404, "Archive not found")
  3230. file_path = settings.base_dir / archive.file_path
  3231. if not file_path.is_file():
  3232. raise HTTPException(404, "Archive file not found")
  3233. try:
  3234. with zipfile.ZipFile(file_path, "r") as zf:
  3235. thumb_path = f"Metadata/plate_{plate_index}.png"
  3236. if thumb_path in zf.namelist():
  3237. data = zf.read(thumb_path)
  3238. return Response(content=data, media_type="image/png")
  3239. except Exception:
  3240. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  3241. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  3242. async def _try_preview_slice_filaments(
  3243. db: AsyncSession,
  3244. *,
  3245. kind: str,
  3246. source_id: int,
  3247. plate_id: int,
  3248. file_path: Path,
  3249. request_id: str | None = None,
  3250. ) -> list[dict] | None:
  3251. """Run a preview slice via the user's configured sidecar so the filament
  3252. list endpoint can return real per-plate filaments for unsliced project
  3253. files. Returns ``None`` on any failure — the caller falls back to the
  3254. painted-face heuristic. ``request_id`` flows through to the sidecar
  3255. for live progress on the SliceModal's inline spinner + toast.
  3256. """
  3257. from backend.app.api.routes.settings import get_setting
  3258. from backend.app.services.slice_preview import get_preview_filaments
  3259. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  3260. if preferred == "orcaslicer":
  3261. configured = await get_setting(db, "orcaslicer_api_url")
  3262. api_url = (configured or settings.slicer_api_url).strip()
  3263. elif preferred == "bambu_studio":
  3264. configured = await get_setting(db, "bambu_studio_api_url")
  3265. api_url = (configured or settings.bambu_studio_api_url).strip()
  3266. else:
  3267. return None
  3268. if not api_url:
  3269. return None
  3270. try:
  3271. file_bytes = file_path.read_bytes()
  3272. except OSError:
  3273. return None
  3274. return await get_preview_filaments(
  3275. kind=kind,
  3276. source_id=source_id,
  3277. plate_id=plate_id,
  3278. file_bytes=file_bytes,
  3279. file_name=file_path.name,
  3280. api_url=api_url,
  3281. request_id=request_id,
  3282. )
  3283. @router.get("/{archive_id}/filament-requirements")
  3284. async def get_filament_requirements(
  3285. archive_id: int,
  3286. plate_id: int | None = None,
  3287. request_id: str | None = None,
  3288. db: AsyncSession = Depends(get_db),
  3289. auth_result: tuple[User | None, bool] = Depends(
  3290. require_ownership_permission(
  3291. Permission.ARCHIVES_READ_ALL,
  3292. Permission.ARCHIVES_READ_OWN,
  3293. )
  3294. ),
  3295. ):
  3296. """Get filament requirements from the archived 3MF file.
  3297. Returns the filaments used in this print with their slot IDs, types, colors,
  3298. and usage amounts. This can be compared with current AMS state before reprinting.
  3299. Args:
  3300. archive_id: The archive ID
  3301. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  3302. """
  3303. import defusedxml.ElementTree as ET
  3304. user, can_read_all = auth_result
  3305. service = ArchiveService(db)
  3306. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  3307. file_path = settings.base_dir / archive.file_path
  3308. if not file_path.is_file():
  3309. raise HTTPException(404, "Archive file not found")
  3310. filaments = []
  3311. try:
  3312. with zipfile.ZipFile(file_path, "r") as zf:
  3313. # Parse slice_info.config for filament requirements
  3314. if "Metadata/slice_info.config" in zf.namelist():
  3315. content = zf.read("Metadata/slice_info.config").decode()
  3316. root = ET.fromstring(content)
  3317. # If plate_id is specified, find filaments for that specific plate
  3318. if plate_id is not None:
  3319. # Find the plate element with matching index
  3320. for plate_elem in root.findall(".//plate"):
  3321. plate_index = None
  3322. for meta in plate_elem.findall("metadata"):
  3323. if meta.get("key") == "index":
  3324. try:
  3325. plate_index = int(meta.get("value", "0"))
  3326. except ValueError:
  3327. pass # Skip plate with non-numeric index metadata
  3328. break
  3329. if plate_index == plate_id:
  3330. # Extract filaments from this plate element
  3331. for filament_elem in plate_elem.findall("filament"):
  3332. filament_id = filament_elem.get("id")
  3333. filament_type = filament_elem.get("type", "")
  3334. filament_color = filament_elem.get("color", "")
  3335. used_g = filament_elem.get("used_g", "0")
  3336. used_m = filament_elem.get("used_m", "0")
  3337. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3338. try:
  3339. used_grams = float(used_g)
  3340. except (ValueError, TypeError):
  3341. used_grams = 0
  3342. if used_grams > 0 and filament_id:
  3343. filaments.append(
  3344. {
  3345. "slot_id": int(filament_id),
  3346. "type": filament_type,
  3347. "color": filament_color,
  3348. "used_grams": round(used_grams, 1),
  3349. "used_meters": float(used_m) if used_m else 0,
  3350. "tray_info_idx": tray_info_idx,
  3351. "used_in_plate": True,
  3352. }
  3353. )
  3354. break
  3355. else:
  3356. # No plate_id specified - extract all filaments with used_g > 0
  3357. # This is the legacy behavior for single-plate files
  3358. for filament_elem in root.findall(".//filament"):
  3359. filament_id = filament_elem.get("id")
  3360. filament_type = filament_elem.get("type", "")
  3361. filament_color = filament_elem.get("color", "")
  3362. used_g = filament_elem.get("used_g", "0")
  3363. used_m = filament_elem.get("used_m", "0")
  3364. tray_info_idx = filament_elem.get("tray_info_idx", "")
  3365. # Only include filaments that are actually used
  3366. try:
  3367. used_grams = float(used_g)
  3368. except (ValueError, TypeError):
  3369. used_grams = 0
  3370. if used_grams > 0 and filament_id:
  3371. filaments.append(
  3372. {
  3373. "slot_id": int(filament_id),
  3374. "type": filament_type,
  3375. "color": filament_color,
  3376. "used_grams": round(used_grams, 1),
  3377. "used_meters": float(used_m) if used_m else 0,
  3378. "tray_info_idx": tray_info_idx,
  3379. "used_in_plate": True,
  3380. }
  3381. )
  3382. # Unsliced project files: see library.py for full rationale.
  3383. # Return the FULL project_settings.config slot list with a
  3384. # used_in_plate flag derived from the preview slice; the
  3385. # CLI needs every slot pre-filled to avoid silent default
  3386. # substitution.
  3387. if not filaments:
  3388. project_filaments = extract_project_filaments_from_3mf(zf)
  3389. used_slot_ids: set[int] = set()
  3390. if project_filaments and plate_id is not None:
  3391. preview = await _try_preview_slice_filaments(
  3392. db,
  3393. kind="archive",
  3394. source_id=archive_id,
  3395. plate_id=plate_id,
  3396. file_path=file_path,
  3397. request_id=request_id,
  3398. )
  3399. if preview is not None:
  3400. used_slot_ids = {f["slot_id"] for f in preview}
  3401. fallback_all_used = not used_slot_ids
  3402. for f in project_filaments:
  3403. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  3404. filaments = project_filaments
  3405. # Sort by slot ID
  3406. filaments.sort(key=lambda x: x["slot_id"])
  3407. # Enrich with nozzle mapping for dual-nozzle printers
  3408. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  3409. if nozzle_mapping:
  3410. for filament in filaments:
  3411. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  3412. except Exception as e:
  3413. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  3414. return {
  3415. "archive_id": archive_id,
  3416. "filename": archive.filename,
  3417. "plate_id": plate_id,
  3418. "filaments": filaments,
  3419. }
  3420. @router.post("/{archive_id}/slice", status_code=202)
  3421. async def slice_archive(
  3422. archive_id: int,
  3423. request: SliceRequest,
  3424. db: AsyncSession = Depends(get_db),
  3425. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  3426. ):
  3427. """Enqueue a slice job for an archive's source. Returns 202 + job_id;
  3428. the slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  3429. Source preference: ``source_3mf_path`` (the un-sliced project file the
  3430. user originally sent to slice) → ``file_path`` (the sliced 3MF/gcode that
  3431. actually printed).
  3432. """
  3433. from backend.app.api.routes.library import guard_nozzle_class_reslice, slice_and_persist_as_archive
  3434. from backend.app.core.database import async_session
  3435. from backend.app.services.slice_dispatch import (
  3436. http_exception_to_job_error,
  3437. slice_dispatch,
  3438. )
  3439. archive = await db.get(PrintArchive, archive_id)
  3440. # Per-row ownership gate — mirror the archive read routes. LIBRARY_UPLOAD
  3441. # alone let a READ_OWN caller slice another user's archive by raw id even
  3442. # though GET on that id returned 404. API-key / auth-disabled callers
  3443. # (current_user is None) keep can_read_all=True — no per-row identity.
  3444. can_read_all = current_user is None or current_user.has_permission(Permission.ARCHIVES_READ_ALL.value)
  3445. archive = _ensure_archive_visible(archive, current_user, can_read_all)
  3446. src_relative = archive.source_3mf_path or archive.file_path
  3447. if not src_relative:
  3448. raise HTTPException(
  3449. status_code=400,
  3450. detail="Archive has no source file to slice",
  3451. )
  3452. src_path = (
  3453. Path(settings.base_dir) / src_relative
  3454. ) # SEC-PATH-OK: src_relative is archive.source_3mf_path from DB, set by _resolve_source_3mf_path which already does resolve+relative_to containment
  3455. if not src_path.exists():
  3456. raise HTTPException(status_code=404, detail="Archive source file missing on disk")
  3457. raw_filename = archive.filename or src_path.name
  3458. src_lower = raw_filename.lower()
  3459. if not (
  3460. src_lower.endswith(".stl")
  3461. or src_lower.endswith(".3mf")
  3462. or src_lower.endswith(".step")
  3463. or src_lower.endswith(".stp")
  3464. ):
  3465. raise HTTPException(
  3466. status_code=400,
  3467. detail="Archive's source file must be STL, 3MF, or STEP to slice",
  3468. )
  3469. # Match the library route: derive the sliced output's filename from
  3470. # `print_name` when set, so the new archive row's display name lines
  3471. # up with the source's display.
  3472. src_ext = Path(raw_filename).suffix.lower() or ".3mf"
  3473. src_filename = (
  3474. f"{archive.print_name.strip()}{src_ext}" if archive.print_name and archive.print_name.strip() else raw_filename
  3475. )
  3476. model_bytes = src_path.read_bytes()
  3477. archive_id_local = archive.id
  3478. user_id = current_user.id if current_user else None
  3479. # Block a cross-nozzle-class re-slice (single-nozzle <-> H2D) up front —
  3480. # BambuStudio's multi-extruder validator would otherwise reject it with a
  3481. # cryptic error. No-op for same-class or un-sliced sources.
  3482. await guard_nozzle_class_reslice(db, current_user, request, archive.sliced_for_model)
  3483. async def _run(job_id: int):
  3484. async with async_session() as task_db:
  3485. # Re-fetch the source archive on the background-task session.
  3486. src_archive = await task_db.get(PrintArchive, archive_id_local)
  3487. if src_archive is None:
  3488. raise http_exception_to_job_error(
  3489. HTTPException(status_code=404, detail="Archive disappeared during slice")
  3490. )
  3491. try:
  3492. response = await slice_and_persist_as_archive(
  3493. task_db,
  3494. model_bytes=model_bytes,
  3495. model_filename=src_filename,
  3496. request=request,
  3497. source_archive=src_archive,
  3498. current_user_id=user_id,
  3499. job_id=job_id,
  3500. )
  3501. except HTTPException as exc:
  3502. raise http_exception_to_job_error(exc) from exc
  3503. return response.model_dump()
  3504. job = await slice_dispatch.enqueue(
  3505. kind="archive",
  3506. source_id=archive.id,
  3507. source_name=archive.print_name or archive.filename or f"archive {archive.id}",
  3508. owner_id=user_id,
  3509. run=_run,
  3510. )
  3511. return {
  3512. "job_id": job.id,
  3513. "status": job.status,
  3514. "status_url": f"/api/v1/slice-jobs/{job.id}",
  3515. }
  3516. @router.post("/{archive_id}/reprint")
  3517. async def reprint_archive(
  3518. archive_id: int,
  3519. printer_id: int,
  3520. # SECURITY.md SEC-AUTH-1: every route either has an explicit auth dep or
  3521. # is in the route-auth-coverage allowlist. Gating the deprecation stub on
  3522. # QUEUE_CREATE matches the replacement route (POST /queue/) and means
  3523. # anonymous callers bounce at auth instead of seeing the deprecation
  3524. # message — leaking "this route exists" to unauthenticated callers is
  3525. # exactly the shape the backstop guards against.
  3526. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  3527. ):
  3528. """Legacy direct reprint endpoint. Use POST /queue/ instead."""
  3529. logger.warning(
  3530. "Gone API used: POST /archives/%s/reprint?printer_id=%s; use POST /queue/ instead",
  3531. archive_id,
  3532. printer_id,
  3533. )
  3534. raise HTTPException(
  3535. status_code=410,
  3536. detail="Direct archive reprint has been removed. Create a print queue item with POST /queue/.",
  3537. )
  3538. # =============================================================================
  3539. # Project Page API
  3540. # =============================================================================
  3541. @router.get("/{archive_id}/project-page")
  3542. async def get_project_page(
  3543. archive_id: int,
  3544. db: AsyncSession = Depends(get_db),
  3545. auth_result: tuple[User | None, bool] = Depends(
  3546. require_ownership_permission(
  3547. Permission.ARCHIVES_READ_ALL,
  3548. Permission.ARCHIVES_READ_OWN,
  3549. )
  3550. ),
  3551. ):
  3552. """Get the project page data from the 3MF file."""
  3553. from backend.app.schemas.archive import ProjectPageResponse
  3554. from backend.app.services.archive import ProjectPageParser
  3555. user, can_read_all = auth_result
  3556. service = ArchiveService(db)
  3557. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_read_all)
  3558. file_path = settings.base_dir / archive.file_path
  3559. if not file_path.is_file():
  3560. raise HTTPException(404, "Archive file not found")
  3561. parser = ProjectPageParser(file_path)
  3562. data = parser.parse(archive_id)
  3563. return ProjectPageResponse(**data)
  3564. @router.patch("/{archive_id}/project-page")
  3565. async def update_project_page(
  3566. archive_id: int,
  3567. update_data: dict,
  3568. db: AsyncSession = Depends(get_db),
  3569. auth_result: tuple[User | None, bool] = Depends(
  3570. require_ownership_permission(
  3571. Permission.ARCHIVES_UPDATE_ALL,
  3572. Permission.ARCHIVES_UPDATE_OWN,
  3573. )
  3574. ),
  3575. ):
  3576. """Update project page metadata in the 3MF file."""
  3577. from backend.app.services.archive import ProjectPageParser
  3578. user, can_modify_all = auth_result
  3579. service = ArchiveService(db)
  3580. archive = _ensure_archive_visible(await service.get_archive(archive_id), user, can_modify_all)
  3581. file_path = settings.base_dir / archive.file_path
  3582. if not file_path.is_file():
  3583. raise HTTPException(404, "Archive file not found")
  3584. parser = ProjectPageParser(file_path)
  3585. success = parser.update_metadata(update_data)
  3586. if not success:
  3587. raise HTTPException(500, "Failed to update project page")
  3588. # Return updated data
  3589. data = parser.parse(archive_id)
  3590. return data
  3591. @router.get("/{archive_id}/project-image/{image_path:path}")
  3592. async def get_project_image(
  3593. archive_id: int,
  3594. image_path: str,
  3595. db: AsyncSession = Depends(get_db),
  3596. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3597. ):
  3598. """Get an image from the 3MF project page.
  3599. Requires a stream token query param (?token=xxx) when auth is enabled.
  3600. """
  3601. from backend.app.services.archive import ProjectPageParser
  3602. service = ArchiveService(db)
  3603. archive = await service.get_archive(archive_id)
  3604. if not archive:
  3605. raise HTTPException(404, "Archive not found")
  3606. file_path = settings.base_dir / archive.file_path
  3607. if not file_path.is_file():
  3608. raise HTTPException(404, "Archive file not found")
  3609. parser = ProjectPageParser(file_path)
  3610. result = parser.get_image(image_path)
  3611. if not result:
  3612. raise HTTPException(404, "Image not found in 3MF file")
  3613. image_data, content_type = result
  3614. return Response(
  3615. content=image_data,
  3616. media_type=content_type,
  3617. headers={"Cache-Control": "max-age=3600"},
  3618. )
  3619. # =============================================================================
  3620. # Source 3MF API (Original Project Files)
  3621. # =============================================================================
  3622. def _resolve_source_3mf_path(archive: PrintArchive, source_filename: str) -> Path:
  3623. """Resolve where to write a source 3MF for ``archive``.
  3624. Normal archives nest the source under ``<archive_file_dir>/source/``.
  3625. "Fallback" archives (created in main.py when MQTT reports a print start
  3626. but Bambuddy never saw the source 3MF — cloud / Handy / pre-existing
  3627. SD-card prints) carry ``file_path=""``. Joining that with ``base_dir``
  3628. via the ``/`` operator silently yields ``base_dir`` itself, whose parent
  3629. is ``base_dir.parent`` — which sent the upload to ``/app/source/`` and
  3630. raised a 500 on the final ``relative_to`` (#1531). Fallback archives
  3631. now land under ``<base_dir>/archive/no_source/<archive_id>/`` instead,
  3632. which stays inside the data volume and remains addressable by every
  3633. read site that does ``base_dir / archive.source_3mf_path``.
  3634. The resolved directory is asserted to be inside ``base_dir`` even when
  3635. ``archive.file_path`` is populated, so a row corrupted by an old import
  3636. or manual SQL edit fails with a clear 500 instead of writing outside
  3637. the data volume.
  3638. """
  3639. if archive.file_path:
  3640. archive_file = settings.base_dir / archive.file_path
  3641. source_dir = archive_file.parent / "source"
  3642. else:
  3643. source_dir = settings.base_dir / "archive" / "no_source" / str(archive.id)
  3644. # Containment check via resolve() — catches absolute file_path, `..`
  3645. # traversal, and any other shape that escapes the data volume — but we
  3646. # return the *literal* source_dir below. Resolving the returned path
  3647. # would canonicalise away a symlinked DATA_DIR (legitimate on TrueNAS /
  3648. # QNAP / Synology storage pools, and any `-v /symlink:/app/data`
  3649. # mount), which would then make the caller's
  3650. # ``source_path.relative_to(settings.base_dir)`` raise because the
  3651. # left side is canonical and the right is the symlink path.
  3652. try:
  3653. source_dir.resolve().relative_to(settings.base_dir.resolve())
  3654. except ValueError as exc:
  3655. raise HTTPException(
  3656. 500,
  3657. f"Archive {archive.id} resolves to a path outside the data directory; cannot attach source.",
  3658. ) from exc
  3659. source_dir.mkdir(parents=True, exist_ok=True)
  3660. return (
  3661. source_dir / source_filename
  3662. ) # SEC-PATH-OK: callers pass _safe_filename(...) basename-stripped; source_dir resolve+relative_to checked above
  3663. @router.post("/{archive_id}/source")
  3664. async def upload_source_3mf(
  3665. archive_id: int,
  3666. file: UploadFile = File(...),
  3667. db: AsyncSession = Depends(get_db),
  3668. auth_result: tuple[User | None, bool] = Depends(
  3669. require_ownership_permission(
  3670. Permission.ARCHIVES_UPDATE_ALL,
  3671. Permission.ARCHIVES_UPDATE_OWN,
  3672. )
  3673. ),
  3674. ):
  3675. """Upload the original source 3MF project file for an archive."""
  3676. user, can_modify_all = auth_result
  3677. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3678. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3679. if not file.filename or not file.filename.endswith(".3mf"):
  3680. raise HTTPException(400, "File must be a .3mf file")
  3681. # Save the source 3MF file - preserve original filename, strip directory components
  3682. source_filename = _safe_filename(file.filename)
  3683. source_path = _resolve_source_3mf_path(archive, source_filename)
  3684. # Delete old source file if exists
  3685. if archive.source_3mf_path:
  3686. old_source_path = settings.base_dir / archive.source_3mf_path
  3687. if old_source_path.exists():
  3688. old_source_path.unlink()
  3689. content = await file.read()
  3690. # #1401: validate zip header on source 3MF uploads too — source files
  3691. # are uploaded for reprint and slicing, so an invalid one breaks the
  3692. # same downstream paths as a bad sliced file.
  3693. from backend.app.api.routes.library import validate_print_file_upload
  3694. validate_print_file_upload(file.filename, content)
  3695. source_path.write_bytes(content)
  3696. # Update archive with source path (relative to base_dir)
  3697. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3698. await db.commit()
  3699. await db.refresh(archive)
  3700. return {
  3701. "status": "uploaded",
  3702. "source_3mf_path": archive.source_3mf_path,
  3703. "filename": source_filename,
  3704. }
  3705. @router.get("/{archive_id}/source")
  3706. async def download_source_3mf(
  3707. archive_id: int,
  3708. db: AsyncSession = Depends(get_db),
  3709. auth_result: tuple[User | None, bool] = Depends(
  3710. require_ownership_permission(
  3711. Permission.ARCHIVES_READ_ALL,
  3712. Permission.ARCHIVES_READ_OWN,
  3713. )
  3714. ),
  3715. ):
  3716. """Download the source 3MF project file."""
  3717. user, can_read_all = auth_result
  3718. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3719. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3720. if not archive.source_3mf_path:
  3721. raise HTTPException(404, "No source 3MF attached to this archive")
  3722. source_path = settings.base_dir / archive.source_3mf_path
  3723. if not source_path.exists():
  3724. raise HTTPException(404, "Source 3MF file not found on disk")
  3725. # Use the actual filename from the path
  3726. filename = source_path.name
  3727. return FileResponse(
  3728. path=source_path,
  3729. filename=filename,
  3730. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3731. )
  3732. @router.get("/{archive_id}/source/{filename}")
  3733. async def download_source_3mf_for_slicer(
  3734. archive_id: int,
  3735. filename: str,
  3736. db: AsyncSession = Depends(get_db),
  3737. auth_result: tuple[User | None, bool] = Depends(
  3738. require_ownership_permission(
  3739. Permission.ARCHIVES_READ_ALL,
  3740. Permission.ARCHIVES_READ_OWN,
  3741. )
  3742. ),
  3743. ):
  3744. """Download source 3MF with filename in URL."""
  3745. user, can_read_all = auth_result
  3746. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3747. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3748. if not archive.source_3mf_path:
  3749. raise HTTPException(404, "No source 3MF attached to this archive")
  3750. source_path = settings.base_dir / archive.source_3mf_path
  3751. if not source_path.exists():
  3752. raise HTTPException(404, "Source 3MF file not found on disk")
  3753. return FileResponse(
  3754. path=source_path,
  3755. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3756. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3757. )
  3758. @router.post("/{archive_id}/source-slicer-token")
  3759. async def create_source_slicer_token(
  3760. archive_id: int,
  3761. db: AsyncSession = Depends(get_db),
  3762. auth_result: tuple[User | None, bool] = Depends(
  3763. require_ownership_permission(
  3764. Permission.ARCHIVES_READ_ALL,
  3765. Permission.ARCHIVES_READ_OWN,
  3766. )
  3767. ),
  3768. ):
  3769. """Create a short-lived download token for opening source 3MF in slicer."""
  3770. from backend.app.core.auth import create_slicer_download_token
  3771. user, can_read_all = auth_result
  3772. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3773. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3774. if not archive.source_3mf_path:
  3775. raise HTTPException(404, "No source 3MF attached to this archive")
  3776. token = await create_slicer_download_token("source", archive_id)
  3777. return {"token": token}
  3778. @router.get("/{archive_id}/source-dl/{token}/{filename}")
  3779. async def download_source_3mf_for_slicer_with_token(
  3780. archive_id: int,
  3781. token: str,
  3782. filename: str,
  3783. db: AsyncSession = Depends(get_db),
  3784. ):
  3785. """Download source 3MF using a slicer download token.
  3786. Token-authenticated (no auth headers needed). The token is short-lived
  3787. and single-use, created by POST /{archive_id}/source-slicer-token.
  3788. """
  3789. from backend.app.core.auth import verify_slicer_download_token
  3790. if not await verify_slicer_download_token(token, "source", archive_id):
  3791. raise HTTPException(403, "Invalid or expired download token")
  3792. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3793. archive = result.scalar_one_or_none()
  3794. if not archive:
  3795. raise HTTPException(404, "Archive not found")
  3796. if not archive.source_3mf_path:
  3797. raise HTTPException(404, "No source 3MF attached to this archive")
  3798. source_path = settings.base_dir / archive.source_3mf_path
  3799. if not source_path.exists():
  3800. raise HTTPException(404, "Source 3MF file not found on disk")
  3801. return FileResponse(
  3802. path=source_path,
  3803. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3804. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3805. )
  3806. @router.post("/upload-source")
  3807. async def upload_source_3mf_by_name(
  3808. file: UploadFile = File(...),
  3809. print_name: str = Query(None, description="Match archive by print name"),
  3810. db: AsyncSession = Depends(get_db),
  3811. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3812. ):
  3813. """Upload source 3MF and match to archive by print name.
  3814. This endpoint is designed for slicer post-processing scripts.
  3815. It finds the most recent archive matching the print name and attaches the source.
  3816. """
  3817. if not file.filename or not file.filename.endswith(".3mf"):
  3818. raise HTTPException(400, "File must be a .3mf file")
  3819. safe_filename = _safe_filename(file.filename)
  3820. # Derive print name from filename if not provided
  3821. if not print_name:
  3822. # Remove .3mf extension and common suffixes
  3823. print_name = safe_filename.rsplit(".3mf", 1)[0]
  3824. # Remove _source suffix if present
  3825. if print_name.endswith("_source"):
  3826. print_name = print_name[:-7]
  3827. # Find matching archive - try exact match first, then fuzzy
  3828. result = await db.execute(
  3829. select(PrintArchive)
  3830. .where(PrintArchive.print_name == print_name)
  3831. .order_by(PrintArchive.created_at.desc())
  3832. .limit(1)
  3833. )
  3834. archive = result.scalar_one_or_none()
  3835. if not archive:
  3836. # Try matching filename without .gcode.3mf
  3837. result = await db.execute(
  3838. select(PrintArchive)
  3839. .where(PrintArchive.filename.like(f"{print_name}%"))
  3840. .order_by(PrintArchive.created_at.desc())
  3841. .limit(1)
  3842. )
  3843. archive = result.scalar_one_or_none()
  3844. if not archive:
  3845. # Try case-insensitive partial match on print_name
  3846. result = await db.execute(
  3847. select(PrintArchive)
  3848. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  3849. .order_by(PrintArchive.created_at.desc())
  3850. .limit(1)
  3851. )
  3852. archive = result.scalar_one_or_none()
  3853. if not archive:
  3854. raise HTTPException(404, f"No archive found matching '{print_name}'")
  3855. # Save the source 3MF file - preserve original filename, strip directory components
  3856. source_filename = safe_filename
  3857. source_path = _resolve_source_3mf_path(archive, source_filename)
  3858. # Delete old source file if exists
  3859. if archive.source_3mf_path:
  3860. old_source_path = settings.base_dir / archive.source_3mf_path
  3861. if old_source_path.exists():
  3862. old_source_path.unlink()
  3863. content = await file.read()
  3864. # #1401: same zip-header check as the other upload routes — the
  3865. # match-by-name endpoint is used by slicer post-processing scripts,
  3866. # so a misconfigured script is exactly how a bad 3MF would slip in.
  3867. from backend.app.api.routes.library import validate_print_file_upload
  3868. validate_print_file_upload(file.filename, content)
  3869. source_path.write_bytes(content)
  3870. # Update archive with source path
  3871. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3872. await db.commit()
  3873. await db.refresh(archive)
  3874. return {
  3875. "status": "uploaded",
  3876. "archive_id": archive.id,
  3877. "archive_name": archive.print_name or archive.filename,
  3878. "source_3mf_path": archive.source_3mf_path,
  3879. "filename": source_filename,
  3880. }
  3881. @router.delete("/{archive_id}/source")
  3882. async def delete_source_3mf(
  3883. archive_id: int,
  3884. db: AsyncSession = Depends(get_db),
  3885. auth_result: tuple[User | None, bool] = Depends(
  3886. require_ownership_permission(
  3887. Permission.ARCHIVES_DELETE_ALL,
  3888. Permission.ARCHIVES_DELETE_OWN,
  3889. )
  3890. ),
  3891. ):
  3892. """Delete the source 3MF project file from an archive."""
  3893. user, can_modify_all = auth_result
  3894. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3895. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3896. if not archive.source_3mf_path:
  3897. raise HTTPException(404, "No source 3MF attached to this archive")
  3898. # Delete the file
  3899. source_path = settings.base_dir / archive.source_3mf_path
  3900. if source_path.exists():
  3901. source_path.unlink()
  3902. # Clear the path in database
  3903. archive.source_3mf_path = None
  3904. await db.commit()
  3905. return {"status": "deleted"}
  3906. # =============================================================================
  3907. # F3D API (Fusion 360 Design Files)
  3908. # =============================================================================
  3909. @router.post("/{archive_id}/f3d")
  3910. async def upload_f3d(
  3911. archive_id: int,
  3912. file: UploadFile = File(...),
  3913. db: AsyncSession = Depends(get_db),
  3914. auth_result: tuple[User | None, bool] = Depends(
  3915. require_ownership_permission(
  3916. Permission.ARCHIVES_UPDATE_ALL,
  3917. Permission.ARCHIVES_UPDATE_OWN,
  3918. )
  3919. ),
  3920. ):
  3921. """Upload a Fusion 360 design file for an archive."""
  3922. user, can_modify_all = auth_result
  3923. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3924. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3925. if not file.filename or not file.filename.endswith(".f3d"):
  3926. raise HTTPException(400, "File must be a .f3d file")
  3927. # Get archive directory and create f3d subdirectory
  3928. file_path = settings.base_dir / archive.file_path
  3929. archive_dir = file_path.parent
  3930. f3d_dir = archive_dir / "f3d"
  3931. f3d_dir.mkdir(exist_ok=True)
  3932. # Delete old F3D file if exists
  3933. if archive.f3d_path:
  3934. old_f3d_path = settings.base_dir / archive.f3d_path
  3935. if old_f3d_path.exists():
  3936. old_f3d_path.unlink()
  3937. # Save the F3D file - preserve original filename, strip directory components
  3938. f3d_filename = _safe_filename(file.filename)
  3939. f3d_path = f3d_dir / f3d_filename # SEC-PATH-OK: f3d_filename = _safe_filename(...) basename-stripped above
  3940. content = await file.read()
  3941. f3d_path.write_bytes(content)
  3942. # Update archive with F3D path (relative to base_dir)
  3943. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  3944. await db.commit()
  3945. await db.refresh(archive)
  3946. return {
  3947. "status": "uploaded",
  3948. "f3d_path": archive.f3d_path,
  3949. "filename": f3d_filename,
  3950. }
  3951. @router.get("/{archive_id}/f3d")
  3952. async def download_f3d(
  3953. archive_id: int,
  3954. db: AsyncSession = Depends(get_db),
  3955. auth_result: tuple[User | None, bool] = Depends(
  3956. require_ownership_permission(
  3957. Permission.ARCHIVES_READ_ALL,
  3958. Permission.ARCHIVES_READ_OWN,
  3959. )
  3960. ),
  3961. ):
  3962. """Download the Fusion 360 design file."""
  3963. user, can_read_all = auth_result
  3964. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3965. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_read_all)
  3966. if not archive.f3d_path:
  3967. raise HTTPException(404, "No F3D file attached to this archive")
  3968. f3d_path = settings.base_dir / archive.f3d_path
  3969. if not f3d_path.exists():
  3970. raise HTTPException(404, "F3D file not found on disk")
  3971. # Use the actual filename from the path
  3972. filename = f3d_path.name
  3973. return FileResponse(
  3974. path=f3d_path,
  3975. filename=filename,
  3976. media_type="application/octet-stream",
  3977. )
  3978. @router.delete("/{archive_id}/f3d")
  3979. async def delete_f3d(
  3980. archive_id: int,
  3981. db: AsyncSession = Depends(get_db),
  3982. auth_result: tuple[User | None, bool] = Depends(
  3983. require_ownership_permission(
  3984. Permission.ARCHIVES_DELETE_ALL,
  3985. Permission.ARCHIVES_DELETE_OWN,
  3986. )
  3987. ),
  3988. ):
  3989. """Delete the Fusion 360 design file from an archive."""
  3990. user, can_modify_all = auth_result
  3991. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3992. archive = _ensure_archive_visible(result.scalar_one_or_none(), user, can_modify_all)
  3993. if not archive.f3d_path:
  3994. raise HTTPException(404, "No F3D file attached to this archive")
  3995. # Delete the file
  3996. f3d_path = settings.base_dir / archive.f3d_path
  3997. if f3d_path.exists():
  3998. f3d_path.unlink()
  3999. # Clear the path in database
  4000. archive.f3d_path = None
  4001. await db.commit()
  4002. return {"status": "deleted"}