archives.py 222 KB

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