archives.py 131 KB

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