archives.py 130 KB

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