archives.py 139 KB

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