archives.py 180 KB

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