archives.py 154 KB

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