archives.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  1. import io
  2. import logging
  3. import zipfile
  4. from pathlib import Path
  5. from fastapi import APIRouter, Depends, File, 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
  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. "duplicates": duplicates,
  57. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  58. "print_name": archive.print_name,
  59. "print_time_seconds": archive.print_time_seconds,
  60. "filament_used_grams": archive.filament_used_grams,
  61. "filament_type": archive.filament_type,
  62. "filament_color": archive.filament_color,
  63. "layer_height": archive.layer_height,
  64. "total_layers": archive.total_layers,
  65. "nozzle_diameter": archive.nozzle_diameter,
  66. "bed_temperature": archive.bed_temperature,
  67. "nozzle_temperature": archive.nozzle_temperature,
  68. "status": archive.status,
  69. "started_at": archive.started_at,
  70. "completed_at": archive.completed_at,
  71. "extra_data": archive.extra_data,
  72. "makerworld_url": archive.makerworld_url,
  73. "designer": archive.designer,
  74. "is_favorite": archive.is_favorite,
  75. "tags": archive.tags,
  76. "notes": archive.notes,
  77. "cost": archive.cost,
  78. "photos": archive.photos,
  79. "failure_reason": archive.failure_reason,
  80. "created_at": archive.created_at,
  81. }
  82. # Add computed time accuracy fields
  83. accuracy_data = compute_time_accuracy(archive)
  84. data.update(accuracy_data)
  85. return data
  86. @router.get("/", response_model=list[ArchiveResponse])
  87. async def list_archives(
  88. printer_id: int | None = None,
  89. project_id: int | None = None,
  90. limit: int = 50,
  91. offset: int = 0,
  92. db: AsyncSession = Depends(get_db),
  93. ):
  94. """List archived prints."""
  95. service = ArchiveService(db)
  96. archives = await service.list_archives(
  97. printer_id=printer_id,
  98. project_id=project_id,
  99. limit=limit,
  100. offset=offset,
  101. )
  102. # Get set of hashes that have duplicates (efficient single query)
  103. duplicate_hashes = await service.get_duplicate_hashes()
  104. # Mark archives that have duplicates
  105. result = []
  106. for a in archives:
  107. has_duplicate = a.content_hash in duplicate_hashes if a.content_hash else False
  108. result.append(archive_to_response(a, duplicate_count=1 if has_duplicate else 0))
  109. return result
  110. @router.get("/search", response_model=list[ArchiveResponse])
  111. async def search_archives(
  112. q: str = Query(..., min_length=2, description="Search query"),
  113. printer_id: int | None = None,
  114. project_id: int | None = None,
  115. status: str | None = None,
  116. limit: int = 50,
  117. offset: int = 0,
  118. db: AsyncSession = Depends(get_db),
  119. ):
  120. """Full-text search across archives.
  121. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  122. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  123. """
  124. from sqlalchemy import text
  125. from sqlalchemy.orm import selectinload
  126. # Prepare search query - add wildcard for partial matches
  127. search_term = q.strip()
  128. if not search_term.endswith("*"):
  129. search_term = f"{search_term}*"
  130. # Build the FTS query
  131. # Using MATCH for FTS5 full-text search
  132. fts_query = text("""
  133. SELECT rowid FROM archive_fts
  134. WHERE archive_fts MATCH :search_term
  135. ORDER BY rank
  136. LIMIT :limit OFFSET :offset
  137. """)
  138. try:
  139. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  140. matched_ids = [row[0] for row in result.fetchall()]
  141. except Exception as e:
  142. logger.warning(f"FTS search failed, falling back to LIKE search: {e}")
  143. # Fallback to LIKE search if FTS fails
  144. like_pattern = f"%{q}%"
  145. query = (
  146. select(PrintArchive)
  147. .options(selectinload(PrintArchive.project))
  148. .where(
  149. (PrintArchive.print_name.ilike(like_pattern))
  150. | (PrintArchive.filename.ilike(like_pattern))
  151. | (PrintArchive.tags.ilike(like_pattern))
  152. | (PrintArchive.notes.ilike(like_pattern))
  153. | (PrintArchive.designer.ilike(like_pattern))
  154. | (PrintArchive.filament_type.ilike(like_pattern))
  155. )
  156. .order_by(PrintArchive.created_at.desc())
  157. )
  158. if printer_id:
  159. query = query.where(PrintArchive.printer_id == printer_id)
  160. if project_id:
  161. query = query.where(PrintArchive.project_id == project_id)
  162. if status:
  163. query = query.where(PrintArchive.status == status)
  164. query = query.limit(limit).offset(offset)
  165. result = await db.execute(query)
  166. archives = result.scalars().all()
  167. return [archive_to_response(a) for a in archives]
  168. if not matched_ids:
  169. return []
  170. # Fetch full archive records for matched IDs
  171. query = select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id.in_(matched_ids))
  172. # Apply additional filters
  173. if printer_id:
  174. query = query.where(PrintArchive.printer_id == printer_id)
  175. if project_id:
  176. query = query.where(PrintArchive.project_id == project_id)
  177. if status:
  178. query = query.where(PrintArchive.status == status)
  179. result = await db.execute(query)
  180. archives_dict = {a.id: a for a in result.scalars().all()}
  181. # Preserve FTS ranking order and apply pagination
  182. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  183. paginated = ordered_archives[offset : offset + limit]
  184. return [archive_to_response(a) for a in paginated]
  185. @router.post("/search/rebuild-index")
  186. async def rebuild_search_index(db: AsyncSession = Depends(get_db)):
  187. """Rebuild the full-text search index from existing archives.
  188. Use this if search results seem incomplete or incorrect.
  189. """
  190. from sqlalchemy import text
  191. try:
  192. # Clear and rebuild the FTS index
  193. await db.execute(text("DELETE FROM archive_fts"))
  194. # Repopulate from print_archives
  195. await db.execute(
  196. text("""
  197. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  198. SELECT id, print_name, filename, tags, notes, designer, filament_type
  199. FROM print_archives
  200. """)
  201. )
  202. await db.commit()
  203. # Count entries
  204. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  205. count = result.scalar() or 0
  206. return {"message": f"Search index rebuilt with {count} entries"}
  207. except Exception as e:
  208. logger.error(f"Failed to rebuild search index: {e}")
  209. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  210. @router.get("/analysis/failures")
  211. async def analyze_failures(
  212. days: int = 30,
  213. printer_id: int | None = None,
  214. project_id: int | None = None,
  215. db: AsyncSession = Depends(get_db),
  216. ):
  217. """Analyze failure patterns across prints.
  218. Returns failure statistics including:
  219. - Overall failure rate
  220. - Failures by reason, filament type, printer
  221. - Time of day distribution
  222. - Recent failures
  223. - Weekly trend
  224. """
  225. from backend.app.services.failure_analysis import FailureAnalysisService
  226. service = FailureAnalysisService(db)
  227. return await service.analyze_failures(
  228. days=days,
  229. printer_id=printer_id,
  230. project_id=project_id,
  231. )
  232. @router.get("/compare")
  233. async def compare_archives(
  234. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  235. db: AsyncSession = Depends(get_db),
  236. ):
  237. """Compare multiple archives side by side.
  238. Compares print settings, filament usage, and print times.
  239. Also analyzes correlation between settings and success/failure.
  240. Args:
  241. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  242. """
  243. from backend.app.services.archive_comparison import ArchiveComparisonService
  244. # Parse and validate archive IDs
  245. try:
  246. ids = [int(id.strip()) for id in archive_ids.split(",")]
  247. except ValueError:
  248. raise HTTPException(400, "Invalid archive IDs format")
  249. if len(ids) < 2:
  250. raise HTTPException(400, "At least 2 archives required for comparison")
  251. if len(ids) > 5:
  252. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  253. service = ArchiveComparisonService(db)
  254. try:
  255. return await service.compare_archives(ids)
  256. except ValueError as e:
  257. raise HTTPException(400, str(e))
  258. @router.get("/export")
  259. async def export_archives(
  260. format: str = Query("csv", description="Export format: csv or xlsx"),
  261. fields: str | None = Query(None, description="Comma-separated field names"),
  262. printer_id: int | None = None,
  263. project_id: int | None = None,
  264. status: str | None = None,
  265. date_from: str | None = Query(None, description="Start date (ISO format)"),
  266. date_to: str | None = Query(None, description="End date (ISO format)"),
  267. search: str | None = None,
  268. db: AsyncSession = Depends(get_db),
  269. ):
  270. """Export archives to CSV or Excel format.
  271. Returns a downloadable file with archive data.
  272. """
  273. from datetime import datetime
  274. from fastapi.responses import StreamingResponse
  275. from backend.app.services.export import ExportService
  276. if format not in ("csv", "xlsx"):
  277. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  278. # Parse fields
  279. field_list = None
  280. if fields:
  281. field_list = [f.strip() for f in fields.split(",")]
  282. # Parse dates
  283. date_from_dt = None
  284. date_to_dt = None
  285. if date_from:
  286. try:
  287. date_from_dt = datetime.fromisoformat(date_from)
  288. except ValueError:
  289. raise HTTPException(400, "Invalid date_from format")
  290. if date_to:
  291. try:
  292. date_to_dt = datetime.fromisoformat(date_to)
  293. except ValueError:
  294. raise HTTPException(400, "Invalid date_to format")
  295. service = ExportService(db)
  296. try:
  297. file_bytes, filename, content_type = await service.export_archives(
  298. format=format,
  299. fields=field_list,
  300. printer_id=printer_id,
  301. project_id=project_id,
  302. status=status,
  303. date_from=date_from_dt,
  304. date_to=date_to_dt,
  305. search=search,
  306. )
  307. except ImportError as e:
  308. raise HTTPException(500, str(e))
  309. return StreamingResponse(
  310. io.BytesIO(file_bytes),
  311. media_type=content_type,
  312. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  313. )
  314. @router.get("/stats/export")
  315. async def export_stats(
  316. format: str = Query("csv", description="Export format: csv or xlsx"),
  317. days: int = 30,
  318. printer_id: int | None = None,
  319. project_id: int | None = None,
  320. db: AsyncSession = Depends(get_db),
  321. ):
  322. """Export statistics summary to CSV or Excel format."""
  323. from fastapi.responses import StreamingResponse
  324. from backend.app.services.export import ExportService
  325. if format not in ("csv", "xlsx"):
  326. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  327. service = ExportService(db)
  328. try:
  329. file_bytes, filename, content_type = await service.export_stats(
  330. format=format,
  331. days=days,
  332. printer_id=printer_id,
  333. project_id=project_id,
  334. )
  335. except ImportError as e:
  336. raise HTTPException(500, str(e))
  337. return StreamingResponse(
  338. io.BytesIO(file_bytes),
  339. media_type=content_type,
  340. headers={"Content-Disposition": f'attachment; filename="{filename}"'},
  341. )
  342. @router.get("/stats", response_model=ArchiveStats)
  343. async def get_archive_stats(db: AsyncSession = Depends(get_db)):
  344. """Get statistics across all archives."""
  345. # Total counts
  346. total_result = await db.execute(select(func.count(PrintArchive.id)))
  347. total_prints = total_result.scalar() or 0
  348. successful_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "completed"))
  349. successful_prints = successful_result.scalar() or 0
  350. failed_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.status == "failed"))
  351. failed_prints = failed_result.scalar() or 0
  352. # Totals
  353. time_result = await db.execute(select(func.sum(PrintArchive.print_time_seconds)))
  354. total_time = (time_result.scalar() or 0) / 3600 # Convert to hours
  355. filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams)))
  356. total_filament = filament_result.scalar() or 0
  357. cost_result = await db.execute(select(func.sum(PrintArchive.cost)))
  358. total_cost = cost_result.scalar() or 0
  359. # By filament type (split comma-separated values for multi-material prints)
  360. filament_type_result = await db.execute(
  361. select(PrintArchive.filament_type).where(PrintArchive.filament_type.isnot(None))
  362. )
  363. prints_by_filament: dict[str, int] = {}
  364. for (filament_types,) in filament_type_result.all():
  365. # Split by comma and count each type
  366. for ftype in filament_types.split(","):
  367. ftype = ftype.strip()
  368. if ftype:
  369. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  370. # By printer
  371. printer_result = await db.execute(
  372. select(PrintArchive.printer_id, func.count(PrintArchive.id)).group_by(PrintArchive.printer_id)
  373. )
  374. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  375. # Time accuracy statistics
  376. # Get all completed archives with both estimated and actual times
  377. accuracy_result = await db.execute(
  378. select(PrintArchive)
  379. .where(PrintArchive.status == "completed")
  380. .where(PrintArchive.print_time_seconds.isnot(None))
  381. .where(PrintArchive.started_at.isnot(None))
  382. .where(PrintArchive.completed_at.isnot(None))
  383. )
  384. archives_with_times = list(accuracy_result.scalars().all())
  385. average_accuracy = None
  386. accuracy_by_printer: dict[str, float] = {}
  387. if archives_with_times:
  388. accuracies = []
  389. printer_accuracies: dict[str, list[float]] = {}
  390. for archive in archives_with_times:
  391. acc_data = compute_time_accuracy(archive)
  392. if acc_data["time_accuracy"] is not None:
  393. accuracies.append(acc_data["time_accuracy"])
  394. # Group by printer
  395. printer_key = str(archive.printer_id) if archive.printer_id else "unknown"
  396. if printer_key not in printer_accuracies:
  397. printer_accuracies[printer_key] = []
  398. printer_accuracies[printer_key].append(acc_data["time_accuracy"])
  399. if accuracies:
  400. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  401. # Calculate per-printer averages
  402. for printer_key, accs in printer_accuracies.items():
  403. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  404. # Energy totals - check which mode to use
  405. from backend.app.api.routes.settings import get_setting
  406. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  407. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  408. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  409. if energy_tracking_mode == "total":
  410. # Total mode: sum up 'total' counter from all smart plugs (lifetime consumption)
  411. from backend.app.models.smart_plug import SmartPlug
  412. from backend.app.services.tasmota import tasmota_service
  413. plugs_result = await db.execute(select(SmartPlug))
  414. plugs = list(plugs_result.scalars().all())
  415. total_energy_kwh = 0.0
  416. for plug in plugs:
  417. energy = await tasmota_service.get_energy(plug)
  418. if energy and energy.get("total") is not None:
  419. total_energy_kwh += energy["total"]
  420. total_energy_kwh = round(total_energy_kwh, 3)
  421. total_energy_cost = round(total_energy_kwh * energy_cost_per_kwh, 2)
  422. else:
  423. # Print mode: sum up per-print energy from archives
  424. energy_kwh_result = await db.execute(select(func.sum(PrintArchive.energy_kwh)))
  425. total_energy_kwh = energy_kwh_result.scalar() or 0
  426. energy_cost_result = await db.execute(select(func.sum(PrintArchive.energy_cost)))
  427. total_energy_cost = energy_cost_result.scalar() or 0
  428. return ArchiveStats(
  429. total_prints=total_prints,
  430. successful_prints=successful_prints,
  431. failed_prints=failed_prints,
  432. total_print_time_hours=round(total_time, 1),
  433. total_filament_grams=round(total_filament, 1),
  434. total_cost=round(total_cost, 2),
  435. prints_by_filament_type=prints_by_filament,
  436. prints_by_printer=prints_by_printer,
  437. average_time_accuracy=average_accuracy,
  438. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  439. total_energy_kwh=round(total_energy_kwh, 3),
  440. total_energy_cost=round(total_energy_cost, 2),
  441. )
  442. @router.get("/{archive_id}", response_model=ArchiveResponse)
  443. async def get_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  444. """Get a specific archive."""
  445. service = ArchiveService(db)
  446. archive = await service.get_archive(archive_id)
  447. if not archive:
  448. raise HTTPException(404, "Archive not found")
  449. # Find duplicates
  450. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  451. duplicates = await service.find_duplicates(
  452. archive_id=archive.id,
  453. content_hash=archive.content_hash,
  454. print_name=archive.print_name,
  455. makerworld_model_id=makerworld_id,
  456. )
  457. return archive_to_response(archive, duplicates)
  458. @router.get("/{archive_id}/similar")
  459. async def find_similar_archives(
  460. archive_id: int,
  461. limit: int = 10,
  462. db: AsyncSession = Depends(get_db),
  463. ):
  464. """Find archives with similar settings for comparison.
  465. Returns archives that match by:
  466. - Same print name (highest priority)
  467. - Same file content hash
  468. - Same filament type
  469. """
  470. from backend.app.services.archive_comparison import ArchiveComparisonService
  471. service = ArchiveComparisonService(db)
  472. try:
  473. return await service.find_similar_archives(archive_id, limit=limit)
  474. except ValueError as e:
  475. raise HTTPException(404, str(e))
  476. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  477. async def update_archive(
  478. archive_id: int,
  479. update_data: ArchiveUpdate,
  480. db: AsyncSession = Depends(get_db),
  481. ):
  482. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  483. from sqlalchemy.orm import selectinload
  484. result = await db.execute(
  485. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  486. )
  487. archive = result.scalar_one_or_none()
  488. if not archive:
  489. raise HTTPException(404, "Archive not found")
  490. for field, value in update_data.model_dump(exclude_unset=True).items():
  491. setattr(archive, field, value)
  492. await db.commit()
  493. # Re-fetch with project relationship loaded after commit
  494. result = await db.execute(
  495. select(PrintArchive).options(selectinload(PrintArchive.project)).where(PrintArchive.id == archive_id)
  496. )
  497. archive = result.scalar_one_or_none()
  498. return archive_to_response(archive)
  499. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  500. async def toggle_favorite(
  501. archive_id: int,
  502. db: AsyncSession = Depends(get_db),
  503. ):
  504. """Toggle favorite status for an archive."""
  505. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  506. archive = result.scalar_one_or_none()
  507. if not archive:
  508. raise HTTPException(404, "Archive not found")
  509. archive.is_favorite = not archive.is_favorite
  510. await db.commit()
  511. await db.refresh(archive)
  512. return archive
  513. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  514. async def rescan_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  515. """Rescan the 3MF file and update metadata."""
  516. from backend.app.services.archive import ThreeMFParser
  517. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  518. archive = result.scalar_one_or_none()
  519. if not archive:
  520. raise HTTPException(404, "Archive not found")
  521. file_path = settings.base_dir / archive.file_path
  522. if not file_path.exists():
  523. raise HTTPException(404, "Archive file not found")
  524. # Parse the 3MF file
  525. parser = ThreeMFParser(file_path)
  526. metadata = parser.parse()
  527. # Update fields from metadata
  528. if metadata.get("filament_type"):
  529. archive.filament_type = metadata["filament_type"]
  530. if metadata.get("filament_color"):
  531. archive.filament_color = metadata["filament_color"]
  532. if metadata.get("print_time_seconds"):
  533. archive.print_time_seconds = metadata["print_time_seconds"]
  534. if metadata.get("filament_used_grams"):
  535. archive.filament_used_grams = metadata["filament_used_grams"]
  536. if metadata.get("layer_height"):
  537. archive.layer_height = metadata["layer_height"]
  538. if metadata.get("nozzle_diameter"):
  539. archive.nozzle_diameter = metadata["nozzle_diameter"]
  540. if metadata.get("bed_temperature"):
  541. archive.bed_temperature = metadata["bed_temperature"]
  542. if metadata.get("nozzle_temperature"):
  543. archive.nozzle_temperature = metadata["nozzle_temperature"]
  544. if metadata.get("makerworld_url"):
  545. archive.makerworld_url = metadata["makerworld_url"]
  546. if metadata.get("designer"):
  547. archive.designer = metadata["designer"]
  548. # Calculate cost based on filament usage and type
  549. if archive.filament_used_grams and archive.filament_type:
  550. primary_type = archive.filament_type.split(",")[0].strip()
  551. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  552. filament = filament_result.scalar_one_or_none()
  553. if filament:
  554. archive.cost = round((archive.filament_used_grams / 1000) * filament.cost_per_kg, 2)
  555. else:
  556. archive.cost = round((archive.filament_used_grams / 1000) * 25.0, 2)
  557. await db.commit()
  558. await db.refresh(archive)
  559. return archive
  560. @router.post("/recalculate-costs")
  561. async def recalculate_all_costs(db: AsyncSession = Depends(get_db)):
  562. """Recalculate costs for all archives based on filament usage and prices."""
  563. result = await db.execute(select(PrintArchive))
  564. archives = list(result.scalars().all())
  565. # Load all filaments for lookup
  566. filament_result = await db.execute(select(Filament))
  567. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  568. default_cost_per_kg = 25.0
  569. updated = 0
  570. for archive in archives:
  571. if archive.filament_used_grams and archive.filament_type:
  572. primary_type = archive.filament_type.split(",")[0].strip()
  573. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  574. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  575. if archive.cost != new_cost:
  576. archive.cost = new_cost
  577. updated += 1
  578. await db.commit()
  579. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  580. @router.post("/rescan-all")
  581. async def rescan_all_archives(db: AsyncSession = Depends(get_db)):
  582. """Rescan all archives and update their metadata."""
  583. from backend.app.services.archive import ThreeMFParser
  584. result = await db.execute(select(PrintArchive))
  585. archives = list(result.scalars().all())
  586. updated = 0
  587. errors = []
  588. for archive in archives:
  589. try:
  590. file_path = settings.base_dir / archive.file_path
  591. if not file_path.exists():
  592. errors.append({"id": archive.id, "error": "File not found"})
  593. continue
  594. parser = ThreeMFParser(file_path)
  595. metadata = parser.parse()
  596. if metadata.get("filament_type"):
  597. archive.filament_type = metadata["filament_type"]
  598. if metadata.get("filament_color"):
  599. archive.filament_color = metadata["filament_color"]
  600. if metadata.get("print_time_seconds"):
  601. archive.print_time_seconds = metadata["print_time_seconds"]
  602. if metadata.get("filament_used_grams"):
  603. archive.filament_used_grams = metadata["filament_used_grams"]
  604. if metadata.get("layer_height"):
  605. archive.layer_height = metadata["layer_height"]
  606. if metadata.get("nozzle_diameter"):
  607. archive.nozzle_diameter = metadata["nozzle_diameter"]
  608. if metadata.get("makerworld_url"):
  609. archive.makerworld_url = metadata["makerworld_url"]
  610. if metadata.get("designer"):
  611. archive.designer = metadata["designer"]
  612. updated += 1
  613. except Exception as e:
  614. errors.append({"id": archive.id, "error": str(e)})
  615. await db.commit()
  616. return {"updated": updated, "errors": errors}
  617. @router.get("/{archive_id}/duplicates")
  618. async def get_archive_duplicates(archive_id: int, db: AsyncSession = Depends(get_db)):
  619. """Get duplicates for a specific archive."""
  620. service = ArchiveService(db)
  621. archive = await service.get_archive(archive_id)
  622. if not archive:
  623. raise HTTPException(404, "Archive not found")
  624. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  625. duplicates = await service.find_duplicates(
  626. archive_id=archive.id,
  627. content_hash=archive.content_hash,
  628. print_name=archive.print_name,
  629. makerworld_model_id=makerworld_id,
  630. )
  631. return {"duplicates": duplicates, "count": len(duplicates)}
  632. @router.post("/backfill-hashes")
  633. async def backfill_content_hashes(db: AsyncSession = Depends(get_db)):
  634. """Compute and store content hashes for all archives missing them."""
  635. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  636. archives = list(result.scalars().all())
  637. updated = 0
  638. errors = []
  639. for archive in archives:
  640. try:
  641. file_path = settings.base_dir / archive.file_path
  642. if not file_path.exists():
  643. errors.append({"id": archive.id, "error": "File not found"})
  644. continue
  645. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  646. updated += 1
  647. except Exception as e:
  648. errors.append({"id": archive.id, "error": str(e)})
  649. await db.commit()
  650. return {"updated": updated, "errors": errors}
  651. @router.delete("/{archive_id}")
  652. async def delete_archive(archive_id: int, db: AsyncSession = Depends(get_db)):
  653. """Delete an archive."""
  654. service = ArchiveService(db)
  655. if not await service.delete_archive(archive_id):
  656. raise HTTPException(404, "Archive not found")
  657. return {"status": "deleted"}
  658. @router.get("/{archive_id}/download")
  659. async def download_archive(
  660. archive_id: int,
  661. inline: bool = False,
  662. db: AsyncSession = Depends(get_db),
  663. ):
  664. """Download the 3MF file."""
  665. service = ArchiveService(db)
  666. archive = await service.get_archive(archive_id)
  667. if not archive:
  668. raise HTTPException(404, "Archive not found")
  669. file_path = settings.base_dir / archive.file_path
  670. if not file_path.exists():
  671. raise HTTPException(404, "File not found")
  672. # Use inline disposition to let browser/OS handle file association
  673. content_disposition = "inline" if inline else "attachment"
  674. return FileResponse(
  675. path=file_path,
  676. filename=archive.filename,
  677. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  678. content_disposition_type=content_disposition,
  679. )
  680. @router.get("/{archive_id}/file/{filename}")
  681. async def download_archive_with_filename(
  682. archive_id: int,
  683. filename: str,
  684. db: AsyncSession = Depends(get_db),
  685. ):
  686. """Download the 3MF file with filename in URL (for Bambu Studio protocol)."""
  687. service = ArchiveService(db)
  688. archive = await service.get_archive(archive_id)
  689. if not archive:
  690. raise HTTPException(404, "Archive not found")
  691. file_path = settings.base_dir / archive.file_path
  692. if not file_path.exists():
  693. raise HTTPException(404, "File not found")
  694. return FileResponse(
  695. path=file_path,
  696. filename=archive.filename,
  697. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  698. )
  699. @router.get("/{archive_id}/thumbnail")
  700. async def get_thumbnail(archive_id: int, db: AsyncSession = Depends(get_db)):
  701. """Get the thumbnail image."""
  702. service = ArchiveService(db)
  703. archive = await service.get_archive(archive_id)
  704. if not archive or not archive.thumbnail_path:
  705. raise HTTPException(404, "Thumbnail not found")
  706. thumb_path = settings.base_dir / archive.thumbnail_path
  707. if not thumb_path.exists():
  708. raise HTTPException(404, "Thumbnail file not found")
  709. return FileResponse(path=thumb_path, media_type="image/png")
  710. @router.get("/{archive_id}/timelapse")
  711. async def get_timelapse(archive_id: int, db: AsyncSession = Depends(get_db)):
  712. """Get the timelapse video."""
  713. service = ArchiveService(db)
  714. archive = await service.get_archive(archive_id)
  715. if not archive or not archive.timelapse_path:
  716. raise HTTPException(404, "Timelapse not found")
  717. timelapse_path = settings.base_dir / archive.timelapse_path
  718. if not timelapse_path.exists():
  719. raise HTTPException(404, "Timelapse file not found")
  720. return FileResponse(
  721. path=timelapse_path,
  722. media_type="video/mp4",
  723. filename=f"{archive.print_name or 'timelapse'}.mp4",
  724. )
  725. @router.post("/{archive_id}/timelapse/scan")
  726. async def scan_timelapse(
  727. archive_id: int,
  728. db: AsyncSession = Depends(get_db),
  729. ):
  730. """Scan printer for timelapse matching this archive and attach it."""
  731. from backend.app.models.printer import Printer
  732. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  733. service = ArchiveService(db)
  734. archive = await service.get_archive(archive_id)
  735. if not archive:
  736. raise HTTPException(404, "Archive not found")
  737. if archive.timelapse_path:
  738. return {"status": "exists", "message": "Timelapse already attached"}
  739. if not archive.printer_id:
  740. raise HTTPException(400, "Archive has no associated printer")
  741. # Get printer
  742. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  743. printer = result.scalar_one_or_none()
  744. if not printer:
  745. raise HTTPException(404, "Printer not found")
  746. # Get base name from archive filename (without .3mf extension)
  747. base_name = Path(archive.filename).stem
  748. # Scan timelapse directory on printer
  749. # Try both /timelapse and /timelapse/video (different printer models use different paths)
  750. files = []
  751. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  752. try:
  753. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  754. if files:
  755. break
  756. except Exception:
  757. continue
  758. if not files:
  759. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  760. # Look for matching timelapse
  761. matching_file = None
  762. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  763. # Strategy 1: Match by print name in filename
  764. for f in mp4_files:
  765. fname = f.get("name", "")
  766. if base_name.lower() in fname.lower():
  767. matching_file = f
  768. break
  769. # Strategy 2: Match by timestamp proximity
  770. # Bambu timelapse filename uses the print START time (when recording began)
  771. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  772. import re
  773. from datetime import datetime, timedelta
  774. # Prefer started_at since video filename is the print start time
  775. # Fall back to completed_at or created_at if started_at is not available
  776. archive_start = archive.started_at
  777. archive_end = archive.completed_at or archive.created_at
  778. best_match = None
  779. best_diff = timedelta(hours=24) # Max 24 hour difference
  780. for f in mp4_files:
  781. fname = f.get("name", "")
  782. # Parse timestamp from filename like "video_2025-11-24_03-17-40.mp4"
  783. match = re.search(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})", fname)
  784. if match:
  785. try:
  786. file_time = datetime.strptime(match.group(1), "%Y-%m-%d_%H-%M-%S")
  787. # Try multiple timezone offsets since printer timezone can vary
  788. # Common cases: local time (0), CST/UTC+8 (+8), or UTC (-local offset)
  789. for hour_offset in [0, 8, -8, 7, -7, 1, -1]:
  790. adjusted_file_time = file_time - timedelta(hours=hour_offset)
  791. # Check against start time (video filename = print start)
  792. if archive_start:
  793. diff = abs(adjusted_file_time - archive_start)
  794. if diff < best_diff:
  795. best_diff = diff
  796. best_match = f
  797. logger.debug(
  798. f"Timelapse match candidate: {fname} with offset {hour_offset}h, "
  799. f"diff from start: {diff}"
  800. )
  801. # Also check against end time with a buffer
  802. # (video timestamp should be BEFORE completion time)
  803. if archive_end:
  804. # The video timestamp should be within the print duration before completion
  805. if adjusted_file_time < archive_end:
  806. diff = archive_end - adjusted_file_time
  807. # Reasonable print duration: up to 48 hours
  808. if diff < timedelta(hours=48) and diff < best_diff:
  809. best_diff = diff
  810. best_match = f
  811. logger.debug(
  812. f"Timelapse match candidate (from end): {fname} with offset {hour_offset}h, "
  813. f"diff: {diff}"
  814. )
  815. except ValueError:
  816. continue
  817. # Accept match within 4 hours (more lenient for timezone issues)
  818. if best_match and best_diff < timedelta(hours=4):
  819. matching_file = best_match
  820. logger.info(f"Matched timelapse by timestamp: {best_match.get('name')} (diff: {best_diff})")
  821. # Strategy 3: Use file modification time from FTP listing
  822. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  823. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  824. from datetime import datetime, timedelta
  825. archive_start = archive.started_at
  826. archive_end = archive.completed_at or archive.created_at
  827. best_match = None
  828. best_diff = timedelta(hours=24)
  829. for f in mp4_files:
  830. mtime = f.get("mtime")
  831. if mtime:
  832. # Timelapse file should be modified during or shortly after the print
  833. # The mtime should be close to completion time (video finishes when print ends)
  834. if archive_end:
  835. diff = abs(mtime - archive_end)
  836. if diff < best_diff:
  837. best_diff = diff
  838. best_match = f
  839. logger.debug(
  840. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  841. )
  842. if best_match and best_diff < timedelta(hours=2):
  843. matching_file = best_match
  844. logger.info(f"Matched timelapse by file mtime: {best_match.get('name')} (diff: {best_diff})")
  845. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  846. # This handles cases where printer clock is wrong or timezone issues exist
  847. if not matching_file and len(mp4_files) == 1:
  848. from datetime import datetime, timedelta
  849. archive_completed = archive.completed_at or archive.created_at
  850. if archive_completed:
  851. time_since_completion = datetime.now() - archive_completed
  852. # If archive was completed within the last hour, assume the single timelapse is for it
  853. if time_since_completion < timedelta(hours=1):
  854. matching_file = mp4_files[0]
  855. logger.info(f"Using single timelapse file as fallback: {mp4_files[0].get('name')}")
  856. # Note: We intentionally don't use a "most recent file" fallback because
  857. # we can't verify if timelapse was actually enabled for this print.
  858. # Instead, return the list of available files for manual selection.
  859. if not matching_file:
  860. # Return available files for manual selection
  861. available_files = [
  862. {
  863. "name": f.get("name"),
  864. "path": f.get("path"),
  865. "size": f.get("size"),
  866. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  867. }
  868. for f in mp4_files
  869. ]
  870. # Sort by mtime descending (most recent first)
  871. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  872. return {
  873. "status": "not_found",
  874. "message": "No matching timelapse found - please select manually",
  875. "available_files": available_files,
  876. }
  877. # Download the timelapse - use the full path from the file listing
  878. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  879. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  880. if not timelapse_data:
  881. raise HTTPException(500, "Failed to download timelapse")
  882. # Attach timelapse to archive
  883. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  884. if not success:
  885. raise HTTPException(500, "Failed to attach timelapse")
  886. return {
  887. "status": "attached",
  888. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  889. "filename": matching_file["name"],
  890. }
  891. @router.post("/{archive_id}/timelapse/select")
  892. async def select_timelapse(
  893. archive_id: int,
  894. filename: str = Query(..., description="Timelapse filename to attach"),
  895. db: AsyncSession = Depends(get_db),
  896. ):
  897. """Manually select a timelapse from the printer to attach."""
  898. from backend.app.models.printer import Printer
  899. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  900. service = ArchiveService(db)
  901. archive = await service.get_archive(archive_id)
  902. if not archive:
  903. raise HTTPException(404, "Archive not found")
  904. if not archive.printer_id:
  905. raise HTTPException(400, "Archive has no associated printer")
  906. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  907. printer = result.scalar_one_or_none()
  908. if not printer:
  909. raise HTTPException(404, "Printer not found")
  910. # Find the file on the printer
  911. files = []
  912. remote_path = None
  913. for timelapse_dir in ["/timelapse", "/timelapse/video"]:
  914. try:
  915. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_dir)
  916. for f in files:
  917. if f.get("name") == filename:
  918. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  919. break
  920. if remote_path:
  921. break
  922. except Exception:
  923. continue
  924. if not remote_path:
  925. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  926. # Download and attach
  927. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  928. if not timelapse_data:
  929. raise HTTPException(500, "Failed to download timelapse")
  930. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  931. if not success:
  932. raise HTTPException(500, "Failed to attach timelapse")
  933. return {
  934. "status": "attached",
  935. "message": f"Timelapse '{filename}' attached successfully",
  936. "filename": filename,
  937. }
  938. @router.post("/{archive_id}/timelapse/upload")
  939. async def upload_timelapse(
  940. archive_id: int,
  941. file: UploadFile = File(...),
  942. db: AsyncSession = Depends(get_db),
  943. ):
  944. """Manually upload a timelapse video to an archive."""
  945. service = ArchiveService(db)
  946. archive = await service.get_archive(archive_id)
  947. if not archive:
  948. raise HTTPException(404, "Archive not found")
  949. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  950. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  951. content = await file.read()
  952. success = await service.attach_timelapse(archive_id, content, file.filename)
  953. if not success:
  954. raise HTTPException(500, "Failed to attach timelapse")
  955. return {"status": "attached", "filename": file.filename}
  956. # ============================================
  957. # Photo Endpoints
  958. # ============================================
  959. @router.post("/{archive_id}/photos")
  960. async def upload_photo(
  961. archive_id: int,
  962. file: UploadFile = File(...),
  963. db: AsyncSession = Depends(get_db),
  964. ):
  965. """Upload a photo of the printed result."""
  966. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  967. archive = result.scalar_one_or_none()
  968. if not archive:
  969. raise HTTPException(404, "Archive not found")
  970. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  971. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  972. # Get archive directory
  973. file_path = settings.base_dir / archive.file_path
  974. archive_dir = file_path.parent
  975. photos_dir = archive_dir / "photos"
  976. photos_dir.mkdir(exist_ok=True)
  977. # Generate unique filename
  978. import uuid
  979. ext = Path(file.filename).suffix.lower()
  980. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  981. photo_path = photos_dir / photo_filename
  982. # Save file
  983. content = await file.read()
  984. photo_path.write_bytes(content)
  985. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  986. photos = list(archive.photos or [])
  987. photos.append(photo_filename)
  988. archive.photos = photos
  989. await db.commit()
  990. await db.refresh(archive)
  991. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  992. @router.get("/{archive_id}/photos/{filename}")
  993. async def get_photo(
  994. archive_id: int,
  995. filename: str,
  996. db: AsyncSession = Depends(get_db),
  997. ):
  998. """Get a specific photo."""
  999. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1000. archive = result.scalar_one_or_none()
  1001. if not archive:
  1002. raise HTTPException(404, "Archive not found")
  1003. file_path = settings.base_dir / archive.file_path
  1004. photo_path = file_path.parent / "photos" / filename
  1005. if not photo_path.exists():
  1006. raise HTTPException(404, "Photo not found")
  1007. # Determine media type
  1008. ext = Path(filename).suffix.lower()
  1009. media_types = {
  1010. ".jpg": "image/jpeg",
  1011. ".jpeg": "image/jpeg",
  1012. ".png": "image/png",
  1013. ".webp": "image/webp",
  1014. }
  1015. media_type = media_types.get(ext, "image/jpeg")
  1016. return FileResponse(path=photo_path, media_type=media_type)
  1017. @router.delete("/{archive_id}/photos/{filename}")
  1018. async def delete_photo(
  1019. archive_id: int,
  1020. filename: str,
  1021. db: AsyncSession = Depends(get_db),
  1022. ):
  1023. """Delete a photo."""
  1024. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1025. archive = result.scalar_one_or_none()
  1026. if not archive:
  1027. raise HTTPException(404, "Archive not found")
  1028. if not archive.photos or filename not in archive.photos:
  1029. raise HTTPException(404, "Photo not found")
  1030. # Delete file
  1031. file_path = settings.base_dir / archive.file_path
  1032. photo_path = file_path.parent / "photos" / filename
  1033. if photo_path.exists():
  1034. photo_path.unlink()
  1035. # Update archive photos list
  1036. photos = [p for p in archive.photos if p != filename]
  1037. archive.photos = photos if photos else None
  1038. await db.commit()
  1039. return {"status": "deleted", "photos": archive.photos}
  1040. # ============================================
  1041. # QR Code Endpoint
  1042. # ============================================
  1043. @router.get("/{archive_id}/qrcode")
  1044. async def get_qrcode(
  1045. archive_id: int,
  1046. request: Request,
  1047. size: int = 200,
  1048. db: AsyncSession = Depends(get_db),
  1049. ):
  1050. """Generate a QR code that links to this archive."""
  1051. import qrcode
  1052. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1053. archive = result.scalar_one_or_none()
  1054. if not archive:
  1055. raise HTTPException(404, "Archive not found")
  1056. # Build URL to archive detail page
  1057. base_url = str(request.base_url).rstrip("/")
  1058. archive_url = f"{base_url}/archives?id={archive_id}"
  1059. # Generate QR code
  1060. qr = qrcode.QRCode(
  1061. version=1,
  1062. error_correction=qrcode.constants.ERROR_CORRECT_M,
  1063. box_size=10,
  1064. border=2,
  1065. )
  1066. qr.add_data(archive_url)
  1067. qr.make(fit=True)
  1068. img = qr.make_image(fill_color="black", back_color="white")
  1069. # Resize if needed
  1070. if size != 200:
  1071. img = img.resize((size, size))
  1072. # Convert to bytes
  1073. buffer = io.BytesIO()
  1074. img.save(buffer, format="PNG")
  1075. buffer.seek(0)
  1076. return Response(
  1077. content=buffer.getvalue(),
  1078. media_type="image/png",
  1079. headers={"Content-Disposition": f'inline; filename="qr_{archive.print_name or archive_id}.png"'},
  1080. )
  1081. @router.get("/{archive_id}/capabilities")
  1082. async def get_archive_capabilities(archive_id: int, db: AsyncSession = Depends(get_db)):
  1083. """Check what viewing capabilities are available for this 3MF file."""
  1084. import json
  1085. import xml.etree.ElementTree as ET
  1086. service = ArchiveService(db)
  1087. archive = await service.get_archive(archive_id)
  1088. if not archive:
  1089. raise HTTPException(404, "Archive not found")
  1090. file_path = settings.base_dir / archive.file_path
  1091. if not file_path.exists():
  1092. raise HTTPException(404, "File not found")
  1093. has_model = False
  1094. has_gcode = False
  1095. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  1096. filament_colors: list[str] = []
  1097. try:
  1098. with zipfile.ZipFile(file_path, "r") as zf:
  1099. names = zf.namelist()
  1100. # Check for G-code
  1101. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  1102. # Check for 3D model - need to look for actual mesh data
  1103. for name in names:
  1104. if name.endswith(".model"):
  1105. try:
  1106. content = zf.read(name).decode("utf-8")
  1107. # Check if this model file contains actual mesh vertices
  1108. if "<vertex" in content or "<mesh" in content:
  1109. has_model = True
  1110. break
  1111. except Exception:
  1112. pass
  1113. # Extract filament colors from slice_info.config
  1114. # These are the actual filaments used in the print, indexed by tool/extruder
  1115. if "Metadata/slice_info.config" in names:
  1116. try:
  1117. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  1118. root = ET.fromstring(slice_content)
  1119. # Get all filaments with their IDs and colors
  1120. # <filament id="1" type="PLA" color="#FFFFFF" used_g="100" />
  1121. # ID corresponds to the tool number in G-code (T0, T1, etc.)
  1122. filaments = root.findall(".//filament")
  1123. filament_map: dict[int, str] = {}
  1124. for f in filaments:
  1125. fid = f.get("id")
  1126. fcolor = f.get("color")
  1127. used_g = f.get("used_g", "0")
  1128. try:
  1129. used_amount = float(used_g)
  1130. except (ValueError, TypeError):
  1131. used_amount = 0
  1132. # Include all filaments, but mark unused ones
  1133. if fid is not None and fcolor:
  1134. try:
  1135. # IDs are 1-based in slice_info, tools are 0-based
  1136. tool_id = int(fid) - 1
  1137. if tool_id >= 0 and used_amount > 0:
  1138. filament_map[tool_id] = fcolor
  1139. except ValueError:
  1140. pass
  1141. # Convert to ordered list (tool 0, tool 1, etc.)
  1142. if filament_map:
  1143. max_tool = max(filament_map.keys())
  1144. for i in range(max_tool + 1):
  1145. filament_colors.append(filament_map.get(i, "#00AE42"))
  1146. except Exception:
  1147. pass
  1148. # Extract build volume from project settings
  1149. if "Metadata/project_settings.config" in names:
  1150. try:
  1151. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  1152. config_data = json.loads(config_content)
  1153. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  1154. printable_area = config_data.get("printable_area", [])
  1155. if printable_area and len(printable_area) >= 3:
  1156. # Get max X and Y from the corner coordinates
  1157. max_x = 0
  1158. max_y = 0
  1159. for coord in printable_area:
  1160. if "x" in coord:
  1161. parts = coord.split("x")
  1162. if len(parts) == 2:
  1163. try:
  1164. x, y = int(parts[0]), int(parts[1])
  1165. max_x = max(max_x, x)
  1166. max_y = max(max_y, y)
  1167. except ValueError:
  1168. pass
  1169. if max_x > 0 and max_y > 0:
  1170. build_volume["x"] = max_x
  1171. build_volume["y"] = max_y
  1172. # Parse printable_height
  1173. printable_height = config_data.get("printable_height")
  1174. if printable_height:
  1175. try:
  1176. build_volume["z"] = int(printable_height)
  1177. except (ValueError, TypeError):
  1178. pass
  1179. except Exception:
  1180. pass
  1181. except zipfile.BadZipFile:
  1182. raise HTTPException(400, "Invalid 3MF file")
  1183. return {
  1184. "has_model": has_model,
  1185. "has_gcode": has_gcode,
  1186. "build_volume": build_volume,
  1187. "filament_colors": filament_colors,
  1188. }
  1189. @router.get("/{archive_id}/gcode")
  1190. async def get_gcode(archive_id: int, db: AsyncSession = Depends(get_db)):
  1191. """Extract and return G-code from the 3MF file."""
  1192. service = ArchiveService(db)
  1193. archive = await service.get_archive(archive_id)
  1194. if not archive:
  1195. raise HTTPException(404, "Archive not found")
  1196. file_path = settings.base_dir / archive.file_path
  1197. if not file_path.exists():
  1198. raise HTTPException(404, "File not found")
  1199. try:
  1200. with zipfile.ZipFile(file_path, "r") as zf:
  1201. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  1202. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  1203. if not gcode_files:
  1204. raise HTTPException(
  1205. 404,
  1206. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  1207. )
  1208. # Get the first plate's G-code (usually plate_1.gcode)
  1209. gcode_content = zf.read(gcode_files[0]).decode("utf-8")
  1210. return Response(content=gcode_content, media_type="text/plain")
  1211. except zipfile.BadZipFile:
  1212. raise HTTPException(400, "Invalid 3MF file")
  1213. except HTTPException:
  1214. raise
  1215. except Exception as e:
  1216. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  1217. @router.post("/upload")
  1218. async def upload_archive(
  1219. file: UploadFile = File(...),
  1220. printer_id: int | None = None,
  1221. db: AsyncSession = Depends(get_db),
  1222. ):
  1223. """Manually upload a 3MF file to archive."""
  1224. if not file.filename or not file.filename.endswith(".3mf"):
  1225. raise HTTPException(400, "File must be a .3mf file")
  1226. # Save uploaded file temporarily
  1227. temp_path = settings.archive_dir / "temp" / file.filename
  1228. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1229. try:
  1230. content = await file.read()
  1231. temp_path.write_bytes(content)
  1232. service = ArchiveService(db)
  1233. archive = await service.archive_print(
  1234. printer_id=printer_id,
  1235. source_file=temp_path,
  1236. )
  1237. if not archive:
  1238. raise HTTPException(400, "Failed to archive file")
  1239. return ArchiveResponse.model_validate(archive)
  1240. finally:
  1241. if temp_path.exists():
  1242. temp_path.unlink()
  1243. @router.post("/upload-bulk")
  1244. async def upload_archives_bulk(
  1245. files: list[UploadFile] = File(...),
  1246. printer_id: int | None = None,
  1247. db: AsyncSession = Depends(get_db),
  1248. ):
  1249. """Bulk upload multiple 3MF files to archive."""
  1250. results = []
  1251. errors = []
  1252. for file in files:
  1253. if not file.filename or not file.filename.endswith(".3mf"):
  1254. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  1255. continue
  1256. temp_path = settings.archive_dir / "temp" / file.filename
  1257. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1258. try:
  1259. content = await file.read()
  1260. temp_path.write_bytes(content)
  1261. service = ArchiveService(db)
  1262. archive = await service.archive_print(
  1263. printer_id=printer_id,
  1264. source_file=temp_path,
  1265. )
  1266. if archive:
  1267. results.append(
  1268. {
  1269. "filename": file.filename,
  1270. "id": archive.id,
  1271. "status": "success",
  1272. }
  1273. )
  1274. else:
  1275. errors.append({"filename": file.filename, "error": "Failed to process"})
  1276. except Exception as e:
  1277. errors.append({"filename": file.filename, "error": str(e)})
  1278. finally:
  1279. if temp_path.exists():
  1280. temp_path.unlink()
  1281. return {
  1282. "uploaded": len(results),
  1283. "failed": len(errors),
  1284. "results": results,
  1285. "errors": errors,
  1286. }
  1287. @router.post("/{archive_id}/reprint")
  1288. async def reprint_archive(
  1289. archive_id: int,
  1290. printer_id: int,
  1291. db: AsyncSession = Depends(get_db),
  1292. ):
  1293. """Send an archived 3MF file to a printer and start printing."""
  1294. from backend.app.main import register_expected_print
  1295. from backend.app.models.printer import Printer
  1296. from backend.app.services.bambu_ftp import upload_file_async
  1297. from backend.app.services.printer_manager import printer_manager
  1298. # Get archive
  1299. service = ArchiveService(db)
  1300. archive = await service.get_archive(archive_id)
  1301. if not archive:
  1302. raise HTTPException(404, "Archive not found")
  1303. # Get printer
  1304. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1305. printer = result.scalar_one_or_none()
  1306. if not printer:
  1307. raise HTTPException(404, "Printer not found")
  1308. # Check printer is connected
  1309. if not printer_manager.is_connected(printer_id):
  1310. raise HTTPException(400, "Printer is not connected")
  1311. # Get the sliced 3MF file path
  1312. file_path = settings.base_dir / archive.file_path
  1313. if not file_path.exists():
  1314. raise HTTPException(404, "Archive file not found")
  1315. # Upload file to printer via FTP
  1316. from backend.app.services.bambu_ftp import delete_file_async
  1317. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1318. # The printer might reject filenames with unusual extensions
  1319. base_name = archive.filename
  1320. if base_name.endswith(".gcode.3mf"):
  1321. base_name = base_name[:-10] # Remove .gcode.3mf
  1322. elif base_name.endswith(".3mf"):
  1323. base_name = base_name[:-4] # Remove .3mf
  1324. remote_filename = f"{base_name}.3mf"
  1325. remote_path = f"/{remote_filename}"
  1326. # Delete existing file if present (avoids 553 error)
  1327. await delete_file_async(
  1328. printer.ip_address,
  1329. printer.access_code,
  1330. remote_path,
  1331. )
  1332. uploaded = await upload_file_async(
  1333. printer.ip_address,
  1334. printer.access_code,
  1335. file_path,
  1336. remote_path,
  1337. )
  1338. if not uploaded:
  1339. raise HTTPException(500, "Failed to upload file to printer")
  1340. # Register this as an expected print so we don't create a duplicate archive
  1341. register_expected_print(printer_id, remote_filename, archive_id)
  1342. # Detect plate ID from 3MF file
  1343. plate_id = 1
  1344. try:
  1345. with zipfile.ZipFile(file_path, "r") as zf:
  1346. for name in zf.namelist():
  1347. if name.startswith("Metadata/plate_") and name.endswith(".gcode"):
  1348. # Extract plate number from "Metadata/plate_X.gcode"
  1349. plate_str = name[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1350. plate_id = int(plate_str)
  1351. break
  1352. except Exception:
  1353. pass # Default to plate 1 if detection fails
  1354. logger.info(f"Reprint archive {archive_id}: using plate_id={plate_id}")
  1355. # Start the print
  1356. started = printer_manager.start_print(printer_id, remote_filename, plate_id)
  1357. if not started:
  1358. raise HTTPException(500, "Failed to start print")
  1359. return {
  1360. "status": "printing",
  1361. "printer_id": printer_id,
  1362. "archive_id": archive_id,
  1363. "filename": archive.filename,
  1364. }
  1365. # =============================================================================
  1366. # Project Page API
  1367. # =============================================================================
  1368. @router.get("/{archive_id}/project-page")
  1369. async def get_project_page(archive_id: int, db: AsyncSession = Depends(get_db)):
  1370. """Get the project page data from the 3MF file."""
  1371. from backend.app.schemas.archive import ProjectPageResponse
  1372. from backend.app.services.archive import ProjectPageParser
  1373. service = ArchiveService(db)
  1374. archive = await service.get_archive(archive_id)
  1375. if not archive:
  1376. raise HTTPException(404, "Archive not found")
  1377. file_path = settings.base_dir / archive.file_path
  1378. if not file_path.exists():
  1379. raise HTTPException(404, "Archive file not found")
  1380. parser = ProjectPageParser(file_path)
  1381. data = parser.parse(archive_id)
  1382. return ProjectPageResponse(**data)
  1383. @router.patch("/{archive_id}/project-page")
  1384. async def update_project_page(
  1385. archive_id: int,
  1386. update_data: dict,
  1387. db: AsyncSession = Depends(get_db),
  1388. ):
  1389. """Update project page metadata in the 3MF file."""
  1390. from backend.app.services.archive import ProjectPageParser
  1391. service = ArchiveService(db)
  1392. archive = await service.get_archive(archive_id)
  1393. if not archive:
  1394. raise HTTPException(404, "Archive not found")
  1395. file_path = settings.base_dir / archive.file_path
  1396. if not file_path.exists():
  1397. raise HTTPException(404, "Archive file not found")
  1398. parser = ProjectPageParser(file_path)
  1399. success = parser.update_metadata(update_data)
  1400. if not success:
  1401. raise HTTPException(500, "Failed to update project page")
  1402. # Return updated data
  1403. data = parser.parse(archive_id)
  1404. return data
  1405. @router.get("/{archive_id}/project-image/{image_path:path}")
  1406. async def get_project_image(
  1407. archive_id: int,
  1408. image_path: str,
  1409. db: AsyncSession = Depends(get_db),
  1410. ):
  1411. """Get an image from the 3MF project page."""
  1412. from backend.app.services.archive import ProjectPageParser
  1413. service = ArchiveService(db)
  1414. archive = await service.get_archive(archive_id)
  1415. if not archive:
  1416. raise HTTPException(404, "Archive not found")
  1417. file_path = settings.base_dir / archive.file_path
  1418. if not file_path.exists():
  1419. raise HTTPException(404, "Archive file not found")
  1420. parser = ProjectPageParser(file_path)
  1421. result = parser.get_image(image_path)
  1422. if not result:
  1423. raise HTTPException(404, "Image not found in 3MF file")
  1424. image_data, content_type = result
  1425. return Response(
  1426. content=image_data,
  1427. media_type=content_type,
  1428. headers={"Cache-Control": "max-age=3600"},
  1429. )
  1430. # =============================================================================
  1431. # Source 3MF API (Original Project Files)
  1432. # =============================================================================
  1433. @router.post("/{archive_id}/source")
  1434. async def upload_source_3mf(
  1435. archive_id: int,
  1436. file: UploadFile = File(...),
  1437. db: AsyncSession = Depends(get_db),
  1438. ):
  1439. """Upload the original source 3MF project file for an archive."""
  1440. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1441. archive = result.scalar_one_or_none()
  1442. if not archive:
  1443. raise HTTPException(404, "Archive not found")
  1444. if not file.filename or not file.filename.endswith(".3mf"):
  1445. raise HTTPException(400, "File must be a .3mf file")
  1446. # Get archive directory and create source subdirectory
  1447. file_path = settings.base_dir / archive.file_path
  1448. archive_dir = file_path.parent
  1449. source_dir = archive_dir / "source"
  1450. source_dir.mkdir(exist_ok=True)
  1451. # Delete old source file if exists
  1452. if archive.source_3mf_path:
  1453. old_source_path = settings.base_dir / archive.source_3mf_path
  1454. if old_source_path.exists():
  1455. old_source_path.unlink()
  1456. # Save the source 3MF file - preserve original filename
  1457. source_filename = file.filename
  1458. source_path = source_dir / source_filename
  1459. content = await file.read()
  1460. source_path.write_bytes(content)
  1461. # Update archive with source path (relative to base_dir)
  1462. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1463. await db.commit()
  1464. await db.refresh(archive)
  1465. return {
  1466. "status": "uploaded",
  1467. "source_3mf_path": archive.source_3mf_path,
  1468. "filename": source_filename,
  1469. }
  1470. @router.get("/{archive_id}/source")
  1471. async def download_source_3mf(
  1472. archive_id: int,
  1473. db: AsyncSession = Depends(get_db),
  1474. ):
  1475. """Download the source 3MF project file."""
  1476. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1477. archive = result.scalar_one_or_none()
  1478. if not archive:
  1479. raise HTTPException(404, "Archive not found")
  1480. if not archive.source_3mf_path:
  1481. raise HTTPException(404, "No source 3MF attached to this archive")
  1482. source_path = settings.base_dir / archive.source_3mf_path
  1483. if not source_path.exists():
  1484. raise HTTPException(404, "Source 3MF file not found on disk")
  1485. # Use the actual filename from the path
  1486. filename = source_path.name
  1487. return FileResponse(
  1488. path=source_path,
  1489. filename=filename,
  1490. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1491. )
  1492. @router.get("/{archive_id}/source/{filename}")
  1493. async def download_source_3mf_for_slicer(
  1494. archive_id: int,
  1495. filename: str,
  1496. db: AsyncSession = Depends(get_db),
  1497. ):
  1498. """Download source 3MF with filename in URL (for Bambu Studio compatibility)."""
  1499. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1500. archive = result.scalar_one_or_none()
  1501. if not archive:
  1502. raise HTTPException(404, "Archive not found")
  1503. if not archive.source_3mf_path:
  1504. raise HTTPException(404, "No source 3MF attached to this archive")
  1505. source_path = settings.base_dir / archive.source_3mf_path
  1506. if not source_path.exists():
  1507. raise HTTPException(404, "Source 3MF file not found on disk")
  1508. return FileResponse(
  1509. path=source_path,
  1510. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  1511. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1512. )
  1513. @router.post("/upload-source")
  1514. async def upload_source_3mf_by_name(
  1515. file: UploadFile = File(...),
  1516. print_name: str = Query(None, description="Match archive by print name"),
  1517. db: AsyncSession = Depends(get_db),
  1518. ):
  1519. """Upload source 3MF and match to archive by print name.
  1520. This endpoint is designed for slicer post-processing scripts.
  1521. It finds the most recent archive matching the print name and attaches the source.
  1522. """
  1523. if not file.filename or not file.filename.endswith(".3mf"):
  1524. raise HTTPException(400, "File must be a .3mf file")
  1525. # Derive print name from filename if not provided
  1526. if not print_name:
  1527. # Remove .3mf extension and common suffixes
  1528. print_name = file.filename.rsplit(".3mf", 1)[0]
  1529. # Remove _source suffix if present
  1530. if print_name.endswith("_source"):
  1531. print_name = print_name[:-7]
  1532. # Find matching archive - try exact match first, then fuzzy
  1533. result = await db.execute(
  1534. select(PrintArchive)
  1535. .where(PrintArchive.print_name == print_name)
  1536. .order_by(PrintArchive.created_at.desc())
  1537. .limit(1)
  1538. )
  1539. archive = result.scalar_one_or_none()
  1540. if not archive:
  1541. # Try matching filename without .gcode.3mf
  1542. result = await db.execute(
  1543. select(PrintArchive)
  1544. .where(PrintArchive.filename.like(f"{print_name}%"))
  1545. .order_by(PrintArchive.created_at.desc())
  1546. .limit(1)
  1547. )
  1548. archive = result.scalar_one_or_none()
  1549. if not archive:
  1550. # Try case-insensitive partial match on print_name
  1551. result = await db.execute(
  1552. select(PrintArchive)
  1553. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  1554. .order_by(PrintArchive.created_at.desc())
  1555. .limit(1)
  1556. )
  1557. archive = result.scalar_one_or_none()
  1558. if not archive:
  1559. raise HTTPException(404, f"No archive found matching '{print_name}'")
  1560. # Get archive directory and create source subdirectory
  1561. file_path = settings.base_dir / archive.file_path
  1562. archive_dir = file_path.parent
  1563. source_dir = archive_dir / "source"
  1564. source_dir.mkdir(exist_ok=True)
  1565. # Delete old source file if exists
  1566. if archive.source_3mf_path:
  1567. old_source_path = settings.base_dir / archive.source_3mf_path
  1568. if old_source_path.exists():
  1569. old_source_path.unlink()
  1570. # Save the source 3MF file - preserve original filename
  1571. source_filename = file.filename
  1572. source_path = source_dir / source_filename
  1573. content = await file.read()
  1574. source_path.write_bytes(content)
  1575. # Update archive with source path
  1576. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  1577. await db.commit()
  1578. await db.refresh(archive)
  1579. return {
  1580. "status": "uploaded",
  1581. "archive_id": archive.id,
  1582. "archive_name": archive.print_name or archive.filename,
  1583. "source_3mf_path": archive.source_3mf_path,
  1584. "filename": source_filename,
  1585. }
  1586. @router.delete("/{archive_id}/source")
  1587. async def delete_source_3mf(
  1588. archive_id: int,
  1589. db: AsyncSession = Depends(get_db),
  1590. ):
  1591. """Delete the source 3MF project file from an archive."""
  1592. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1593. archive = result.scalar_one_or_none()
  1594. if not archive:
  1595. raise HTTPException(404, "Archive not found")
  1596. if not archive.source_3mf_path:
  1597. raise HTTPException(404, "No source 3MF attached to this archive")
  1598. # Delete the file
  1599. source_path = settings.base_dir / archive.source_3mf_path
  1600. if source_path.exists():
  1601. source_path.unlink()
  1602. # Clear the path in database
  1603. archive.source_3mf_path = None
  1604. await db.commit()
  1605. return {"status": "deleted"}