archives.py 131 KB

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