archives.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  6. from fastapi.responses import FileResponse, Response
  7. from sqlalchemy import func, select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.config import settings
  10. from backend.app.core.database import get_db
  11. from backend.app.models.archive import PrintArchive
  12. from backend.app.models.filament import Filament
  13. from backend.app.schemas.archive import ArchiveResponse, ArchiveStats, ArchiveUpdate, ReprintRequest
  14. from backend.app.services.archive import ArchiveService
  15. logger = logging.getLogger(__name__)
  16. router = APIRouter(prefix="/archives", tags=["archives"])
  17. def compute_time_accuracy(archive: PrintArchive) -> dict:
  18. """Compute actual print time and accuracy for an archive.
  19. Returns dict with actual_time_seconds and time_accuracy.
  20. time_accuracy = (estimated / actual) * 100
  21. - 100% = perfect estimate
  22. - >100% = print was faster than estimated
  23. - <100% = print took longer than estimated
  24. """
  25. result = {"actual_time_seconds": None, "time_accuracy": None}
  26. if archive.started_at and archive.completed_at and archive.status == "completed":
  27. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  28. if actual_seconds > 0:
  29. result["actual_time_seconds"] = actual_seconds
  30. if archive.print_time_seconds and archive.print_time_seconds > 0:
  31. # Calculate accuracy as percentage
  32. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  33. # Sanity check: skip unreasonable values (e.g., manually changed status)
  34. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  35. if 5 <= accuracy <= 500:
  36. result["time_accuracy"] = round(accuracy, 1)
  37. return result
  38. def archive_to_response(
  39. archive: PrintArchive,
  40. duplicates: list[dict] | None = None,
  41. duplicate_count: int = 0,
  42. ) -> dict:
  43. """Convert archive model to response dict with computed fields."""
  44. data = {
  45. "id": archive.id,
  46. "printer_id": archive.printer_id,
  47. "project_id": archive.project_id,
  48. "project_name": archive.project.name if archive.project else None,
  49. "filename": archive.filename,
  50. "file_path": archive.file_path,
  51. "file_size": archive.file_size,
  52. "content_hash": archive.content_hash,
  53. "thumbnail_path": archive.thumbnail_path,
  54. "timelapse_path": archive.timelapse_path,
  55. "source_3mf_path": archive.source_3mf_path,
  56. "f3d_path": archive.f3d_path,
  57. "duplicates": duplicates,
  58. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  59. "print_name": archive.print_name,
  60. "print_time_seconds": archive.print_time_seconds,
  61. "filament_used_grams": archive.filament_used_grams,
  62. "filament_type": archive.filament_type,
  63. "filament_color": archive.filament_color,
  64. "layer_height": archive.layer_height,
  65. "total_layers": archive.total_layers,
  66. "nozzle_diameter": archive.nozzle_diameter,
  67. "bed_temperature": archive.bed_temperature,
  68. "nozzle_temperature": archive.nozzle_temperature,
  69. "status": archive.status,
  70. "started_at": archive.started_at,
  71. "completed_at": archive.completed_at,
  72. "extra_data": archive.extra_data,
  73. "makerworld_url": archive.makerworld_url,
  74. "designer": archive.designer,
  75. "is_favorite": archive.is_favorite,
  76. "tags": archive.tags,
  77. "notes": archive.notes,
  78. "cost": archive.cost,
  79. "photos": archive.photos,
  80. "failure_reason": archive.failure_reason,
  81. "quantity": archive.quantity,
  82. "energy_kwh": archive.energy_kwh,
  83. "energy_cost": archive.energy_cost,
  84. "created_at": archive.created_at,
  85. }
  86. # Add computed time accuracy fields
  87. accuracy_data = compute_time_accuracy(archive)
  88. data.update(accuracy_data)
  89. return data
  90. @router.get("/", response_model=list[ArchiveResponse])
  91. async def list_archives(
  92. printer_id: int | None = None,
  93. project_id: int | None = None,
  94. limit: int = 50,
  95. offset: int = 0,
  96. db: AsyncSession = Depends(get_db),
  97. ):
  98. """List archived prints."""
  99. service = ArchiveService(db)
  100. archives = await service.list_archives(
  101. printer_id=printer_id,
  102. project_id=project_id,
  103. limit=limit,
  104. offset=offset,
  105. )
  106. # Get set of hashes that have duplicates (efficient single query)
  107. duplicate_hashes = await service.get_duplicate_hashes()
  108. # Mark archives that have duplicates
  109. result = []
  110. for a in archives:
  111. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  112. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  113. return result
  114. @router.get("/search", response_model=list[ArchiveResponse])
  115. async def search_archives(
  116. q: str = Query(..., min_length=2, description="Search query"),
  117. printer_id: int | None = None,
  118. project_id: int | None = None,
  119. status: str | None = None,
  120. limit: int = 50,
  121. offset: int = 0,
  122. db: AsyncSession = Depends(get_db),
  123. ):
  124. """Full-text search across archives.
  125. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  126. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  127. """
  128. from sqlalchemy import text
  129. from sqlalchemy.orm import selectinload
  130. # Prepare search query - add wildcard for partial matches
  131. search_term = q.strip()
  132. if not search_term.endswith("*"):
  133. search_term = f"{search_term}*"
  134. # Build the FTS query
  135. # Using MATCH for FTS5 full-text search
  136. fts_query = text("""
  137. SELECT rowid FROM archive_fts
  138. WHERE archive_fts MATCH :search_term
  139. ORDER BY rank
  140. LIMIT :limit OFFSET :offset
  141. """)
  142. try:
  143. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  144. matched_ids = [row[0] for row in result.fetchall()]
  145. except Exception as e:
  146. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  147. # Fallback to LIKE search if FTS fails
  148. like_pattern = f"%{q}%"
  149. query = (
  150. select(PrintArchive)
  151. .options(selectinload(PrintArchive.project))
  152. .where(
  153. (PrintArchive.print_name.ilike(like_pattern))
  154. | (PrintArchive.filename.ilike(like_pattern))
  155. | (PrintArchive.tags.ilike(like_pattern))
  156. | (PrintArchive.notes.ilike(like_pattern))
  157. | (PrintArchive.designer.ilike(like_pattern))
  158. | (PrintArchive.filament_type.ilike(like_pattern))
  159. )
  160. .order_by(PrintArchive.created_at.desc())
  161. )
  162. if printer_id:
  163. query = query.where(PrintArchive.printer_id == printer_id)
  164. if project_id:
  165. query = query.where(PrintArchive.project_id == project_id)
  166. if status:
  167. query = query.where(PrintArchive.status == status)
  168. query = query.limit(limit).offset(offset)
  169. result = await db.execute(query)
  170. archives = result.scalars().all()
  171. return [archive_to_response(a) for a in archives]
  172. if not matched_ids:
  173. return []
  174. # Fetch full archive records for matched IDs
  175. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  176. # Apply additional filters
  177. if printer_id:
  178. query = query.where(PrintArchive.printer_id == printer_id)
  179. if project_id:
  180. query = query.where(PrintArchive.project_id == project_id)
  181. if status:
  182. query = query.where(PrintArchive.status == status)
  183. result = await db.execute(query)
  184. archives_dict = {a.id: a for a in result.scalars().all()}
  185. # Preserve FTS ranking order and apply pagination
  186. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  187. paginated = ordered_archives[offset : offset + limit]
  188. return [archive_to_response(a) for a in paginated]
  189. @router.post("/search/rebuild-index")
  190. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  191. """Rebuild the full-text search index from existing archives.
  192. Use this if search results seem incomplete or incorrect.
  193. """
  194. from sqlalchemy import text
  195. try:
  196. # Clear and rebuild the FTS index
  197. await db.execute(text("DELETE FROM archive_fts"))
  198. # Repopulate from print_archives
  199. await db.execute(
  200. text("""
  201. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  202. SELECT id, print_name, filename, tags, notes, designer, filament_type
  203. FROM print_archives
  204. """)
  205. )
  206. await db.commit()
  207. # Count entries
  208. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  209. count = result.scalar() or 0
  210. return {"message": f"Search index rebuilt with {count} entries"}
  211. except Exception as e:
  212. logger.error(f"Failed to rebuild search index: {e}")
  213. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  214. @router.get("/analysis/failures")
  215. async def analyze_failures(
  216. days: int = 30,
  217. printer_id: int | None = None,
  218. project_id: int | None = None,
  219. db: AsyncSession = Depends(get_db),
  220. ):
  221. """Analyze failure patterns across prints.
  222. Returns failure statistics including:
  223. - Overall failure rate
  224. - Failures by reason, filament type, printer
  225. - Time of day distribution
  226. - Recent failures
  227. - Weekly trend
  228. """
  229. from backend.app.services.failure_analysis import FailureAnalysisService
  230. service = FailureAnalysisService(db)
  231. return await service.analyze_failures(
  232. days=days,
  233. printer_id=printer_id,
  234. project_id=project_id,
  235. )
  236. @router.get("/compare")
  237. async def compare_archives(
  238. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  239. db: AsyncSession = Depends(get_db),
  240. ):
  241. """Compare multiple archives side by side.
  242. Compares print settings, filament usage, and print times.
  243. Also analyzes correlation between settings and success/failure.
  244. Args:
  245. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  246. """
  247. from backend.app.services.archive_comparison import ArchiveComparisonService
  248. # Parse and validate archive IDs
  249. try:
  250. ids = [int(id.strip()) for id in archive_ids.split(",")]
  251. except ValueError:
  252. raise HTTPException(400, "Invalid archive IDs format")
  253. if len(ids) < 2:
  254. raise HTTPException(400, "At least 2 archives required for comparison")
  255. if len(ids) > 5:
  256. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  257. service = ArchiveComparisonService(db)
  258. try:
  259. return await service.compare_archives(ids)
  260. except ValueError as e:
  261. raise HTTPException(400, str(e))
  262. @router.get("/export")
  263. async def export_archives(
  264. format: str = Query("csv", description="Export format: csv or xlsx"),
  265. fields: str | None = Query(None, description="Comma-separated field names"),
  266. printer_id: int | None = None,
  267. project_id: int | None = None,
  268. status: str | None = None,
  269. date_from: str | None = Query(None, description="Start date (ISO format)"),
  270. date_to: str | None = Query(None, description="End date (ISO format)"),
  271. search: str | None = None,
  272. db: AsyncSession = Depends(get_db),
  273. ):
  274. """Export archives to CSV or Excel format.
  275. Returns a downloadable file with archive data.
  276. """
  277. from datetime import datetime
  278. from fastapi.responses import StreamingResponse
  279. from backend.app.services.export import ExportService
  280. if format not in ("csv", "xlsx"):
  281. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  282. # Parse fields
  283. field_list = None
  284. if fields:
  285. field_list = [f.strip() for f in fields.split(",")]
  286. # Parse dates
  287. date_from_dt = None
  288. date_to_dt = None
  289. if date_from:
  290. try:
  291. date_from_dt = datetime.fromisoformat(date_from)
  292. except ValueError:
  293. raise HTTPException(400, "Invalid date_from format")
  294. if date_to:
  295. try:
  296. date_to_dt = datetime.fromisoformat(date_to)
  297. except ValueError:
  298. raise HTTPException(400, "Invalid date_to format")
  299. service = ExportService(db)
  300. try:
  301. file_bytes, filename, content_type = await service.export_archives(
  302. format=format,
  303. fields=field_list,
  304. printer_id=printer_id,
  305. project_id=project_id,
  306. status=status,
  307. date_from=date_from_dt,
  308. date_to=date_to_dt,
  309. search=search,
  310. )
  311. except ImportError as e:
  312. raise HTTPException(500, str(e))
  313. return StreamingResponse(
  314. io.BytesIO(file_bytes),
  315. media_type=content_type,
  316. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  317. )
  318. @router.get("/stats/export")
  319. async def export_stats(
  320. format: str = Query("csv", description="Export format: csv or xlsx"),
  321. days: int = 30,
  322. printer_id: int | None = None,
  323. project_id: int | None = None,
  324. db: AsyncSession = Depends(get_db),
  325. ):
  326. """Export statistics summary to CSV or Excel format."""
  327. from fastapi.responses import StreamingResponse
  328. from backend.app.services.export import ExportService
  329. if format not in ("csv", "xlsx"):
  330. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  331. service = ExportService(db)
  332. try:
  333. file_bytes, filename, content_type = await service.export_stats(
  334. format=format,
  335. days=days,
  336. printer_id=printer_id,
  337. project_id=project_id,
  338. )
  339. except ImportError as e:
  340. raise HTTPException(500, str(e))
  341. return StreamingResponse(
  342. io.BytesIO(file_bytes),
  343. media_type=content_type,
  344. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  345. )
  346. @router.get("/stats", response_model=ArchiveStats)
  347. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  348. """Get statistics across all archives."""
  349. # Total counts
  350. total_result = await db.execute(select(func.count(PrintArchive.id)))
  351. total_prints = total_result.scalar() or 0
  352. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  353. successful_prints = successful_result.scalar() or 0
  354. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  355. failed_prints = failed_result.scalar() or 0
  356. # Totals
  357. time_result = await db.execute(select(func.sum(PrintArchive.print_time_seconds)))
  358. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  359. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  360. total_filament = filament_result.scalar() or 0
  361. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  362. total_cost = cost_result.scalar() or 0
  363. # By filament type (split comma-separated values for multi-material prints)
  364. filament_type_result = await db.execute(
  365. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  366. )
  367. prints_by_filament: dict[str, int] = {}
  368. for (filament_types,) in filament_type_result.all():
  369. # Split by comma and count each type
  370. for ftype in filament_types.split(","):
  371. ftype = ftype.strip()
  372. if ftype:
  373. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  374. # By printer
  375. printer_result = await db.execute(
  376. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  377. )
  378. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  379. # Time accuracy statistics
  380. # Get all completed archives with both estimated and actual times
  381. accuracy_result = await db.execute(
  382. select(PrintArchive)
  383. .where(PrintArchive.status == "completed")
  384. .where(PrintArchive.print_time_seconds.isnot(None))
  385. .where(PrintArchive.started_at.isnot(None))
  386. .where(PrintArchive.completed_at.isnot(None))
  387. )
  388. archives_with_times = list(accuracy_result.scalars().all())
  389. average_accuracy = None
  390. accuracy_by_printer: dict[str, float] = {}
  391. if archives_with_times:
  392. accuracies = []
  393. printer_accuracies: dict[str, list[float]] = {}
  394. for archive in archives_with_times:
  395. acc_data = compute_time_accuracy(archive)
  396. if acc_data["time_accuracy"] is not None:
  397. accuracies.append(acc_data["time_accuracy"])
  398. # Group by printer
  399. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  400. if printer_key not in printer_accuracies:
  401. printer_accuracies[printer_key] = []
  402. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  403. if accuracies:
  404. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  405. # Calculate per-printer averages
  406. for printer_key, accs in printer_accuracies.items():
  407. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  408. # Energy totals - check which mode to use
  409. from backend.app.api.routes.settings import get_setting
  410. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  411. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  412. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  413. if energy_tracking_mode == "total":
  414. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  415. from backend.app.models.smart_plug import SmartPlug
  416. from backend.app.services.tasmota import tasmota_service
  417. plugs_result = await db.execute(select(SmartPlug))
  418. plugs = list(plugs_result.scalars().all())
  419. total_energy_kwh = 0.0
  420. for plug in plugs:
  421. energy = await tasmota_service.get_energy(plug)
  422. if energy and energy.get("total") is not None:
  423. total_energy_kwh += energy["total"]
  424. total_energy_kwh = round(total_energy_kwh, 3)
  425. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  426. else:
  427. # Print mode: sum up per-print energy from archives
  428. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  429. total_energy_kwh = energy_kwh_result.scalar() or 0
  430. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  431. total_energy_cost = energy_cost_result.scalar() or 0
  432. return ArchiveStats(
  433. total_prints=total_prints,
  434. successful_prints=successful_prints,
  435. failed_prints=failed_prints,
  436. total_print_time_hours=round(total_time, 1),
  437. total_filament_grams=round(total_filament, 1),
  438. total_cost=round(total_cost, 2),
  439. prints_by_filament_type=prints_by_filament,
  440. prints_by_printer=prints_by_printer,
  441. average_time_accuracy=average_accuracy,
  442. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  443. total_energy_kwh=round(total_energy_kwh, 3),
  444. total_energy_cost=round(total_energy_cost, 2),
  445. )
  446. @router.get("/{archive_id}", response_model=ArchiveResponse)
  447. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  448. """Get a specific archive."""
  449. service = ArchiveService(db)
  450. archive = await service.get_archive(archive_id)
  451. if not archive:
  452. raise HTTPException(404, "Archive not found")
  453. # Find duplicates
  454. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  455. duplicates = await service.find_duplicates(
  456. archive_id=archive.id,
  457. content_hash=archive.content_hash,
  458. print_name=archive.print_name,
  459. makerworld_model_id=makerworld_id,
  460. )
  461. return archive_to_response(archive, duplicates)
  462. @router.get("/{archive_id}/similar")
  463. async def find_similar_archives(
  464. archive_id: int,
  465. limit: int = 10,
  466. db: AsyncSession = Depends(get_db),
  467. ):
  468. """Find archives with similar settings for comparison.
  469. Returns archives that match by:
  470. - Same print name (highest priority)
  471. - Same file content hash
  472. - Same filament type
  473. """
  474. from backend.app.services.archive_comparison import ArchiveComparisonService
  475. service = ArchiveComparisonService(db)
  476. try:
  477. return await service.find_similar_archives(archive_id, limit=limit)
  478. except ValueError as e:
  479. raise HTTPException(404, str(e))
  480. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  481. async def update_archive(
  482. archive_id: int,
  483. update_data: ArchiveUpdate,
  484. db: AsyncSession = Depends(get_db),
  485. ):
  486. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  487. from sqlalchemy.orm import selectinload
  488. result = await db.execute(
  489. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  490. )
  491. archive = result.scalar_one_or_none()
  492. if not archive:
  493. raise HTTPException(404, "Archive not found")
  494. for field, value in update_data.model_dump(exclude_unset=True).items():
  495. setattr(archive, field, value)
  496. await db.commit()
  497. # Re-fetch with project relationship loaded after commit
  498. result = await db.execute(
  499. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  500. )
  501. archive = result.scalar_one_or_none()
  502. return archive_to_response(archive)
  503. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  504. async def toggle_favorite(
  505. archive_id: int,
  506. db: AsyncSession = Depends(get_db),
  507. ):
  508. """Toggle favorite status for an archive."""
  509. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  510. archive = result.scalar_one_or_none()
  511. if not archive:
  512. raise HTTPException(404, "Archive not found")
  513. archive.is_favorite = not archive.is_favorite
  514. await db.commit()
  515. await db.refresh(archive)
  516. return archive
  517. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  518. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  519. """Rescan the 3MF file and update metadata."""
  520. from backend.app.services.archive import ThreeMFParser
  521. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  522. archive = result.scalar_one_or_none()
  523. if not archive:
  524. raise HTTPException(404, "Archive not found")
  525. file_path = settings.base_dir / archive.file_path
  526. if not file_path.exists():
  527. raise HTTPException(404, "Archive file not found")
  528. # Parse the 3MF file
  529. parser = ThreeMFParser(file_path)
  530. metadata = parser.parse()
  531. # Update fields from metadata
  532. if metadata.get("filament_type"):
  533. archive.filament_type = metadata["filament_type"]
  534. if metadata.get("filament_color"):
  535. archive.filament_color = metadata["filament_color"]
  536. if metadata.get("print_time_seconds"):
  537. archive.print_time_seconds = metadata["print_time_seconds"]
  538. if metadata.get("filament_used_grams"):
  539. archive.filament_used_grams = metadata["filament_used_grams"]
  540. if metadata.get("layer_height"):
  541. archive.layer_height = metadata["layer_height"]
  542. if metadata.get("nozzle_diameter"):
  543. archive.nozzle_diameter = metadata["nozzle_diameter"]
  544. if metadata.get("bed_temperature"):
  545. archive.bed_temperature = metadata["bed_temperature"]
  546. if metadata.get("nozzle_temperature"):
  547. archive.nozzle_temperature = metadata["nozzle_temperature"]
  548. if metadata.get("makerworld_url"):
  549. archive.makerworld_url = metadata["makerworld_url"]
  550. if metadata.get("designer"):
  551. archive.designer = metadata["designer"]
  552. # Calculate cost based on filament usage and type
  553. if archive.filament_used_grams and archive.filament_type:
  554. primary_type = archive.filament_type.split(",")[0].strip()
  555. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  556. filament = filament_result.scalar_one_or_none()
  557. if filament:
  558. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  559. else:
  560. archive.cost = round((archive.filament_used_grams / 1000) * 25.0, 2)
  561. await db.commit()
  562. await db.refresh(archive)
  563. return archive
  564. @router.post("/recalculate-costs")
  565. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  566. """Recalculate costs for all archives based on filament usage and prices."""
  567. result = await db.execute(select(PrintArchive))
  568. archives = list(result.scalars().all())
  569. # Load all filaments for lookup
  570. filament_result = await db.execute(select(Filament))
  571. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  572. default_cost_per_kg = 25.0
  573. updated = 0
  574. for archive in archives:
  575. if archive.filament_used_grams and archive.filament_type:
  576. primary_type = archive.filament_type.split(",")[0].strip()
  577. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  578. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  579. if archive.cost != new_cost:
  580. archive.cost = new_cost
  581. updated += 1
  582. await db.commit()
  583. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  584. @router.post("/rescan-all")
  585. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  586. """Rescan all archives and update their metadata."""
  587. from backend.app.services.archive import ThreeMFParser
  588. result = await db.execute(select(PrintArchive))
  589. archives = list(result.scalars().all())
  590. updated = 0
  591. errors = []
  592. for archive in archives:
  593. try:
  594. file_path = settings.base_dir / archive.file_path
  595. if not file_path.exists():
  596. errors.append({"id": archive.id, "error": "File not found"})
  597. continue
  598. parser = ThreeMFParser(file_path)
  599. metadata = parser.parse()
  600. if metadata.get("filament_type"):
  601. archive.filament_type = metadata["filament_type"]
  602. if metadata.get("filament_color"):
  603. archive.filament_color = metadata["filament_color"]
  604. if metadata.get("print_time_seconds"):
  605. archive.print_time_seconds = metadata["print_time_seconds"]
  606. if metadata.get("filament_used_grams"):
  607. archive.filament_used_grams = metadata["filament_used_grams"]
  608. if metadata.get("layer_height"):
  609. archive.layer_height = metadata["layer_height"]
  610. if metadata.get("nozzle_diameter"):
  611. archive.nozzle_diameter = metadata["nozzle_diameter"]
  612. if metadata.get("makerworld_url"):
  613. archive.makerworld_url = metadata["makerworld_url"]
  614. if metadata.get("designer"):
  615. archive.designer = metadata["designer"]
  616. updated += 1
  617. except Exception as e:
  618. errors.append({"id": archive.id, "error": str(e)})
  619. await db.commit()
  620. return {"updated": updated, "errors": errors}
  621. @router.get("/{archive_id}/duplicates")
  622. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  623. """Get duplicates for a specific archive."""
  624. service = ArchiveService(db)
  625. archive = await service.get_archive(archive_id)
  626. if not archive:
  627. raise HTTPException(404, "Archive not found")
  628. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  629. duplicates = await service.find_duplicates(
  630. archive_id=archive.id,
  631. content_hash=archive.content_hash,
  632. print_name=archive.print_name,
  633. makerworld_model_id=makerworld_id,
  634. )
  635. return {"duplicates": duplicates, "count": len(duplicates)}
  636. @router.post("/backfill-hashes")
  637. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  638. """Compute and store content hashes for all archives missing them."""
  639. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  640. archives = list(result.scalars().all())
  641. updated = 0
  642. errors = []
  643. for archive in archives:
  644. try:
  645. file_path = settings.base_dir / archive.file_path
  646. if not file_path.exists():
  647. errors.append({"id": archive.id, "error": "File not found"})
  648. continue
  649. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  650. updated += 1
  651. except Exception as e:
  652. errors.append({"id": archive.id, "error": str(e)})
  653. await db.commit()
  654. return {"updated": updated, "errors": errors}
  655. @router.delete("/{archive_id}")
  656. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  657. """Delete an archive."""
  658. service = ArchiveService(db)
  659. if not await service.delete_archive(archive_id):
  660. raise HTTPException(404, "Archive not found")
  661. return {"status": "deleted"}
  662. @router.get("/{archive_id}/download")
  663. async def download_archive(
  664. archive_id: int,
  665. inline: bool = False,
  666. db: AsyncSession = Depends(get_db),
  667. ):
  668. """Download the 3MF file."""
  669. service = ArchiveService(db)
  670. archive = await service.get_archive(archive_id)
  671. if not archive:
  672. raise HTTPException(404, "Archive not found")
  673. file_path = settings.base_dir / archive.file_path
  674. if not file_path.exists():
  675. raise HTTPException(404, "File not found")
  676. # Use inline disposition to let browser/OS handle file association
  677. content_disposition = "inline" if inline else "attachment"
  678. return FileResponse(
  679. path=file_path,
  680. filename=archive.filename,
  681. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  682. content_disposition_type=content_disposition,
  683. )
  684. @router.get("/{archive_id}/file/{filename}")
  685. async def download_archive_with_filename(
  686. archive_id: int,
  687. filename: str,
  688. db: AsyncSession = Depends(get_db),
  689. ):
  690. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  691. service = ArchiveService(db)
  692. archive = await service.get_archive(archive_id)
  693. if not archive:
  694. raise HTTPException(404, "Archive not found")
  695. file_path = settings.base_dir / archive.file_path
  696. if not file_path.exists():
  697. raise HTTPException(404, "File not found")
  698. return FileResponse(
  699. path=file_path,
  700. filename=archive.filename,
  701. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  702. )
  703. @router.get("/{archive_id}/thumbnail")
  704. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  705. """Get the thumbnail image."""
  706. service = ArchiveService(db)
  707. archive = await service.get_archive(archive_id)
  708. if not archive or not archive.thumbnail_path:
  709. raise HTTPException(404, "Thumbnail not found")
  710. thumb_path = settings.base_dir / archive.thumbnail_path
  711. if not thumb_path.exists():
  712. raise HTTPException(404, "Thumbnail file not found")
  713. # Use file modification time as ETag to bust cache
  714. mtime = int(thumb_path.stat().st_mtime)
  715. return FileResponse(
  716. path=thumb_path,
  717. media_type="image/png",
  718. headers={
  719. "Cache-Control": "no-cache, must-revalidate",
  720. "ETag": f'"{mtime}"',
  721. },
  722. )
  723. @router.get("/{archive_id}/timelapse")
  724. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  725. """Get the timelapse video."""
  726. service = ArchiveService(db)
  727. archive = await service.get_archive(archive_id)
  728. if not archive or not archive.timelapse_path:
  729. raise HTTPException(404, "Timelapse not found")
  730. timelapse_path = settings.base_dir / archive.timelapse_path
  731. if not timelapse_path.exists():
  732. raise HTTPException(404, "Timelapse file not found")
  733. # Use file modification time as ETag to bust cache after processing
  734. mtime = int(timelapse_path.stat().st_mtime)
  735. return FileResponse(
  736. path=timelapse_path,
  737. media_type="video/mp4",
  738. filename=f"{archive.print_name or 'timelapse'}.mp4",
  739. headers={
  740. "Cache-Control": "no-cache, must-revalidate",
  741. "ETag": f'"{mtime}"',
  742. },
  743. )
  744. @router.post("/{archive_id}/timelapse/scan")
  745. async def scan_timelapse(
  746. archive_id: int,
  747. db: AsyncSession = Depends(get_db),
  748. ):
  749. """Scan printer for timelapse matching this archive and attach it."""
  750. from backend.app.models.printer import Printer
  751. from backend.app.services.bambu_ftp import (
  752. download_file_bytes_async,
  753. get_ftp_retry_settings,
  754. list_files_async,
  755. with_ftp_retry,
  756. )
  757. service = ArchiveService(db)
  758. archive = await service.get_archive(archive_id)
  759. if not archive:
  760. raise HTTPException(404, "Archive not found")
  761. if archive.timelapse_path:
  762. return {"status": "exists", "message": "Timelapse already attached"}
  763. if not archive.printer_id:
  764. raise HTTPException(400, "Archive has no associated printer")
  765. # Get printer
  766. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  767. printer = result.scalar_one_or_none()
  768. if not printer:
  769. raise HTTPException(404, "Printer not found")
  770. # Get base name from archive filename (without .3mf extension)
  771. base_name = Path(archive.filename).stem
  772. # Scan timelapse directory on printer
  773. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  774. files = []
  775. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  776. try:
  777. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  778. if files:
  779. break
  780. except Exception:
  781. continue
  782. if not files:
  783. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  784. # Look for matching timelapse
  785. matching_file = None
  786. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  787. # Strategy 1: Match by print name in filename
  788. for f in mp4_files:
  789. fname = f.get("name", "")
  790. if base_name.lower() in fname.lower():
  791. matching_file = f
  792. break
  793. # Strategy 2: Match by timestamp proximity
  794. # Bambu timelapse filename uses the print START time (when recording began)
  795. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  796. import re
  797. from datetime import datetime, timedelta
  798. # Prefer started_at since video filename is the print start time
  799. # Fall back to completed_at or created_at if started_at is not available
  800. archive_start = archive.started_at
  801. archive_end = archive.completed_at or archive.created_at
  802. best_match = None
  803. best_diff = timedelta(hours=24) # Max 24 hour difference
  804. for f in mp4_files:
  805. fname = f.get("name", "")
  806. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  807. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  808. if match:
  809. try:
  810. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  811. # Try multiple timezone offsets since printer timezone can vary
  812. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  813. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  814. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  815. # Check against start time (video filename = print start)
  816. if archive_start:
  817. diff = abs(adjusted_file_time - archive_start)
  818. if diff < best_diff:
  819. best_diff = diff
  820. best_match = f
  821. logger.debug(
  822. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  823. f"diff from start: {diff}"
  824. )
  825. # Also check against end time with a buffer
  826. # (video timestamp should be BEFORE completion time)
  827. if archive_end:
  828. # The video timestamp should be within the print duration before completion
  829. if adjusted_file_time < archive_end:
  830. diff = archive_end - adjusted_file_time
  831. # Reasonable print duration: up to 48 hours
  832. if diff < timedelta(hours=48) and diff < best_diff:
  833. best_diff = diff
  834. best_match = f
  835. logger.debug(
  836. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  837. f"diff: {diff}"
  838. )
  839. except ValueError:
  840. continue
  841. # Accept match within 4 hours (more lenient for timezone issues)
  842. if best_match and best_diff < timedelta(hours=4):
  843. matching_file = best_match
  844. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  845. # Strategy 3: Use file modification time from FTP listing
  846. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  847. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  848. from datetime import datetime, timedelta
  849. archive_start = archive.started_at
  850. archive_end = archive.completed_at or archive.created_at
  851. best_match = None
  852. best_diff = timedelta(hours=24)
  853. for f in mp4_files:
  854. mtime = f.get("mtime")
  855. if mtime:
  856. # Timelapse file should be modified during or shortly after the print
  857. # The mtime should be close to completion time (video finishes when print ends)
  858. if archive_end:
  859. diff = abs(mtime - archive_end)
  860. if diff < best_diff:
  861. best_diff = diff
  862. best_match = f
  863. logger.debug(
  864. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  865. )
  866. if best_match and best_diff < timedelta(hours=2):
  867. matching_file = best_match
  868. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  869. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  870. # This handles cases where printer clock is wrong or timezone issues exist
  871. if not matching_file and len(mp4_files) == 1:
  872. from datetime import datetime, timedelta
  873. archive_completed = archive.completed_at or archive.created_at
  874. if archive_completed:
  875. time_since_completion = datetime.now() - archive_completed
  876. # If archive was completed within the last hour, assume the single timelapse is for it
  877. if time_since_completion < timedelta(hours=1):
  878. matching_file = mp4_files[0]
  879. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  880. # Note: We intentionally don't use a "most recent file" fallback because
  881. # we can't verify if timelapse was actually enabled for this print.
  882. # Instead, return the list of available files for manual selection.
  883. if not matching_file:
  884. # Return available files for manual selection
  885. available_files = [
  886. {
  887. "name": f.get("name"),
  888. "path": f.get("path"),
  889. "size": f.get("size"),
  890. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  891. }
  892. for f in mp4_files
  893. ]
  894. # Sort by mtime descending (most recent first)
  895. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  896. return {
  897. "status": "not_found",
  898. "message": "No matching timelapse found - please select manually",
  899. "available_files": available_files,
  900. }
  901. # Download the timelapse - use the full path from the file listing
  902. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  903. # Get FTP retry settings
  904. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  905. if ftp_retry_enabled:
  906. timelapse_data = await with_ftp_retry(
  907. download_file_bytes_async,
  908. printer.ip_address,
  909. printer.access_code,
  910. remote_path,
  911. socket_timeout=ftp_timeout,
  912. printer_model=printer.model,
  913. max_retries=ftp_retry_count,
  914. retry_delay=ftp_retry_delay,
  915. operation_name=f"Download timelapse {matching_file['name']}",
  916. )
  917. else:
  918. timelapse_data = await download_file_bytes_async(
  919. printer.ip_address,
  920. printer.access_code,
  921. remote_path,
  922. socket_timeout=ftp_timeout,
  923. printer_model=printer.model,
  924. )
  925. if not timelapse_data:
  926. raise HTTPException(500, "Failed to download timelapse")
  927. # Attach timelapse to archive
  928. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  929. if not success:
  930. raise HTTPException(500, "Failed to attach timelapse")
  931. return {
  932. "status": "attached",
  933. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  934. "filename": matching_file["name"],
  935. }
  936. @router.post("/{archive_id}/timelapse/select")
  937. async def select_timelapse(
  938. archive_id: int,
  939. filename: str = Query(..., description="Timelapse filename to attach"),
  940. db: AsyncSession = Depends(get_db),
  941. ):
  942. """Manually select a timelapse from the printer to attach."""
  943. from backend.app.models.printer import Printer
  944. from backend.app.services.bambu_ftp import (
  945. download_file_bytes_async,
  946. get_ftp_retry_settings,
  947. list_files_async,
  948. with_ftp_retry,
  949. )
  950. service = ArchiveService(db)
  951. archive = await service.get_archive(archive_id)
  952. if not archive:
  953. raise HTTPException(404, "Archive not found")
  954. if not archive.printer_id:
  955. raise HTTPException(400, "Archive has no associated printer")
  956. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  957. printer = result.scalar_one_or_none()
  958. if not printer:
  959. raise HTTPException(404, "Printer not found")
  960. # Find the file on the printer
  961. files = []
  962. remote_path = None
  963. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  964. try:
  965. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  966. for f in files:
  967. if f.get("name") == filename:
  968. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  969. break
  970. if remote_path:
  971. break
  972. except Exception:
  973. continue
  974. if not remote_path:
  975. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  976. # Download and attach
  977. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  978. if ftp_retry_enabled:
  979. timelapse_data = await with_ftp_retry(
  980. download_file_bytes_async,
  981. printer.ip_address,
  982. printer.access_code,
  983. remote_path,
  984. socket_timeout=ftp_timeout,
  985. printer_model=printer.model,
  986. max_retries=ftp_retry_count,
  987. retry_delay=ftp_retry_delay,
  988. operation_name=f"Download timelapse {filename}",
  989. )
  990. else:
  991. timelapse_data = await download_file_bytes_async(
  992. printer.ip_address,
  993. printer.access_code,
  994. remote_path,
  995. socket_timeout=ftp_timeout,
  996. printer_model=printer.model,
  997. )
  998. if not timelapse_data:
  999. raise HTTPException(500, "Failed to download timelapse")
  1000. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1001. if not success:
  1002. raise HTTPException(500, "Failed to attach timelapse")
  1003. return {
  1004. "status": "attached",
  1005. "message": f"Timelapse '{filename}' attached successfully",
  1006. "filename": filename,
  1007. }
  1008. @router.post("/{archive_id}/timelapse/upload")
  1009. async def upload_timelapse(
  1010. archive_id: int,
  1011. file: UploadFile = File(...),
  1012. db: AsyncSession = Depends(get_db),
  1013. ):
  1014. """Manually upload a timelapse video to an archive."""
  1015. service = ArchiveService(db)
  1016. archive = await service.get_archive(archive_id)
  1017. if not archive:
  1018. raise HTTPException(404, "Archive not found")
  1019. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1020. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1021. content = await file.read()
  1022. success = await service.attach_timelapse(archive_id, content, file.filename)
  1023. if not success:
  1024. raise HTTPException(500, "Failed to attach timelapse")
  1025. return {"status": "attached", "filename": file.filename}
  1026. @router.get("/{archive_id}/timelapse/info")
  1027. async def get_timelapse_info(archive_id: int, db: AsyncSession = Depends(get_db)):
  1028. """Get timelapse video metadata for editor."""
  1029. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1030. from backend.app.services.timelapse_processor import TimelapseProcessor
  1031. service = ArchiveService(db)
  1032. archive = await service.get_archive(archive_id)
  1033. if not archive or not archive.timelapse_path:
  1034. raise HTTPException(404, "Timelapse not found")
  1035. timelapse_path = settings.base_dir / archive.timelapse_path
  1036. if not timelapse_path.exists():
  1037. raise HTTPException(404, "Timelapse file not found")
  1038. try:
  1039. processor = TimelapseProcessor(timelapse_path)
  1040. info = await processor.get_info()
  1041. return TimelapseInfoResponse(**info)
  1042. except Exception as e:
  1043. logger.error(f"Failed to get timelapse info: {e}")
  1044. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1045. @router.get("/{archive_id}/timelapse/thumbnails")
  1046. async def get_timelapse_thumbnails(
  1047. archive_id: int,
  1048. count: int = Query(10, ge=1, le=30),
  1049. width: int = Query(160, ge=80, le=320),
  1050. db: AsyncSession = Depends(get_db),
  1051. ):
  1052. """Generate timeline thumbnail frames for visual scrubbing."""
  1053. import base64
  1054. from backend.app.schemas.timelapse import ThumbnailResponse
  1055. from backend.app.services.timelapse_processor import TimelapseProcessor
  1056. service = ArchiveService(db)
  1057. archive = await service.get_archive(archive_id)
  1058. if not archive or not archive.timelapse_path:
  1059. raise HTTPException(404, "Timelapse not found")
  1060. timelapse_path = settings.base_dir / archive.timelapse_path
  1061. if not timelapse_path.exists():
  1062. raise HTTPException(404, "Timelapse file not found")
  1063. try:
  1064. processor = TimelapseProcessor(timelapse_path)
  1065. thumbnails = await processor.generate_thumbnails(count, width)
  1066. return ThumbnailResponse(
  1067. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1068. timestamps=[ts for ts, _ in thumbnails],
  1069. )
  1070. except Exception as e:
  1071. logger.error(f"Failed to generate thumbnails: {e}")
  1072. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1073. @router.post("/{archive_id}/timelapse/process")
  1074. async def process_timelapse(
  1075. archive_id: int,
  1076. trim_start: float = Form(0),
  1077. trim_end: float = Form(None),
  1078. speed: float = Form(1.0),
  1079. save_mode: str = Form("new"),
  1080. output_filename: str = Form(None),
  1081. audio: UploadFile = File(None),
  1082. db: AsyncSession = Depends(get_db),
  1083. ):
  1084. """Process timelapse with trim, speed, and optional audio overlay."""
  1085. import shutil
  1086. import tempfile
  1087. from backend.app.schemas.timelapse import ProcessResponse
  1088. from backend.app.services.timelapse_processor import TimelapseProcessor
  1089. # Validate speed
  1090. if not 0.25 <= speed <= 4.0:
  1091. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1092. if save_mode not in ("replace", "new"):
  1093. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1094. service = ArchiveService(db)
  1095. archive = await service.get_archive(archive_id)
  1096. if not archive or not archive.timelapse_path:
  1097. raise HTTPException(404, "Timelapse not found")
  1098. timelapse_path = settings.base_dir / archive.timelapse_path
  1099. if not timelapse_path.exists():
  1100. raise HTTPException(404, "Timelapse file not found")
  1101. archive_dir = timelapse_path.parent
  1102. # Handle audio file
  1103. audio_temp_path = None
  1104. if audio and audio.filename:
  1105. # Validate audio file extension
  1106. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1107. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1108. audio_content = await audio.read()
  1109. suffix = Path(audio.filename).suffix
  1110. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1111. audio_temp_path.write_bytes(audio_content)
  1112. try:
  1113. processor = TimelapseProcessor(timelapse_path)
  1114. # Determine output path
  1115. if save_mode == "replace":
  1116. # Process to temp file first, then replace
  1117. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1118. output_path = temp_output
  1119. else:
  1120. # Save as new file alongside original
  1121. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1122. # Sanitize filename
  1123. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1124. if not filename.endswith(".mp4"):
  1125. filename += ".mp4"
  1126. output_path = archive_dir / filename
  1127. success = await processor.process(
  1128. output_path=output_path,
  1129. trim_start=trim_start,
  1130. trim_end=trim_end,
  1131. speed=speed,
  1132. audio_path=audio_temp_path,
  1133. )
  1134. if not success:
  1135. raise HTTPException(500, "Video processing failed")
  1136. # Handle save mode
  1137. if save_mode == "replace":
  1138. # Replace original file
  1139. shutil.move(str(output_path), str(timelapse_path))
  1140. final_path = archive.timelapse_path
  1141. message = "Timelapse replaced successfully"
  1142. else:
  1143. final_path = str(output_path.relative_to(settings.base_dir))
  1144. message = f"Saved as {output_path.name}"
  1145. return ProcessResponse(
  1146. status="completed",
  1147. output_path=final_path,
  1148. message=message,
  1149. )
  1150. except HTTPException:
  1151. raise
  1152. except Exception as e:
  1153. logger.error(f"Timelapse processing failed: {e}")
  1154. raise HTTPException(500, f"Processing failed: {str(e)}")
  1155. finally:
  1156. # Cleanup temp audio file
  1157. if audio_temp_path and audio_temp_path.exists():
  1158. audio_temp_path.unlink()
  1159. # ============================================
  1160. # Photo Endpoints
  1161. # ============================================
  1162. @router.post("/{archive_id}/photos")
  1163. async def upload_photo(
  1164. archive_id: int,
  1165. file: UploadFile = File(...),
  1166. db: AsyncSession = Depends(get_db),
  1167. ):
  1168. """Upload a photo of the printed result."""
  1169. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1170. archive = result.scalar_one_or_none()
  1171. if not archive:
  1172. raise HTTPException(404, "Archive not found")
  1173. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  1174. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  1175. # Get archive directory
  1176. file_path = settings.base_dir / archive.file_path
  1177. archive_dir = file_path.parent
  1178. photos_dir = archive_dir / "photos"
  1179. photos_dir.mkdir(exist_ok=True)
  1180. # Generate unique filename
  1181. import uuid
  1182. ext = Path(file.filename).suffix.lower()
  1183. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  1184. photo_path = photos_dir / photo_filename
  1185. # Save file
  1186. content = await file.read()
  1187. photo_path.write_bytes(content)
  1188. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  1189. photos = list(archive.photos or [])
  1190. photos.append(photo_filename)
  1191. archive.photos = photos
  1192. await db.commit()
  1193. await db.refresh(archive)
  1194. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  1195. @router.get("/{archive_id}/photos/{filename}")
  1196. async def get_photo(
  1197. archive_id: int,
  1198. filename: str,
  1199. db: AsyncSession = Depends(get_db),
  1200. ):
  1201. """Get a specific photo."""
  1202. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1203. archive = result.scalar_one_or_none()
  1204. if not archive:
  1205. raise HTTPException(404, "Archive not found")
  1206. file_path = settings.base_dir / archive.file_path
  1207. photo_path = file_path.parent / "photos" / filename
  1208. if not photo_path.exists():
  1209. raise HTTPException(404, "Photo not found")
  1210. # Determine media type
  1211. ext = Path(filename).suffix.lower()
  1212. media_types = {
  1213. ".jpg": "image/jpeg",
  1214. ".jpeg": "image/jpeg",
  1215. ".png": "image/png",
  1216. ".webp": "image/webp",
  1217. }
  1218. media_type = media_types.get(ext, "image/jpeg")
  1219. return FileResponse(path=photo_path, media_type=media_type)
  1220. @router.delete("/{archive_id}/photos/{filename}")
  1221. async def delete_photo(
  1222. archive_id: int,
  1223. filename: str,
  1224. db: AsyncSession = Depends(get_db),
  1225. ):
  1226. """Delete a photo."""
  1227. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1228. archive = result.scalar_one_or_none()
  1229. if not archive:
  1230. raise HTTPException(404, "Archive not found")
  1231. if not archive.photos or filename not in archive.photos:
  1232. raise HTTPException(404, "Photo not found")
  1233. # Delete file
  1234. file_path = settings.base_dir / archive.file_path
  1235. photo_path = file_path.parent / "photos" / filename
  1236. if photo_path.exists():
  1237. photo_path.unlink()
  1238. # Update archive photos list
  1239. photos = [p for p in archive.photos if p != filename]
  1240. archive.photos = photos if photos else None
  1241. await db.commit()
  1242. return {"status": "deleted", "photos": archive.photos}
  1243. # ============================================
  1244. # QR Code Endpoint
  1245. # ============================================
  1246. @router.get("/{archive_id}/qrcode")
  1247. async def get_qrcode(
  1248. archive_id: int,
  1249. request: Request,
  1250. size: int = 200,
  1251. db: AsyncSession = Depends(get_db),
  1252. ):
  1253. """Generate a QR code that links to this archive."""
  1254. try:
  1255. import qrcode
  1256. from PIL import Image as PILImage
  1257. except ImportError:
  1258. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  1259. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1260. archive = result.scalar_one_or_none()
  1261. if not archive:
  1262. raise HTTPException(404, "Archive not found")
  1263. # Build URL to archive download
  1264. base_url = str(request.base_url).rstrip("/")
  1265. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  1266. # Generate QR code
  1267. qr = qrcode.QRCode(
  1268. version=1,
  1269. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1270. box_size=10,
  1271. border=2,
  1272. )
  1273. qr.add_data(archive_url)
  1274. qr.make(fit=True)
  1275. img = qr.make_image(fill_color="black", back_color="white")
  1276. # Convert to PIL Image for resizing
  1277. pil_img = img.get_image()
  1278. # Resize if needed
  1279. if size != 200:
  1280. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  1281. # Convert to bytes
  1282. buffer = io.BytesIO()
  1283. pil_img.save(buffer, format="PNG")
  1284. buffer.seek(0)
  1285. return Response(
  1286. content=buffer.getvalue(),
  1287. media_type="image/png",
  1288. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1289. )
  1290. @router.get("/{archive_id}/capabilities")
  1291. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1292. """Check what viewing capabilities are available for this 3MF file."""
  1293. import json
  1294. import xml.etree.ElementTree as ET
  1295. service = ArchiveService(db)
  1296. archive = await service.get_archive(archive_id)
  1297. if not archive:
  1298. raise HTTPException(404, "Archive not found")
  1299. file_path = settings.base_dir / archive.file_path
  1300. if not file_path.exists():
  1301. raise HTTPException(404, "File not found")
  1302. has_model = False
  1303. has_gcode = False
  1304. has_source = False
  1305. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1306. filament_colors: list[str] = []
  1307. # Check if source 3MF exists - this is where actual mesh data typically lives
  1308. source_path = None
  1309. if archive.source_3mf_path:
  1310. source_path = settings.base_dir / archive.source_3mf_path
  1311. if source_path.exists():
  1312. has_source = True
  1313. # Helper function to check for mesh data and extract colors from a 3MF file
  1314. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  1315. """Extract mesh presence, colors, and build volume from a 3MF file."""
  1316. found_mesh = False
  1317. colors: list[str] = []
  1318. volume = {"x": 256, "y": 256, "z": 256}
  1319. try:
  1320. with zipfile.ZipFile(zf_path, "r") as zf:
  1321. names = zf.namelist()
  1322. # Check for 3D model - look for actual mesh data
  1323. for name in names:
  1324. if name.endswith(".model"):
  1325. try:
  1326. content = zf.read(name).decode("utf-8")
  1327. if "<vertex" in content or "<mesh" in content:
  1328. found_mesh = True
  1329. break
  1330. except Exception:
  1331. pass
  1332. # Extract filament colors from project_settings.config
  1333. if "Metadata/project_settings.config" in names:
  1334. try:
  1335. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1336. config_data = json.loads(config_content)
  1337. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1338. printable_area = config_data.get("printable_area", [])
  1339. if printable_area and len(printable_area) >= 3:
  1340. max_x = 0
  1341. max_y = 0
  1342. for coord in printable_area:
  1343. if "x" in coord:
  1344. parts = coord.split("x")
  1345. if len(parts) == 2:
  1346. try:
  1347. x, y = int(parts[0]), int(parts[1])
  1348. max_x = max(max_x, x)
  1349. max_y = max(max_y, y)
  1350. except ValueError:
  1351. pass
  1352. if max_x > 0 and max_y > 0:
  1353. volume["x"] = max_x
  1354. volume["y"] = max_y
  1355. # Parse printable_height
  1356. printable_height = config_data.get("printable_height")
  1357. if printable_height:
  1358. try:
  1359. volume["z"] = int(printable_height)
  1360. except (ValueError, TypeError):
  1361. pass
  1362. # Extract filament colors
  1363. raw_colors = config_data.get("filament_colour", [])
  1364. if raw_colors:
  1365. for color in raw_colors:
  1366. if color and isinstance(color, str):
  1367. colors.append(color)
  1368. except Exception:
  1369. pass
  1370. except zipfile.BadZipFile:
  1371. pass
  1372. return found_mesh, colors, volume
  1373. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  1374. if has_source and source_path:
  1375. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  1376. if source_has_mesh:
  1377. has_model = True
  1378. if source_colors:
  1379. filament_colors = source_colors
  1380. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  1381. build_volume = source_volume
  1382. try:
  1383. with zipfile.ZipFile(file_path, "r") as zf:
  1384. names = zf.namelist()
  1385. # Check for G-code in the sliced file
  1386. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1387. # Check for 3D model in sliced file (fallback if no source)
  1388. if not has_model:
  1389. for name in names:
  1390. if name.endswith(".model"):
  1391. try:
  1392. content = zf.read(name).decode("utf-8")
  1393. if "<vertex" in content or "<mesh" in content:
  1394. has_model = True
  1395. break
  1396. except Exception:
  1397. pass
  1398. # Extract filament colors from slice_info.config (for gcode preview)
  1399. # These are the actual filaments used in the print, indexed by tool/extruder
  1400. slice_colors: list[str] = []
  1401. if "Metadata/slice_info.config" in names:
  1402. try:
  1403. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1404. root = ET.fromstring(slice_content)
  1405. filaments = root.findall(".//filament")
  1406. filament_map: dict[int, str] = {}
  1407. for f in filaments:
  1408. fid = f.get("id")
  1409. fcolor = f.get("color")
  1410. used_g = f.get("used_g", "0")
  1411. try:
  1412. used_amount = float(used_g)
  1413. except (ValueError, TypeError):
  1414. used_amount = 0
  1415. if fid is not None and fcolor:
  1416. try:
  1417. tool_id = int(fid) - 1
  1418. if tool_id >= 0 and used_amount > 0:
  1419. filament_map[tool_id] = fcolor
  1420. except ValueError:
  1421. pass
  1422. if filament_map:
  1423. max_tool = max(filament_map.keys())
  1424. for i in range(max_tool + 1):
  1425. slice_colors.append(filament_map.get(i, "#00AE42"))
  1426. except Exception:
  1427. pass
  1428. # Use slice_info colors if we don't have colors from source yet
  1429. if not filament_colors and slice_colors:
  1430. filament_colors = slice_colors
  1431. # Extract build volume from sliced file if not already set from source
  1432. if build_volume["x"] == 256 and build_volume["y"] == 256:
  1433. if "Metadata/project_settings.config" in names:
  1434. try:
  1435. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1436. config_data = json.loads(config_content)
  1437. printable_area = config_data.get("printable_area", [])
  1438. if printable_area and len(printable_area) >= 3:
  1439. max_x = 0
  1440. max_y = 0
  1441. for coord in printable_area:
  1442. if "x" in coord:
  1443. parts = coord.split("x")
  1444. if len(parts) == 2:
  1445. try:
  1446. x, y = int(parts[0]), int(parts[1])
  1447. max_x = max(max_x, x)
  1448. max_y = max(max_y, y)
  1449. except ValueError:
  1450. pass
  1451. if max_x > 0 and max_y > 0:
  1452. build_volume["x"] = max_x
  1453. build_volume["y"] = max_y
  1454. printable_height = config_data.get("printable_height")
  1455. if printable_height:
  1456. try:
  1457. build_volume["z"] = int(printable_height)
  1458. except (ValueError, TypeError):
  1459. pass
  1460. # Fallback colors from project_settings if still empty
  1461. if not filament_colors:
  1462. raw_colors = config_data.get("filament_colour", [])
  1463. if raw_colors:
  1464. for color in raw_colors:
  1465. if color and isinstance(color, str):
  1466. filament_colors.append(color)
  1467. except Exception:
  1468. pass
  1469. except zipfile.BadZipFile:
  1470. raise HTTPException(400, "Invalid 3MF file")
  1471. return {
  1472. "has_model": has_model,
  1473. "has_gcode": has_gcode,
  1474. "has_source": has_source,
  1475. "build_volume": build_volume,
  1476. "filament_colors": filament_colors,
  1477. }
  1478. @router.get("/{archive_id}/gcode")
  1479. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1480. """Extract and return G-code from the 3MF file."""
  1481. service = ArchiveService(db)
  1482. archive = await service.get_archive(archive_id)
  1483. if not archive:
  1484. raise HTTPException(404, "Archive not found")
  1485. file_path = settings.base_dir / archive.file_path
  1486. if not file_path.exists():
  1487. raise HTTPException(404, "File not found")
  1488. try:
  1489. with zipfile.ZipFile(file_path, "r") as zf:
  1490. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1491. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1492. if not gcode_files:
  1493. raise HTTPException(
  1494. 404,
  1495. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1496. )
  1497. # Get the first plate's G-code (usually plate_1.gcode)
  1498. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1499. return Response(content=gcode_content, media_type="text/plain")
  1500. except zipfile.BadZipFile:
  1501. raise HTTPException(400, "Invalid 3MF file")
  1502. except HTTPException:
  1503. raise
  1504. except Exception as e:
  1505. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1506. @router.get("/{archive_id}/plate-preview")
  1507. async def get_plate_preview(archive_id: int, db: AsyncSession = Depends(get_db)):
  1508. """Get the plate preview image from the 3MF file.
  1509. Returns the slicer-generated plate thumbnail which shows the model
  1510. with correct colors and positioning.
  1511. """
  1512. service = ArchiveService(db)
  1513. archive = await service.get_archive(archive_id)
  1514. if not archive:
  1515. raise HTTPException(404, "Archive not found")
  1516. file_path = settings.base_dir / archive.file_path
  1517. if not file_path.exists():
  1518. raise HTTPException(404, "File not found")
  1519. try:
  1520. with zipfile.ZipFile(file_path, "r") as zf:
  1521. names = zf.namelist()
  1522. # Try to find plate preview images in order of preference
  1523. # First look for the specific plate being printed (check slice_info for plate index)
  1524. plate_num = 1
  1525. if "Metadata/slice_info.config" in names:
  1526. try:
  1527. import xml.etree.ElementTree as ET
  1528. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1529. root = ET.fromstring(slice_content)
  1530. plate_elem = root.find(".//plate/metadata[@key='index']")
  1531. if plate_elem is not None:
  1532. plate_num = int(plate_elem.get("value", "1"))
  1533. except Exception:
  1534. pass
  1535. # Try plate-specific image first, then fall back to plate_1
  1536. preview_paths = [
  1537. f"Metadata/plate_{plate_num}.png",
  1538. "Metadata/plate_1.png",
  1539. "Metadata/thumbnail.png",
  1540. ]
  1541. for preview_path in preview_paths:
  1542. if preview_path in names:
  1543. image_data = zf.read(preview_path)
  1544. return Response(content=image_data, media_type="image/png")
  1545. # If no plate image, try any PNG in Metadata
  1546. for name in names:
  1547. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  1548. image_data = zf.read(name)
  1549. return Response(content=image_data, media_type="image/png")
  1550. raise HTTPException(404, "No plate preview found in 3MF file")
  1551. except zipfile.BadZipFile:
  1552. raise HTTPException(400, "Invalid 3MF file")
  1553. except HTTPException:
  1554. raise
  1555. except Exception as e:
  1556. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  1557. @router.post("/upload")
  1558. async def upload_archive(
  1559. file: UploadFile = File(...),
  1560. printer_id: int | None = None,
  1561. db: AsyncSession = Depends(get_db),
  1562. ):
  1563. """Manually upload a 3MF file to archive."""
  1564. if not file.filename or not file.filename.endswith(".3mf"):
  1565. raise HTTPException(400, "File must be a .3mf file")
  1566. # Save uploaded file temporarily
  1567. temp_path = settings.archive_dir / "temp" / file.filename
  1568. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1569. try:
  1570. content = await file.read()
  1571. temp_path.write_bytes(content)
  1572. service = ArchiveService(db)
  1573. archive = await service.archive_print(
  1574. printer_id=printer_id,
  1575. source_file=temp_path,
  1576. )
  1577. if not archive:
  1578. raise HTTPException(400, "Failed to archive file")
  1579. return ArchiveResponse.model_validate(archive)
  1580. finally:
  1581. if temp_path.exists():
  1582. temp_path.unlink()
  1583. @router.post("/upload-bulk")
  1584. async def upload_archives_bulk(
  1585. files: list[UploadFile] = File(...),
  1586. printer_id: int | None = None,
  1587. db: AsyncSession = Depends(get_db),
  1588. ):
  1589. """Bulk upload multiple 3MF files to archive."""
  1590. results = []
  1591. errors = []
  1592. for file in files:
  1593. if not file.filename or not file.filename.endswith(".3mf"):
  1594. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1595. continue
  1596. temp_path = settings.archive_dir / "temp" / file.filename
  1597. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1598. try:
  1599. content = await file.read()
  1600. temp_path.write_bytes(content)
  1601. service = ArchiveService(db)
  1602. archive = await service.archive_print(
  1603. printer_id=printer_id,
  1604. source_file=temp_path,
  1605. )
  1606. if archive:
  1607. results.append(
  1608. {
  1609. "filename": file.filename,
  1610. "id": archive.id,
  1611. "status": "success",
  1612. }
  1613. )
  1614. else:
  1615. errors.append({"filename": file.filename, "error": "Failed to process"})
  1616. except Exception as e:
  1617. errors.append({"filename": file.filename, "error": str(e)})
  1618. finally:
  1619. if temp_path.exists():
  1620. temp_path.unlink()
  1621. return {
  1622. "uploaded": len(results),
  1623. "failed": len(errors),
  1624. "results": results,
  1625. "errors": errors,
  1626. }
  1627. @router.get("/{archive_id}/filament-requirements")
  1628. async def get_filament_requirements(
  1629. archive_id: int,
  1630. db: AsyncSession = Depends(get_db),
  1631. ):
  1632. """Get filament requirements from the archived 3MF file.
  1633. Returns the filaments used in this print with their slot IDs, types, colors,
  1634. and usage amounts. This can be compared with current AMS state before reprinting.
  1635. """
  1636. import xml.etree.ElementTree as ET
  1637. service = ArchiveService(db)
  1638. archive = await service.get_archive(archive_id)
  1639. if not archive:
  1640. raise HTTPException(404, "Archive not found")
  1641. file_path = settings.base_dir / archive.file_path
  1642. if not file_path.exists():
  1643. raise HTTPException(404, "Archive file not found")
  1644. filaments = []
  1645. try:
  1646. with zipfile.ZipFile(file_path, "r") as zf:
  1647. # Parse slice_info.config for filament requirements
  1648. if "Metadata/slice_info.config" in zf.namelist():
  1649. content = zf.read("Metadata/slice_info.config").decode()
  1650. root = ET.fromstring(content)
  1651. # Extract filament elements
  1652. # Format: <filament id="1" type="PLA" color="#FFFFFF" used_g="100" used_m="10" />
  1653. for filament_elem in root.findall(".//filament"):
  1654. filament_id = filament_elem.get("id")
  1655. filament_type = filament_elem.get("type", "")
  1656. filament_color = filament_elem.get("color", "")
  1657. used_g = filament_elem.get("used_g", "0")
  1658. used_m = filament_elem.get("used_m", "0")
  1659. # Only include filaments that are actually used
  1660. try:
  1661. used_grams = float(used_g)
  1662. except (ValueError, TypeError):
  1663. used_grams = 0
  1664. if used_grams > 0 and filament_id:
  1665. filaments.append(
  1666. {
  1667. "slot_id": int(filament_id),
  1668. "type": filament_type,
  1669. "color": filament_color,
  1670. "used_grams": round(used_grams, 1),
  1671. "used_meters": float(used_m) if used_m else 0,
  1672. }
  1673. )
  1674. # Sort by slot ID
  1675. filaments.sort(key=lambda x: x["slot_id"])
  1676. except Exception as e:
  1677. logger.warning(f"Failed to parse filament requirements from archive {archive_id}: {e}")
  1678. return {
  1679. "archive_id": archive_id,
  1680. "filename": archive.filename,
  1681. "filaments": filaments,
  1682. }
  1683. @router.post("/{archive_id}/reprint")
  1684. async def reprint_archive(
  1685. archive_id: int,
  1686. printer_id: int,
  1687. body: ReprintRequest | None = None,
  1688. db: AsyncSession = Depends(get_db),
  1689. ):
  1690. """Send an archived 3MF file to a printer and start printing."""
  1691. from backend.app.main import register_expected_print
  1692. from backend.app.models.printer import Printer
  1693. from backend.app.services.bambu_ftp import (
  1694. get_ftp_retry_settings,
  1695. upload_file_async,
  1696. with_ftp_retry,
  1697. )
  1698. from backend.app.services.printer_manager import printer_manager
  1699. # Use defaults if no body provided
  1700. if body is None:
  1701. body = ReprintRequest()
  1702. # Get archive
  1703. service = ArchiveService(db)
  1704. archive = await service.get_archive(archive_id)
  1705. if not archive:
  1706. raise HTTPException(404, "Archive not found")
  1707. # Get printer
  1708. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1709. printer = result.scalar_one_or_none()
  1710. if not printer:
  1711. raise HTTPException(404, "Printer not found")
  1712. # Check printer is connected
  1713. if not printer_manager.is_connected(printer_id):
  1714. raise HTTPException(400, "Printer is not connected")
  1715. # Get the sliced 3MF file path
  1716. file_path = settings.base_dir / archive.file_path
  1717. if not file_path.exists():
  1718. raise HTTPException(404, "Archive file not found")
  1719. # Upload file to printer via FTP
  1720. from backend.app.services.bambu_ftp import delete_file_async
  1721. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1722. # The printer might reject filenames with unusual extensions
  1723. base_name = archive.filename
  1724. if base_name.endswith(".gcode.3mf"):
  1725. base_name = base_name[:-10] # Remove .gcode.3mf
  1726. elif base_name.endswith(".3mf"):
  1727. base_name = base_name[:-4] # Remove .3mf
  1728. remote_filename = f"{base_name}.3mf"
  1729. remote_path = f"/{remote_filename}"
  1730. # Get FTP retry settings
  1731. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1732. # Delete existing file if present (avoids 553 error)
  1733. await delete_file_async(
  1734. printer.ip_address,
  1735. printer.access_code,
  1736. remote_path,
  1737. socket_timeout=ftp_timeout,
  1738. printer_model=printer.model,
  1739. )
  1740. if ftp_retry_enabled:
  1741. uploaded = await with_ftp_retry(
  1742. upload_file_async,
  1743. printer.ip_address,
  1744. printer.access_code,
  1745. file_path,
  1746. remote_path,
  1747. socket_timeout=ftp_timeout,
  1748. printer_model=printer.model,
  1749. max_retries=ftp_retry_count,
  1750. retry_delay=ftp_retry_delay,
  1751. operation_name=f"Upload for reprint to {printer.name}",
  1752. )
  1753. else:
  1754. uploaded = await upload_file_async(
  1755. printer.ip_address,
  1756. printer.access_code,
  1757. file_path,
  1758. remote_path,
  1759. socket_timeout=ftp_timeout,
  1760. printer_model=printer.model,
  1761. )
  1762. if not uploaded:
  1763. raise HTTPException(500, "Failed to upload file to printer")
  1764. # Register this as an expected print so we don't create a duplicate archive
  1765. register_expected_print(printer_id, remote_filename, archive_id)
  1766. # Detect plate ID from 3MF file
  1767. plate_id = 1
  1768. try:
  1769. with zipfile.ZipFile(file_path, "r") as zf:
  1770. for name in zf.namelist():
  1771. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1772. # Extract plate number from "Metadata/plate_X.gcode"
  1773. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1774. plate_id = int(plate_str)
  1775. break
  1776. except Exception:
  1777. pass # Default to plate 1 if detection fails
  1778. logger.info(
  1779. f"Reprint archive {archive_id}: plate_id={plate_id}, "
  1780. f"ams_mapping={body.ams_mapping}, bed_levelling={body.bed_levelling}, "
  1781. f"flow_cali={body.flow_cali}, vibration_cali={body.vibration_cali}, "
  1782. f"layer_inspect={body.layer_inspect}, timelapse={body.timelapse}"
  1783. )
  1784. # Start the print with options
  1785. started = printer_manager.start_print(
  1786. printer_id,
  1787. remote_filename,
  1788. plate_id,
  1789. ams_mapping=body.ams_mapping,
  1790. timelapse=body.timelapse,
  1791. bed_levelling=body.bed_levelling,
  1792. flow_cali=body.flow_cali,
  1793. vibration_cali=body.vibration_cali,
  1794. layer_inspect=body.layer_inspect,
  1795. use_ams=body.use_ams,
  1796. )
  1797. if not started:
  1798. raise HTTPException(500, "Failed to start print")
  1799. return {
  1800. "status": "printing",
  1801. "printer_id": printer_id,
  1802. "archive_id": archive_id,
  1803. "filename": archive.filename,
  1804. }
  1805. # =============================================================================
  1806. # Project Page API
  1807. # =============================================================================
  1808. @router.get("/{archive_id}/project-page")
  1809. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  1810. """Get the project page data from the 3MF file."""
  1811. from backend.app.schemas.archive import ProjectPageResponse
  1812. from backend.app.services.archive import ProjectPageParser
  1813. service = ArchiveService(db)
  1814. archive = await service.get_archive(archive_id)
  1815. if not archive:
  1816. raise HTTPException(404, "Archive not found")
  1817. file_path = settings.base_dir / archive.file_path
  1818. if not file_path.exists():
  1819. raise HTTPException(404, "Archive file not found")
  1820. parser = ProjectPageParser(file_path)
  1821. data = parser.parse(archive_id)
  1822. return ProjectPageResponse(**data)
  1823. @router.patch("/{archive_id}/project-page")
  1824. async def update_project_page(
  1825. archive_id: int,
  1826. update_data: dict,
  1827. db: AsyncSession = Depends(get_db),
  1828. ):
  1829. """Update project page metadata in the 3MF file."""
  1830. from backend.app.services.archive import ProjectPageParser
  1831. service = ArchiveService(db)
  1832. archive = await service.get_archive(archive_id)
  1833. if not archive:
  1834. raise HTTPException(404, "Archive not found")
  1835. file_path = settings.base_dir / archive.file_path
  1836. if not file_path.exists():
  1837. raise HTTPException(404, "Archive file not found")
  1838. parser = ProjectPageParser(file_path)
  1839. success = parser.update_metadata(update_data)
  1840. if not success:
  1841. raise HTTPException(500, "Failed to update project page")
  1842. # Return updated data
  1843. data = parser.parse(archive_id)
  1844. return data
  1845. @router.get("/{archive_id}/project-image/{image_path:path}")
  1846. async def get_project_image(
  1847. archive_id: int,
  1848. image_path: str,
  1849. db: AsyncSession = Depends(get_db),
  1850. ):
  1851. """Get an image from the 3MF project page."""
  1852. from backend.app.services.archive import ProjectPageParser
  1853. service = ArchiveService(db)
  1854. archive = await service.get_archive(archive_id)
  1855. if not archive:
  1856. raise HTTPException(404, "Archive not found")
  1857. file_path = settings.base_dir / archive.file_path
  1858. if not file_path.exists():
  1859. raise HTTPException(404, "Archive file not found")
  1860. parser = ProjectPageParser(file_path)
  1861. result = parser.get_image(image_path)
  1862. if not result:
  1863. raise HTTPException(404, "Image not found in 3MF file")
  1864. image_data, content_type = result
  1865. return Response(
  1866. content=image_data,
  1867. media_type=content_type,
  1868. headers={"Cache-Control": "max-age=3600"},
  1869. )
  1870. # =============================================================================
  1871. # Source 3MF API (Original Project Files)
  1872. # =============================================================================
  1873. @router.post("/{archive_id}/source")
  1874. async def upload_source_3mf(
  1875. archive_id: int,
  1876. file: UploadFile = File(...),
  1877. db: AsyncSession = Depends(get_db),
  1878. ):
  1879. """Upload the original source 3MF project file for an archive."""
  1880. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1881. archive = result.scalar_one_or_none()
  1882. if not archive:
  1883. raise HTTPException(404, "Archive not found")
  1884. if not file.filename or not file.filename.endswith(".3mf"):
  1885. raise HTTPException(400, "File must be a .3mf file")
  1886. # Get archive directory and create source subdirectory
  1887. file_path = settings.base_dir / archive.file_path
  1888. archive_dir = file_path.parent
  1889. source_dir = archive_dir / "source"
  1890. source_dir.mkdir(exist_ok=True)
  1891. # Delete old source file if exists
  1892. if archive.source_3mf_path:
  1893. old_source_path = settings.base_dir / archive.source_3mf_path
  1894. if old_source_path.exists():
  1895. old_source_path.unlink()
  1896. # Save the source 3MF file - preserve original filename
  1897. source_filename = file.filename
  1898. source_path = source_dir / source_filename
  1899. content = await file.read()
  1900. source_path.write_bytes(content)
  1901. # Update archive with source path (relative to base_dir)
  1902. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1903. await db.commit()
  1904. await db.refresh(archive)
  1905. return {
  1906. "status": "uploaded",
  1907. "source_3mf_path": archive.source_3mf_path,
  1908. "filename": source_filename,
  1909. }
  1910. @router.get("/{archive_id}/source")
  1911. async def download_source_3mf(
  1912. archive_id: int,
  1913. db: AsyncSession = Depends(get_db),
  1914. ):
  1915. """Download the source 3MF project file."""
  1916. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1917. archive = result.scalar_one_or_none()
  1918. if not archive:
  1919. raise HTTPException(404, "Archive not found")
  1920. if not archive.source_3mf_path:
  1921. raise HTTPException(404, "No source 3MF attached to this archive")
  1922. source_path = settings.base_dir / archive.source_3mf_path
  1923. if not source_path.exists():
  1924. raise HTTPException(404, "Source 3MF file not found on disk")
  1925. # Use the actual filename from the path
  1926. filename = source_path.name
  1927. return FileResponse(
  1928. path=source_path,
  1929. filename=filename,
  1930. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1931. )
  1932. @router.get("/{archive_id}/source/{filename}")
  1933. async def download_source_3mf_for_slicer(
  1934. archive_id: int,
  1935. filename: str,
  1936. db: AsyncSession = Depends(get_db),
  1937. ):
  1938. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  1939. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1940. archive = result.scalar_one_or_none()
  1941. if not archive:
  1942. raise HTTPException(404, "Archive not found")
  1943. if not archive.source_3mf_path:
  1944. raise HTTPException(404, "No source 3MF attached to this archive")
  1945. source_path = settings.base_dir / archive.source_3mf_path
  1946. if not source_path.exists():
  1947. raise HTTPException(404, "Source 3MF file not found on disk")
  1948. return FileResponse(
  1949. path=source_path,
  1950. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  1951. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1952. )
  1953. @router.post("/upload-source")
  1954. async def upload_source_3mf_by_name(
  1955. file: UploadFile = File(...),
  1956. print_name: str = Query(None, description="Match archive by print name"),
  1957. db: AsyncSession = Depends(get_db),
  1958. ):
  1959. """Upload source 3MF and match to archive by print name.
  1960. This endpoint is designed for slicer post-processing scripts.
  1961. It finds the most recent archive matching the print name and attaches the source.
  1962. """
  1963. if not file.filename or not file.filename.endswith(".3mf"):
  1964. raise HTTPException(400, "File must be a .3mf file")
  1965. # Derive print name from filename if not provided
  1966. if not print_name:
  1967. # Remove .3mf extension and common suffixes
  1968. print_name = file.filename.rsplit(".3mf", 1)[0]
  1969. # Remove _source suffix if present
  1970. if print_name.endswith("_source"):
  1971. print_name = print_name[:-7]
  1972. # Find matching archive - try exact match first, then fuzzy
  1973. result = await db.execute(
  1974. select(PrintArchive)
  1975. .where(PrintArchive.print_name == print_name)
  1976. .order_by(PrintArchive.created_at.desc())
  1977. .limit(1)
  1978. )
  1979. archive = result.scalar_one_or_none()
  1980. if not archive:
  1981. # Try matching filename without .gcode.3mf
  1982. result = await db.execute(
  1983. select(PrintArchive)
  1984. .where(PrintArchive.filename.like(f"{print_name}%"))
  1985. .order_by(PrintArchive.created_at.desc())
  1986. .limit(1)
  1987. )
  1988. archive = result.scalar_one_or_none()
  1989. if not archive:
  1990. # Try case-insensitive partial match on print_name
  1991. result = await db.execute(
  1992. select(PrintArchive)
  1993. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  1994. .order_by(PrintArchive.created_at.desc())
  1995. .limit(1)
  1996. )
  1997. archive = result.scalar_one_or_none()
  1998. if not archive:
  1999. raise HTTPException(404, f"No archive found matching '{print_name}'")
  2000. # Get archive directory and create source subdirectory
  2001. file_path = settings.base_dir / archive.file_path
  2002. archive_dir = file_path.parent
  2003. source_dir = archive_dir / "source"
  2004. source_dir.mkdir(exist_ok=True)
  2005. # Delete old source file if exists
  2006. if archive.source_3mf_path:
  2007. old_source_path = settings.base_dir / archive.source_3mf_path
  2008. if old_source_path.exists():
  2009. old_source_path.unlink()
  2010. # Save the source 3MF file - preserve original filename
  2011. source_filename = file.filename
  2012. source_path = source_dir / source_filename
  2013. content = await file.read()
  2014. source_path.write_bytes(content)
  2015. # Update archive with source path
  2016. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  2017. await db.commit()
  2018. await db.refresh(archive)
  2019. return {
  2020. "status": "uploaded",
  2021. "archive_id": archive.id,
  2022. "archive_name": archive.print_name or archive.filename,
  2023. "source_3mf_path": archive.source_3mf_path,
  2024. "filename": source_filename,
  2025. }
  2026. @router.delete("/{archive_id}/source")
  2027. async def delete_source_3mf(
  2028. archive_id: int,
  2029. db: AsyncSession = Depends(get_db),
  2030. ):
  2031. """Delete the source 3MF project file from an archive."""
  2032. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2033. archive = result.scalar_one_or_none()
  2034. if not archive:
  2035. raise HTTPException(404, "Archive not found")
  2036. if not archive.source_3mf_path:
  2037. raise HTTPException(404, "No source 3MF attached to this archive")
  2038. # Delete the file
  2039. source_path = settings.base_dir / archive.source_3mf_path
  2040. if source_path.exists():
  2041. source_path.unlink()
  2042. # Clear the path in database
  2043. archive.source_3mf_path = None
  2044. await db.commit()
  2045. return {"status": "deleted"}
  2046. # =============================================================================
  2047. # F3D API (Fusion 360 Design Files)
  2048. # =============================================================================
  2049. @router.post("/{archive_id}/f3d")
  2050. async def upload_f3d(
  2051. archive_id: int,
  2052. file: UploadFile = File(...),
  2053. db: AsyncSession = Depends(get_db),
  2054. ):
  2055. """Upload a Fusion 360 design file for an archive."""
  2056. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2057. archive = result.scalar_one_or_none()
  2058. if not archive:
  2059. raise HTTPException(404, "Archive not found")
  2060. if not file.filename or not file.filename.endswith(".f3d"):
  2061. raise HTTPException(400, "File must be a .f3d file")
  2062. # Get archive directory and create f3d subdirectory
  2063. file_path = settings.base_dir / archive.file_path
  2064. archive_dir = file_path.parent
  2065. f3d_dir = archive_dir / "f3d"
  2066. f3d_dir.mkdir(exist_ok=True)
  2067. # Delete old F3D file if exists
  2068. if archive.f3d_path:
  2069. old_f3d_path = settings.base_dir / archive.f3d_path
  2070. if old_f3d_path.exists():
  2071. old_f3d_path.unlink()
  2072. # Save the F3D file - preserve original filename
  2073. f3d_filename = file.filename
  2074. f3d_path = f3d_dir / f3d_filename
  2075. content = await file.read()
  2076. f3d_path.write_bytes(content)
  2077. # Update archive with F3D path (relative to base_dir)
  2078. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  2079. await db.commit()
  2080. await db.refresh(archive)
  2081. return {
  2082. "status": "uploaded",
  2083. "f3d_path": archive.f3d_path,
  2084. "filename": f3d_filename,
  2085. }
  2086. @router.get("/{archive_id}/f3d")
  2087. async def download_f3d(
  2088. archive_id: int,
  2089. db: AsyncSession = Depends(get_db),
  2090. ):
  2091. """Download the Fusion 360 design file."""
  2092. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2093. archive = result.scalar_one_or_none()
  2094. if not archive:
  2095. raise HTTPException(404, "Archive not found")
  2096. if not archive.f3d_path:
  2097. raise HTTPException(404, "No F3D file attached to this archive")
  2098. f3d_path = settings.base_dir / archive.f3d_path
  2099. if not f3d_path.exists():
  2100. raise HTTPException(404, "F3D file not found on disk")
  2101. # Use the actual filename from the path
  2102. filename = f3d_path.name
  2103. return FileResponse(
  2104. path=f3d_path,
  2105. filename=filename,
  2106. media_type="application/octet-stream",
  2107. )
  2108. @router.delete("/{archive_id}/f3d")
  2109. async def delete_f3d(
  2110. archive_id: int,
  2111. db: AsyncSession = Depends(get_db),
  2112. ):
  2113. """Delete the Fusion 360 design file from an archive."""
  2114. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2115. archive = result.scalar_one_or_none()
  2116. if not archive:
  2117. raise HTTPException(404, "Archive not found")
  2118. if not archive.f3d_path:
  2119. raise HTTPException(404, "No F3D file attached to this archive")
  2120. # Delete the file
  2121. f3d_path = settings.base_dir / archive.f3d_path
  2122. if f3d_path.exists():
  2123. f3d_path.unlink()
  2124. # Clear the path in database
  2125. archive.f3d_path = None
  2126. await db.commit()
  2127. return {"status": "deleted"}