archives.py 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643
  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. elif plug.plug_type == "rest":
  688. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  689. energy = await rest_smart_plug_service.get_energy(plug)
  690. if energy and energy.get("today") is not None:
  691. total_energy_kwh += energy["today"]
  692. total_energy_kwh = round(total_energy_kwh, 3)
  693. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 3)
  694. else:
  695. # Print mode: sum up per-print energy from archives
  696. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)).where(*base_conditions))
  697. total_energy_kwh = energy_kwh_result.scalar() or 0
  698. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)).where(*base_conditions))
  699. total_energy_cost = energy_cost_result.scalar() or 0
  700. return ArchiveStats(
  701. total_prints=total_prints,
  702. successful_prints=successful_prints,
  703. failed_prints=failed_prints,
  704. total_print_time_hours=round(total_time, 1),
  705. total_filament_grams=round(total_filament, 1),
  706. total_cost=round(total_cost, 2),
  707. prints_by_filament_type=prints_by_filament,
  708. prints_by_printer=prints_by_printer,
  709. average_time_accuracy=average_accuracy,
  710. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  711. total_energy_kwh=round(total_energy_kwh, 3),
  712. total_energy_cost=round(total_energy_cost, 3),
  713. )
  714. @router.get("/tags")
  715. async def get_all_tags(
  716. db: AsyncSession = Depends(get_db),
  717. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  718. ):
  719. """List all unique tags with usage counts.
  720. Returns a list of tags sorted by count (descending), then by name.
  721. """
  722. # Query all archives with non-null tags
  723. result = await db.execute(select(PrintArchive.tags).where(PrintArchive.tags.isnot(None)))
  724. all_tags_rows = result.all()
  725. # Count occurrences of each tag
  726. tag_counts: dict[str, int] = {}
  727. for (tags_str,) in all_tags_rows:
  728. if tags_str:
  729. for tag in tags_str.split(","):
  730. tag = tag.strip()
  731. if tag:
  732. tag_counts[tag] = tag_counts.get(tag, 0) + 1
  733. # Convert to list and sort by count (desc), then name (asc)
  734. tags_list = [{"name": name, "count": count} for name, count in tag_counts.items()]
  735. tags_list.sort(key=lambda x: (-x["count"], x["name"].lower()))
  736. return tags_list
  737. @router.put("/tags/{tag_name}")
  738. async def rename_tag(
  739. tag_name: str,
  740. request: Request,
  741. db: AsyncSession = Depends(get_db),
  742. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  743. ):
  744. """Rename a tag across all archives.
  745. Request body should contain {"new_name": "new tag name"}.
  746. Returns the count of affected archives.
  747. """
  748. body = await request.json()
  749. new_name = body.get("new_name", "").strip()
  750. if not new_name:
  751. raise HTTPException(400, "new_name is required")
  752. if new_name == tag_name:
  753. return {"affected": 0}
  754. # Find all archives containing the old tag
  755. result = await db.execute(select(PrintArchive).where(PrintArchive.tags.isnot(None)))
  756. archives = list(result.scalars().all())
  757. affected = 0
  758. for archive in archives:
  759. if not archive.tags:
  760. continue
  761. tags = [t.strip() for t in archive.tags.split(",")]
  762. if tag_name in tags:
  763. # Replace old tag with new tag
  764. new_tags = [new_name if t == tag_name else t for t in tags]
  765. # Remove duplicates while preserving order
  766. seen = set()
  767. unique_tags = []
  768. for t in new_tags:
  769. if t not in seen:
  770. seen.add(t)
  771. unique_tags.append(t)
  772. archive.tags = ", ".join(unique_tags)
  773. affected += 1
  774. await db.commit()
  775. return {"affected": affected}
  776. @router.delete("/tags/{tag_name}")
  777. async def delete_tag(
  778. tag_name: str,
  779. db: AsyncSession = Depends(get_db),
  780. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  781. ):
  782. """Delete a tag from all archives.
  783. Returns the count of affected archives.
  784. """
  785. # Find all archives containing the tag
  786. result = await db.execute(select(PrintArchive).where(PrintArchive.tags.isnot(None)))
  787. archives = list(result.scalars().all())
  788. affected = 0
  789. for archive in archives:
  790. if not archive.tags:
  791. continue
  792. tags = [t.strip() for t in archive.tags.split(",")]
  793. if tag_name in tags:
  794. # Remove the tag
  795. new_tags = [t for t in tags if t != tag_name]
  796. archive.tags = ", ".join(new_tags) if new_tags else None
  797. affected += 1
  798. await db.commit()
  799. return {"affected": affected}
  800. @router.get("/{archive_id}", response_model=ArchiveResponse)
  801. async def get_archive(
  802. archive_id: int,
  803. db: AsyncSession = Depends(get_db),
  804. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  805. ):
  806. """Get a specific archive."""
  807. service = ArchiveService(db)
  808. archive = await service.get_archive(archive_id)
  809. if not archive:
  810. raise HTTPException(404, "Archive not found")
  811. # Find duplicates
  812. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  813. duplicates = await service.find_duplicates(
  814. archive_id=archive.id,
  815. content_hash=archive.content_hash,
  816. print_name=archive.print_name,
  817. makerworld_model_id=makerworld_id,
  818. )
  819. return archive_to_response(archive, duplicates)
  820. @router.get("/{archive_id}/similar")
  821. async def find_similar_archives(
  822. archive_id: int,
  823. limit: int = 10,
  824. db: AsyncSession = Depends(get_db),
  825. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  826. ):
  827. """Find archives with similar settings for comparison.
  828. Returns archives that match by:
  829. - Same print name (highest priority)
  830. - Same file content hash
  831. - Same filament type
  832. """
  833. from backend.app.services.archive_comparison import ArchiveComparisonService
  834. service = ArchiveComparisonService(db)
  835. try:
  836. return await service.find_similar_archives(archive_id, limit=limit)
  837. except ValueError as e:
  838. raise HTTPException(404, str(e))
  839. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  840. async def update_archive(
  841. archive_id: int,
  842. update_data: ArchiveUpdate,
  843. db: AsyncSession = Depends(get_db),
  844. auth_result: tuple[User | None, bool] = Depends(
  845. require_ownership_permission(
  846. Permission.ARCHIVES_UPDATE_ALL,
  847. Permission.ARCHIVES_UPDATE_OWN,
  848. )
  849. ),
  850. ):
  851. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  852. from sqlalchemy.orm import selectinload
  853. user, can_modify_all = auth_result
  854. result = await db.execute(
  855. select(PrintArchive)
  856. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  857. .where(PrintArchive.id == archive_id)
  858. )
  859. archive = result.scalar_one_or_none()
  860. if not archive:
  861. raise HTTPException(404, "Archive not found")
  862. # Ownership check
  863. if not can_modify_all:
  864. if archive.created_by_id != user.id:
  865. raise HTTPException(403, "You can only update your own archives")
  866. for field, value in update_data.model_dump(exclude_unset=True).items():
  867. setattr(archive, field, value)
  868. await db.commit()
  869. # Re-fetch with relationships loaded after commit
  870. result = await db.execute(
  871. select(PrintArchive)
  872. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  873. .where(PrintArchive.id == archive_id)
  874. )
  875. archive = result.scalar_one_or_none()
  876. return archive_to_response(archive)
  877. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  878. async def toggle_favorite(
  879. archive_id: int,
  880. db: AsyncSession = Depends(get_db),
  881. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  882. ):
  883. """Toggle favorite status for an archive."""
  884. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  885. archive = result.scalar_one_or_none()
  886. if not archive:
  887. raise HTTPException(404, "Archive not found")
  888. archive.is_favorite = not archive.is_favorite
  889. await db.commit()
  890. await db.refresh(archive)
  891. return archive
  892. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  893. async def rescan_archive(
  894. archive_id: int,
  895. db: AsyncSession = Depends(get_db),
  896. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  897. ):
  898. """Rescan the 3MF file and update metadata."""
  899. from backend.app.api.routes.settings import get_setting
  900. from backend.app.services.archive import ThreeMFParser
  901. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  902. archive = result.scalar_one_or_none()
  903. if not archive:
  904. raise HTTPException(404, "Archive not found")
  905. file_path = settings.base_dir / archive.file_path
  906. if not file_path.is_file():
  907. raise HTTPException(404, "Archive file not found")
  908. # Parse the 3MF file
  909. parser = ThreeMFParser(file_path)
  910. metadata = parser.parse()
  911. # Update fields from metadata
  912. if metadata.get("filament_type"):
  913. archive.filament_type = metadata["filament_type"]
  914. if metadata.get("filament_color"):
  915. archive.filament_color = metadata["filament_color"]
  916. if metadata.get("print_time_seconds"):
  917. archive.print_time_seconds = metadata["print_time_seconds"]
  918. if metadata.get("filament_used_grams"):
  919. archive.filament_used_grams = metadata["filament_used_grams"]
  920. if metadata.get("layer_height"):
  921. archive.layer_height = metadata["layer_height"]
  922. if metadata.get("nozzle_diameter"):
  923. archive.nozzle_diameter = metadata["nozzle_diameter"]
  924. if metadata.get("bed_temperature"):
  925. archive.bed_temperature = metadata["bed_temperature"]
  926. if metadata.get("nozzle_temperature"):
  927. archive.nozzle_temperature = metadata["nozzle_temperature"]
  928. if metadata.get("makerworld_url"):
  929. archive.makerworld_url = metadata["makerworld_url"]
  930. if metadata.get("designer"):
  931. archive.designer = metadata["designer"]
  932. # Calculate cost: prefer spool-based cost if available, else catalog-based
  933. if archive.filament_used_grams and archive.filament_type:
  934. usage_result = await db.execute(
  935. select(func.sum(SpoolUsageHistory.cost)).where(SpoolUsageHistory.archive_id == archive.id)
  936. )
  937. usage_cost = usage_result.scalar()
  938. if usage_cost is not None and usage_cost > 0:
  939. archive.cost = float(Decimal(str(usage_cost)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
  940. else:
  941. primary_type = archive.filament_type.split(",")[0].strip()
  942. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  943. filament = filament_result.scalar_one_or_none()
  944. if filament:
  945. archive.cost = float(
  946. Decimal(str((archive.filament_used_grams / 1000) * filament.cost_per_kg)).quantize(
  947. Decimal("0.01"), rounding=ROUND_HALF_UP
  948. )
  949. )
  950. else:
  951. # Use default filament cost from settings
  952. default_cost_setting = await get_setting(db, "default_filament_cost")
  953. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  954. archive.cost = float(
  955. Decimal(str((archive.filament_used_grams / 1000) * default_cost_per_kg)).quantize(
  956. Decimal("0.01"), rounding=ROUND_HALF_UP
  957. )
  958. )
  959. await db.commit()
  960. await db.refresh(archive)
  961. return archive
  962. @router.post("/recalculate-costs")
  963. async def recalculate_all_costs(
  964. db: AsyncSession = Depends(get_db),
  965. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  966. ):
  967. """Recalculate costs for all archives based on filament usage and prices."""
  968. from backend.app.api.routes.settings import get_setting
  969. result = await db.execute(select(PrintArchive))
  970. archives = list(result.scalars().all())
  971. # Load all filaments for lookup
  972. filament_result = await db.execute(select(Filament))
  973. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  974. # Get default filament cost from settings
  975. default_cost_setting = await get_setting(db, "default_filament_cost")
  976. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  977. # Pre-fetch all usage costs by archive_id
  978. usage_costs_result = await db.execute(
  979. select(SpoolUsageHistory.archive_id, func.sum(SpoolUsageHistory.cost)).group_by(SpoolUsageHistory.archive_id)
  980. )
  981. usage_costs = usage_costs_result.fetchall()
  982. 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}
  983. updated = 0
  984. for archive in archives:
  985. usage_cost = cost_map.get(archive.id)
  986. if usage_cost is not None:
  987. new_cost = round(usage_cost, 2)
  988. else:
  989. # Fallback: sum costs for old records by print_name
  990. usage_result = await db.execute(
  991. select(func.sum(SpoolUsageHistory.cost)).where(
  992. SpoolUsageHistory.print_name == archive.print_name,
  993. SpoolUsageHistory.archive_id.is_(None),
  994. )
  995. )
  996. fallback_cost = usage_result.scalar()
  997. if fallback_cost is not None and fallback_cost > 0:
  998. new_cost = round(fallback_cost, 2)
  999. elif archive.filament_used_grams and archive.filament_type:
  1000. primary_type = archive.filament_type.split(",")[0].strip()
  1001. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  1002. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  1003. else:
  1004. new_cost = None
  1005. if new_cost is not None and archive.cost != new_cost:
  1006. archive.cost = new_cost
  1007. updated += 1
  1008. await db.commit()
  1009. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  1010. @router.post("/rescan-all")
  1011. async def rescan_all_archives(
  1012. db: AsyncSession = Depends(get_db),
  1013. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1014. ):
  1015. """Rescan all archives and update their metadata."""
  1016. from backend.app.services.archive import ThreeMFParser
  1017. result = await db.execute(select(PrintArchive))
  1018. archives = list(result.scalars().all())
  1019. updated = 0
  1020. errors = []
  1021. for archive in archives:
  1022. try:
  1023. file_path = settings.base_dir / archive.file_path
  1024. if not file_path.is_file():
  1025. errors.append({"id": archive.id, "error": "File not found"})
  1026. continue
  1027. parser = ThreeMFParser(file_path)
  1028. metadata = parser.parse()
  1029. if metadata.get("filament_type"):
  1030. archive.filament_type = metadata["filament_type"]
  1031. if metadata.get("filament_color"):
  1032. archive.filament_color = metadata["filament_color"]
  1033. if metadata.get("print_time_seconds"):
  1034. archive.print_time_seconds = metadata["print_time_seconds"]
  1035. if metadata.get("filament_used_grams"):
  1036. archive.filament_used_grams = metadata["filament_used_grams"]
  1037. if metadata.get("layer_height"):
  1038. archive.layer_height = metadata["layer_height"]
  1039. if metadata.get("nozzle_diameter"):
  1040. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1041. if metadata.get("makerworld_url"):
  1042. archive.makerworld_url = metadata["makerworld_url"]
  1043. if metadata.get("designer"):
  1044. archive.designer = metadata["designer"]
  1045. updated += 1
  1046. except Exception as e:
  1047. logger.exception("Failed to rescan archive %s: %s", archive.id, e)
  1048. errors.append({"id": archive.id, "error": "Failed to parse 3MF file"})
  1049. await db.commit()
  1050. return {"updated": updated, "errors": errors}
  1051. @router.get("/{archive_id}/duplicates")
  1052. async def get_archive_duplicates(
  1053. archive_id: int,
  1054. db: AsyncSession = Depends(get_db),
  1055. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1056. ):
  1057. """Get duplicates for a specific archive."""
  1058. service = ArchiveService(db)
  1059. archive = await service.get_archive(archive_id)
  1060. if not archive:
  1061. raise HTTPException(404, "Archive not found")
  1062. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1063. duplicates = await service.find_duplicates(
  1064. archive_id=archive.id,
  1065. content_hash=archive.content_hash,
  1066. print_name=archive.print_name,
  1067. makerworld_model_id=makerworld_id,
  1068. )
  1069. return {"duplicates": duplicates, "count": len(duplicates)}
  1070. @router.post("/backfill-hashes")
  1071. async def backfill_content_hashes(
  1072. db: AsyncSession = Depends(get_db),
  1073. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1074. ):
  1075. """Compute and store content hashes for all archives missing them."""
  1076. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  1077. archives = list(result.scalars().all())
  1078. updated = 0
  1079. errors = []
  1080. for archive in archives:
  1081. try:
  1082. file_path = settings.base_dir / archive.file_path
  1083. if not file_path.is_file():
  1084. errors.append({"id": archive.id, "error": "File not found"})
  1085. continue
  1086. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  1087. updated += 1
  1088. except Exception as e:
  1089. logger.exception("Failed to compute hash for archive %s: %s", archive.id, e)
  1090. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  1091. await db.commit()
  1092. return {"updated": updated, "errors": errors}
  1093. @router.delete("/{archive_id}")
  1094. async def delete_archive(
  1095. archive_id: int,
  1096. db: AsyncSession = Depends(get_db),
  1097. auth_result: tuple[User | None, bool] = Depends(
  1098. require_ownership_permission(
  1099. Permission.ARCHIVES_DELETE_ALL,
  1100. Permission.ARCHIVES_DELETE_OWN,
  1101. )
  1102. ),
  1103. ):
  1104. """Delete an archive."""
  1105. user, can_modify_all = auth_result
  1106. # Get archive first to check ownership
  1107. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1108. archive = result.scalar_one_or_none()
  1109. if not archive:
  1110. raise HTTPException(404, "Archive not found")
  1111. # Ownership check
  1112. if not can_modify_all:
  1113. if archive.created_by_id != user.id:
  1114. raise HTTPException(403, "You can only delete your own archives")
  1115. service = ArchiveService(db)
  1116. if not await service.delete_archive(archive_id):
  1117. raise HTTPException(404, "Archive not found")
  1118. return {"status": "deleted"}
  1119. @router.get("/{archive_id}/download")
  1120. async def download_archive(
  1121. archive_id: int,
  1122. inline: bool = False,
  1123. db: AsyncSession = Depends(get_db),
  1124. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1125. ):
  1126. """Download the 3MF file."""
  1127. service = ArchiveService(db)
  1128. archive = await service.get_archive(archive_id)
  1129. if not archive:
  1130. raise HTTPException(404, "Archive not found")
  1131. file_path = settings.base_dir / archive.file_path
  1132. if not file_path.is_file():
  1133. raise HTTPException(404, "File not found")
  1134. # Use inline disposition to let browser/OS handle file association
  1135. content_disposition = "inline" if inline else "attachment"
  1136. return FileResponse(
  1137. path=file_path,
  1138. filename=archive.filename,
  1139. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1140. content_disposition_type=content_disposition,
  1141. )
  1142. @router.get("/{archive_id}/file/{filename}")
  1143. async def download_archive_with_filename(
  1144. archive_id: int,
  1145. filename: str,
  1146. db: AsyncSession = Depends(get_db),
  1147. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1148. ):
  1149. """Download the 3MF file with filename in URL."""
  1150. service = ArchiveService(db)
  1151. archive = await service.get_archive(archive_id)
  1152. if not archive:
  1153. raise HTTPException(404, "Archive not found")
  1154. file_path = settings.base_dir / archive.file_path
  1155. if not file_path.is_file():
  1156. raise HTTPException(404, "File not found")
  1157. return FileResponse(
  1158. path=file_path,
  1159. filename=archive.filename,
  1160. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1161. )
  1162. @router.post("/{archive_id}/slicer-token")
  1163. async def create_archive_slicer_token(
  1164. archive_id: int,
  1165. db: AsyncSession = Depends(get_db),
  1166. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1167. ):
  1168. """Create a short-lived download token for opening files in slicer applications.
  1169. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  1170. auth headers, so they use this token in the URL path instead.
  1171. """
  1172. from backend.app.core.auth import create_slicer_download_token
  1173. service = ArchiveService(db)
  1174. archive = await service.get_archive(archive_id)
  1175. if not archive:
  1176. raise HTTPException(404, "Archive not found")
  1177. token = create_slicer_download_token("archive", archive_id)
  1178. return {"token": token}
  1179. @router.get("/{archive_id}/dl/{token}/{filename}")
  1180. async def download_archive_for_slicer(
  1181. archive_id: int,
  1182. token: str,
  1183. filename: str,
  1184. db: AsyncSession = Depends(get_db),
  1185. ):
  1186. """Download 3MF file using a slicer download token.
  1187. Token-authenticated (no auth headers needed). The token is short-lived
  1188. and single-use, created by POST /{archive_id}/slicer-token.
  1189. Filename is at the end of the URL so slicers can detect the file format.
  1190. """
  1191. from backend.app.core.auth import verify_slicer_download_token
  1192. if not verify_slicer_download_token(token, "archive", archive_id):
  1193. raise HTTPException(403, "Invalid or expired download token")
  1194. service = ArchiveService(db)
  1195. archive = await service.get_archive(archive_id)
  1196. if not archive:
  1197. raise HTTPException(404, "Archive not found")
  1198. file_path = settings.base_dir / archive.file_path
  1199. if not file_path.is_file():
  1200. raise HTTPException(404, "File not found")
  1201. return FileResponse(
  1202. path=file_path,
  1203. filename=archive.filename,
  1204. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1205. )
  1206. @router.get("/{archive_id}/thumbnail")
  1207. async def get_thumbnail(
  1208. archive_id: int,
  1209. db: AsyncSession = Depends(get_db),
  1210. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1211. ):
  1212. """Get the thumbnail image.
  1213. Requires a stream token query param (?token=xxx) when auth is enabled.
  1214. """
  1215. service = ArchiveService(db)
  1216. archive = await service.get_archive(archive_id)
  1217. if not archive or not archive.thumbnail_path:
  1218. raise HTTPException(404, "Thumbnail not found")
  1219. thumb_path = settings.base_dir / archive.thumbnail_path
  1220. if not thumb_path.exists():
  1221. raise HTTPException(404, "Thumbnail file not found")
  1222. # Use file modification time as ETag to bust cache
  1223. mtime = int(thumb_path.stat().st_mtime)
  1224. return FileResponse(
  1225. path=thumb_path,
  1226. media_type="image/png",
  1227. headers={
  1228. "Cache-Control": "no-cache, must-revalidate",
  1229. "ETag": f'"{mtime}"',
  1230. },
  1231. )
  1232. @router.get("/{archive_id}/timelapse")
  1233. async def get_timelapse(
  1234. archive_id: int,
  1235. db: AsyncSession = Depends(get_db),
  1236. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1237. ):
  1238. """Get the timelapse video.
  1239. Requires a stream token query param (?token=xxx) when auth is enabled.
  1240. """
  1241. service = ArchiveService(db)
  1242. archive = await service.get_archive(archive_id)
  1243. if not archive or not archive.timelapse_path:
  1244. raise HTTPException(404, "Timelapse not found")
  1245. timelapse_path = settings.base_dir / archive.timelapse_path
  1246. if not timelapse_path.exists():
  1247. raise HTTPException(404, "Timelapse file not found")
  1248. # Use file modification time as ETag to bust cache after processing
  1249. mtime = int(timelapse_path.stat().st_mtime)
  1250. # Detect media type from file extension (AVI from P1S before background conversion)
  1251. suffix = timelapse_path.suffix.lower()
  1252. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  1253. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  1254. return FileResponse(
  1255. path=timelapse_path,
  1256. media_type=media_type,
  1257. filename=f"{archive.print_name or 'timelapse'}{ext}",
  1258. headers={
  1259. "Cache-Control": "no-cache, must-revalidate",
  1260. "ETag": f'"{mtime}"',
  1261. },
  1262. )
  1263. @router.delete("/{archive_id}/timelapse")
  1264. async def delete_timelapse(
  1265. archive_id: int,
  1266. db: AsyncSession = Depends(get_db),
  1267. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  1268. ):
  1269. """Remove the timelapse video from an archive."""
  1270. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1271. archive = result.scalar_one_or_none()
  1272. if not archive:
  1273. raise HTTPException(404, "Archive not found")
  1274. if not archive.timelapse_path:
  1275. raise HTTPException(404, "No timelapse attached to this archive")
  1276. # Delete the file
  1277. timelapse_path = settings.base_dir / archive.timelapse_path
  1278. if timelapse_path.exists():
  1279. timelapse_path.unlink()
  1280. # Clear the path in database
  1281. archive.timelapse_path = None
  1282. await db.commit()
  1283. return {"status": "deleted"}
  1284. @router.post("/{archive_id}/timelapse/scan")
  1285. async def scan_timelapse(
  1286. archive_id: int,
  1287. db: AsyncSession = Depends(get_db),
  1288. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1289. ):
  1290. """Scan printer for timelapse matching this archive and attach it."""
  1291. from backend.app.models.printer import Printer
  1292. from backend.app.services.bambu_ftp import (
  1293. download_file_bytes_async,
  1294. get_ftp_retry_settings,
  1295. list_files_async,
  1296. with_ftp_retry,
  1297. )
  1298. service = ArchiveService(db)
  1299. archive = await service.get_archive(archive_id)
  1300. if not archive:
  1301. raise HTTPException(404, "Archive not found")
  1302. if archive.timelapse_path:
  1303. return {"status": "exists", "message": "Timelapse already attached"}
  1304. if not archive.printer_id:
  1305. raise HTTPException(400, "Archive has no associated printer")
  1306. # Get printer
  1307. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1308. printer = result.scalar_one_or_none()
  1309. if not printer:
  1310. raise HTTPException(404, "Printer not found")
  1311. # Get base name from archive filename (without .3mf extension)
  1312. base_name = Path(archive.filename).stem
  1313. # Scan timelapse directory on printer
  1314. # Different printer models use different paths
  1315. files = []
  1316. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1317. try:
  1318. files = await list_files_async(
  1319. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1320. )
  1321. if files:
  1322. break
  1323. except Exception:
  1324. continue
  1325. if not files:
  1326. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  1327. # Look for matching timelapse
  1328. matching_file = None
  1329. video_files = [
  1330. f for f in files if not f.get("is_directory") and f.get("name", "").lower().endswith((".mp4", ".avi"))
  1331. ]
  1332. # Strategy 1: Match by print name in filename
  1333. for f in video_files:
  1334. fname = f.get("name", "")
  1335. if base_name.lower() in fname.lower():
  1336. matching_file = f
  1337. break
  1338. # Strategy 2: Match by timestamp proximity
  1339. # Bambu timelapse filename uses the print START time (when recording began)
  1340. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1341. import re
  1342. from datetime import datetime, timedelta
  1343. # Prefer started_at since video filename is the print start time
  1344. # Fall back to completed_at or created_at if started_at is not available
  1345. archive_start = archive.started_at
  1346. archive_end = archive.completed_at or archive.created_at
  1347. best_match = None
  1348. best_diff = timedelta(hours=24) # Max 24 hour difference
  1349. for f in video_files:
  1350. fname = f.get("name", "")
  1351. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  1352. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  1353. if match:
  1354. try:
  1355. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  1356. # Try multiple timezone offsets since printer timezone can vary
  1357. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  1358. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  1359. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  1360. # Check against start time (video filename = print start)
  1361. if archive_start:
  1362. diff = abs(adjusted_file_time - archive_start)
  1363. if diff < best_diff:
  1364. best_diff = diff
  1365. best_match = f
  1366. logger.debug(
  1367. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  1368. f"diff from start: {diff}"
  1369. )
  1370. # Also check against end time with a buffer
  1371. # (video timestamp should be BEFORE completion time)
  1372. if archive_end:
  1373. # The video timestamp should be within the print duration before completion
  1374. if adjusted_file_time < archive_end:
  1375. diff = archive_end - adjusted_file_time
  1376. # Reasonable print duration: up to 48 hours
  1377. if diff < timedelta(hours=48) and diff < best_diff:
  1378. best_diff = diff
  1379. best_match = f
  1380. logger.debug(
  1381. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  1382. f"diff: {diff}"
  1383. )
  1384. except ValueError:
  1385. continue
  1386. # Accept match within 4 hours (more lenient for timezone issues)
  1387. if best_match and best_diff < timedelta(hours=4):
  1388. matching_file = best_match
  1389. logger.info("Matched timelapse by timestamp: %s (diff: %s)", best_match.get("name"), best_diff)
  1390. # Strategy 3: Use file modification time from FTP listing
  1391. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  1392. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1393. from datetime import datetime, timedelta
  1394. _archive_start = archive.started_at
  1395. archive_end = archive.completed_at or archive.created_at
  1396. best_match = None
  1397. best_diff = timedelta(hours=24)
  1398. for f in video_files:
  1399. mtime = f.get("mtime")
  1400. if mtime:
  1401. # Timelapse file should be modified during or shortly after the print
  1402. # The mtime should be close to completion time (video finishes when print ends)
  1403. if archive_end:
  1404. diff = abs(mtime - archive_end)
  1405. if diff < best_diff:
  1406. best_diff = diff
  1407. best_match = f
  1408. logger.debug(
  1409. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  1410. )
  1411. if best_match and best_diff < timedelta(hours=2):
  1412. matching_file = best_match
  1413. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  1414. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  1415. # This handles cases where printer clock is wrong or timezone issues exist
  1416. if not matching_file and len(video_files) == 1:
  1417. from datetime import datetime, timedelta, timezone
  1418. archive_completed = archive.completed_at or archive.created_at
  1419. if archive_completed:
  1420. if archive_completed.tzinfo is None:
  1421. archive_completed = archive_completed.replace(tzinfo=timezone.utc)
  1422. time_since_completion = datetime.now(timezone.utc) - archive_completed
  1423. # If archive was completed within the last hour, assume the single timelapse is for it
  1424. if time_since_completion < timedelta(hours=1):
  1425. matching_file = video_files[0]
  1426. logger.info("Using single timelapse file as fallback: %s", video_files[0].get("name"))
  1427. # Note: We intentionally don't use a "most recent file" fallback because
  1428. # we can't verify if timelapse was actually enabled for this print.
  1429. # Instead, return the list of available files for manual selection.
  1430. if not matching_file:
  1431. # Return available files for manual selection
  1432. available_files = [
  1433. {
  1434. "name": f.get("name"),
  1435. "path": f.get("path"),
  1436. "size": f.get("size"),
  1437. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  1438. }
  1439. for f in video_files
  1440. ]
  1441. # Sort by mtime descending (most recent first)
  1442. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  1443. return {
  1444. "status": "not_found",
  1445. "message": "No matching timelapse found - please select manually",
  1446. "available_files": available_files,
  1447. }
  1448. # Download the timelapse - use the full path from the file listing
  1449. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  1450. # Get FTP retry settings
  1451. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1452. if ftp_retry_enabled:
  1453. timelapse_data = await with_ftp_retry(
  1454. download_file_bytes_async,
  1455. printer.ip_address,
  1456. printer.access_code,
  1457. remote_path,
  1458. socket_timeout=ftp_timeout,
  1459. printer_model=printer.model,
  1460. max_retries=ftp_retry_count,
  1461. retry_delay=ftp_retry_delay,
  1462. operation_name=f"Download timelapse {matching_file['name']}",
  1463. )
  1464. else:
  1465. timelapse_data = await download_file_bytes_async(
  1466. printer.ip_address,
  1467. printer.access_code,
  1468. remote_path,
  1469. socket_timeout=ftp_timeout,
  1470. printer_model=printer.model,
  1471. )
  1472. if not timelapse_data:
  1473. raise HTTPException(500, "Failed to download timelapse")
  1474. # Attach timelapse to archive
  1475. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  1476. if not success:
  1477. raise HTTPException(500, "Failed to attach timelapse")
  1478. return {
  1479. "status": "attached",
  1480. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  1481. "filename": matching_file["name"],
  1482. }
  1483. @router.post("/{archive_id}/timelapse/select")
  1484. async def select_timelapse(
  1485. archive_id: int,
  1486. filename: str = Query(..., description="Timelapse filename to attach"),
  1487. db: AsyncSession = Depends(get_db),
  1488. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1489. ):
  1490. """Manually select a timelapse from the printer to attach."""
  1491. from backend.app.models.printer import Printer
  1492. from backend.app.services.bambu_ftp import (
  1493. download_file_bytes_async,
  1494. get_ftp_retry_settings,
  1495. list_files_async,
  1496. with_ftp_retry,
  1497. )
  1498. service = ArchiveService(db)
  1499. archive = await service.get_archive(archive_id)
  1500. if not archive:
  1501. raise HTTPException(404, "Archive not found")
  1502. if not archive.printer_id:
  1503. raise HTTPException(400, "Archive has no associated printer")
  1504. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1505. printer = result.scalar_one_or_none()
  1506. if not printer:
  1507. raise HTTPException(404, "Printer not found")
  1508. # Find the file on the printer
  1509. files = []
  1510. remote_path = None
  1511. for timelapse_dir in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1512. try:
  1513. files = await list_files_async(
  1514. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  1515. )
  1516. for f in files:
  1517. if f.get("name") == filename:
  1518. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  1519. break
  1520. if remote_path:
  1521. break
  1522. except Exception:
  1523. continue
  1524. if not remote_path:
  1525. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  1526. # Download and attach
  1527. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1528. if ftp_retry_enabled:
  1529. timelapse_data = await with_ftp_retry(
  1530. download_file_bytes_async,
  1531. printer.ip_address,
  1532. printer.access_code,
  1533. remote_path,
  1534. socket_timeout=ftp_timeout,
  1535. printer_model=printer.model,
  1536. max_retries=ftp_retry_count,
  1537. retry_delay=ftp_retry_delay,
  1538. operation_name=f"Download timelapse {filename}",
  1539. )
  1540. else:
  1541. timelapse_data = await download_file_bytes_async(
  1542. printer.ip_address,
  1543. printer.access_code,
  1544. remote_path,
  1545. socket_timeout=ftp_timeout,
  1546. printer_model=printer.model,
  1547. )
  1548. if not timelapse_data:
  1549. raise HTTPException(500, "Failed to download timelapse")
  1550. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1551. if not success:
  1552. raise HTTPException(500, "Failed to attach timelapse")
  1553. return {
  1554. "status": "attached",
  1555. "message": f"Timelapse '{filename}' attached successfully",
  1556. "filename": filename,
  1557. }
  1558. @router.post("/{archive_id}/timelapse/upload")
  1559. async def upload_timelapse(
  1560. archive_id: int,
  1561. file: UploadFile = File(...),
  1562. db: AsyncSession = Depends(get_db),
  1563. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1564. ):
  1565. """Manually upload a timelapse video to an archive."""
  1566. service = ArchiveService(db)
  1567. archive = await service.get_archive(archive_id)
  1568. if not archive:
  1569. raise HTTPException(404, "Archive not found")
  1570. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1571. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1572. content = await file.read()
  1573. success = await service.attach_timelapse(archive_id, content, file.filename)
  1574. if not success:
  1575. raise HTTPException(500, "Failed to attach timelapse")
  1576. return {"status": "attached", "filename": file.filename}
  1577. @router.get("/{archive_id}/timelapse/info")
  1578. async def get_timelapse_info(
  1579. archive_id: int,
  1580. db: AsyncSession = Depends(get_db),
  1581. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1582. ):
  1583. """Get timelapse video metadata for editor."""
  1584. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1585. from backend.app.services.timelapse_processor import TimelapseProcessor
  1586. service = ArchiveService(db)
  1587. archive = await service.get_archive(archive_id)
  1588. if not archive or not archive.timelapse_path:
  1589. raise HTTPException(404, "Timelapse not found")
  1590. timelapse_path = settings.base_dir / archive.timelapse_path
  1591. if not timelapse_path.exists():
  1592. raise HTTPException(404, "Timelapse file not found")
  1593. try:
  1594. processor = TimelapseProcessor(timelapse_path)
  1595. info = await processor.get_info()
  1596. return TimelapseInfoResponse(**info)
  1597. except Exception as e:
  1598. logger.error("Failed to get timelapse info: %s", e)
  1599. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1600. @router.get("/{archive_id}/timelapse/thumbnails")
  1601. async def get_timelapse_thumbnails(
  1602. archive_id: int,
  1603. count: int = Query(10, ge=1, le=30),
  1604. width: int = Query(160, ge=80, le=320),
  1605. db: AsyncSession = Depends(get_db),
  1606. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1607. ):
  1608. """Generate timeline thumbnail frames for visual scrubbing."""
  1609. import base64
  1610. from backend.app.schemas.timelapse import ThumbnailResponse
  1611. from backend.app.services.timelapse_processor import TimelapseProcessor
  1612. service = ArchiveService(db)
  1613. archive = await service.get_archive(archive_id)
  1614. if not archive or not archive.timelapse_path:
  1615. raise HTTPException(404, "Timelapse not found")
  1616. timelapse_path = settings.base_dir / archive.timelapse_path
  1617. if not timelapse_path.exists():
  1618. raise HTTPException(404, "Timelapse file not found")
  1619. try:
  1620. processor = TimelapseProcessor(timelapse_path)
  1621. thumbnails = await processor.generate_thumbnails(count, width)
  1622. return ThumbnailResponse(
  1623. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1624. timestamps=[ts for ts, _ in thumbnails],
  1625. )
  1626. except Exception as e:
  1627. logger.error("Failed to generate thumbnails: %s", e)
  1628. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1629. @router.post("/{archive_id}/timelapse/process")
  1630. async def process_timelapse(
  1631. archive_id: int,
  1632. trim_start: float = Form(0),
  1633. trim_end: float = Form(None),
  1634. speed: float = Form(1.0),
  1635. save_mode: str = Form("new"),
  1636. output_filename: str = Form(None),
  1637. audio: UploadFile = File(None),
  1638. db: AsyncSession = Depends(get_db),
  1639. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1640. ):
  1641. """Process timelapse with trim, speed, and optional audio overlay."""
  1642. import shutil
  1643. import tempfile
  1644. from backend.app.schemas.timelapse import ProcessResponse
  1645. from backend.app.services.timelapse_processor import TimelapseProcessor
  1646. # Validate speed
  1647. if not 0.25 <= speed <= 4.0:
  1648. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1649. if save_mode not in ("replace", "new"):
  1650. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1651. service = ArchiveService(db)
  1652. archive = await service.get_archive(archive_id)
  1653. if not archive or not archive.timelapse_path:
  1654. raise HTTPException(404, "Timelapse not found")
  1655. timelapse_path = settings.base_dir / archive.timelapse_path
  1656. if not timelapse_path.exists():
  1657. raise HTTPException(404, "Timelapse file not found")
  1658. archive_dir = timelapse_path.parent
  1659. # Handle audio file
  1660. audio_temp_path = None
  1661. if audio and audio.filename:
  1662. # Validate audio file extension
  1663. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1664. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1665. audio_content = await audio.read()
  1666. # Extract and validate suffix to prevent path injection
  1667. suffix = Path(audio.filename).suffix.lower()
  1668. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  1669. raise HTTPException(400, "Invalid audio file extension")
  1670. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1671. audio_temp_path.write_bytes(audio_content)
  1672. try:
  1673. processor = TimelapseProcessor(timelapse_path)
  1674. # Determine output path
  1675. if save_mode == "replace":
  1676. # Process to temp file first, then replace
  1677. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1678. output_path = temp_output
  1679. else:
  1680. # Save as new file alongside original
  1681. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1682. # Sanitize filename - remove path separators and traversal sequences
  1683. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1684. # Prevent path traversal
  1685. if ".." in filename or not filename or filename.startswith("."):
  1686. filename = f"timelapse_{archive_id}_edited"
  1687. if not filename.endswith(".mp4"):
  1688. filename += ".mp4"
  1689. output_path = archive_dir / filename
  1690. success = await processor.process(
  1691. output_path=output_path,
  1692. trim_start=trim_start,
  1693. trim_end=trim_end,
  1694. speed=speed,
  1695. audio_path=audio_temp_path,
  1696. )
  1697. if not success:
  1698. raise HTTPException(500, "Video processing failed")
  1699. # Handle save mode
  1700. if save_mode == "replace":
  1701. # Replace original file
  1702. shutil.move(str(output_path), str(timelapse_path))
  1703. final_path = archive.timelapse_path
  1704. message = "Timelapse replaced successfully"
  1705. else:
  1706. final_path = str(output_path.relative_to(settings.base_dir))
  1707. message = f"Saved as {output_path.name}"
  1708. return ProcessResponse(
  1709. status="completed",
  1710. output_path=final_path,
  1711. message=message,
  1712. )
  1713. except HTTPException:
  1714. raise
  1715. except Exception as e:
  1716. logger.error("Timelapse processing failed: %s", e)
  1717. raise HTTPException(500, f"Processing failed: {str(e)}")
  1718. finally:
  1719. # Cleanup temp audio file
  1720. if audio_temp_path and audio_temp_path.exists():
  1721. audio_temp_path.unlink()
  1722. # ============================================
  1723. # Photo Endpoints
  1724. # ============================================
  1725. @router.post("/{archive_id}/photos")
  1726. async def upload_photo(
  1727. archive_id: int,
  1728. file: UploadFile = File(...),
  1729. db: AsyncSession = Depends(get_db),
  1730. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  1731. ):
  1732. """Upload a photo of the printed result."""
  1733. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1734. archive = result.scalar_one_or_none()
  1735. if not archive:
  1736. raise HTTPException(404, "Archive not found")
  1737. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1738. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1739. # Get archive directory
  1740. archive_dir = settings.base_dir / Path(archive.file_path).parent
  1741. photos_dir = archive_dir / "photos"
  1742. photos_dir.mkdir(exist_ok=True)
  1743. # Generate unique filename
  1744. import uuid
  1745. ext = Path(file.filename).suffix.lower()
  1746. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1747. photo_path = photos_dir / photo_filename
  1748. # Save file
  1749. content = await file.read()
  1750. photo_path.write_bytes(content)
  1751. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1752. photos = list(archive.photos or [])
  1753. photos.append(photo_filename)
  1754. archive.photos = photos
  1755. await db.commit()
  1756. await db.refresh(archive)
  1757. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1758. @router.get("/{archive_id}/photos/{filename}")
  1759. async def get_photo(
  1760. archive_id: int,
  1761. filename: str,
  1762. db: AsyncSession = Depends(get_db),
  1763. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1764. ):
  1765. """Get a specific photo.
  1766. Requires a stream token query param (?token=xxx) when auth is enabled.
  1767. """
  1768. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1769. archive = result.scalar_one_or_none()
  1770. if not archive:
  1771. raise HTTPException(404, "Archive not found")
  1772. archive_dir = settings.base_dir / Path(archive.file_path).parent
  1773. photo_path = archive_dir / "photos" / filename
  1774. if not photo_path.exists():
  1775. raise HTTPException(404, "Photo not found")
  1776. # Determine media type
  1777. ext = Path(filename).suffix.lower()
  1778. media_types = {
  1779. ".jpg": "image/jpeg",
  1780. ".jpeg": "image/jpeg",
  1781. ".png": "image/png",
  1782. ".webp": "image/webp",
  1783. }
  1784. media_type = media_types.get(ext, "image/jpeg")
  1785. return FileResponse(path=photo_path, media_type=media_type)
  1786. @router.delete("/{archive_id}/photos/{filename}")
  1787. async def delete_photo(
  1788. archive_id: int,
  1789. filename: str,
  1790. db: AsyncSession = Depends(get_db),
  1791. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  1792. ):
  1793. """Delete a photo."""
  1794. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1795. archive = result.scalar_one_or_none()
  1796. if not archive:
  1797. raise HTTPException(404, "Archive not found")
  1798. if not archive.photos or filename not in archive.photos:
  1799. raise HTTPException(404, "Photo not found")
  1800. # Delete file
  1801. archive_dir = settings.base_dir / Path(archive.file_path).parent
  1802. photo_path = archive_dir / "photos" / filename
  1803. if photo_path.exists():
  1804. photo_path.unlink()
  1805. # Update archive photos list
  1806. photos = [p for p in archive.photos if p != filename]
  1807. archive.photos = photos if photos else None
  1808. await db.commit()
  1809. return {"status": "deleted", "photos": archive.photos}
  1810. # ============================================
  1811. # QR Code Endpoint
  1812. # ============================================
  1813. @router.get("/{archive_id}/qrcode")
  1814. async def get_qrcode(
  1815. archive_id: int,
  1816. request: Request,
  1817. size: int = 200,
  1818. db: AsyncSession = Depends(get_db),
  1819. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1820. ):
  1821. """Generate a QR code that links to this archive.
  1822. Requires a stream token query param (?token=xxx) when auth is enabled.
  1823. """
  1824. try:
  1825. import qrcode
  1826. from PIL import Image as PILImage
  1827. except ImportError:
  1828. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1829. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1830. archive = result.scalar_one_or_none()
  1831. if not archive:
  1832. raise HTTPException(404, "Archive not found")
  1833. # Build URL to archive download
  1834. base_url = str(request.base_url).rstrip("/")
  1835. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1836. # Generate QR code
  1837. qr = qrcode.QRCode(
  1838. version=1,
  1839. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1840. box_size=10,
  1841. border=2,
  1842. )
  1843. qr.add_data(archive_url)
  1844. qr.make(fit=True)
  1845. img = qr.make_image(fill_color="black", back_color="white")
  1846. # Convert to PIL Image for resizing
  1847. pil_img = img.get_image()
  1848. # Resize if needed
  1849. if size != 200:
  1850. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1851. # Convert to bytes
  1852. buffer = io.BytesIO()
  1853. pil_img.save(buffer, format="PNG")
  1854. buffer.seek(0)
  1855. return Response(
  1856. content=buffer.getvalue(),
  1857. media_type="image/png",
  1858. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1859. )
  1860. @router.get("/{archive_id}/capabilities")
  1861. async def get_archive_capabilities(
  1862. archive_id: int,
  1863. db: AsyncSession = Depends(get_db),
  1864. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1865. ):
  1866. """Check what viewing capabilities are available for this 3MF file."""
  1867. import defusedxml.ElementTree as ET
  1868. service = ArchiveService(db)
  1869. archive = await service.get_archive(archive_id)
  1870. if not archive:
  1871. raise HTTPException(404, "Archive not found")
  1872. file_path = settings.base_dir / archive.file_path
  1873. if not file_path.is_file():
  1874. raise HTTPException(404, "File not found")
  1875. has_model = False
  1876. has_gcode = False
  1877. has_source = False
  1878. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1879. filament_colors: list[str] = []
  1880. # Check if source 3MF exists - this is where actual mesh data typically lives
  1881. source_path = None
  1882. if archive.source_3mf_path:
  1883. source_path = settings.base_dir / archive.source_3mf_path
  1884. if source_path.exists():
  1885. has_source = True
  1886. # Helper function to check for mesh data and extract colors from a 3MF file
  1887. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1888. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1889. found_mesh = False
  1890. colors: list[str] = []
  1891. volume = {"x": 256, "y": 256, "z": 256}
  1892. try:
  1893. with zipfile.ZipFile(zf_path, "r") as zf:
  1894. names = zf.namelist()
  1895. # Check for 3D model - look for actual mesh data
  1896. for name in names:
  1897. if name.endswith(".model"):
  1898. try:
  1899. content = zf.read(name).decode("utf-8")
  1900. if "<vertex" in content or "<mesh" in content:
  1901. found_mesh = True
  1902. break
  1903. except Exception:
  1904. pass # Skip unreadable .model entries in archive
  1905. # Extract filament colors from project_settings.config
  1906. if "Metadata/project_settings.config" in names:
  1907. try:
  1908. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1909. config_data = json.loads(config_content)
  1910. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1911. printable_area = config_data.get("printable_area", [])
  1912. if printable_area and len(printable_area) >= 3:
  1913. max_x = 0
  1914. max_y = 0
  1915. for coord in printable_area:
  1916. if "x" in coord:
  1917. parts = coord.split("x")
  1918. if len(parts) == 2:
  1919. try:
  1920. x, y = int(parts[0]), int(parts[1])
  1921. max_x = max(max_x, x)
  1922. max_y = max(max_y, y)
  1923. except ValueError:
  1924. pass # Skip non-numeric printable_area coordinate
  1925. if max_x > 0 and max_y > 0:
  1926. volume["x"] = max_x
  1927. volume["y"] = max_y
  1928. # Parse printable_height
  1929. printable_height = config_data.get("printable_height")
  1930. if printable_height:
  1931. try:
  1932. volume["z"] = int(printable_height)
  1933. except (ValueError, TypeError):
  1934. pass # Skip unparseable printable_height value
  1935. # Extract filament colors
  1936. raw_colors = config_data.get("filament_colour", [])
  1937. if raw_colors:
  1938. for color in raw_colors:
  1939. if color and isinstance(color, str):
  1940. colors.append(color)
  1941. except Exception:
  1942. pass # Skip malformed project_settings.config
  1943. except zipfile.BadZipFile:
  1944. pass # File is not a valid zip/3MF archive
  1945. return found_mesh, colors, volume
  1946. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1947. if has_source and source_path:
  1948. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1949. if source_has_mesh:
  1950. has_model = True
  1951. if source_colors:
  1952. filament_colors = source_colors
  1953. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1954. build_volume = source_volume
  1955. try:
  1956. with zipfile.ZipFile(file_path, "r") as zf:
  1957. names = zf.namelist()
  1958. # Check for G-code in the sliced file
  1959. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1960. # Check for 3D model in sliced file (fallback if no source)
  1961. if not has_model:
  1962. for name in names:
  1963. if name.endswith(".model"):
  1964. try:
  1965. content = zf.read(name).decode("utf-8")
  1966. if "<vertex" in content or "<mesh" in content:
  1967. has_model = True
  1968. break
  1969. except Exception:
  1970. pass # Skip unreadable .model entries in archive
  1971. # Extract filament colors from slice_info.config (for gcode preview)
  1972. # These are the actual filaments used in the print, indexed by tool/extruder
  1973. slice_colors: list[str] = []
  1974. if "Metadata/slice_info.config" in names:
  1975. try:
  1976. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1977. root = ET.fromstring(slice_content)
  1978. filaments = root.findall(".//filament")
  1979. filament_map: dict[int, str] = {}
  1980. for f in filaments:
  1981. fid = f.get("id")
  1982. fcolor = f.get("color")
  1983. used_g = f.get("used_g", "0")
  1984. try:
  1985. used_amount = float(used_g)
  1986. except (ValueError, TypeError):
  1987. used_amount = 0
  1988. if fid is not None and fcolor:
  1989. try:
  1990. tool_id = int(fid) - 1
  1991. if tool_id >= 0 and used_amount > 0:
  1992. filament_map[tool_id] = fcolor
  1993. except ValueError:
  1994. pass # Skip filament entry with non-numeric ID
  1995. if filament_map:
  1996. max_tool = max(filament_map.keys())
  1997. for i in range(max_tool + 1):
  1998. slice_colors.append(filament_map.get(i, "#00AE42"))
  1999. except Exception:
  2000. pass # Skip malformed slice_info.config XML
  2001. # Use slice_info colors if we don't have colors from source yet
  2002. if not filament_colors and slice_colors:
  2003. filament_colors = slice_colors
  2004. # Extract build volume from sliced file if not already set from source
  2005. if build_volume["x"] == 256 and build_volume["y"] == 256:
  2006. if "Metadata/project_settings.config" in names:
  2007. try:
  2008. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2009. config_data = json.loads(config_content)
  2010. printable_area = config_data.get("printable_area", [])
  2011. if printable_area and len(printable_area) >= 3:
  2012. max_x = 0
  2013. max_y = 0
  2014. for coord in printable_area:
  2015. if "x" in coord:
  2016. parts = coord.split("x")
  2017. if len(parts) == 2:
  2018. try:
  2019. x, y = int(parts[0]), int(parts[1])
  2020. max_x = max(max_x, x)
  2021. max_y = max(max_y, y)
  2022. except ValueError:
  2023. pass # Skip non-numeric printable_area coordinate
  2024. if max_x > 0 and max_y > 0:
  2025. build_volume["x"] = max_x
  2026. build_volume["y"] = max_y
  2027. printable_height = config_data.get("printable_height")
  2028. if printable_height:
  2029. try:
  2030. build_volume["z"] = int(printable_height)
  2031. except (ValueError, TypeError):
  2032. pass # Skip unparseable printable_height value
  2033. # Fallback colors from project_settings if still empty
  2034. if not filament_colors:
  2035. raw_colors = config_data.get("filament_colour", [])
  2036. if raw_colors:
  2037. for color in raw_colors:
  2038. if color and isinstance(color, str):
  2039. filament_colors.append(color)
  2040. except Exception:
  2041. pass # Skip malformed project_settings.config
  2042. except zipfile.BadZipFile:
  2043. raise HTTPException(400, "Invalid 3MF file")
  2044. return {
  2045. "has_model": has_model,
  2046. "has_gcode": has_gcode,
  2047. "has_source": has_source,
  2048. "build_volume": build_volume,
  2049. "filament_colors": filament_colors,
  2050. }
  2051. @router.get("/{archive_id}/gcode")
  2052. async def get_gcode(
  2053. archive_id: int,
  2054. db: AsyncSession = Depends(get_db),
  2055. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2056. ):
  2057. """Extract and return G-code from the 3MF file."""
  2058. service = ArchiveService(db)
  2059. archive = await service.get_archive(archive_id)
  2060. if not archive:
  2061. raise HTTPException(404, "Archive not found")
  2062. file_path = settings.base_dir / archive.file_path
  2063. if not file_path.is_file():
  2064. raise HTTPException(404, "File not found")
  2065. try:
  2066. with zipfile.ZipFile(file_path, "r") as zf:
  2067. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  2068. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  2069. if not gcode_files:
  2070. raise HTTPException(
  2071. 404,
  2072. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  2073. )
  2074. # Get the first plate's G-code (usually plate_1.gcode)
  2075. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  2076. return Response(content=gcode_content, media_type="text/plain")
  2077. except zipfile.BadZipFile:
  2078. raise HTTPException(400, "Invalid 3MF file")
  2079. except HTTPException:
  2080. raise
  2081. except Exception as e:
  2082. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  2083. @router.get("/{archive_id}/plate-preview")
  2084. async def get_plate_preview(
  2085. archive_id: int,
  2086. db: AsyncSession = Depends(get_db),
  2087. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2088. ):
  2089. """Get the plate preview image from the 3MF file.
  2090. Returns the slicer-generated plate thumbnail which shows the model
  2091. with correct colors and positioning.
  2092. Requires a stream token query param (?token=xxx) when auth is enabled.
  2093. """
  2094. service = ArchiveService(db)
  2095. archive = await service.get_archive(archive_id)
  2096. if not archive:
  2097. raise HTTPException(404, "Archive not found")
  2098. file_path = settings.base_dir / archive.file_path
  2099. if not file_path.is_file():
  2100. raise HTTPException(404, "File not found")
  2101. try:
  2102. with zipfile.ZipFile(file_path, "r") as zf:
  2103. names = zf.namelist()
  2104. # Try to find plate preview images in order of preference
  2105. # First look for the specific plate being printed (check slice_info for plate index)
  2106. plate_num = 1
  2107. if "Metadata/slice_info.config" in names:
  2108. try:
  2109. import defusedxml.ElementTree as ET
  2110. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2111. root = ET.fromstring(slice_content)
  2112. plate_elem = root.find(".//plate/metadata[@key='index']")
  2113. if plate_elem is not None:
  2114. plate_num = int(plate_elem.get("value", "1"))
  2115. except Exception:
  2116. pass # Default plate_num=1 if slice_info is missing or malformed
  2117. # Try plate-specific image first, then fall back to plate_1
  2118. preview_paths = [
  2119. f"Metadata/plate_{plate_num}.png",
  2120. "Metadata/plate_1.png",
  2121. "Metadata/thumbnail.png",
  2122. ]
  2123. for preview_path in preview_paths:
  2124. if preview_path in names:
  2125. image_data = zf.read(preview_path)
  2126. return Response(content=image_data, media_type="image/png")
  2127. # If no plate image, try any PNG in Metadata
  2128. for name in names:
  2129. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  2130. image_data = zf.read(name)
  2131. return Response(content=image_data, media_type="image/png")
  2132. raise HTTPException(404, "No plate preview found in 3MF file")
  2133. except zipfile.BadZipFile:
  2134. raise HTTPException(400, "Invalid 3MF file")
  2135. except HTTPException:
  2136. raise
  2137. except Exception as e:
  2138. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  2139. @router.post("/upload")
  2140. async def upload_archive(
  2141. file: UploadFile = File(...),
  2142. printer_id: int | None = None,
  2143. db: AsyncSession = Depends(get_db),
  2144. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2145. ):
  2146. """Manually upload a 3MF file to archive."""
  2147. if not file.filename or not file.filename.endswith(".3mf"):
  2148. raise HTTPException(400, "File must be a .3mf file")
  2149. # Save uploaded file temporarily
  2150. temp_path = settings.archive_dir / "temp" / file.filename
  2151. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2152. try:
  2153. content = await file.read()
  2154. temp_path.write_bytes(content)
  2155. service = ArchiveService(db)
  2156. archive = await service.archive_print(
  2157. printer_id=printer_id,
  2158. source_file=temp_path,
  2159. created_by_id=current_user.id if current_user else None,
  2160. )
  2161. if not archive:
  2162. raise HTTPException(400, "Failed to archive file")
  2163. return ArchiveResponse.model_validate(archive)
  2164. finally:
  2165. if temp_path.exists():
  2166. temp_path.unlink()
  2167. @router.post("/upload-bulk")
  2168. async def upload_archives_bulk(
  2169. files: list[UploadFile] = File(...),
  2170. printer_id: int | None = None,
  2171. db: AsyncSession = Depends(get_db),
  2172. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2173. ):
  2174. """Bulk upload multiple 3MF files to archive."""
  2175. results = []
  2176. errors = []
  2177. for file in files:
  2178. if not file.filename or not file.filename.endswith(".3mf"):
  2179. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  2180. continue
  2181. temp_path = settings.archive_dir / "temp" / file.filename
  2182. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2183. try:
  2184. content = await file.read()
  2185. temp_path.write_bytes(content)
  2186. service = ArchiveService(db)
  2187. archive = await service.archive_print(
  2188. printer_id=printer_id,
  2189. source_file=temp_path,
  2190. created_by_id=current_user.id if current_user else None,
  2191. )
  2192. if archive:
  2193. results.append(
  2194. {
  2195. "filename": file.filename,
  2196. "id": archive.id,
  2197. "status": "success",
  2198. }
  2199. )
  2200. else:
  2201. errors.append({"filename": file.filename, "error": "Failed to process"})
  2202. except Exception as e:
  2203. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  2204. errors.append({"filename": file.filename, "error": "Failed to process file"})
  2205. finally:
  2206. if temp_path.exists():
  2207. temp_path.unlink()
  2208. return {
  2209. "uploaded": len(results),
  2210. "failed": len(errors),
  2211. "results": results,
  2212. "errors": errors,
  2213. }
  2214. @router.get("/{archive_id}/plates")
  2215. async def get_archive_plates(
  2216. archive_id: int,
  2217. db: AsyncSession = Depends(get_db),
  2218. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2219. ):
  2220. """Get available plates from a multi-plate 3MF archive.
  2221. Returns a list of plates with their index, name, thumbnail availability,
  2222. and filament requirements. For single-plate exports, returns a single plate.
  2223. """
  2224. import re
  2225. import defusedxml.ElementTree as ET
  2226. service = ArchiveService(db)
  2227. archive = await service.get_archive(archive_id)
  2228. if not archive:
  2229. raise HTTPException(404, "Archive not found")
  2230. file_path = settings.base_dir / archive.file_path
  2231. if not file_path.is_file():
  2232. raise HTTPException(404, "Archive file not found")
  2233. plates = []
  2234. try:
  2235. with zipfile.ZipFile(file_path, "r") as zf:
  2236. namelist = zf.namelist()
  2237. # Find all plate gcode files to determine available plates
  2238. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  2239. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  2240. plate_indices: list[int] = []
  2241. if gcode_files:
  2242. # Extract plate indices from gcode filenames
  2243. for gf in gcode_files:
  2244. # "Metadata/plate_5.gcode" -> 5
  2245. try:
  2246. # Remove "Metadata/plate_" and ".gcode"
  2247. plate_str = gf[15:-6]
  2248. plate_indices.append(int(plate_str))
  2249. except ValueError:
  2250. pass # Skip gcode file with non-numeric plate index
  2251. else:
  2252. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  2253. plate_png_files = [
  2254. n
  2255. for n in namelist
  2256. if n.startswith("Metadata/plate_")
  2257. and n.endswith(".png")
  2258. and "_small" not in n
  2259. and "no_light" not in n
  2260. ]
  2261. plate_name_candidates = plate_json_files + plate_png_files
  2262. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  2263. seen_indices: set[int] = set()
  2264. for name in plate_name_candidates:
  2265. match = plate_re.match(name)
  2266. if match:
  2267. try:
  2268. index = int(match.group(1))
  2269. except ValueError:
  2270. continue
  2271. if index in seen_indices:
  2272. continue
  2273. seen_indices.add(index)
  2274. plate_indices.append(index)
  2275. if not plate_indices:
  2276. # No plate metadata found
  2277. return {
  2278. "archive_id": archive_id,
  2279. "filename": archive.filename,
  2280. "plates": [],
  2281. "is_multi_plate": False,
  2282. }
  2283. plate_indices.sort()
  2284. # Parse model_settings.config for plate names + object assignments
  2285. # Plate names are stored with plater_id and plater_name keys
  2286. plate_names = {} # plater_id -> name
  2287. plate_object_ids: dict[int, list[str]] = {}
  2288. object_names_by_id: dict[str, str] = {}
  2289. if "Metadata/model_settings.config" in namelist:
  2290. try:
  2291. model_content = zf.read("Metadata/model_settings.config").decode()
  2292. model_root = ET.fromstring(model_content)
  2293. # Build object ID -> name map
  2294. for obj_elem in model_root.findall(".//object"):
  2295. obj_id = obj_elem.get("id")
  2296. if not obj_id:
  2297. continue
  2298. name_meta = obj_elem.find("metadata[@key='name']")
  2299. obj_name = name_meta.get("value") if name_meta is not None else None
  2300. if obj_name:
  2301. object_names_by_id[obj_id] = obj_name
  2302. for plate_elem in model_root.findall(".//plate"):
  2303. plater_id = None
  2304. plater_name = None
  2305. for meta in plate_elem.findall("metadata"):
  2306. key = meta.get("key")
  2307. value = meta.get("value")
  2308. if key == "plater_id" and value:
  2309. try:
  2310. plater_id = int(value)
  2311. except ValueError:
  2312. pass # Skip plate with non-numeric plater_id
  2313. elif key == "plater_name" and value:
  2314. plater_name = value.strip()
  2315. if plater_id is not None and plater_name:
  2316. plate_names[plater_id] = plater_name
  2317. if plater_id is not None:
  2318. for instance_elem in plate_elem.findall("model_instance"):
  2319. for inst_meta in instance_elem.findall("metadata"):
  2320. if inst_meta.get("key") == "object_id":
  2321. obj_id = inst_meta.get("value")
  2322. if not obj_id:
  2323. continue
  2324. plate_object_ids.setdefault(plater_id, [])
  2325. if obj_id not in plate_object_ids[plater_id]:
  2326. plate_object_ids[plater_id].append(obj_id)
  2327. except Exception:
  2328. pass # model_settings.config parsing is optional
  2329. # Parse slice_info.config for plate metadata
  2330. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  2331. if "Metadata/slice_info.config" in namelist:
  2332. content = zf.read("Metadata/slice_info.config").decode()
  2333. root = ET.fromstring(content)
  2334. for plate_elem in root.findall(".//plate"):
  2335. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  2336. # Get plate index from metadata
  2337. plate_index = None
  2338. for meta in plate_elem.findall("metadata"):
  2339. key = meta.get("key")
  2340. value = meta.get("value")
  2341. if key == "index" and value:
  2342. try:
  2343. plate_index = int(value)
  2344. except ValueError:
  2345. pass # Skip plate with non-numeric index
  2346. elif key == "prediction" and value:
  2347. try:
  2348. plate_info["prediction"] = int(value)
  2349. except ValueError:
  2350. pass # Skip non-numeric print time prediction
  2351. elif key == "weight" and value:
  2352. try:
  2353. plate_info["weight"] = float(value)
  2354. except ValueError:
  2355. pass # Skip non-numeric filament weight
  2356. # Get filaments used in this plate
  2357. for filament_elem in plate_elem.findall("filament"):
  2358. filament_id = filament_elem.get("id")
  2359. filament_type = filament_elem.get("type", "")
  2360. filament_color = filament_elem.get("color", "")
  2361. used_g = filament_elem.get("used_g", "0")
  2362. used_m = filament_elem.get("used_m", "0")
  2363. try:
  2364. used_grams = float(used_g)
  2365. except (ValueError, TypeError):
  2366. used_grams = 0
  2367. if used_grams > 0 and filament_id:
  2368. plate_info["filaments"].append(
  2369. {
  2370. "slot_id": int(filament_id),
  2371. "type": filament_type,
  2372. "color": filament_color,
  2373. "used_grams": round(used_grams, 1),
  2374. "used_meters": float(used_m) if used_m else 0,
  2375. }
  2376. )
  2377. # Sort filaments by slot ID
  2378. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  2379. # Collect all object names on this plate
  2380. for obj_elem in plate_elem.findall("object"):
  2381. obj_name = obj_elem.get("name")
  2382. if obj_name and obj_name not in plate_info["objects"]:
  2383. plate_info["objects"].append(obj_name)
  2384. # Set plate name: prefer custom name from model_settings.config,
  2385. # fall back to first object name if no custom name was set
  2386. if plate_index is not None:
  2387. custom_name = plate_names.get(plate_index)
  2388. if custom_name:
  2389. plate_info["name"] = custom_name
  2390. else:
  2391. # Fall back to first object name as hint
  2392. if plate_info["objects"]:
  2393. plate_info["name"] = plate_info["objects"][0]
  2394. plate_metadata[plate_index] = plate_info
  2395. # Parse plate_*.json for object lists when slice_info is missing
  2396. plate_json_objects: dict[int, list[str]] = {}
  2397. for name in namelist:
  2398. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  2399. if not match:
  2400. continue
  2401. try:
  2402. plate_index = int(match.group(1))
  2403. except ValueError:
  2404. continue
  2405. try:
  2406. payload = json.loads(zf.read(name).decode())
  2407. bbox_objects = payload.get("bbox_objects", [])
  2408. names = []
  2409. for obj in bbox_objects:
  2410. obj_name = obj.get("name") if isinstance(obj, dict) else None
  2411. if obj_name and obj_name not in names:
  2412. names.append(obj_name)
  2413. if names:
  2414. plate_json_objects[plate_index] = names
  2415. except Exception:
  2416. continue
  2417. # Build plate list
  2418. for idx in plate_indices:
  2419. meta = plate_metadata.get(idx, {})
  2420. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  2421. objects = meta.get("objects", [])
  2422. if not objects:
  2423. objects = plate_json_objects.get(idx, [])
  2424. if not objects and plate_object_ids.get(idx):
  2425. objects = [
  2426. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  2427. ]
  2428. plate_name = meta.get("name")
  2429. if not plate_name:
  2430. plate_name = plate_names.get(idx)
  2431. if not plate_name and objects:
  2432. plate_name = objects[0]
  2433. plates.append(
  2434. {
  2435. "index": idx,
  2436. "name": plate_name,
  2437. "objects": objects,
  2438. "object_count": len(objects),
  2439. "has_thumbnail": has_thumbnail,
  2440. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  2441. if has_thumbnail
  2442. else None,
  2443. "print_time_seconds": meta.get("prediction"),
  2444. "filament_used_grams": meta.get("weight"),
  2445. "filaments": meta.get("filaments", []),
  2446. }
  2447. )
  2448. except Exception as e:
  2449. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  2450. return {
  2451. "archive_id": archive_id,
  2452. "filename": archive.filename,
  2453. "plates": plates,
  2454. "is_multi_plate": len(plates) > 1,
  2455. }
  2456. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  2457. async def get_plate_thumbnail(
  2458. archive_id: int,
  2459. plate_index: int,
  2460. db: AsyncSession = Depends(get_db),
  2461. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2462. ):
  2463. """Get the thumbnail image for a specific plate.
  2464. Requires a stream token query param (?token=xxx) when auth is enabled.
  2465. """
  2466. service = ArchiveService(db)
  2467. archive = await service.get_archive(archive_id)
  2468. if not archive:
  2469. raise HTTPException(404, "Archive not found")
  2470. file_path = settings.base_dir / archive.file_path
  2471. if not file_path.is_file():
  2472. raise HTTPException(404, "Archive file not found")
  2473. try:
  2474. with zipfile.ZipFile(file_path, "r") as zf:
  2475. thumb_path = f"Metadata/plate_{plate_index}.png"
  2476. if thumb_path in zf.namelist():
  2477. data = zf.read(thumb_path)
  2478. return Response(content=data, media_type="image/png")
  2479. except Exception:
  2480. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  2481. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  2482. @router.get("/{archive_id}/filament-requirements")
  2483. async def get_filament_requirements(
  2484. archive_id: int,
  2485. plate_id: int | None = None,
  2486. db: AsyncSession = Depends(get_db),
  2487. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2488. ):
  2489. """Get filament requirements from the archived 3MF file.
  2490. Returns the filaments used in this print with their slot IDs, types, colors,
  2491. and usage amounts. This can be compared with current AMS state before reprinting.
  2492. Args:
  2493. archive_id: The archive ID
  2494. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  2495. """
  2496. import defusedxml.ElementTree as ET
  2497. service = ArchiveService(db)
  2498. archive = await service.get_archive(archive_id)
  2499. if not archive:
  2500. raise HTTPException(404, "Archive not found")
  2501. file_path = settings.base_dir / archive.file_path
  2502. if not file_path.is_file():
  2503. raise HTTPException(404, "Archive file not found")
  2504. filaments = []
  2505. try:
  2506. with zipfile.ZipFile(file_path, "r") as zf:
  2507. # Parse slice_info.config for filament requirements
  2508. if "Metadata/slice_info.config" in zf.namelist():
  2509. content = zf.read("Metadata/slice_info.config").decode()
  2510. root = ET.fromstring(content)
  2511. # If plate_id is specified, find filaments for that specific plate
  2512. if plate_id is not None:
  2513. # Find the plate element with matching index
  2514. for plate_elem in root.findall(".//plate"):
  2515. plate_index = None
  2516. for meta in plate_elem.findall("metadata"):
  2517. if meta.get("key") == "index":
  2518. try:
  2519. plate_index = int(meta.get("value", "0"))
  2520. except ValueError:
  2521. pass # Skip plate with non-numeric index metadata
  2522. break
  2523. if plate_index == plate_id:
  2524. # Extract filaments from this plate element
  2525. for filament_elem in plate_elem.findall("filament"):
  2526. filament_id = filament_elem.get("id")
  2527. filament_type = filament_elem.get("type", "")
  2528. filament_color = filament_elem.get("color", "")
  2529. used_g = filament_elem.get("used_g", "0")
  2530. used_m = filament_elem.get("used_m", "0")
  2531. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2532. try:
  2533. used_grams = float(used_g)
  2534. except (ValueError, TypeError):
  2535. used_grams = 0
  2536. if used_grams > 0 and filament_id:
  2537. filaments.append(
  2538. {
  2539. "slot_id": int(filament_id),
  2540. "type": filament_type,
  2541. "color": filament_color,
  2542. "used_grams": round(used_grams, 1),
  2543. "used_meters": float(used_m) if used_m else 0,
  2544. "tray_info_idx": tray_info_idx,
  2545. }
  2546. )
  2547. break
  2548. else:
  2549. # No plate_id specified - extract all filaments with used_g > 0
  2550. # This is the legacy behavior for single-plate files
  2551. for filament_elem in root.findall(".//filament"):
  2552. filament_id = filament_elem.get("id")
  2553. filament_type = filament_elem.get("type", "")
  2554. filament_color = filament_elem.get("color", "")
  2555. used_g = filament_elem.get("used_g", "0")
  2556. used_m = filament_elem.get("used_m", "0")
  2557. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2558. # Only include filaments that are actually used
  2559. try:
  2560. used_grams = float(used_g)
  2561. except (ValueError, TypeError):
  2562. used_grams = 0
  2563. if used_grams > 0 and filament_id:
  2564. filaments.append(
  2565. {
  2566. "slot_id": int(filament_id),
  2567. "type": filament_type,
  2568. "color": filament_color,
  2569. "used_grams": round(used_grams, 1),
  2570. "used_meters": float(used_m) if used_m else 0,
  2571. "tray_info_idx": tray_info_idx,
  2572. }
  2573. )
  2574. # Sort by slot ID
  2575. filaments.sort(key=lambda x: x["slot_id"])
  2576. # Enrich with nozzle mapping for dual-nozzle printers
  2577. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  2578. if nozzle_mapping:
  2579. for filament in filaments:
  2580. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  2581. except Exception as e:
  2582. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  2583. return {
  2584. "archive_id": archive_id,
  2585. "filename": archive.filename,
  2586. "plate_id": plate_id,
  2587. "filaments": filaments,
  2588. }
  2589. @router.post("/{archive_id}/reprint")
  2590. async def reprint_archive(
  2591. archive_id: int,
  2592. printer_id: int,
  2593. body: ReprintRequest | None = None,
  2594. db: AsyncSession = Depends(get_db),
  2595. auth_result: tuple[User | None, bool] = Depends(
  2596. require_ownership_permission(
  2597. Permission.ARCHIVES_REPRINT_ALL,
  2598. Permission.ARCHIVES_REPRINT_OWN,
  2599. )
  2600. ),
  2601. ):
  2602. """Dispatch an archived 3MF file for send/start on a printer."""
  2603. from backend.app.models.printer import Printer
  2604. from backend.app.services.background_dispatch import DispatchEnqueueRejected, background_dispatch
  2605. from backend.app.services.printer_manager import printer_manager
  2606. user, can_modify_all = auth_result
  2607. # Use defaults if no body provided
  2608. if body is None:
  2609. body = ReprintRequest()
  2610. # Get archive
  2611. service = ArchiveService(db)
  2612. archive = await service.get_archive(archive_id)
  2613. if not archive:
  2614. raise HTTPException(404, "Archive not found")
  2615. # Ownership check
  2616. if not can_modify_all:
  2617. if archive.created_by_id != user.id:
  2618. raise HTTPException(403, "You can only reprint your own archives")
  2619. # Get printer
  2620. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2621. printer = result.scalar_one_or_none()
  2622. if not printer:
  2623. raise HTTPException(404, "Printer not found")
  2624. # Check printer is connected
  2625. if not printer_manager.is_connected(printer_id):
  2626. raise HTTPException(400, "Printer is not connected")
  2627. if not archive.file_path:
  2628. raise HTTPException(
  2629. 404,
  2630. "No 3MF file available for this archive. "
  2631. "The file could not be downloaded from the printer when the print was recorded.",
  2632. )
  2633. # Validate archive file exists
  2634. file_path = settings.base_dir / archive.file_path
  2635. if not file_path.is_file():
  2636. raise HTTPException(404, "Archive file not found")
  2637. plate_name = body.plate_name
  2638. if not plate_name and body.plate_id is not None:
  2639. plate_name = f"Plate {body.plate_id}"
  2640. dispatch_source_name = archive.filename
  2641. if plate_name:
  2642. dispatch_source_name = f"{archive.filename} • {plate_name}"
  2643. try:
  2644. dispatch_result = await background_dispatch.dispatch_reprint_archive(
  2645. archive_id=archive_id,
  2646. archive_name=dispatch_source_name,
  2647. printer_id=printer_id,
  2648. printer_name=printer.name,
  2649. options=body.model_dump(exclude_none=True),
  2650. requested_by_user_id=user.id if user else None,
  2651. requested_by_username=user.username if user else None,
  2652. )
  2653. except DispatchEnqueueRejected as e:
  2654. raise HTTPException(status_code=409, detail=str(e)) from e
  2655. logger.info(
  2656. "Dispatched reprint archive %s for printer %s (dispatch_job_id=%s, dispatch_position=%s)",
  2657. archive_id,
  2658. printer_id,
  2659. dispatch_result["dispatch_job_id"],
  2660. dispatch_result["dispatch_position"],
  2661. )
  2662. return {
  2663. "status": "dispatched",
  2664. "printer_id": printer_id,
  2665. "archive_id": archive_id,
  2666. "filename": archive.filename,
  2667. "dispatch_job_id": dispatch_result["dispatch_job_id"],
  2668. "dispatch_position": dispatch_result["dispatch_position"],
  2669. }
  2670. # =============================================================================
  2671. # Project Page API
  2672. # =============================================================================
  2673. @router.get("/{archive_id}/project-page")
  2674. async def get_project_page(
  2675. archive_id: int,
  2676. db: AsyncSession = Depends(get_db),
  2677. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2678. ):
  2679. """Get the project page data from the 3MF file."""
  2680. from backend.app.schemas.archive import ProjectPageResponse
  2681. from backend.app.services.archive import ProjectPageParser
  2682. service = ArchiveService(db)
  2683. archive = await service.get_archive(archive_id)
  2684. if not archive:
  2685. raise HTTPException(404, "Archive not found")
  2686. file_path = settings.base_dir / archive.file_path
  2687. if not file_path.is_file():
  2688. raise HTTPException(404, "Archive file not found")
  2689. parser = ProjectPageParser(file_path)
  2690. data = parser.parse(archive_id)
  2691. return ProjectPageResponse(**data)
  2692. @router.patch("/{archive_id}/project-page")
  2693. async def update_project_page(
  2694. archive_id: int,
  2695. update_data: dict,
  2696. db: AsyncSession = Depends(get_db),
  2697. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2698. ):
  2699. """Update project page metadata in the 3MF file."""
  2700. from backend.app.services.archive import ProjectPageParser
  2701. service = ArchiveService(db)
  2702. archive = await service.get_archive(archive_id)
  2703. if not archive:
  2704. raise HTTPException(404, "Archive not found")
  2705. file_path = settings.base_dir / archive.file_path
  2706. if not file_path.is_file():
  2707. raise HTTPException(404, "Archive file not found")
  2708. parser = ProjectPageParser(file_path)
  2709. success = parser.update_metadata(update_data)
  2710. if not success:
  2711. raise HTTPException(500, "Failed to update project page")
  2712. # Return updated data
  2713. data = parser.parse(archive_id)
  2714. return data
  2715. @router.get("/{archive_id}/project-image/{image_path:path}")
  2716. async def get_project_image(
  2717. archive_id: int,
  2718. image_path: str,
  2719. db: AsyncSession = Depends(get_db),
  2720. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2721. ):
  2722. """Get an image from the 3MF project page.
  2723. Requires a stream token query param (?token=xxx) when auth is enabled.
  2724. """
  2725. from backend.app.services.archive import ProjectPageParser
  2726. service = ArchiveService(db)
  2727. archive = await service.get_archive(archive_id)
  2728. if not archive:
  2729. raise HTTPException(404, "Archive not found")
  2730. file_path = settings.base_dir / archive.file_path
  2731. if not file_path.is_file():
  2732. raise HTTPException(404, "Archive file not found")
  2733. parser = ProjectPageParser(file_path)
  2734. result = parser.get_image(image_path)
  2735. if not result:
  2736. raise HTTPException(404, "Image not found in 3MF file")
  2737. image_data, content_type = result
  2738. return Response(
  2739. content=image_data,
  2740. media_type=content_type,
  2741. headers={"Cache-Control": "max-age=3600"},
  2742. )
  2743. # =============================================================================
  2744. # Source 3MF API (Original Project Files)
  2745. # =============================================================================
  2746. @router.post("/{archive_id}/source")
  2747. async def upload_source_3mf(
  2748. archive_id: int,
  2749. file: UploadFile = File(...),
  2750. db: AsyncSession = Depends(get_db),
  2751. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2752. ):
  2753. """Upload the original source 3MF project file for an archive."""
  2754. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2755. archive = result.scalar_one_or_none()
  2756. if not archive:
  2757. raise HTTPException(404, "Archive not found")
  2758. if not file.filename or not file.filename.endswith(".3mf"):
  2759. raise HTTPException(400, "File must be a .3mf file")
  2760. # Get archive directory and create source subdirectory
  2761. file_path = settings.base_dir / archive.file_path
  2762. archive_dir = file_path.parent
  2763. source_dir = archive_dir / "source"
  2764. source_dir.mkdir(exist_ok=True)
  2765. # Delete old source file if exists
  2766. if archive.source_3mf_path:
  2767. old_source_path = settings.base_dir / archive.source_3mf_path
  2768. if old_source_path.exists():
  2769. old_source_path.unlink()
  2770. # Save the source 3MF file - preserve original filename
  2771. source_filename = file.filename
  2772. source_path = source_dir / source_filename
  2773. content = await file.read()
  2774. source_path.write_bytes(content)
  2775. # Update archive with source path (relative to base_dir)
  2776. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2777. await db.commit()
  2778. await db.refresh(archive)
  2779. return {
  2780. "status": "uploaded",
  2781. "source_3mf_path": archive.source_3mf_path,
  2782. "filename": source_filename,
  2783. }
  2784. @router.get("/{archive_id}/source")
  2785. async def download_source_3mf(
  2786. archive_id: int,
  2787. db: AsyncSession = Depends(get_db),
  2788. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2789. ):
  2790. """Download the source 3MF project file."""
  2791. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2792. archive = result.scalar_one_or_none()
  2793. if not archive:
  2794. raise HTTPException(404, "Archive not found")
  2795. if not archive.source_3mf_path:
  2796. raise HTTPException(404, "No source 3MF attached to this archive")
  2797. source_path = settings.base_dir / archive.source_3mf_path
  2798. if not source_path.exists():
  2799. raise HTTPException(404, "Source 3MF file not found on disk")
  2800. # Use the actual filename from the path
  2801. filename = source_path.name
  2802. return FileResponse(
  2803. path=source_path,
  2804. filename=filename,
  2805. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2806. )
  2807. @router.get("/{archive_id}/source/{filename}")
  2808. async def download_source_3mf_for_slicer(
  2809. archive_id: int,
  2810. filename: str,
  2811. db: AsyncSession = Depends(get_db),
  2812. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2813. ):
  2814. """Download source 3MF with filename in URL."""
  2815. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2816. archive = result.scalar_one_or_none()
  2817. if not archive:
  2818. raise HTTPException(404, "Archive not found")
  2819. if not archive.source_3mf_path:
  2820. raise HTTPException(404, "No source 3MF attached to this archive")
  2821. source_path = settings.base_dir / archive.source_3mf_path
  2822. if not source_path.exists():
  2823. raise HTTPException(404, "Source 3MF file not found on disk")
  2824. return FileResponse(
  2825. path=source_path,
  2826. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2827. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2828. )
  2829. @router.post("/{archive_id}/source-slicer-token")
  2830. async def create_source_slicer_token(
  2831. archive_id: int,
  2832. db: AsyncSession = Depends(get_db),
  2833. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2834. ):
  2835. """Create a short-lived download token for opening source 3MF in slicer."""
  2836. from backend.app.core.auth import create_slicer_download_token
  2837. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2838. archive = result.scalar_one_or_none()
  2839. if not archive:
  2840. raise HTTPException(404, "Archive not found")
  2841. if not archive.source_3mf_path:
  2842. raise HTTPException(404, "No source 3MF attached to this archive")
  2843. token = create_slicer_download_token("source", archive_id)
  2844. return {"token": token}
  2845. @router.get("/{archive_id}/source-dl/{token}/{filename}")
  2846. async def download_source_3mf_for_slicer_with_token(
  2847. archive_id: int,
  2848. token: str,
  2849. filename: str,
  2850. db: AsyncSession = Depends(get_db),
  2851. ):
  2852. """Download source 3MF using a slicer download token.
  2853. Token-authenticated (no auth headers needed). The token is short-lived
  2854. and single-use, created by POST /{archive_id}/source-slicer-token.
  2855. """
  2856. from backend.app.core.auth import verify_slicer_download_token
  2857. if not verify_slicer_download_token(token, "source", archive_id):
  2858. raise HTTPException(403, "Invalid or expired download token")
  2859. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2860. archive = result.scalar_one_or_none()
  2861. if not archive:
  2862. raise HTTPException(404, "Archive not found")
  2863. if not archive.source_3mf_path:
  2864. raise HTTPException(404, "No source 3MF attached to this archive")
  2865. source_path = settings.base_dir / archive.source_3mf_path
  2866. if not source_path.exists():
  2867. raise HTTPException(404, "Source 3MF file not found on disk")
  2868. return FileResponse(
  2869. path=source_path,
  2870. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  2871. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  2872. )
  2873. @router.post("/upload-source")
  2874. async def upload_source_3mf_by_name(
  2875. file: UploadFile = File(...),
  2876. print_name: str = Query(None, description="Match archive by print name"),
  2877. db: AsyncSession = Depends(get_db),
  2878. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  2879. ):
  2880. """Upload source 3MF and match to archive by print name.
  2881. This endpoint is designed for slicer post-processing scripts.
  2882. It finds the most recent archive matching the print name and attaches the source.
  2883. """
  2884. if not file.filename or not file.filename.endswith(".3mf"):
  2885. raise HTTPException(400, "File must be a .3mf file")
  2886. # Derive print name from filename if not provided
  2887. if not print_name:
  2888. # Remove .3mf extension and common suffixes
  2889. print_name = file.filename.rsplit(".3mf", 1)[0]
  2890. # Remove _source suffix if present
  2891. if print_name.endswith("_source"):
  2892. print_name = print_name[:-7]
  2893. # Find matching archive - try exact match first, then fuzzy
  2894. result = await db.execute(
  2895. select(PrintArchive)
  2896. .where(PrintArchive.print_name == print_name)
  2897. .order_by(PrintArchive.created_at.desc())
  2898. .limit(1)
  2899. )
  2900. archive = result.scalar_one_or_none()
  2901. if not archive:
  2902. # Try matching filename without .gcode.3mf
  2903. result = await db.execute(
  2904. select(PrintArchive)
  2905. .where(PrintArchive.filename.like(f"{print_name}%"))
  2906. .order_by(PrintArchive.created_at.desc())
  2907. .limit(1)
  2908. )
  2909. archive = result.scalar_one_or_none()
  2910. if not archive:
  2911. # Try case-insensitive partial match on print_name
  2912. result = await db.execute(
  2913. select(PrintArchive)
  2914. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  2915. .order_by(PrintArchive.created_at.desc())
  2916. .limit(1)
  2917. )
  2918. archive = result.scalar_one_or_none()
  2919. if not archive:
  2920. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2921. # Get archive directory and create source subdirectory
  2922. file_path = settings.base_dir / archive.file_path
  2923. archive_dir = file_path.parent
  2924. source_dir = archive_dir / "source"
  2925. source_dir.mkdir(exist_ok=True)
  2926. # Delete old source file if exists
  2927. if archive.source_3mf_path:
  2928. old_source_path = settings.base_dir / archive.source_3mf_path
  2929. if old_source_path.exists():
  2930. old_source_path.unlink()
  2931. # Save the source 3MF file - preserve original filename
  2932. source_filename = file.filename
  2933. source_path = source_dir / source_filename
  2934. content = await file.read()
  2935. source_path.write_bytes(content)
  2936. # Update archive with source path
  2937. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2938. await db.commit()
  2939. await db.refresh(archive)
  2940. return {
  2941. "status": "uploaded",
  2942. "archive_id": archive.id,
  2943. "archive_name": archive.print_name or archive.filename,
  2944. "source_3mf_path": archive.source_3mf_path,
  2945. "filename": source_filename,
  2946. }
  2947. @router.delete("/{archive_id}/source")
  2948. async def delete_source_3mf(
  2949. archive_id: int,
  2950. db: AsyncSession = Depends(get_db),
  2951. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  2952. ):
  2953. """Delete the source 3MF project file from an archive."""
  2954. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2955. archive = result.scalar_one_or_none()
  2956. if not archive:
  2957. raise HTTPException(404, "Archive not found")
  2958. if not archive.source_3mf_path:
  2959. raise HTTPException(404, "No source 3MF attached to this archive")
  2960. # Delete the file
  2961. source_path = settings.base_dir / archive.source_3mf_path
  2962. if source_path.exists():
  2963. source_path.unlink()
  2964. # Clear the path in database
  2965. archive.source_3mf_path = None
  2966. await db.commit()
  2967. return {"status": "deleted"}
  2968. # =============================================================================
  2969. # F3D API (Fusion 360 Design Files)
  2970. # =============================================================================
  2971. @router.post("/{archive_id}/f3d")
  2972. async def upload_f3d(
  2973. archive_id: int,
  2974. file: UploadFile = File(...),
  2975. db: AsyncSession = Depends(get_db),
  2976. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2977. ):
  2978. """Upload a Fusion 360 design file for an archive."""
  2979. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2980. archive = result.scalar_one_or_none()
  2981. if not archive:
  2982. raise HTTPException(404, "Archive not found")
  2983. if not file.filename or not file.filename.endswith(".f3d"):
  2984. raise HTTPException(400, "File must be a .f3d file")
  2985. # Get archive directory and create f3d subdirectory
  2986. file_path = settings.base_dir / archive.file_path
  2987. archive_dir = file_path.parent
  2988. f3d_dir = archive_dir / "f3d"
  2989. f3d_dir.mkdir(exist_ok=True)
  2990. # Delete old F3D file if exists
  2991. if archive.f3d_path:
  2992. old_f3d_path = settings.base_dir / archive.f3d_path
  2993. if old_f3d_path.exists():
  2994. old_f3d_path.unlink()
  2995. # Save the F3D file - preserve original filename
  2996. f3d_filename = file.filename
  2997. f3d_path = f3d_dir / f3d_filename
  2998. content = await file.read()
  2999. f3d_path.write_bytes(content)
  3000. # Update archive with F3D path (relative to base_dir)
  3001. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  3002. await db.commit()
  3003. await db.refresh(archive)
  3004. return {
  3005. "status": "uploaded",
  3006. "f3d_path": archive.f3d_path,
  3007. "filename": f3d_filename,
  3008. }
  3009. @router.get("/{archive_id}/f3d")
  3010. async def download_f3d(
  3011. archive_id: int,
  3012. db: AsyncSession = Depends(get_db),
  3013. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3014. ):
  3015. """Download the Fusion 360 design file."""
  3016. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3017. archive = result.scalar_one_or_none()
  3018. if not archive:
  3019. raise HTTPException(404, "Archive not found")
  3020. if not archive.f3d_path:
  3021. raise HTTPException(404, "No F3D file attached to this archive")
  3022. f3d_path = settings.base_dir / archive.f3d_path
  3023. if not f3d_path.exists():
  3024. raise HTTPException(404, "F3D file not found on disk")
  3025. # Use the actual filename from the path
  3026. filename = f3d_path.name
  3027. return FileResponse(
  3028. path=f3d_path,
  3029. filename=filename,
  3030. media_type="application/octet-stream",
  3031. )
  3032. @router.delete("/{archive_id}/f3d")
  3033. async def delete_f3d(
  3034. archive_id: int,
  3035. db: AsyncSession = Depends(get_db),
  3036. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  3037. ):
  3038. """Delete the Fusion 360 design file from an archive."""
  3039. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3040. archive = result.scalar_one_or_none()
  3041. if not archive:
  3042. raise HTTPException(404, "Archive not found")
  3043. if not archive.f3d_path:
  3044. raise HTTPException(404, "No F3D file attached to this archive")
  3045. # Delete the file
  3046. f3d_path = settings.base_dir / archive.f3d_path
  3047. if f3d_path.exists():
  3048. f3d_path.unlink()
  3049. # Clear the path in database
  3050. archive.f3d_path = None
  3051. await db.commit()
  3052. return {"status": "deleted"}