archives.py 172 KB

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