archives.py 206 KB

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