archives.py 105 KB

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