archives.py 229 KB

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