archives.py 184 KB

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