archives.py 233 KB

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