archives.py 137 KB

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