archives.py 174 KB

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