archives.py 249 KB

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