archives.py 135 KB

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