archives.py 229 KB

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