archives.py 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257
  1. import io
  2. import json
  3. import logging
  4. import re as _re
  5. import zipfile
  6. from collections import defaultdict
  7. from datetime import date, datetime, time, timedelta, timezone
  8. from decimal import ROUND_HALF_UP, Decimal
  9. from pathlib import Path
  10. from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
  11. from fastapi.responses import FileResponse, Response
  12. from sqlalchemy import and_, case, func, or_, select
  13. from sqlalchemy.ext.asyncio import AsyncSession
  14. from backend.app.core.auth import (
  15. RequireCameraStreamTokenIfAuthEnabled,
  16. RequirePermissionIfAuthEnabled,
  17. require_ownership_permission,
  18. )
  19. from backend.app.core.config import settings
  20. from backend.app.core.database import get_db
  21. from backend.app.core.permissions import Permission
  22. from backend.app.models.archive import PrintArchive
  23. from backend.app.models.filament import Filament
  24. from backend.app.models.spool_usage_history import SpoolUsageHistory
  25. from backend.app.models.user import User
  26. from backend.app.schemas.archive import ArchiveResponse, ArchiveSlim, ArchiveStats, ArchiveUpdate, ReprintRequest
  27. from backend.app.schemas.print_log import PrintLogResponse
  28. from backend.app.schemas.slicer import SliceRequest
  29. from backend.app.services.archive import ArchiveService
  30. from backend.app.utils.http import build_content_disposition
  31. from backend.app.utils.threemf_tools import (
  32. extract_nozzle_mapping_from_3mf,
  33. extract_project_filaments_from_3mf,
  34. extract_source_printer_model_from_3mf,
  35. )
  36. logger = logging.getLogger(__name__)
  37. router = APIRouter(prefix="/archives", tags=["archives"])
  38. def _safe_filename(filename: str) -> str:
  39. """Extract basename from a client-supplied filename, preventing path traversal.
  40. Normalizes backslashes (Windows paths) before extracting so that
  41. '..\\\\..\\\\evil.3mf' is correctly stripped to 'evil.3mf' on Linux.
  42. """
  43. return Path(filename.replace("\\", "/")).name
  44. _TIMELAPSE_FILENAME_TS_RE = _re.compile(r"(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})")
  45. _DEFAULT_TIMELAPSE_OFFSETS_HOURS: tuple[int, ...] = (0, 8, -8, 7, -7, 1, -1)
  46. _DEFAULT_TIMELAPSE_TOLERANCE = timedelta(hours=4)
  47. _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN = timedelta(minutes=15)
  48. def _match_timelapse_by_timestamp(
  49. video_files: list[dict],
  50. archive_start: datetime | None,
  51. *,
  52. tolerance: timedelta = _DEFAULT_TIMELAPSE_TOLERANCE,
  53. ambiguity_margin: timedelta = _DEFAULT_TIMELAPSE_AMBIGUITY_MARGIN,
  54. offsets_hours: tuple[int, ...] = _DEFAULT_TIMELAPSE_OFFSETS_HOURS,
  55. ) -> tuple[dict | None, timedelta | None]:
  56. """Pick the timelapse whose filename timestamp best matches the print start time.
  57. Bambu timelapse filenames embed the printer-local START time (e.g.
  58. "video_2026-05-08_09-41-29.mp4"). The printer's clock may be offset from the
  59. server's — especially in LAN-Only mode where NTP is unreachable — so we try a
  60. small set of common UTC offsets and keep the (video, offset) pair with the
  61. smallest absolute distance from archive_start. We deliberately do NOT consider
  62. archive_end here: the filename is start time, not end time, so comparing it to
  63. completion is not a real signal (Strategy 3 handles end via file mtime).
  64. Because the offset list densely covers a wide span, an unrelated video's
  65. filename can coincidentally land near a later print's start at some offset.
  66. To avoid that false positive, we require the best (video, offset) pair to
  67. beat the next-best pair *from a different video* by at least `ambiguity_margin`.
  68. When the top two candidates from different videos are too close to call,
  69. we return None and let the caller fall back to manual selection.
  70. """
  71. if archive_start is None:
  72. return None, None
  73. # (diff, video) for every (video, offset) pair within tolerance.
  74. candidates: list[tuple[timedelta, dict]] = []
  75. for f in video_files:
  76. fname = f.get("name", "")
  77. m = _TIMELAPSE_FILENAME_TS_RE.search(fname)
  78. if not m:
  79. continue
  80. try:
  81. file_time = datetime.strptime(m.group(1), "%Y-%m-%d_%H-%M-%S")
  82. except ValueError:
  83. continue
  84. for hour_offset in offsets_hours:
  85. adjusted = file_time - timedelta(hours=hour_offset)
  86. diff = abs(adjusted - archive_start)
  87. if diff <= tolerance:
  88. candidates.append((diff, f))
  89. if not candidates:
  90. return None, None
  91. candidates.sort(key=lambda c: c[0])
  92. best_diff, best_video = candidates[0]
  93. best_name = best_video.get("name")
  94. for diff, video in candidates[1:]:
  95. if video.get("name") != best_name and (diff - best_diff) < ambiguity_margin:
  96. # Another video matches almost as well — refuse to auto-pick.
  97. return None, None
  98. return best_video, best_diff
  99. def _validate_user_filter_permission(current_user: User | None, created_by_id: int | None):
  100. """Raise 403 if created_by_id filter is used without stats:filter_by_user permission."""
  101. if created_by_id is None or current_user is None:
  102. return
  103. if current_user.is_admin:
  104. return
  105. if not current_user.has_permission(Permission.STATS_FILTER_BY_USER.value):
  106. raise HTTPException(status_code=403, detail="Permission stats:filter_by_user required")
  107. def _apply_user_filter(conditions: list, created_by_id: int | None):
  108. """Append created_by_id filter to conditions list if specified."""
  109. if created_by_id is not None:
  110. if created_by_id == -1:
  111. conditions.append(PrintArchive.created_by_id.is_(None))
  112. else:
  113. conditions.append(PrintArchive.created_by_id == created_by_id)
  114. def _apply_run_user_filter(conditions: list, created_by_id: int | None):
  115. """Append created_by_id filter scoped to PrintLogEntry rows."""
  116. from backend.app.models.print_log import PrintLogEntry
  117. if created_by_id is not None:
  118. if created_by_id == -1:
  119. conditions.append(PrintLogEntry.created_by_id.is_(None))
  120. else:
  121. conditions.append(PrintLogEntry.created_by_id == created_by_id)
  122. def compute_time_accuracy(archive: PrintArchive) -> dict:
  123. """Compute actual print time and accuracy for an archive.
  124. Returns dict with actual_time_seconds and time_accuracy.
  125. time_accuracy = (estimated / actual) * 100
  126. - 100% = perfect estimate
  127. - >100% = print was faster than estimated
  128. - <100% = print took longer than estimated
  129. """
  130. result = {"actual_time_seconds": None, "time_accuracy": None}
  131. if archive.started_at and archive.completed_at and archive.status == "completed":
  132. actual_seconds = int((archive.completed_at - archive.started_at).total_seconds())
  133. if actual_seconds > 0:
  134. result["actual_time_seconds"] = actual_seconds
  135. if archive.print_time_seconds and archive.print_time_seconds > 0:
  136. # Calculate accuracy as percentage
  137. accuracy = (archive.print_time_seconds / actual_seconds) * 100
  138. # Sanity check: skip unreasonable values (e.g., manually changed status)
  139. # Valid range: 5% to 500% (print took 20x longer to 5x faster than estimated)
  140. if 5 <= accuracy <= 500:
  141. result["time_accuracy"] = round(accuracy, 1)
  142. return result
  143. async def _load_run_aggregates(db: AsyncSession, archive_ids: list[int]) -> dict[int, dict]:
  144. """Batch-load per-archive run aggregates from PrintLogEntry.
  145. Returns ``{archive_id: {run_count, last_run_at, total_filament_actual_grams,
  146. successful_run_count, failed_run_count}}``. Archives with no logged runs are
  147. absent from the map; callers should treat that as zero/none.
  148. """
  149. from backend.app.models.print_log import PrintLogEntry
  150. if not archive_ids:
  151. return {}
  152. rows = await db.execute(
  153. select(
  154. PrintLogEntry.archive_id,
  155. func.count(PrintLogEntry.id).label("run_count"),
  156. func.max(PrintLogEntry.started_at).label("last_run_at"),
  157. func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0).label("total_filament"),
  158. func.sum(case((PrintLogEntry.status == "completed", 1), else_=0)).label("successful"),
  159. func.sum(case((PrintLogEntry.status == "failed", 1), else_=0)).label("failed"),
  160. )
  161. .where(PrintLogEntry.archive_id.in_(archive_ids))
  162. .group_by(PrintLogEntry.archive_id)
  163. )
  164. aggregates: dict[int, dict] = {}
  165. for archive_id, run_count, last_run_at, total_filament, successful, failed in rows.all():
  166. aggregates[archive_id] = {
  167. "run_count": int(run_count or 0),
  168. "last_run_at": last_run_at,
  169. "total_filament_actual_grams": float(total_filament) if total_filament else None,
  170. "successful_run_count": int(successful or 0),
  171. "failed_run_count": int(failed or 0),
  172. }
  173. return aggregates
  174. def archive_to_response(
  175. archive: PrintArchive,
  176. duplicates: list[dict] | None = None,
  177. duplicate_count: int = 0,
  178. duplicate_sequence: int = 0,
  179. original_archive_id: int | None = None,
  180. run_aggregate: dict | None = None,
  181. ) -> dict:
  182. """Convert archive model to response dict with computed fields."""
  183. data = {
  184. "id": archive.id,
  185. "printer_id": archive.printer_id,
  186. "project_id": archive.project_id,
  187. "project_name": archive.project.name if archive.project else None,
  188. "filename": archive.filename,
  189. "file_path": archive.file_path,
  190. "file_size": archive.file_size,
  191. "content_hash": archive.content_hash,
  192. "thumbnail_path": archive.thumbnail_path,
  193. "timelapse_path": archive.timelapse_path,
  194. "source_3mf_path": archive.source_3mf_path,
  195. "f3d_path": archive.f3d_path,
  196. "duplicates": duplicates,
  197. "duplicate_count": duplicate_count if duplicates is None else len(duplicates),
  198. "duplicate_sequence": duplicate_sequence,
  199. "original_archive_id": original_archive_id,
  200. "print_name": archive.print_name,
  201. "print_time_seconds": archive.print_time_seconds,
  202. "filament_used_grams": archive.filament_used_grams,
  203. "filament_type": archive.filament_type,
  204. "filament_color": archive.filament_color,
  205. "layer_height": archive.layer_height,
  206. "total_layers": archive.total_layers,
  207. "nozzle_diameter": archive.nozzle_diameter,
  208. "bed_temperature": archive.bed_temperature,
  209. "bed_type": archive.bed_type,
  210. "nozzle_temperature": archive.nozzle_temperature,
  211. "sliced_for_model": archive.sliced_for_model,
  212. "status": archive.status,
  213. "started_at": archive.started_at,
  214. "completed_at": archive.completed_at,
  215. "extra_data": archive.extra_data,
  216. "makerworld_url": archive.makerworld_url,
  217. "designer": archive.designer,
  218. "external_url": archive.external_url,
  219. "is_favorite": archive.is_favorite,
  220. "tags": archive.tags,
  221. "notes": archive.notes,
  222. "cost": archive.cost,
  223. "photos": archive.photos,
  224. "failure_reason": archive.failure_reason,
  225. "quantity": archive.quantity,
  226. "energy_kwh": archive.energy_kwh,
  227. "energy_cost": archive.energy_cost,
  228. "created_at": archive.created_at,
  229. # User tracking (Issue #206)
  230. "created_by_id": archive.created_by_id,
  231. "created_by_username": archive.created_by.username if archive.created_by else None,
  232. }
  233. # Add computed time accuracy fields
  234. accuracy_data = compute_time_accuracy(archive)
  235. data.update(accuracy_data)
  236. if run_aggregate:
  237. data["run_count"] = run_aggregate.get("run_count", 0)
  238. data["last_run_at"] = run_aggregate.get("last_run_at")
  239. data["total_filament_actual_grams"] = run_aggregate.get("total_filament_actual_grams")
  240. data["successful_run_count"] = run_aggregate.get("successful_run_count", 0)
  241. data["failed_run_count"] = run_aggregate.get("failed_run_count", 0)
  242. return data
  243. @router.get("/", response_model=list[ArchiveResponse])
  244. async def list_archives(
  245. printer_id: int | None = None,
  246. project_id: int | None = None,
  247. date_from: date | None = Query(None),
  248. date_to: date | None = Query(None),
  249. limit: int = 50,
  250. offset: int = 0,
  251. db: AsyncSession = Depends(get_db),
  252. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  253. ):
  254. """List archived prints."""
  255. service = ArchiveService(db)
  256. archives = await service.list_archives(
  257. printer_id=printer_id,
  258. project_id=project_id,
  259. date_from=date_from,
  260. date_to=date_to,
  261. limit=limit,
  262. offset=offset,
  263. )
  264. # Get sets of duplicate hashes and duplicate (name, hash) pairs (efficient single queries)
  265. duplicate_hashes, duplicate_name_hash_pairs = await service.get_duplicate_hashes_and_names()
  266. # Batch-load duplicate groups once for the current page keys.
  267. duplicate_hashes_in_page = {
  268. a.content_hash for a in archives if a.content_hash and a.content_hash in duplicate_hashes
  269. }
  270. duplicate_name_hash_keys_in_page = {
  271. (a.print_name.lower(), a.content_hash)
  272. for a in archives
  273. if a.print_name and a.content_hash and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  274. }
  275. duplicate_meta_by_archive_id: dict[int, tuple[int, int, int]] = {}
  276. if duplicate_hashes_in_page or duplicate_name_hash_keys_in_page:
  277. duplicate_group_conditions = []
  278. if duplicate_hashes_in_page:
  279. duplicate_group_conditions.append(PrintArchive.content_hash.in_(duplicate_hashes_in_page))
  280. if duplicate_name_hash_keys_in_page:
  281. name_hash_conditions = [
  282. and_(func.lower(PrintArchive.print_name) == name, PrintArchive.content_hash == hash_)
  283. for name, hash_ in duplicate_name_hash_keys_in_page
  284. ]
  285. duplicate_group_conditions.extend(name_hash_conditions)
  286. duplicate_group_rows = await db.execute(
  287. select(
  288. PrintArchive.id,
  289. PrintArchive.created_at,
  290. PrintArchive.content_hash,
  291. func.lower(PrintArchive.print_name).label("print_name_lower"),
  292. ).where(or_(*duplicate_group_conditions), PrintArchive.deleted_at.is_(None))
  293. )
  294. duplicate_groups_by_hash: dict[str, list[tuple[int, datetime]]] = defaultdict(list)
  295. duplicate_groups_by_name_hash: dict[tuple[str, str], list[tuple[int, datetime]]] = defaultdict(list)
  296. for archive_id, created_at, content_hash, print_name_lower in duplicate_group_rows.all():
  297. if content_hash and content_hash in duplicate_hashes_in_page:
  298. duplicate_groups_by_hash[content_hash].append((archive_id, created_at))
  299. if (
  300. print_name_lower
  301. and content_hash
  302. and (print_name_lower, content_hash) in duplicate_name_hash_keys_in_page
  303. ):
  304. duplicate_groups_by_name_hash[(print_name_lower, content_hash)].append((archive_id, created_at))
  305. for group in duplicate_groups_by_hash.values():
  306. if len(group) < 2:
  307. continue
  308. group.sort(key=lambda x: x[1])
  309. original_id = group[0][0]
  310. duplicate_count = len(group) - 1
  311. for sequence, (archive_id, _) in enumerate(group):
  312. duplicate_meta_by_archive_id[archive_id] = (sequence, original_id, duplicate_count)
  313. # Keep hash-based grouping precedence; name/hash groups only fill missing items.
  314. for group in duplicate_groups_by_name_hash.values():
  315. if len(group) < 2:
  316. continue
  317. group.sort(key=lambda x: x[1])
  318. original_id = group[0][0]
  319. duplicate_count = len(group) - 1
  320. for sequence, (archive_id, _) in enumerate(group):
  321. duplicate_meta_by_archive_id.setdefault(archive_id, (sequence, original_id, duplicate_count))
  322. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  323. # Build response with duplicate sequence and original archive ID pre-computed
  324. result = []
  325. for a in archives:
  326. has_hash_dup = a.content_hash in duplicate_hashes if a.content_hash else False
  327. has_name_dup = (
  328. bool(a.print_name and a.content_hash)
  329. and (a.print_name.lower(), a.content_hash) in duplicate_name_hash_pairs
  330. )
  331. has_duplicate = has_hash_dup or has_name_dup
  332. # Pre-compute duplicate sequence and original archive ID
  333. duplicate_sequence = 0
  334. original_archive_id: int | None = None
  335. duplicate_count = 1 if has_duplicate else 0
  336. if has_duplicate and a.id in duplicate_meta_by_archive_id:
  337. duplicate_sequence, original_archive_id, duplicate_count = duplicate_meta_by_archive_id[a.id]
  338. result.append(
  339. archive_to_response(
  340. a,
  341. duplicate_count=duplicate_count,
  342. duplicate_sequence=duplicate_sequence,
  343. original_archive_id=original_archive_id,
  344. run_aggregate=run_aggregates.get(a.id),
  345. )
  346. )
  347. return result
  348. @router.get("/slim", response_model=list[ArchiveSlim])
  349. async def list_archives_slim(
  350. date_from: date | None = Query(None),
  351. date_to: date | None = Query(None),
  352. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  353. limit: int = Query(default=10000, le=50000),
  354. offset: int = 0,
  355. db: AsyncSession = Depends(get_db),
  356. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  357. ):
  358. """Per-event listing for stats/dashboard widgets.
  359. Reads from print_log_entries so reprints contribute each run and
  360. orphaned events (archive deleted, log row survived via ON DELETE
  361. SET NULL) still aggregate consistently with Quick Stats. The sliced
  362. print_time_seconds is joined from the archive when available; for
  363. orphan events it is null and downstream widgets fall back to the
  364. measured duration_seconds.
  365. """
  366. from backend.app.models.print_log import PrintLogEntry
  367. _validate_user_filter_permission(current_user, created_by_id)
  368. filters = []
  369. if date_from:
  370. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  371. filters.append(PrintLogEntry.created_at >= dt_from)
  372. if date_to:
  373. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  374. filters.append(PrintLogEntry.created_at <= dt_to)
  375. _apply_run_user_filter(filters, created_by_id)
  376. query = (
  377. select(
  378. PrintLogEntry.printer_id,
  379. PrintLogEntry.print_name,
  380. PrintArchive.print_time_seconds,
  381. PrintLogEntry.started_at,
  382. PrintLogEntry.completed_at,
  383. PrintLogEntry.duration_seconds,
  384. PrintLogEntry.filament_used_grams,
  385. PrintLogEntry.filament_type,
  386. PrintLogEntry.filament_color,
  387. PrintLogEntry.status,
  388. PrintLogEntry.cost,
  389. PrintLogEntry.created_at,
  390. )
  391. .outerjoin(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  392. .where(*filters)
  393. .order_by(PrintLogEntry.created_at.desc())
  394. .limit(limit)
  395. .offset(offset)
  396. )
  397. result = await db.execute(query)
  398. rows = result.all()
  399. return [
  400. {
  401. "printer_id": r.printer_id,
  402. "print_name": r.print_name,
  403. "print_time_seconds": r.print_time_seconds,
  404. "actual_time_seconds": (
  405. r.duration_seconds
  406. if r.duration_seconds and r.duration_seconds > 0 and r.status == "completed"
  407. else (
  408. int((r.completed_at - r.started_at).total_seconds())
  409. if r.started_at
  410. and r.completed_at
  411. and r.status == "completed"
  412. and (r.completed_at - r.started_at).total_seconds() > 0
  413. else None
  414. )
  415. ),
  416. "filament_used_grams": r.filament_used_grams,
  417. "filament_type": r.filament_type,
  418. "filament_color": r.filament_color,
  419. "status": r.status,
  420. "started_at": r.started_at,
  421. "completed_at": r.completed_at,
  422. "cost": r.cost,
  423. "quantity": 1,
  424. "created_at": r.created_at,
  425. }
  426. for r in rows
  427. ]
  428. @router.get("/search", response_model=list[ArchiveResponse])
  429. async def search_archives(
  430. q: str = Query(..., min_length=2, description="Search query"),
  431. printer_id: int | None = None,
  432. project_id: int | None = None,
  433. status: str | None = None,
  434. limit: int = 50,
  435. offset: int = 0,
  436. db: AsyncSession = Depends(get_db),
  437. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  438. ):
  439. """Full-text search across archives.
  440. Searches print_name, filename, tags, notes, designer, and filament_type fields.
  441. Supports partial matches with wildcards (e.g., 'vor*' matches 'voron').
  442. """
  443. from sqlalchemy import text
  444. from sqlalchemy.orm import selectinload
  445. from backend.app.core.db_dialect import is_sqlite
  446. search_term = q.strip()
  447. # Build dialect-specific full-text search query
  448. if is_sqlite():
  449. # SQLite FTS5: wildcard suffix for partial matches
  450. if not search_term.endswith("*"):
  451. search_term = f"{search_term}*"
  452. fts_query = text("""
  453. SELECT rowid FROM archive_fts
  454. WHERE archive_fts MATCH :search_term
  455. ORDER BY rank
  456. LIMIT :limit OFFSET :offset
  457. """)
  458. else:
  459. # PostgreSQL: tsvector + plainto_tsquery with prefix matching
  460. fts_query = text("""
  461. SELECT id FROM print_archives
  462. WHERE to_tsvector('simple',
  463. COALESCE(print_name, '') || ' ' ||
  464. COALESCE(filename, '') || ' ' ||
  465. COALESCE(tags, '') || ' ' ||
  466. COALESCE(notes, '') || ' ' ||
  467. COALESCE(designer, '') || ' ' ||
  468. COALESCE(filament_type, '')
  469. ) @@ to_tsquery('simple', :search_term)
  470. LIMIT :limit OFFSET :offset
  471. """)
  472. # Convert "benchy" to "benchy:*" for prefix matching in tsquery
  473. search_term = " & ".join(f"{word}:*" for word in search_term.split() if word)
  474. try:
  475. result = await db.execute(fts_query, {"search_term": search_term, "limit": limit + 100, "offset": 0})
  476. matched_ids = [row[0] for row in result.fetchall()]
  477. except Exception as e:
  478. logger.warning("FTS search failed, falling back to LIKE search: %s", e)
  479. # Fallback to LIKE search if FTS fails
  480. like_pattern = f"%{q}%"
  481. query = (
  482. select(PrintArchive)
  483. .options(selectinload(PrintArchive.project))
  484. .where(
  485. (
  486. (PrintArchive.print_name.ilike(like_pattern))
  487. | (PrintArchive.filename.ilike(like_pattern))
  488. | (PrintArchive.tags.ilike(like_pattern))
  489. | (PrintArchive.notes.ilike(like_pattern))
  490. | (PrintArchive.designer.ilike(like_pattern))
  491. | (PrintArchive.filament_type.ilike(like_pattern))
  492. ),
  493. PrintArchive.deleted_at.is_(None),
  494. )
  495. .order_by(PrintArchive.created_at.desc())
  496. )
  497. if printer_id:
  498. query = query.where(PrintArchive.printer_id == printer_id)
  499. if project_id:
  500. query = query.where(PrintArchive.project_id == project_id)
  501. if status:
  502. query = query.where(PrintArchive.status == status)
  503. query = query.limit(limit).offset(offset)
  504. result = await db.execute(query)
  505. archives = result.scalars().all()
  506. return [archive_to_response(a) for a in archives]
  507. if not matched_ids:
  508. return []
  509. # Fetch full archive records for matched IDs (excluding soft-deleted, #1343)
  510. query = (
  511. select(PrintArchive)
  512. .options(selectinload(PrintArchive.project))
  513. .where(PrintArchive.id.in_(matched_ids), PrintArchive.deleted_at.is_(None))
  514. )
  515. # Apply additional filters
  516. if printer_id:
  517. query = query.where(PrintArchive.printer_id == printer_id)
  518. if project_id:
  519. query = query.where(PrintArchive.project_id == project_id)
  520. if status:
  521. query = query.where(PrintArchive.status == status)
  522. result = await db.execute(query)
  523. archives_dict = {a.id: a for a in result.scalars().all()}
  524. # Preserve FTS ranking order and apply pagination
  525. ordered_archives = [archives_dict[id] for id in matched_ids if id in archives_dict]
  526. paginated = ordered_archives[offset : offset + limit]
  527. return [archive_to_response(a) for a in paginated]
  528. @router.post("/search/rebuild-index")
  529. async def rebuild_search_index(
  530. db: AsyncSession = Depends(get_db),
  531. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  532. ):
  533. """Rebuild the full-text search index from existing archives.
  534. Use this if search results seem incomplete or incorrect.
  535. """
  536. from sqlalchemy import text
  537. from backend.app.core.db_dialect import is_sqlite
  538. try:
  539. if is_sqlite():
  540. # SQLite: rebuild FTS5 virtual table
  541. await db.execute(text("DELETE FROM archive_fts"))
  542. await db.execute(
  543. text("""
  544. INSERT INTO archive_fts(rowid, print_name, filename, tags, notes, designer, filament_type)
  545. SELECT id, print_name, filename, tags, notes, designer, filament_type
  546. FROM print_archives
  547. """)
  548. )
  549. await db.commit()
  550. result = await db.execute(text("SELECT COUNT(*) FROM archive_fts"))
  551. count = result.scalar() or 0
  552. else:
  553. # PostgreSQL: GIN index is auto-maintained, just reindex
  554. await db.execute(text("REINDEX INDEX idx_archives_fulltext"))
  555. await db.commit()
  556. result = await db.execute(text("SELECT COUNT(*) FROM print_archives"))
  557. count = result.scalar() or 0
  558. return {"message": f"Search index rebuilt with {count} entries"}
  559. except Exception as e:
  560. logger.error("Failed to rebuild search index: %s", e)
  561. raise HTTPException(status_code=500, detail=f"Failed to rebuild index: {str(e)}")
  562. @router.get("/analysis/failures")
  563. async def analyze_failures(
  564. days: int | None = None,
  565. date_from: date | None = Query(None),
  566. date_to: date | None = Query(None),
  567. printer_id: int | None = None,
  568. project_id: int | None = None,
  569. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  570. db: AsyncSession = Depends(get_db),
  571. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  572. ):
  573. """Analyze failure patterns across prints.
  574. Returns failure statistics including:
  575. - Overall failure rate
  576. - Failures by reason, filament type, printer
  577. - Time of day distribution
  578. - Recent failures
  579. - Weekly trend
  580. """
  581. _validate_user_filter_permission(current_user, created_by_id)
  582. from backend.app.services.failure_analysis import FailureAnalysisService
  583. service = FailureAnalysisService(db)
  584. return await service.analyze_failures(
  585. days=days,
  586. date_from=date_from,
  587. date_to=date_to,
  588. printer_id=printer_id,
  589. project_id=project_id,
  590. created_by_id=created_by_id,
  591. )
  592. @router.get("/compare")
  593. async def compare_archives(
  594. archive_ids: str = Query(..., description="Comma-separated archive IDs (2-5)"),
  595. db: AsyncSession = Depends(get_db),
  596. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  597. ):
  598. """Compare multiple archives side by side.
  599. Compares print settings, filament usage, and print times.
  600. Also analyzes correlation between settings and success/failure.
  601. Args:
  602. archive_ids: Comma-separated list of 2-5 archive IDs to compare
  603. """
  604. from backend.app.services.archive_comparison import ArchiveComparisonService
  605. # Parse and validate archive IDs
  606. try:
  607. ids = [int(id.strip()) for id in archive_ids.split(",")]
  608. except ValueError:
  609. raise HTTPException(400, "Invalid archive IDs format")
  610. if len(ids) < 2:
  611. raise HTTPException(400, "At least 2 archives required for comparison")
  612. if len(ids) > 5:
  613. raise HTTPException(400, "Maximum 5 archives can be compared at once")
  614. service = ArchiveComparisonService(db)
  615. try:
  616. return await service.compare_archives(ids)
  617. except ValueError as e:
  618. raise HTTPException(400, str(e))
  619. @router.get("/export")
  620. async def export_archives(
  621. format: str = Query("csv", description="Export format: csv or xlsx"),
  622. fields: str | None = Query(None, description="Comma-separated field names"),
  623. printer_id: int | None = None,
  624. project_id: int | None = None,
  625. status: str | None = None,
  626. date_from: str | None = Query(None, description="Start date (ISO format)"),
  627. date_to: str | None = Query(None, description="End date (ISO format)"),
  628. search: str | None = None,
  629. db: AsyncSession = Depends(get_db),
  630. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  631. ):
  632. """Export archives to CSV or Excel format.
  633. Returns a downloadable file with archive data.
  634. """
  635. from datetime import datetime
  636. from fastapi.responses import StreamingResponse
  637. from backend.app.services.export import ExportService
  638. if format not in ("csv", "xlsx"):
  639. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  640. # Parse fields
  641. field_list = None
  642. if fields:
  643. field_list = [f.strip() for f in fields.split(",")]
  644. # Parse dates
  645. date_from_dt = None
  646. date_to_dt = None
  647. if date_from:
  648. try:
  649. date_from_dt = datetime.fromisoformat(date_from)
  650. except ValueError:
  651. raise HTTPException(400, "Invalid date_from format")
  652. if date_to:
  653. try:
  654. date_to_dt = datetime.fromisoformat(date_to)
  655. except ValueError:
  656. raise HTTPException(400, "Invalid date_to format")
  657. service = ExportService(db)
  658. try:
  659. file_bytes, filename, content_type = await service.export_archives(
  660. format=format,
  661. fields=field_list,
  662. printer_id=printer_id,
  663. project_id=project_id,
  664. status=status,
  665. date_from=date_from_dt,
  666. date_to=date_to_dt,
  667. search=search,
  668. )
  669. except ImportError as e:
  670. raise HTTPException(500, str(e))
  671. return StreamingResponse(
  672. io.BytesIO(file_bytes),
  673. media_type=content_type,
  674. headers={"Content-Disposition": build_content_disposition(filename)},
  675. )
  676. @router.get("/stats/export")
  677. async def export_stats(
  678. format: str = Query("csv", description="Export format: csv or xlsx"),
  679. days: int = 30,
  680. printer_id: int | None = None,
  681. project_id: int | None = None,
  682. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  683. db: AsyncSession = Depends(get_db),
  684. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  685. ):
  686. """Export statistics summary to CSV or Excel format."""
  687. _validate_user_filter_permission(current_user, created_by_id)
  688. from fastapi.responses import StreamingResponse
  689. from backend.app.services.export import ExportService
  690. if format not in ("csv", "xlsx"):
  691. raise HTTPException(400, "Format must be 'csv' or 'xlsx'")
  692. service = ExportService(db)
  693. try:
  694. file_bytes, filename, content_type = await service.export_stats(
  695. format=format,
  696. days=days,
  697. printer_id=printer_id,
  698. project_id=project_id,
  699. created_by_id=created_by_id,
  700. )
  701. except ImportError as e:
  702. raise HTTPException(500, str(e))
  703. return StreamingResponse(
  704. io.BytesIO(file_bytes),
  705. media_type=content_type,
  706. headers={"Content-Disposition": build_content_disposition(filename)},
  707. )
  708. @router.get("/stats", response_model=ArchiveStats)
  709. async def get_archive_stats(
  710. date_from: date | None = Query(None, description="Start date (inclusive), YYYY-MM-DD"),
  711. date_to: date | None = Query(None, description="End date (inclusive), YYYY-MM-DD"),
  712. created_by_id: int | None = Query(None, description="Filter by user who created the print (-1 for no user)"),
  713. db: AsyncSession = Depends(get_db),
  714. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.STATS_READ),
  715. ):
  716. """Get statistics across all archives.
  717. Stats aggregate over PrintLogEntry (one row per print event), not over
  718. PrintArchive (one row per file). A reprint contributes a new PrintLogEntry
  719. so its filament/cost/time/energy add to the totals instead of overwriting
  720. the source archive's first-run values (#1378).
  721. """
  722. from backend.app.models.print_log import PrintLogEntry
  723. _validate_user_filter_permission(current_user, created_by_id)
  724. # Build date filter conditions scoped to PrintLogEntry (event-time).
  725. base_conditions = []
  726. if date_from:
  727. dt_from = datetime.combine(date_from, time.min, tzinfo=timezone.utc)
  728. base_conditions.append(PrintLogEntry.created_at >= dt_from)
  729. if date_to:
  730. dt_to = datetime.combine(date_to, time.max, tzinfo=timezone.utc)
  731. base_conditions.append(PrintLogEntry.created_at <= dt_to)
  732. _apply_run_user_filter(base_conditions, created_by_id)
  733. # Total counts (one row per print event).
  734. total_result = await db.execute(select(func.count(PrintLogEntry.id)).where(*base_conditions))
  735. total_prints = total_result.scalar() or 0
  736. successful_result = await db.execute(
  737. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status == "completed", *base_conditions)
  738. )
  739. successful_prints = successful_result.scalar() or 0
  740. failed_result = await db.execute(
  741. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.status == "failed", *base_conditions)
  742. )
  743. failed_prints = failed_result.scalar() or 0
  744. # Total elapsed time — PrintLogEntry stores duration_seconds directly so we
  745. # can sum it server-side. Rows missing duration fall back to the slicer
  746. # estimate from the archive (joined for that case only).
  747. time_rows = await db.execute(
  748. select(
  749. PrintLogEntry.duration_seconds,
  750. PrintLogEntry.started_at,
  751. PrintLogEntry.completed_at,
  752. ).where(*base_conditions)
  753. )
  754. total_seconds = 0
  755. for duration_seconds, started_at, completed_at in time_rows.all():
  756. if duration_seconds:
  757. total_seconds += duration_seconds
  758. elif started_at and completed_at:
  759. elapsed = (completed_at - started_at).total_seconds()
  760. if elapsed > 0:
  761. total_seconds += int(elapsed)
  762. total_time = total_seconds / 3600 # Convert to hours
  763. filament_result = await db.execute(
  764. select(func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0)).where(*base_conditions)
  765. )
  766. total_filament = filament_result.scalar() or 0
  767. cost_result = await db.execute(select(func.sum(PrintLogEntry.cost)).where(*base_conditions))
  768. total_cost = cost_result.scalar() or 0
  769. # By filament type (split comma-separated values for multi-material prints)
  770. filament_type_result = await db.execute(
  771. select(PrintLogEntry.filament_type).where(PrintLogEntry.filament_type.isnot(None), *base_conditions)
  772. )
  773. prints_by_filament: dict[str, int] = {}
  774. for (filament_types,) in filament_type_result.all():
  775. for ftype in filament_types.split(","):
  776. ftype = ftype.strip()
  777. if ftype:
  778. prints_by_filament[ftype] = prints_by_filament.get(ftype, 0) + 1
  779. # By printer
  780. printer_result = await db.execute(
  781. select(PrintLogEntry.printer_id, func.count(PrintLogEntry.id))
  782. .where(*base_conditions)
  783. .group_by(PrintLogEntry.printer_id)
  784. )
  785. prints_by_printer = {str(k): v for k, v in printer_result.all()}
  786. # Time accuracy — compare each completed run's actual duration to the
  787. # slicer's estimate on the linked archive. Runs without a linked archive
  788. # (NULL archive_id) or without an estimate are excluded.
  789. accuracy_rows = await db.execute(
  790. select(
  791. PrintLogEntry.duration_seconds,
  792. PrintLogEntry.started_at,
  793. PrintLogEntry.completed_at,
  794. PrintLogEntry.printer_id,
  795. PrintArchive.print_time_seconds,
  796. )
  797. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  798. .where(
  799. PrintLogEntry.status == "completed",
  800. PrintArchive.print_time_seconds.isnot(None),
  801. *base_conditions,
  802. )
  803. )
  804. average_accuracy = None
  805. accuracy_by_printer: dict[str, float] = {}
  806. accuracies: list[float] = []
  807. printer_accuracies: dict[str, list[float]] = {}
  808. for duration_seconds, started_at, completed_at, run_printer_id, estimate_seconds in accuracy_rows.all():
  809. actual_seconds = duration_seconds
  810. if not actual_seconds and started_at and completed_at:
  811. elapsed = (completed_at - started_at).total_seconds()
  812. actual_seconds = int(elapsed) if elapsed > 0 else None
  813. if not actual_seconds or not estimate_seconds:
  814. continue
  815. accuracy = (estimate_seconds / actual_seconds) * 100
  816. accuracies.append(accuracy)
  817. printer_key = str(run_printer_id) if run_printer_id else "unknown"
  818. printer_accuracies.setdefault(printer_key, []).append(accuracy)
  819. if accuracies:
  820. average_accuracy = round(sum(accuracies) / len(accuracies), 1)
  821. for printer_key, accs in printer_accuracies.items():
  822. accuracy_by_printer[printer_key] = round(sum(accs) / len(accs), 1)
  823. # Energy totals - check which mode to use
  824. from backend.app.api.routes.settings import get_setting
  825. energy_tracking_mode = await get_setting(db, "energy_tracking_mode") or "total"
  826. energy_cost_per_kwh_str = await get_setting(db, "energy_cost_per_kwh")
  827. energy_cost_per_kwh = float(energy_cost_per_kwh_str) if energy_cost_per_kwh_str else 0.15
  828. total_energy_kwh: float = 0.0
  829. total_energy_cost: float = 0.0
  830. energy_data_warming_up = False
  831. if energy_tracking_mode == "total" and not date_from and not date_to:
  832. # All-time total consumption — read live lifetime counters.
  833. total_energy_kwh = await _sum_live_plug_totals(db)
  834. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  835. elif energy_tracking_mode == "total":
  836. # Total consumption mode with a date filter (#941): use hourly snapshots
  837. # to compute per-plug (endpoint - baseline) deltas.
  838. total_energy_kwh, energy_data_warming_up = await _sum_snapshot_deltas(
  839. db,
  840. dt_from=(datetime.combine(date_from, time.min, tzinfo=timezone.utc) if date_from else None),
  841. dt_to=(datetime.combine(date_to, time.max, tzinfo=timezone.utc) if date_to else None),
  842. )
  843. total_energy_cost = total_energy_kwh * energy_cost_per_kwh
  844. else:
  845. # Per-print mode: sum the per-run energy column from PrintLogEntry.
  846. energy_kwh_result = await db.execute(select(func.sum(PrintLogEntry.energy_kwh)).where(*base_conditions))
  847. total_energy_kwh = energy_kwh_result.scalar() or 0
  848. energy_cost_result = await db.execute(select(func.sum(PrintLogEntry.energy_cost)).where(*base_conditions))
  849. total_energy_cost = energy_cost_result.scalar() or 0
  850. return ArchiveStats(
  851. total_prints=total_prints,
  852. successful_prints=successful_prints,
  853. failed_prints=failed_prints,
  854. total_print_time_hours=round(total_time, 1),
  855. total_filament_grams=round(total_filament, 1),
  856. total_cost=round(total_cost, 2),
  857. prints_by_filament_type=prints_by_filament,
  858. prints_by_printer=prints_by_printer,
  859. average_time_accuracy=average_accuracy,
  860. time_accuracy_by_printer=accuracy_by_printer if accuracy_by_printer else None,
  861. total_energy_kwh=round(total_energy_kwh, 3),
  862. total_energy_cost=round(total_energy_cost, 3),
  863. energy_data_warming_up=energy_data_warming_up,
  864. )
  865. async def _sum_live_plug_totals(db: AsyncSession) -> float:
  866. """Sum the live lifetime counter from every smart plug.
  867. Used for all-time "total consumption" mode. Only the current value is
  868. available so this can't be date-filtered — use `_sum_snapshot_deltas` for
  869. that case.
  870. """
  871. from backend.app.api.routes.settings import get_setting
  872. from backend.app.models.smart_plug import SmartPlug
  873. from backend.app.services.homeassistant import homeassistant_service
  874. from backend.app.services.mqtt_relay import mqtt_relay
  875. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  876. from backend.app.services.tasmota import tasmota_service
  877. plugs_result = await db.execute(select(SmartPlug))
  878. plugs = list(plugs_result.scalars().all())
  879. ha_url = await get_setting(db, "ha_url") or ""
  880. ha_token = await get_setting(db, "ha_token") or ""
  881. homeassistant_service.configure(ha_url, ha_token)
  882. total = 0.0
  883. for plug in plugs:
  884. if plug.plug_type == "tasmota":
  885. energy = await tasmota_service.get_energy(plug)
  886. if energy and energy.get("total") is not None:
  887. total += energy["total"]
  888. elif plug.plug_type == "homeassistant":
  889. energy = await homeassistant_service.get_energy(plug)
  890. if energy and energy.get("total") is not None:
  891. total += energy["total"]
  892. elif plug.plug_type == "mqtt":
  893. # MQTT plugs only expose today's counter, not lifetime.
  894. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  895. if mqtt_data and mqtt_data.energy is not None:
  896. total += mqtt_data.energy
  897. elif plug.plug_type == "rest":
  898. energy = await rest_smart_plug_service.get_energy(plug)
  899. if energy and energy.get("today") is not None:
  900. total += energy["today"]
  901. return total
  902. async def _sum_snapshot_deltas(
  903. db: AsyncSession,
  904. *,
  905. dt_from: datetime | None,
  906. dt_to: datetime | None,
  907. ) -> tuple[float, bool]:
  908. """Sum per-plug energy consumption over a date range using hourly snapshots.
  909. For each plug:
  910. * baseline = last snapshot at or before `dt_from` (ideal)
  911. — if missing, fall back to the earliest snapshot ever
  912. recorded for the plug and flag the result as warming up.
  913. * endpoint = last snapshot at or before `dt_to` (or most recent overall)
  914. * delta = max(0, endpoint - baseline) — clamp counter resets to 0.
  915. Returns (total_kwh, warming_up). `warming_up = True` means at least one plug
  916. had no baseline before `dt_from` (fresh install or fresh upgrade), so the
  917. result undercounts the beginning of the range.
  918. """
  919. from backend.app.models.smart_plug import SmartPlug
  920. from backend.app.models.smart_plug_energy_snapshot import SmartPlugEnergySnapshot
  921. plug_ids_result = await db.execute(select(SmartPlug.id))
  922. plug_ids = [row[0] for row in plug_ids_result.all()]
  923. if not plug_ids:
  924. return 0.0, False
  925. total = 0.0
  926. warming_up = False
  927. for plug_id in plug_ids:
  928. baseline: float | None = None
  929. if dt_from is not None:
  930. baseline_q = await db.execute(
  931. select(SmartPlugEnergySnapshot.lifetime_kwh)
  932. .where(
  933. SmartPlugEnergySnapshot.plug_id == plug_id,
  934. SmartPlugEnergySnapshot.recorded_at <= dt_from,
  935. )
  936. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  937. .limit(1)
  938. )
  939. baseline = baseline_q.scalar()
  940. if baseline is None:
  941. # No snapshot before range start — fall back to the earliest
  942. # snapshot ever recorded. Result undercounts the pre-first-snapshot
  943. # portion of the range; signal that to the frontend.
  944. earliest_q = await db.execute(
  945. select(SmartPlugEnergySnapshot.lifetime_kwh)
  946. .where(SmartPlugEnergySnapshot.plug_id == plug_id)
  947. .order_by(SmartPlugEnergySnapshot.recorded_at.asc())
  948. .limit(1)
  949. )
  950. baseline = earliest_q.scalar()
  951. if baseline is None:
  952. # No snapshots at all for this plug yet.
  953. warming_up = True
  954. continue
  955. warming_up = True
  956. endpoint_conditions = [SmartPlugEnergySnapshot.plug_id == plug_id]
  957. if dt_to is not None:
  958. endpoint_conditions.append(SmartPlugEnergySnapshot.recorded_at <= dt_to)
  959. endpoint_q = await db.execute(
  960. select(SmartPlugEnergySnapshot.lifetime_kwh)
  961. .where(*endpoint_conditions)
  962. .order_by(SmartPlugEnergySnapshot.recorded_at.desc())
  963. .limit(1)
  964. )
  965. endpoint = endpoint_q.scalar()
  966. if endpoint is None:
  967. continue
  968. total += max(0.0, endpoint - baseline)
  969. return total, warming_up
  970. @router.get("/tags")
  971. async def get_all_tags(
  972. db: AsyncSession = Depends(get_db),
  973. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  974. ):
  975. """List all unique tags with usage counts.
  976. Returns a list of tags sorted by count (descending), then by name.
  977. """
  978. # Query all archives with non-null tags
  979. result = await db.execute(
  980. select(PrintArchive.tags).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  981. )
  982. all_tags_rows = result.all()
  983. # Count occurrences of each tag
  984. tag_counts: dict[str, int] = {}
  985. for (tags_str,) in all_tags_rows:
  986. if tags_str:
  987. for tag in tags_str.split(","):
  988. tag = tag.strip()
  989. if tag:
  990. tag_counts[tag] = tag_counts.get(tag, 0) + 1
  991. # Convert to list and sort by count (desc), then name (asc)
  992. tags_list = [{"name": name, "count": count} for name, count in tag_counts.items()]
  993. tags_list.sort(key=lambda x: (-x["count"], x["name"].lower()))
  994. return tags_list
  995. @router.put("/tags/{tag_name}")
  996. async def rename_tag(
  997. tag_name: str,
  998. request: Request,
  999. db: AsyncSession = Depends(get_db),
  1000. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1001. ):
  1002. """Rename a tag across all archives.
  1003. Request body should contain {"new_name": "new tag name"}.
  1004. Returns the count of affected archives.
  1005. """
  1006. body = await request.json()
  1007. new_name = body.get("new_name", "").strip()
  1008. if not new_name:
  1009. raise HTTPException(400, "new_name is required")
  1010. if new_name == tag_name:
  1011. return {"affected": 0}
  1012. # Find all archives containing the old tag
  1013. result = await db.execute(
  1014. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1015. )
  1016. archives = list(result.scalars().all())
  1017. affected = 0
  1018. for archive in archives:
  1019. if not archive.tags:
  1020. continue
  1021. tags = [t.strip() for t in archive.tags.split(",")]
  1022. if tag_name in tags:
  1023. # Replace old tag with new tag
  1024. new_tags = [new_name if t == tag_name else t for t in tags]
  1025. # Remove duplicates while preserving order
  1026. seen = set()
  1027. unique_tags = []
  1028. for t in new_tags:
  1029. if t not in seen:
  1030. seen.add(t)
  1031. unique_tags.append(t)
  1032. archive.tags = ", ".join(unique_tags)
  1033. affected += 1
  1034. await db.commit()
  1035. return {"affected": affected}
  1036. @router.delete("/tags/{tag_name}")
  1037. async def delete_tag(
  1038. tag_name: str,
  1039. db: AsyncSession = Depends(get_db),
  1040. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1041. ):
  1042. """Delete a tag from all archives.
  1043. Returns the count of affected archives.
  1044. """
  1045. # Find all archives containing the tag
  1046. result = await db.execute(
  1047. select(PrintArchive).where(PrintArchive.tags.isnot(None), PrintArchive.deleted_at.is_(None))
  1048. )
  1049. archives = list(result.scalars().all())
  1050. affected = 0
  1051. for archive in archives:
  1052. if not archive.tags:
  1053. continue
  1054. tags = [t.strip() for t in archive.tags.split(",")]
  1055. if tag_name in tags:
  1056. # Remove the tag
  1057. new_tags = [t for t in tags if t != tag_name]
  1058. archive.tags = ", ".join(new_tags) if new_tags else None
  1059. affected += 1
  1060. await db.commit()
  1061. return {"affected": affected}
  1062. @router.get("/{archive_id}", response_model=ArchiveResponse)
  1063. async def get_archive(
  1064. archive_id: int,
  1065. db: AsyncSession = Depends(get_db),
  1066. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1067. ):
  1068. """Get a specific archive."""
  1069. service = ArchiveService(db)
  1070. archive = await service.get_archive(archive_id)
  1071. # Soft-deleted archives are hidden from the UI (#1343) — surface them as
  1072. # 404 here too so a stale bookmark / direct URL doesn't expose a row the
  1073. # user has already removed. The hard-delete (?purge_stats=true) path
  1074. # bypasses this check by querying PrintArchive directly.
  1075. if not archive or archive.deleted_at is not None:
  1076. raise HTTPException(404, "Archive not found")
  1077. # Find duplicates
  1078. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1079. duplicates = await service.find_duplicates(
  1080. archive_id=archive.id,
  1081. content_hash=archive.content_hash,
  1082. print_name=archive.print_name,
  1083. makerworld_model_id=makerworld_id,
  1084. )
  1085. run_aggregates = await _load_run_aggregates(db, [archive.id])
  1086. return archive_to_response(archive, duplicates, run_aggregate=run_aggregates.get(archive.id))
  1087. @router.get("/{archive_id}/runs", response_model=PrintLogResponse)
  1088. async def list_archive_runs(
  1089. archive_id: int,
  1090. db: AsyncSession = Depends(get_db),
  1091. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1092. ):
  1093. """List PrintLogEntry rows for this archive — one per print event.
  1094. Newest first. Drives the per-archive "Print Log" view (#1378).
  1095. """
  1096. from backend.app.models.print_log import PrintLogEntry
  1097. from backend.app.schemas.print_log import PrintLogEntrySchema
  1098. archive = await db.get(PrintArchive, archive_id)
  1099. if not archive or archive.deleted_at is not None:
  1100. raise HTTPException(404, "Archive not found")
  1101. rows = await db.execute(
  1102. select(PrintLogEntry)
  1103. .where(PrintLogEntry.archive_id == archive_id)
  1104. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  1105. )
  1106. entries = list(rows.scalars().all())
  1107. items = [PrintLogEntrySchema.model_validate(e, from_attributes=True) for e in entries]
  1108. return PrintLogResponse(items=items, total=len(items))
  1109. @router.get("/{archive_id}/similar")
  1110. async def find_similar_archives(
  1111. archive_id: int,
  1112. limit: int = 10,
  1113. db: AsyncSession = Depends(get_db),
  1114. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1115. ):
  1116. """Find archives with similar settings for comparison.
  1117. Returns archives that match by:
  1118. - Same print name (highest priority)
  1119. - Same file content hash
  1120. - Same filament type
  1121. """
  1122. from backend.app.services.archive_comparison import ArchiveComparisonService
  1123. service = ArchiveComparisonService(db)
  1124. try:
  1125. return await service.find_similar_archives(archive_id, limit=limit)
  1126. except ValueError as e:
  1127. raise HTTPException(404, str(e))
  1128. @router.patch("/{archive_id}", response_model=ArchiveResponse)
  1129. async def update_archive(
  1130. archive_id: int,
  1131. update_data: ArchiveUpdate,
  1132. db: AsyncSession = Depends(get_db),
  1133. auth_result: tuple[User | None, bool] = Depends(
  1134. require_ownership_permission(
  1135. Permission.ARCHIVES_UPDATE_ALL,
  1136. Permission.ARCHIVES_UPDATE_OWN,
  1137. )
  1138. ),
  1139. ):
  1140. """Update archive metadata (tags, notes, cost, is_favorite, project_id)."""
  1141. from sqlalchemy.orm import selectinload
  1142. user, can_modify_all = auth_result
  1143. result = await db.execute(
  1144. select(PrintArchive)
  1145. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1146. .where(PrintArchive.id == archive_id)
  1147. )
  1148. archive = result.scalar_one_or_none()
  1149. if not archive:
  1150. raise HTTPException(404, "Archive not found")
  1151. # Ownership check
  1152. if not can_modify_all:
  1153. if archive.created_by_id != user.id:
  1154. raise HTTPException(403, "You can only update your own archives")
  1155. for field, value in update_data.model_dump(exclude_unset=True).items():
  1156. setattr(archive, field, value)
  1157. await db.commit()
  1158. # Re-fetch with relationships loaded after commit
  1159. result = await db.execute(
  1160. select(PrintArchive)
  1161. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  1162. .where(PrintArchive.id == archive_id)
  1163. )
  1164. archive = result.scalar_one_or_none()
  1165. return archive_to_response(archive)
  1166. @router.post("/{archive_id}/favorite", response_model=ArchiveResponse)
  1167. async def toggle_favorite(
  1168. archive_id: int,
  1169. db: AsyncSession = Depends(get_db),
  1170. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  1171. ):
  1172. """Toggle favorite status for an archive."""
  1173. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1174. archive = result.scalar_one_or_none()
  1175. if not archive:
  1176. raise HTTPException(404, "Archive not found")
  1177. archive.is_favorite = not archive.is_favorite
  1178. await db.commit()
  1179. await db.refresh(archive)
  1180. return archive
  1181. @router.post("/{archive_id}/rescan", response_model=ArchiveResponse)
  1182. async def rescan_archive(
  1183. archive_id: int,
  1184. db: AsyncSession = Depends(get_db),
  1185. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1186. ):
  1187. """Rescan the 3MF file and update metadata."""
  1188. from backend.app.api.routes.settings import get_setting
  1189. from backend.app.services.archive import ThreeMFParser
  1190. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1191. archive = result.scalar_one_or_none()
  1192. if not archive:
  1193. raise HTTPException(404, "Archive not found")
  1194. file_path = settings.base_dir / archive.file_path
  1195. if not file_path.is_file():
  1196. raise HTTPException(404, "Archive file not found")
  1197. # Parse the 3MF file
  1198. parser = ThreeMFParser(file_path)
  1199. metadata = parser.parse()
  1200. # Update fields from metadata
  1201. if metadata.get("filament_type"):
  1202. archive.filament_type = metadata["filament_type"]
  1203. if metadata.get("filament_color"):
  1204. archive.filament_color = metadata["filament_color"]
  1205. if metadata.get("print_time_seconds"):
  1206. archive.print_time_seconds = metadata["print_time_seconds"]
  1207. if metadata.get("filament_used_grams"):
  1208. archive.filament_used_grams = metadata["filament_used_grams"]
  1209. if metadata.get("layer_height"):
  1210. archive.layer_height = metadata["layer_height"]
  1211. if metadata.get("nozzle_diameter"):
  1212. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1213. if metadata.get("bed_temperature"):
  1214. archive.bed_temperature = metadata["bed_temperature"]
  1215. if metadata.get("bed_type"):
  1216. archive.bed_type = metadata["bed_type"]
  1217. if metadata.get("nozzle_temperature"):
  1218. archive.nozzle_temperature = metadata["nozzle_temperature"]
  1219. if metadata.get("makerworld_url"):
  1220. archive.makerworld_url = metadata["makerworld_url"]
  1221. if metadata.get("designer"):
  1222. archive.designer = metadata["designer"]
  1223. # Calculate cost: prefer spool-based cost if available, else catalog-based.
  1224. # When spool-based costs exist but don't cover every filament gram used
  1225. # (#1344), fall back to the global default rate for the untracked weight
  1226. # so the displayed cost still reflects the whole print.
  1227. if archive.filament_used_grams and archive.filament_type:
  1228. default_cost_setting = await get_setting(db, "default_filament_cost")
  1229. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1230. usage_result = await db.execute(
  1231. select(
  1232. func.sum(SpoolUsageHistory.cost),
  1233. func.sum(SpoolUsageHistory.weight_used),
  1234. ).where(SpoolUsageHistory.archive_id == archive.id)
  1235. )
  1236. usage_cost_row = usage_result.one()
  1237. usage_cost = usage_cost_row[0]
  1238. tracked_grams = float(usage_cost_row[1] or 0)
  1239. if usage_cost is not None and usage_cost > 0:
  1240. total_cost = float(usage_cost)
  1241. untracked_grams = max(0.0, archive.filament_used_grams - tracked_grams)
  1242. if untracked_grams > 0 and default_cost_per_kg > 0:
  1243. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1244. archive.cost = float(Decimal(str(total_cost)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
  1245. else:
  1246. primary_type = archive.filament_type.split(",")[0].strip()
  1247. filament_result = await db.execute(select(Filament).where(Filament.type == primary_type).limit(1))
  1248. filament = filament_result.scalar_one_or_none()
  1249. if filament:
  1250. archive.cost = float(
  1251. Decimal(str((archive.filament_used_grams / 1000) * filament.cost_per_kg)).quantize(
  1252. Decimal("0.01"), rounding=ROUND_HALF_UP
  1253. )
  1254. )
  1255. else:
  1256. archive.cost = float(
  1257. Decimal(str((archive.filament_used_grams / 1000) * default_cost_per_kg)).quantize(
  1258. Decimal("0.01"), rounding=ROUND_HALF_UP
  1259. )
  1260. )
  1261. await db.commit()
  1262. await db.refresh(archive)
  1263. return archive
  1264. @router.post("/recalculate-costs")
  1265. async def recalculate_all_costs(
  1266. db: AsyncSession = Depends(get_db),
  1267. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1268. ):
  1269. """Recalculate costs for all archives based on filament usage and prices."""
  1270. from backend.app.api.routes.settings import get_setting
  1271. result = await db.execute(select(PrintArchive))
  1272. archives = list(result.scalars().all())
  1273. # Load all filaments for lookup
  1274. filament_result = await db.execute(select(Filament))
  1275. filaments = {f.type: f.cost_per_kg for f in filament_result.scalars().all()}
  1276. # Get default filament cost from settings
  1277. default_cost_setting = await get_setting(db, "default_filament_cost")
  1278. default_cost_per_kg = float(default_cost_setting) if default_cost_setting else 25.0
  1279. # Pre-fetch all usage costs and tracked weight by archive_id.
  1280. # Tracked weight is used to top-up the cost at the default rate for any
  1281. # filament grams not covered by an inventory spool (#1344).
  1282. usage_costs_result = await db.execute(
  1283. select(
  1284. SpoolUsageHistory.archive_id,
  1285. func.sum(SpoolUsageHistory.cost),
  1286. func.sum(SpoolUsageHistory.weight_used),
  1287. ).group_by(SpoolUsageHistory.archive_id)
  1288. )
  1289. usage_costs = usage_costs_result.fetchall()
  1290. cost_map = {
  1291. row[0]: (row[1], float(row[2] or 0))
  1292. for row in usage_costs
  1293. if row[0] is not None and row[1] is not None and row[1] > 0
  1294. }
  1295. updated = 0
  1296. for archive in archives:
  1297. usage = cost_map.get(archive.id)
  1298. if usage is not None:
  1299. usage_cost, tracked_grams = usage
  1300. total_cost = float(usage_cost)
  1301. archive_grams = float(archive.filament_used_grams or 0)
  1302. untracked_grams = max(0.0, archive_grams - tracked_grams)
  1303. if untracked_grams > 0 and default_cost_per_kg > 0:
  1304. total_cost += (untracked_grams / 1000.0) * default_cost_per_kg
  1305. new_cost = round(total_cost, 2)
  1306. else:
  1307. # Fallback: sum costs for old records by print_name
  1308. usage_result = await db.execute(
  1309. select(func.sum(SpoolUsageHistory.cost)).where(
  1310. SpoolUsageHistory.print_name == archive.print_name,
  1311. SpoolUsageHistory.archive_id.is_(None),
  1312. )
  1313. )
  1314. fallback_cost = usage_result.scalar()
  1315. if fallback_cost is not None and fallback_cost > 0:
  1316. new_cost = round(fallback_cost, 2)
  1317. elif archive.filament_used_grams and archive.filament_type:
  1318. primary_type = archive.filament_type.split(",")[0].strip()
  1319. cost_per_kg = filaments.get(primary_type, default_cost_per_kg)
  1320. new_cost = round((archive.filament_used_grams / 1000) * cost_per_kg, 2)
  1321. else:
  1322. new_cost = None
  1323. if new_cost is not None and archive.cost != new_cost:
  1324. archive.cost = new_cost
  1325. updated += 1
  1326. await db.commit()
  1327. return {"message": f"Recalculated costs for {updated} archives", "updated": updated}
  1328. @router.post("/rescan-all")
  1329. async def rescan_all_archives(
  1330. db: AsyncSession = Depends(get_db),
  1331. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1332. ):
  1333. """Rescan all archives and update their metadata."""
  1334. from backend.app.services.archive import ThreeMFParser
  1335. result = await db.execute(select(PrintArchive))
  1336. archives = list(result.scalars().all())
  1337. updated = 0
  1338. errors = []
  1339. for archive in archives:
  1340. try:
  1341. file_path = settings.base_dir / archive.file_path
  1342. if not file_path.is_file():
  1343. errors.append({"id": archive.id, "error": "File not found"})
  1344. continue
  1345. parser = ThreeMFParser(file_path)
  1346. metadata = parser.parse()
  1347. if metadata.get("filament_type"):
  1348. archive.filament_type = metadata["filament_type"]
  1349. if metadata.get("filament_color"):
  1350. archive.filament_color = metadata["filament_color"]
  1351. if metadata.get("print_time_seconds"):
  1352. archive.print_time_seconds = metadata["print_time_seconds"]
  1353. if metadata.get("filament_used_grams"):
  1354. archive.filament_used_grams = metadata["filament_used_grams"]
  1355. if metadata.get("layer_height"):
  1356. archive.layer_height = metadata["layer_height"]
  1357. if metadata.get("nozzle_diameter"):
  1358. archive.nozzle_diameter = metadata["nozzle_diameter"]
  1359. if metadata.get("makerworld_url"):
  1360. archive.makerworld_url = metadata["makerworld_url"]
  1361. if metadata.get("designer"):
  1362. archive.designer = metadata["designer"]
  1363. updated += 1
  1364. except Exception as e:
  1365. logger.exception("Failed to rescan archive %s: %s", archive.id, e)
  1366. errors.append({"id": archive.id, "error": "Failed to parse 3MF file"})
  1367. await db.commit()
  1368. return {"updated": updated, "errors": errors}
  1369. @router.get("/{archive_id}/duplicates")
  1370. async def get_archive_duplicates(
  1371. archive_id: int,
  1372. db: AsyncSession = Depends(get_db),
  1373. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1374. ):
  1375. """Get duplicates for a specific archive."""
  1376. service = ArchiveService(db)
  1377. archive = await service.get_archive(archive_id)
  1378. if not archive:
  1379. raise HTTPException(404, "Archive not found")
  1380. makerworld_id = archive.extra_data.get("makerworld_model_id") if archive.extra_data else None
  1381. duplicates = await service.find_duplicates(
  1382. archive_id=archive.id,
  1383. content_hash=archive.content_hash,
  1384. print_name=archive.print_name,
  1385. makerworld_model_id=makerworld_id,
  1386. )
  1387. return {"duplicates": duplicates, "count": len(duplicates)}
  1388. @router.post("/backfill-hashes")
  1389. async def backfill_content_hashes(
  1390. db: AsyncSession = Depends(get_db),
  1391. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1392. ):
  1393. """Compute and store content hashes for all archives missing them."""
  1394. result = await db.execute(select(PrintArchive).where(PrintArchive.content_hash.is_(None)))
  1395. archives = list(result.scalars().all())
  1396. updated = 0
  1397. errors = []
  1398. for archive in archives:
  1399. try:
  1400. file_path = settings.base_dir / archive.file_path
  1401. if not file_path.is_file():
  1402. errors.append({"id": archive.id, "error": "File not found"})
  1403. continue
  1404. archive.content_hash = ArchiveService.compute_file_hash(file_path)
  1405. updated += 1
  1406. except Exception as e:
  1407. logger.exception("Failed to compute hash for archive %s: %s", archive.id, e)
  1408. errors.append({"id": archive.id, "error": "Failed to compute hash"})
  1409. await db.commit()
  1410. return {"updated": updated, "errors": errors}
  1411. @router.delete("/{archive_id}")
  1412. async def delete_archive(
  1413. archive_id: int,
  1414. purge_stats: bool = Query(
  1415. False,
  1416. description=(
  1417. "When false (default) the archive is soft-deleted — files removed "
  1418. "from disk, row hidden from listings, but its filament / energy / "
  1419. "time / cost contribution stays in Quick Stats. Set true to also "
  1420. "drop the row from statistics (#1343)."
  1421. ),
  1422. ),
  1423. db: AsyncSession = Depends(get_db),
  1424. auth_result: tuple[User | None, bool] = Depends(
  1425. require_ownership_permission(
  1426. Permission.ARCHIVES_DELETE_ALL,
  1427. Permission.ARCHIVES_DELETE_OWN,
  1428. )
  1429. ),
  1430. ):
  1431. """Delete an archive (soft by default; ``?purge_stats=true`` to hard-delete)."""
  1432. user, can_modify_all = auth_result
  1433. # Get archive first to check ownership
  1434. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1435. archive = result.scalar_one_or_none()
  1436. if not archive:
  1437. raise HTTPException(404, "Archive not found")
  1438. # Ownership check
  1439. if not can_modify_all:
  1440. if archive.created_by_id != user.id:
  1441. raise HTTPException(403, "You can only delete your own archives")
  1442. service = ArchiveService(db)
  1443. if purge_stats:
  1444. # Hard-delete the linked PrintLogEntry rows first so their filament /
  1445. # cost / count contributions disappear from /archives/stats. The FK is
  1446. # ON DELETE SET NULL, so without this delete the runs would survive
  1447. # the archive row and keep showing up in totals (#1343 / #1378).
  1448. from sqlalchemy import delete as sa_delete
  1449. from backend.app.models.print_log import PrintLogEntry
  1450. await db.execute(sa_delete(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id))
  1451. await db.commit()
  1452. if not await service.delete_archive(archive_id):
  1453. raise HTTPException(404, "Archive not found")
  1454. return {"status": "deleted", "purged_from_stats": True}
  1455. if not await service.soft_delete_archive(archive_id):
  1456. raise HTTPException(404, "Archive not found")
  1457. return {"status": "deleted", "purged_from_stats": False}
  1458. @router.get("/{archive_id}/download")
  1459. async def download_archive(
  1460. archive_id: int,
  1461. inline: bool = False,
  1462. db: AsyncSession = Depends(get_db),
  1463. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1464. ):
  1465. """Download the 3MF file."""
  1466. service = ArchiveService(db)
  1467. archive = await service.get_archive(archive_id)
  1468. if not archive:
  1469. raise HTTPException(404, "Archive not found")
  1470. file_path = settings.base_dir / archive.file_path
  1471. if not file_path.is_file():
  1472. raise HTTPException(404, "File not found")
  1473. # Use inline disposition to let browser/OS handle file association
  1474. content_disposition = "inline" if inline else "attachment"
  1475. return FileResponse(
  1476. path=file_path,
  1477. filename=archive.filename,
  1478. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1479. content_disposition_type=content_disposition,
  1480. )
  1481. @router.get("/{archive_id}/file/{filename}")
  1482. async def download_archive_with_filename(
  1483. archive_id: int,
  1484. filename: str,
  1485. db: AsyncSession = Depends(get_db),
  1486. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1487. ):
  1488. """Download the 3MF file with filename in URL."""
  1489. service = ArchiveService(db)
  1490. archive = await service.get_archive(archive_id)
  1491. if not archive:
  1492. raise HTTPException(404, "Archive not found")
  1493. file_path = settings.base_dir / archive.file_path
  1494. if not file_path.is_file():
  1495. raise HTTPException(404, "File not found")
  1496. return FileResponse(
  1497. path=file_path,
  1498. filename=archive.filename,
  1499. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1500. )
  1501. @router.post("/{archive_id}/slicer-token")
  1502. async def create_archive_slicer_token(
  1503. archive_id: int,
  1504. db: AsyncSession = Depends(get_db),
  1505. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1506. ):
  1507. """Create a short-lived download token for opening files in slicer applications.
  1508. Slicer protocol handlers (bambustudioopen://, orcaslicer://) cannot send
  1509. auth headers, so they use this token in the URL path instead.
  1510. """
  1511. from backend.app.core.auth import create_slicer_download_token
  1512. service = ArchiveService(db)
  1513. archive = await service.get_archive(archive_id)
  1514. if not archive:
  1515. raise HTTPException(404, "Archive not found")
  1516. token = await create_slicer_download_token("archive", archive_id)
  1517. return {"token": token}
  1518. @router.get("/{archive_id}/dl/{token}/{filename}")
  1519. async def download_archive_for_slicer(
  1520. archive_id: int,
  1521. token: str,
  1522. filename: str,
  1523. db: AsyncSession = Depends(get_db),
  1524. ):
  1525. """Download 3MF file using a slicer download token.
  1526. Token-authenticated (no auth headers needed). The token is short-lived
  1527. and single-use, created by POST /{archive_id}/slicer-token.
  1528. Filename is at the end of the URL so slicers can detect the file format.
  1529. """
  1530. from backend.app.core.auth import verify_slicer_download_token
  1531. if not await verify_slicer_download_token(token, "archive", archive_id):
  1532. raise HTTPException(403, "Invalid or expired download token")
  1533. service = ArchiveService(db)
  1534. archive = await service.get_archive(archive_id)
  1535. if not archive:
  1536. raise HTTPException(404, "Archive not found")
  1537. file_path = settings.base_dir / archive.file_path
  1538. if not file_path.is_file():
  1539. raise HTTPException(404, "File not found")
  1540. return FileResponse(
  1541. path=file_path,
  1542. filename=archive.filename,
  1543. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1544. )
  1545. @router.get("/{archive_id}/thumbnail")
  1546. async def get_thumbnail(
  1547. archive_id: int,
  1548. db: AsyncSession = Depends(get_db),
  1549. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1550. ):
  1551. """Get the thumbnail image.
  1552. Requires a stream token query param (?token=xxx) when auth is enabled.
  1553. """
  1554. service = ArchiveService(db)
  1555. archive = await service.get_archive(archive_id)
  1556. if not archive or not archive.thumbnail_path:
  1557. raise HTTPException(404, "Thumbnail not found")
  1558. thumb_path = settings.base_dir / archive.thumbnail_path
  1559. if not thumb_path.exists():
  1560. raise HTTPException(404, "Thumbnail file not found")
  1561. # Use file modification time as ETag to bust cache
  1562. mtime = int(thumb_path.stat().st_mtime)
  1563. return FileResponse(
  1564. path=thumb_path,
  1565. media_type="image/png",
  1566. headers={
  1567. "Cache-Control": "no-cache, must-revalidate",
  1568. "ETag": f'"{mtime}"',
  1569. },
  1570. )
  1571. @router.get("/{archive_id}/timelapse")
  1572. async def get_timelapse(
  1573. archive_id: int,
  1574. db: AsyncSession = Depends(get_db),
  1575. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1576. ):
  1577. """Get the timelapse video.
  1578. Requires a stream token query param (?token=xxx) when auth is enabled.
  1579. """
  1580. service = ArchiveService(db)
  1581. archive = await service.get_archive(archive_id)
  1582. if not archive or not archive.timelapse_path:
  1583. raise HTTPException(404, "Timelapse not found")
  1584. timelapse_path = settings.base_dir / archive.timelapse_path
  1585. if not timelapse_path.exists():
  1586. raise HTTPException(404, "Timelapse file not found")
  1587. # Use file modification time as ETag to bust cache after processing
  1588. mtime = int(timelapse_path.stat().st_mtime)
  1589. # Detect media type from file extension (AVI from P1S before background conversion)
  1590. suffix = timelapse_path.suffix.lower()
  1591. media_type = {".mp4": "video/mp4", ".avi": "video/x-msvideo", ".mkv": "video/x-matroska"}.get(suffix, "video/mp4")
  1592. ext = suffix if suffix in (".mp4", ".avi", ".mkv") else ".mp4"
  1593. return FileResponse(
  1594. path=timelapse_path,
  1595. media_type=media_type,
  1596. filename=f"{archive.print_name or 'timelapse'}{ext}",
  1597. headers={
  1598. "Cache-Control": "no-cache, must-revalidate",
  1599. "ETag": f'"{mtime}"',
  1600. },
  1601. )
  1602. @router.delete("/{archive_id}/timelapse")
  1603. async def delete_timelapse(
  1604. archive_id: int,
  1605. db: AsyncSession = Depends(get_db),
  1606. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  1607. ):
  1608. """Remove the timelapse video from an archive."""
  1609. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1610. archive = result.scalar_one_or_none()
  1611. if not archive:
  1612. raise HTTPException(404, "Archive not found")
  1613. if not archive.timelapse_path:
  1614. raise HTTPException(404, "No timelapse attached to this archive")
  1615. # Delete the file
  1616. timelapse_path = settings.base_dir / archive.timelapse_path
  1617. if timelapse_path.exists():
  1618. timelapse_path.unlink()
  1619. # Clear the path in database
  1620. archive.timelapse_path = None
  1621. await db.commit()
  1622. return {"status": "deleted"}
  1623. @router.post("/{archive_id}/timelapse/scan")
  1624. async def scan_timelapse(
  1625. archive_id: int,
  1626. db: AsyncSession = Depends(get_db),
  1627. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1628. ):
  1629. """Scan printer for timelapse matching this archive and attach it."""
  1630. from backend.app.models.printer import Printer
  1631. from backend.app.services.bambu_ftp import (
  1632. download_file_bytes_async,
  1633. get_ftp_retry_settings,
  1634. list_files_async,
  1635. with_ftp_retry,
  1636. )
  1637. service = ArchiveService(db)
  1638. archive = await service.get_archive(archive_id)
  1639. if not archive:
  1640. raise HTTPException(404, "Archive not found")
  1641. if archive.timelapse_path:
  1642. return {"status": "exists", "message": "Timelapse already attached"}
  1643. if not archive.printer_id:
  1644. raise HTTPException(400, "Archive has no associated printer")
  1645. # Get printer
  1646. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1647. printer = result.scalar_one_or_none()
  1648. if not printer:
  1649. raise HTTPException(404, "Printer not found")
  1650. # Get base name from archive filename (without .3mf extension)
  1651. base_name = Path(archive.filename).stem
  1652. # Scan timelapse directory on printer
  1653. # Different printer models use different paths
  1654. files = []
  1655. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1656. try:
  1657. files = await list_files_async(
  1658. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1659. )
  1660. if files:
  1661. break
  1662. except Exception:
  1663. continue
  1664. if not files:
  1665. raise HTTPException(500, "Failed to connect to printer or no timelapse directory found")
  1666. # Look for matching timelapse
  1667. matching_file = None
  1668. video_files = [
  1669. f for f in files if not f.get("is_directory") and f.get("name", "").lower().endswith((".mp4", ".avi"))
  1670. ]
  1671. # Strategy 1: Match by print name in filename
  1672. for f in video_files:
  1673. fname = f.get("name", "")
  1674. if base_name.lower() in fname.lower():
  1675. matching_file = f
  1676. break
  1677. # Strategy 2: Match by timestamp proximity against print START time.
  1678. # Bambu timelapse filename embeds the print start time in printer-local clock.
  1679. # See _match_timelapse_by_timestamp for the offset-search rationale and why we
  1680. # intentionally don't try to match filename against end time here.
  1681. if not matching_file and archive.started_at:
  1682. candidate, diff = _match_timelapse_by_timestamp(video_files, archive.started_at)
  1683. if candidate is not None:
  1684. matching_file = candidate
  1685. logger.info("Matched timelapse by timestamp: %s (diff: %s)", candidate.get("name"), diff)
  1686. # Strategy 3: Use file modification time from FTP listing
  1687. # This handles cases where printer's filename timestamp is wrong but file mtime is correct
  1688. if not matching_file and (archive.started_at or archive.completed_at or archive.created_at):
  1689. from datetime import datetime, timedelta
  1690. _archive_start = archive.started_at
  1691. archive_end = archive.completed_at or archive.created_at
  1692. best_match = None
  1693. best_diff = timedelta(hours=24)
  1694. for f in video_files:
  1695. mtime = f.get("mtime")
  1696. if mtime:
  1697. # Timelapse file should be modified during or shortly after the print
  1698. # The mtime should be close to completion time (video finishes when print ends)
  1699. if archive_end:
  1700. diff = abs(mtime - archive_end)
  1701. if diff < best_diff:
  1702. best_diff = diff
  1703. best_match = f
  1704. logger.debug(
  1705. f"Timelapse mtime match candidate: {f.get('name')}, mtime: {mtime}, diff from end: {diff}"
  1706. )
  1707. if best_match and best_diff < timedelta(hours=2):
  1708. matching_file = best_match
  1709. logger.info("Matched timelapse by file mtime: %s (diff: %s)", best_match.get("name"), best_diff)
  1710. # Strategy 4: If only one timelapse exists and archive was recently completed, use it
  1711. # This handles cases where printer clock is wrong or timezone issues exist
  1712. if not matching_file and len(video_files) == 1:
  1713. from datetime import datetime, timedelta, timezone
  1714. archive_completed = archive.completed_at or archive.created_at
  1715. if archive_completed:
  1716. if archive_completed.tzinfo is None:
  1717. archive_completed = archive_completed.replace(tzinfo=timezone.utc)
  1718. time_since_completion = datetime.now(timezone.utc) - archive_completed
  1719. # If archive was completed within the last hour, assume the single timelapse is for it
  1720. if time_since_completion < timedelta(hours=1):
  1721. matching_file = video_files[0]
  1722. logger.info("Using single timelapse file as fallback: %s", video_files[0].get("name"))
  1723. # Note: We intentionally don't use a "most recent file" fallback because
  1724. # we can't verify if timelapse was actually enabled for this print.
  1725. # Instead, return the list of available files for manual selection.
  1726. if not matching_file:
  1727. # Return available files for manual selection
  1728. available_files = [
  1729. {
  1730. "name": f.get("name"),
  1731. "path": f.get("path"),
  1732. "size": f.get("size"),
  1733. "mtime": f.get("mtime").isoformat() if f.get("mtime") else None,
  1734. }
  1735. for f in video_files
  1736. ]
  1737. # Sort by mtime descending (most recent first)
  1738. available_files.sort(key=lambda x: x.get("mtime") or "", reverse=True)
  1739. return {
  1740. "status": "not_found",
  1741. "message": "No matching timelapse found - please select manually",
  1742. "available_files": available_files,
  1743. }
  1744. # Download the timelapse - use the full path from the file listing
  1745. remote_path = matching_file.get("path") or f"/timelapse/{matching_file['name']}"
  1746. # Get FTP retry settings
  1747. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1748. if ftp_retry_enabled:
  1749. timelapse_data = await with_ftp_retry(
  1750. download_file_bytes_async,
  1751. printer.ip_address,
  1752. printer.access_code,
  1753. remote_path,
  1754. socket_timeout=ftp_timeout,
  1755. printer_model=printer.model,
  1756. max_retries=ftp_retry_count,
  1757. retry_delay=ftp_retry_delay,
  1758. operation_name=f"Download timelapse {matching_file['name']}",
  1759. )
  1760. else:
  1761. timelapse_data = await download_file_bytes_async(
  1762. printer.ip_address,
  1763. printer.access_code,
  1764. remote_path,
  1765. socket_timeout=ftp_timeout,
  1766. printer_model=printer.model,
  1767. )
  1768. if not timelapse_data:
  1769. raise HTTPException(500, "Failed to download timelapse")
  1770. # Attach timelapse to archive
  1771. success = await service.attach_timelapse(archive_id, timelapse_data, matching_file["name"])
  1772. if not success:
  1773. raise HTTPException(500, "Failed to attach timelapse")
  1774. return {
  1775. "status": "attached",
  1776. "message": f"Timelapse '{matching_file['name']}' attached successfully",
  1777. "filename": matching_file["name"],
  1778. }
  1779. @router.post("/{archive_id}/timelapse/select")
  1780. async def select_timelapse(
  1781. archive_id: int,
  1782. filename: str = Query(..., description="Timelapse filename to attach"),
  1783. db: AsyncSession = Depends(get_db),
  1784. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1785. ):
  1786. """Manually select a timelapse from the printer to attach."""
  1787. from backend.app.models.printer import Printer
  1788. from backend.app.services.bambu_ftp import (
  1789. download_file_bytes_async,
  1790. get_ftp_retry_settings,
  1791. list_files_async,
  1792. with_ftp_retry,
  1793. )
  1794. service = ArchiveService(db)
  1795. archive = await service.get_archive(archive_id)
  1796. if not archive:
  1797. raise HTTPException(404, "Archive not found")
  1798. if not archive.printer_id:
  1799. raise HTTPException(400, "Archive has no associated printer")
  1800. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1801. printer = result.scalar_one_or_none()
  1802. if not printer:
  1803. raise HTTPException(404, "Printer not found")
  1804. # Find the file on the printer
  1805. files = []
  1806. remote_path = None
  1807. for timelapse_dir in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1808. try:
  1809. files = await list_files_async(
  1810. printer.ip_address, printer.access_code, timelapse_dir, printer_model=printer.model
  1811. )
  1812. for f in files:
  1813. if f.get("name") == filename:
  1814. remote_path = f.get("path") or f"{timelapse_dir}/{filename}"
  1815. break
  1816. if remote_path:
  1817. break
  1818. except Exception:
  1819. continue
  1820. if not remote_path:
  1821. raise HTTPException(404, f"Timelapse '{filename}' not found on printer")
  1822. # Download and attach
  1823. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1824. if ftp_retry_enabled:
  1825. timelapse_data = await with_ftp_retry(
  1826. download_file_bytes_async,
  1827. printer.ip_address,
  1828. printer.access_code,
  1829. remote_path,
  1830. socket_timeout=ftp_timeout,
  1831. printer_model=printer.model,
  1832. max_retries=ftp_retry_count,
  1833. retry_delay=ftp_retry_delay,
  1834. operation_name=f"Download timelapse {filename}",
  1835. )
  1836. else:
  1837. timelapse_data = await download_file_bytes_async(
  1838. printer.ip_address,
  1839. printer.access_code,
  1840. remote_path,
  1841. socket_timeout=ftp_timeout,
  1842. printer_model=printer.model,
  1843. )
  1844. if not timelapse_data:
  1845. raise HTTPException(500, "Failed to download timelapse")
  1846. success = await service.attach_timelapse(archive_id, timelapse_data, filename)
  1847. if not success:
  1848. raise HTTPException(500, "Failed to attach timelapse")
  1849. return {
  1850. "status": "attached",
  1851. "message": f"Timelapse '{filename}' attached successfully",
  1852. "filename": filename,
  1853. }
  1854. @router.post("/{archive_id}/timelapse/upload")
  1855. async def upload_timelapse(
  1856. archive_id: int,
  1857. file: UploadFile = File(...),
  1858. db: AsyncSession = Depends(get_db),
  1859. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1860. ):
  1861. """Manually upload a timelapse video to an archive."""
  1862. service = ArchiveService(db)
  1863. archive = await service.get_archive(archive_id)
  1864. if not archive:
  1865. raise HTTPException(404, "Archive not found")
  1866. if not file.filename or not file.filename.endswith((".mp4", ".avi", ".mkv")):
  1867. raise HTTPException(400, "File must be a video file (.mp4, .avi, .mkv)")
  1868. content = await file.read()
  1869. safe_filename = _safe_filename(file.filename)
  1870. success = await service.attach_timelapse(archive_id, content, safe_filename)
  1871. if not success:
  1872. raise HTTPException(500, "Failed to attach timelapse")
  1873. return {"status": "attached", "filename": safe_filename}
  1874. @router.get("/{archive_id}/timelapse/info")
  1875. async def get_timelapse_info(
  1876. archive_id: int,
  1877. db: AsyncSession = Depends(get_db),
  1878. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1879. ):
  1880. """Get timelapse video metadata for editor."""
  1881. from backend.app.schemas.timelapse import TimelapseInfoResponse
  1882. from backend.app.services.timelapse_processor import TimelapseProcessor
  1883. service = ArchiveService(db)
  1884. archive = await service.get_archive(archive_id)
  1885. if not archive or not archive.timelapse_path:
  1886. raise HTTPException(404, "Timelapse not found")
  1887. timelapse_path = settings.base_dir / archive.timelapse_path
  1888. if not timelapse_path.exists():
  1889. raise HTTPException(404, "Timelapse file not found")
  1890. try:
  1891. processor = TimelapseProcessor(timelapse_path)
  1892. info = await processor.get_info()
  1893. return TimelapseInfoResponse(**info)
  1894. except Exception as e:
  1895. logger.error("Failed to get timelapse info: %s", e)
  1896. raise HTTPException(500, f"Failed to get video info: {str(e)}")
  1897. @router.get("/{archive_id}/timelapse/thumbnails")
  1898. async def get_timelapse_thumbnails(
  1899. archive_id: int,
  1900. count: int = Query(10, ge=1, le=30),
  1901. width: int = Query(160, ge=80, le=320),
  1902. db: AsyncSession = Depends(get_db),
  1903. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  1904. ):
  1905. """Generate timeline thumbnail frames for visual scrubbing."""
  1906. import base64
  1907. from backend.app.schemas.timelapse import ThumbnailResponse
  1908. from backend.app.services.timelapse_processor import TimelapseProcessor
  1909. service = ArchiveService(db)
  1910. archive = await service.get_archive(archive_id)
  1911. if not archive or not archive.timelapse_path:
  1912. raise HTTPException(404, "Timelapse not found")
  1913. timelapse_path = settings.base_dir / archive.timelapse_path
  1914. if not timelapse_path.exists():
  1915. raise HTTPException(404, "Timelapse file not found")
  1916. try:
  1917. processor = TimelapseProcessor(timelapse_path)
  1918. thumbnails = await processor.generate_thumbnails(count, width)
  1919. return ThumbnailResponse(
  1920. thumbnails=[base64.b64encode(data).decode() for _, data in thumbnails],
  1921. timestamps=[ts for ts, _ in thumbnails],
  1922. )
  1923. except Exception as e:
  1924. logger.error("Failed to generate thumbnails: %s", e)
  1925. raise HTTPException(500, f"Failed to generate thumbnails: {str(e)}")
  1926. @router.post("/{archive_id}/timelapse/process")
  1927. async def process_timelapse(
  1928. archive_id: int,
  1929. trim_start: float = Form(0),
  1930. trim_end: float = Form(None),
  1931. speed: float = Form(1.0),
  1932. save_mode: str = Form("new"),
  1933. output_filename: str = Form(None),
  1934. audio: UploadFile = File(None),
  1935. db: AsyncSession = Depends(get_db),
  1936. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  1937. ):
  1938. """Process timelapse with trim, speed, and optional audio overlay."""
  1939. import shutil
  1940. import tempfile
  1941. from backend.app.schemas.timelapse import ProcessResponse
  1942. from backend.app.services.timelapse_processor import TimelapseProcessor
  1943. # Validate speed
  1944. if not 0.25 <= speed <= 4.0:
  1945. raise HTTPException(400, "Speed must be between 0.25 and 4.0")
  1946. if save_mode not in ("replace", "new"):
  1947. raise HTTPException(400, "save_mode must be 'replace' or 'new'")
  1948. service = ArchiveService(db)
  1949. archive = await service.get_archive(archive_id)
  1950. if not archive or not archive.timelapse_path:
  1951. raise HTTPException(404, "Timelapse not found")
  1952. timelapse_path = settings.base_dir / archive.timelapse_path
  1953. if not timelapse_path.exists():
  1954. raise HTTPException(404, "Timelapse file not found")
  1955. archive_dir = timelapse_path.parent
  1956. # Handle audio file
  1957. audio_temp_path = None
  1958. if audio and audio.filename:
  1959. # Validate audio file extension
  1960. if not audio.filename.lower().endswith((".mp3", ".wav", ".m4a", ".aac", ".ogg")):
  1961. raise HTTPException(400, "Audio must be .mp3, .wav, .m4a, .aac, or .ogg")
  1962. audio_content = await audio.read()
  1963. # Extract and validate suffix to prevent path injection
  1964. suffix = Path(audio.filename).suffix.lower()
  1965. if suffix not in (".mp3", ".wav", ".m4a", ".aac", ".ogg"):
  1966. raise HTTPException(400, "Invalid audio file extension")
  1967. audio_temp_path = Path(tempfile.gettempdir()) / f"audio_{archive_id}{suffix}"
  1968. audio_temp_path.write_bytes(audio_content)
  1969. try:
  1970. processor = TimelapseProcessor(timelapse_path)
  1971. # Determine output path
  1972. if save_mode == "replace":
  1973. # Process to temp file first, then replace
  1974. temp_output = Path(tempfile.gettempdir()) / f"processed_{archive_id}.mp4"
  1975. output_path = temp_output
  1976. else:
  1977. # Save as new file alongside original
  1978. filename = output_filename or f"{archive.print_name or 'timelapse'}_edited.mp4"
  1979. # Sanitize filename - remove path separators and traversal sequences
  1980. filename = "".join(c for c in filename if c.isalnum() or c in "._- ")
  1981. # Prevent path traversal
  1982. if ".." in filename or not filename or filename.startswith("."):
  1983. filename = f"timelapse_{archive_id}_edited"
  1984. if not filename.endswith(".mp4"):
  1985. filename += ".mp4"
  1986. output_path = archive_dir / filename
  1987. success = await processor.process(
  1988. output_path=output_path,
  1989. trim_start=trim_start,
  1990. trim_end=trim_end,
  1991. speed=speed,
  1992. audio_path=audio_temp_path,
  1993. )
  1994. if not success:
  1995. raise HTTPException(500, "Video processing failed")
  1996. # Handle save mode
  1997. if save_mode == "replace":
  1998. # Replace original file
  1999. shutil.move(str(output_path), str(timelapse_path))
  2000. final_path = archive.timelapse_path
  2001. message = "Timelapse replaced successfully"
  2002. else:
  2003. final_path = str(output_path.relative_to(settings.base_dir))
  2004. message = f"Saved as {output_path.name}"
  2005. return ProcessResponse(
  2006. status="completed",
  2007. output_path=final_path,
  2008. message=message,
  2009. )
  2010. except HTTPException:
  2011. raise
  2012. except Exception as e:
  2013. logger.error("Timelapse processing failed: %s", e)
  2014. raise HTTPException(500, f"Processing failed: {str(e)}")
  2015. finally:
  2016. # Cleanup temp audio file
  2017. if audio_temp_path and audio_temp_path.exists():
  2018. audio_temp_path.unlink()
  2019. # ============================================
  2020. # Photo Endpoints
  2021. # ============================================
  2022. @router.post("/{archive_id}/photos")
  2023. async def upload_photo(
  2024. archive_id: int,
  2025. file: UploadFile = File(...),
  2026. db: AsyncSession = Depends(get_db),
  2027. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  2028. ):
  2029. """Upload a photo of the printed result."""
  2030. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2031. archive = result.scalar_one_or_none()
  2032. if not archive:
  2033. raise HTTPException(404, "Archive not found")
  2034. if not file.filename or not file.filename.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
  2035. raise HTTPException(400, "File must be an image (.jpg, .jpeg, .png, .webp)")
  2036. # Get archive directory
  2037. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2038. photos_dir = archive_dir / "photos"
  2039. photos_dir.mkdir(exist_ok=True)
  2040. # Generate unique filename
  2041. import uuid
  2042. ext = Path(file.filename).suffix.lower()
  2043. photo_filename = f"{uuid.uuid4().hex[:8]}{ext}"
  2044. photo_path = photos_dir / photo_filename
  2045. # Save file
  2046. content = await file.read()
  2047. photo_path.write_bytes(content)
  2048. # Update archive photos list (create new list to trigger SQLAlchemy change detection)
  2049. photos = list(archive.photos or [])
  2050. photos.append(photo_filename)
  2051. archive.photos = photos
  2052. await db.commit()
  2053. await db.refresh(archive)
  2054. return {"status": "uploaded", "filename": photo_filename, "photos": archive.photos}
  2055. @router.get("/{archive_id}/photos/{filename}")
  2056. async def get_photo(
  2057. archive_id: int,
  2058. filename: str,
  2059. db: AsyncSession = Depends(get_db),
  2060. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2061. ):
  2062. """Get a specific photo.
  2063. Requires a stream token query param (?token=xxx) when auth is enabled.
  2064. """
  2065. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2066. archive = result.scalar_one_or_none()
  2067. if not archive:
  2068. raise HTTPException(404, "Archive not found")
  2069. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2070. photo_path = archive_dir / "photos" / filename
  2071. if not photo_path.exists():
  2072. raise HTTPException(404, "Photo not found")
  2073. # Determine media type
  2074. ext = Path(filename).suffix.lower()
  2075. media_types = {
  2076. ".jpg": "image/jpeg",
  2077. ".jpeg": "image/jpeg",
  2078. ".png": "image/png",
  2079. ".webp": "image/webp",
  2080. }
  2081. media_type = media_types.get(ext, "image/jpeg")
  2082. return FileResponse(path=photo_path, media_type=media_type)
  2083. @router.delete("/{archive_id}/photos/{filename}")
  2084. async def delete_photo(
  2085. archive_id: int,
  2086. filename: str,
  2087. db: AsyncSession = Depends(get_db),
  2088. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  2089. ):
  2090. """Delete a photo."""
  2091. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2092. archive = result.scalar_one_or_none()
  2093. if not archive:
  2094. raise HTTPException(404, "Archive not found")
  2095. if not archive.photos or filename not in archive.photos:
  2096. raise HTTPException(404, "Photo not found")
  2097. # Delete file
  2098. archive_dir = settings.base_dir / Path(archive.file_path).parent
  2099. photo_path = archive_dir / "photos" / filename
  2100. if photo_path.exists():
  2101. photo_path.unlink()
  2102. # Update archive photos list
  2103. photos = [p for p in archive.photos if p != filename]
  2104. archive.photos = photos if photos else None
  2105. await db.commit()
  2106. return {"status": "deleted", "photos": archive.photos}
  2107. # ============================================
  2108. # QR Code Endpoint
  2109. # ============================================
  2110. @router.get("/{archive_id}/qrcode")
  2111. async def get_qrcode(
  2112. archive_id: int,
  2113. request: Request,
  2114. size: int = 200,
  2115. db: AsyncSession = Depends(get_db),
  2116. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2117. ):
  2118. """Generate a QR code that links to this archive.
  2119. Requires a stream token query param (?token=xxx) when auth is enabled.
  2120. """
  2121. try:
  2122. import qrcode
  2123. from PIL import Image as PILImage
  2124. except ImportError:
  2125. raise HTTPException(500, "QR code generation not available - qrcode package not installed")
  2126. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2127. archive = result.scalar_one_or_none()
  2128. if not archive:
  2129. raise HTTPException(404, "Archive not found")
  2130. # Build URL to archive download
  2131. base_url = str(request.base_url).rstrip("/")
  2132. archive_url = f"{base_url}/api/v1/archives/{archive_id}/download"
  2133. # Generate QR code
  2134. qr = qrcode.QRCode(
  2135. version=1,
  2136. error_correction=qrcode.constants.ERROR_CORRECT_M,
  2137. box_size=10,
  2138. border=2,
  2139. )
  2140. qr.add_data(archive_url)
  2141. qr.make(fit=True)
  2142. img = qr.make_image(fill_color="black", back_color="white")
  2143. # Convert to PIL Image for resizing
  2144. pil_img = img.get_image()
  2145. # Resize if needed
  2146. if size != 200:
  2147. pil_img = pil_img.resize((size, size), PILImage.Resampling.LANCZOS)
  2148. # Convert to bytes
  2149. buffer = io.BytesIO()
  2150. pil_img.save(buffer, format="PNG")
  2151. buffer.seek(0)
  2152. qr_filename = f"qr_{archive.print_name or archive_id}.png"
  2153. return Response(
  2154. content=buffer.getvalue(),
  2155. media_type="image/png",
  2156. headers={"Content-Disposition": build_content_disposition(qr_filename, disposition="inline")},
  2157. )
  2158. @router.get("/{archive_id}/capabilities")
  2159. async def get_archive_capabilities(
  2160. archive_id: int,
  2161. db: AsyncSession = Depends(get_db),
  2162. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2163. ):
  2164. """Check what viewing capabilities are available for this 3MF file."""
  2165. import defusedxml.ElementTree as ET
  2166. service = ArchiveService(db)
  2167. archive = await service.get_archive(archive_id)
  2168. if not archive:
  2169. raise HTTPException(404, "Archive not found")
  2170. file_path = settings.base_dir / archive.file_path
  2171. if not file_path.is_file():
  2172. raise HTTPException(404, "File not found")
  2173. has_model = False
  2174. has_gcode = False
  2175. has_source = False
  2176. build_volume = {"x": 256, "y": 256, "z": 256} # Default to X1/P1 size
  2177. filament_colors: list[str] = []
  2178. # Check if source 3MF exists - this is where actual mesh data typically lives
  2179. source_path = None
  2180. if archive.source_3mf_path:
  2181. source_path = settings.base_dir / archive.source_3mf_path
  2182. if source_path.exists():
  2183. has_source = True
  2184. # Helper function to check for mesh data and extract colors from a 3MF file
  2185. def extract_3mf_info(zf_path: Path) -> tuple[bool, list[str], dict]:
  2186. """Extract mesh presence, colors, and build volume from a 3MF file."""
  2187. found_mesh = False
  2188. colors: list[str] = []
  2189. volume = {"x": 256, "y": 256, "z": 256}
  2190. try:
  2191. with zipfile.ZipFile(zf_path, "r") as zf:
  2192. names = zf.namelist()
  2193. # Check for 3D model - look for actual mesh data
  2194. for name in names:
  2195. if name.endswith(".model"):
  2196. try:
  2197. content = zf.read(name).decode("utf-8")
  2198. if "<vertex" in content or "<mesh" in content:
  2199. found_mesh = True
  2200. break
  2201. except Exception:
  2202. pass # Skip unreadable .model entries in archive
  2203. # Extract filament colors from project_settings.config
  2204. if "Metadata/project_settings.config" in names:
  2205. try:
  2206. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2207. config_data = json.loads(config_content)
  2208. # Parse printable_area: ['0x0', '256x0', '256x256', '0x256']
  2209. printable_area = config_data.get("printable_area", [])
  2210. if printable_area and len(printable_area) >= 3:
  2211. max_x = 0
  2212. max_y = 0
  2213. for coord in printable_area:
  2214. if "x" in coord:
  2215. parts = coord.split("x")
  2216. if len(parts) == 2:
  2217. try:
  2218. x, y = int(parts[0]), int(parts[1])
  2219. max_x = max(max_x, x)
  2220. max_y = max(max_y, y)
  2221. except ValueError:
  2222. pass # Skip non-numeric printable_area coordinate
  2223. if max_x > 0 and max_y > 0:
  2224. volume["x"] = max_x
  2225. volume["y"] = max_y
  2226. # Parse printable_height
  2227. printable_height = config_data.get("printable_height")
  2228. if printable_height:
  2229. try:
  2230. volume["z"] = int(printable_height)
  2231. except (ValueError, TypeError):
  2232. pass # Skip unparseable printable_height value
  2233. # Extract filament colors
  2234. raw_colors = config_data.get("filament_colour", [])
  2235. if raw_colors:
  2236. for color in raw_colors:
  2237. if color and isinstance(color, str):
  2238. colors.append(color)
  2239. except Exception:
  2240. pass # Skip malformed project_settings.config
  2241. except zipfile.BadZipFile:
  2242. pass # File is not a valid zip/3MF archive
  2243. return found_mesh, colors, volume
  2244. # First check source 3MF for mesh data and colors (preferred for 3D model viewing)
  2245. if has_source and source_path:
  2246. source_has_mesh, source_colors, source_volume = extract_3mf_info(source_path)
  2247. if source_has_mesh:
  2248. has_model = True
  2249. if source_colors:
  2250. filament_colors = source_colors
  2251. if source_volume["x"] != 256 or source_volume["y"] != 256 or source_volume["z"] != 256:
  2252. build_volume = source_volume
  2253. try:
  2254. with zipfile.ZipFile(file_path, "r") as zf:
  2255. names = zf.namelist()
  2256. # Check for G-code in the sliced file
  2257. has_gcode = any(n.startswith("Metadata/") and n.endswith(".gcode") for n in names)
  2258. # Check for 3D model in sliced file (fallback if no source)
  2259. if not has_model:
  2260. for name in names:
  2261. if name.endswith(".model"):
  2262. try:
  2263. content = zf.read(name).decode("utf-8")
  2264. if "<vertex" in content or "<mesh" in content:
  2265. has_model = True
  2266. break
  2267. except Exception:
  2268. pass # Skip unreadable .model entries in archive
  2269. # Extract filament colors from slice_info.config (for gcode preview)
  2270. # These are the actual filaments used in the print, indexed by tool/extruder
  2271. slice_colors: list[str] = []
  2272. if "Metadata/slice_info.config" in names:
  2273. try:
  2274. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2275. root = ET.fromstring(slice_content)
  2276. filaments = root.findall(".//filament")
  2277. filament_map: dict[int, str] = {}
  2278. for f in filaments:
  2279. fid = f.get("id")
  2280. fcolor = f.get("color")
  2281. used_g = f.get("used_g", "0")
  2282. try:
  2283. used_amount = float(used_g)
  2284. except (ValueError, TypeError):
  2285. used_amount = 0
  2286. if fid is not None and fcolor:
  2287. try:
  2288. tool_id = int(fid) - 1
  2289. if tool_id >= 0 and used_amount > 0:
  2290. filament_map[tool_id] = fcolor
  2291. except ValueError:
  2292. pass # Skip filament entry with non-numeric ID
  2293. if filament_map:
  2294. max_tool = max(filament_map.keys())
  2295. for i in range(max_tool + 1):
  2296. slice_colors.append(filament_map.get(i, "#00AE42"))
  2297. except Exception:
  2298. pass # Skip malformed slice_info.config XML
  2299. # Use slice_info colors if we don't have colors from source yet
  2300. if not filament_colors and slice_colors:
  2301. filament_colors = slice_colors
  2302. # Extract build volume from sliced file if not already set from source
  2303. if build_volume["x"] == 256 and build_volume["y"] == 256:
  2304. if "Metadata/project_settings.config" in names:
  2305. try:
  2306. config_content = zf.read("Metadata/project_settings.config").decode("utf-8")
  2307. config_data = json.loads(config_content)
  2308. printable_area = config_data.get("printable_area", [])
  2309. if printable_area and len(printable_area) >= 3:
  2310. max_x = 0
  2311. max_y = 0
  2312. for coord in printable_area:
  2313. if "x" in coord:
  2314. parts = coord.split("x")
  2315. if len(parts) == 2:
  2316. try:
  2317. x, y = int(parts[0]), int(parts[1])
  2318. max_x = max(max_x, x)
  2319. max_y = max(max_y, y)
  2320. except ValueError:
  2321. pass # Skip non-numeric printable_area coordinate
  2322. if max_x > 0 and max_y > 0:
  2323. build_volume["x"] = max_x
  2324. build_volume["y"] = max_y
  2325. printable_height = config_data.get("printable_height")
  2326. if printable_height:
  2327. try:
  2328. build_volume["z"] = int(printable_height)
  2329. except (ValueError, TypeError):
  2330. pass # Skip unparseable printable_height value
  2331. # Fallback colors from project_settings if still empty
  2332. if not filament_colors:
  2333. raw_colors = config_data.get("filament_colour", [])
  2334. if raw_colors:
  2335. for color in raw_colors:
  2336. if color and isinstance(color, str):
  2337. filament_colors.append(color)
  2338. except Exception:
  2339. pass # Skip malformed project_settings.config
  2340. except zipfile.BadZipFile:
  2341. raise HTTPException(400, "Invalid 3MF file")
  2342. return {
  2343. "has_model": has_model,
  2344. "has_gcode": has_gcode,
  2345. "has_source": has_source,
  2346. "build_volume": build_volume,
  2347. "filament_colors": filament_colors,
  2348. }
  2349. @router.get("/{archive_id}/gcode")
  2350. async def get_gcode(
  2351. archive_id: int,
  2352. plate: int | None = None,
  2353. db: AsyncSession = Depends(get_db),
  2354. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2355. ):
  2356. """Extract and return G-code from the 3MF file.
  2357. When *plate* is provided, returns the G-code for that specific plate
  2358. (e.g. ``?plate=2`` returns ``Metadata/plate_2.gcode``). If omitted, falls
  2359. back to the first plate found in the archive (preserving the original
  2360. behaviour for callers that predate the multi-plate viewer).
  2361. """
  2362. service = ArchiveService(db)
  2363. archive = await service.get_archive(archive_id)
  2364. if not archive:
  2365. raise HTTPException(404, "Archive not found")
  2366. file_path = settings.base_dir / archive.file_path
  2367. if not file_path.is_file():
  2368. raise HTTPException(404, "File not found")
  2369. if plate is not None and plate < 1:
  2370. raise HTTPException(400, "Plate index must be >= 1")
  2371. try:
  2372. with zipfile.ZipFile(file_path, "r") as zf:
  2373. # Bambu 3MF files store G-code in Metadata/plate_X.gcode
  2374. gcode_files = [n for n in zf.namelist() if n.startswith("Metadata/") and n.endswith(".gcode")]
  2375. if not gcode_files:
  2376. raise HTTPException(
  2377. 404,
  2378. "No G-code found. This file hasn't been sliced yet - G-code is only available after slicing in Bambu Studio.",
  2379. )
  2380. if plate is not None:
  2381. # Resolve plate → filename via the same parsing the plates
  2382. # endpoint uses (int() on the suffix), so zero-padded names
  2383. # like plate_01.gcode are found when the plates endpoint
  2384. # reported index 1.
  2385. selected = None
  2386. for gf in gcode_files:
  2387. if not gf.startswith("Metadata/plate_"):
  2388. continue
  2389. suffix = gf[len("Metadata/plate_") : -len(".gcode")]
  2390. try:
  2391. if int(suffix) == plate:
  2392. selected = gf
  2393. break
  2394. except ValueError:
  2395. continue
  2396. if selected is None:
  2397. raise HTTPException(404, f"Plate {plate} not found in this archive")
  2398. else:
  2399. selected = gcode_files[0]
  2400. gcode_content = zf.read(selected).decode("utf-8")
  2401. return Response(content=gcode_content, media_type="text/plain")
  2402. except zipfile.BadZipFile:
  2403. raise HTTPException(400, "Invalid 3MF file")
  2404. except HTTPException:
  2405. raise
  2406. except Exception as e:
  2407. raise HTTPException(500, f"Error extracting G-code: {str(e)}")
  2408. @router.get("/{archive_id}/plate-preview")
  2409. async def get_plate_preview(
  2410. archive_id: int,
  2411. db: AsyncSession = Depends(get_db),
  2412. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2413. ):
  2414. """Get the plate preview image from the 3MF file.
  2415. Returns the slicer-generated plate thumbnail which shows the model
  2416. with correct colors and positioning.
  2417. Requires a stream token query param (?token=xxx) when auth is enabled.
  2418. """
  2419. service = ArchiveService(db)
  2420. archive = await service.get_archive(archive_id)
  2421. if not archive:
  2422. raise HTTPException(404, "Archive not found")
  2423. file_path = settings.base_dir / archive.file_path
  2424. if not file_path.is_file():
  2425. raise HTTPException(404, "File not found")
  2426. try:
  2427. with zipfile.ZipFile(file_path, "r") as zf:
  2428. names = zf.namelist()
  2429. # Try to find plate preview images in order of preference
  2430. # First look for the specific plate being printed (check slice_info for plate index)
  2431. plate_num = 1
  2432. if "Metadata/slice_info.config" in names:
  2433. try:
  2434. import defusedxml.ElementTree as ET
  2435. slice_content = zf.read("Metadata/slice_info.config").decode("utf-8")
  2436. root = ET.fromstring(slice_content)
  2437. plate_elem = root.find(".//plate/metadata[@key='index']")
  2438. if plate_elem is not None:
  2439. plate_num = int(plate_elem.get("value", "1"))
  2440. except Exception:
  2441. pass # Default plate_num=1 if slice_info is missing or malformed
  2442. # Try plate-specific image first, then fall back to plate_1
  2443. preview_paths = [
  2444. f"Metadata/plate_{plate_num}.png",
  2445. "Metadata/plate_1.png",
  2446. "Metadata/thumbnail.png",
  2447. ]
  2448. for preview_path in preview_paths:
  2449. if preview_path in names:
  2450. image_data = zf.read(preview_path)
  2451. return Response(content=image_data, media_type="image/png")
  2452. # If no plate image, try any PNG in Metadata
  2453. for name in names:
  2454. if name.startswith("Metadata/plate_") and name.endswith(".png") and "_small" not in name:
  2455. image_data = zf.read(name)
  2456. return Response(content=image_data, media_type="image/png")
  2457. raise HTTPException(404, "No plate preview found in 3MF file")
  2458. except zipfile.BadZipFile:
  2459. raise HTTPException(400, "Invalid 3MF file")
  2460. except HTTPException:
  2461. raise
  2462. except Exception as e:
  2463. raise HTTPException(500, f"Error extracting plate preview: {str(e)}")
  2464. @router.post("/upload")
  2465. async def upload_archive(
  2466. file: UploadFile = File(...),
  2467. printer_id: int | None = None,
  2468. db: AsyncSession = Depends(get_db),
  2469. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2470. ):
  2471. """Manually upload a 3MF file to archive."""
  2472. if not file.filename or not file.filename.endswith(".3mf"):
  2473. raise HTTPException(400, "File must be a .3mf file")
  2474. # Save uploaded file temporarily — strip directory components to prevent path traversal
  2475. safe_filename = _safe_filename(file.filename)
  2476. temp_path = settings.archive_dir / "temp" / safe_filename
  2477. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2478. try:
  2479. content = await file.read()
  2480. # #1401: same content validation as library upload — catches
  2481. # raw-gcode-renamed-to-.3mf and other unprintable shapes before
  2482. # archiving them and offering them up for print.
  2483. from backend.app.api.routes.library import validate_print_file_upload
  2484. validate_print_file_upload(file.filename, content)
  2485. temp_path.write_bytes(content)
  2486. service = ArchiveService(db)
  2487. archive = await service.archive_print(
  2488. printer_id=printer_id,
  2489. source_file=temp_path,
  2490. created_by_id=current_user.id if current_user else None,
  2491. )
  2492. if not archive:
  2493. raise HTTPException(400, "Failed to archive file")
  2494. return ArchiveResponse.model_validate(archive)
  2495. finally:
  2496. if temp_path.exists():
  2497. temp_path.unlink()
  2498. @router.post("/upload-bulk")
  2499. async def upload_archives_bulk(
  2500. files: list[UploadFile] = File(...),
  2501. printer_id: int | None = None,
  2502. db: AsyncSession = Depends(get_db),
  2503. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_CREATE),
  2504. ):
  2505. """Bulk upload multiple 3MF files to archive."""
  2506. from backend.app.api.routes.library import validate_print_file_upload
  2507. results = []
  2508. errors = []
  2509. for file in files:
  2510. if not file.filename or not file.filename.endswith(".3mf"):
  2511. errors.append({"filename": file.filename or "unknown", "error": "Not a .3mf file"})
  2512. continue
  2513. safe_filename = _safe_filename(file.filename)
  2514. temp_path = settings.archive_dir / "temp" / safe_filename
  2515. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2516. try:
  2517. content = await file.read()
  2518. # #1401: bulk-upload variant of the library validation. Collect
  2519. # the rejection per-file rather than aborting the whole batch
  2520. # so one bad file in a 10-file drag-drop doesn't lose the
  2521. # other nine.
  2522. try:
  2523. validate_print_file_upload(file.filename, content)
  2524. except HTTPException as exc:
  2525. errors.append({"filename": file.filename, "error": exc.detail})
  2526. continue
  2527. temp_path.write_bytes(content)
  2528. service = ArchiveService(db)
  2529. archive = await service.archive_print(
  2530. printer_id=printer_id,
  2531. source_file=temp_path,
  2532. created_by_id=current_user.id if current_user else None,
  2533. )
  2534. if archive:
  2535. results.append(
  2536. {
  2537. "filename": file.filename,
  2538. "id": archive.id,
  2539. "status": "success",
  2540. }
  2541. )
  2542. else:
  2543. errors.append({"filename": file.filename, "error": "Failed to process"})
  2544. except Exception as e:
  2545. logger.exception("Failed to upload archive %s: %s", file.filename, e)
  2546. errors.append({"filename": file.filename, "error": "Failed to process file"})
  2547. finally:
  2548. if temp_path.exists():
  2549. temp_path.unlink()
  2550. return {
  2551. "uploaded": len(results),
  2552. "failed": len(errors),
  2553. "results": results,
  2554. "errors": errors,
  2555. }
  2556. @router.get("/{archive_id}/plates")
  2557. async def get_archive_plates(
  2558. archive_id: int,
  2559. db: AsyncSession = Depends(get_db),
  2560. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2561. ):
  2562. """Get available plates from a multi-plate 3MF archive.
  2563. Returns a list of plates with their index, name, thumbnail availability,
  2564. and filament requirements. For single-plate exports, returns a single plate.
  2565. """
  2566. import re
  2567. import defusedxml.ElementTree as ET
  2568. service = ArchiveService(db)
  2569. archive = await service.get_archive(archive_id)
  2570. if not archive:
  2571. raise HTTPException(404, "Archive not found")
  2572. file_path = settings.base_dir / archive.file_path
  2573. if not file_path.is_file():
  2574. raise HTTPException(404, "Archive file not found")
  2575. plates = []
  2576. # Initialize so the `has_gcode = bool(gcode_files)` after the try/except
  2577. # never raises NameError when the archive isn't a valid zip (e.g. plain
  2578. # .gcode file from a sliced-archive flow that didn't request 3MF output).
  2579. gcode_files: list[str] = []
  2580. try:
  2581. with zipfile.ZipFile(file_path, "r") as zf:
  2582. namelist = zf.namelist()
  2583. # Find all plate gcode files to determine available plates
  2584. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  2585. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  2586. plate_indices: list[int] = []
  2587. if gcode_files:
  2588. # Extract plate indices from gcode filenames
  2589. for gf in gcode_files:
  2590. # "Metadata/plate_5.gcode" -> 5
  2591. try:
  2592. # Remove "Metadata/plate_" and ".gcode"
  2593. plate_str = gf[15:-6]
  2594. plate_indices.append(int(plate_str))
  2595. except ValueError:
  2596. pass # Skip gcode file with non-numeric plate index
  2597. else:
  2598. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  2599. plate_png_files = [
  2600. n
  2601. for n in namelist
  2602. if n.startswith("Metadata/plate_")
  2603. and n.endswith(".png")
  2604. and "_small" not in n
  2605. and "no_light" not in n
  2606. ]
  2607. plate_name_candidates = plate_json_files + plate_png_files
  2608. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  2609. seen_indices: set[int] = set()
  2610. for name in plate_name_candidates:
  2611. match = plate_re.match(name)
  2612. if match:
  2613. try:
  2614. index = int(match.group(1))
  2615. except ValueError:
  2616. continue
  2617. if index in seen_indices:
  2618. continue
  2619. seen_indices.add(index)
  2620. plate_indices.append(index)
  2621. if not plate_indices:
  2622. # No plate metadata found
  2623. return {
  2624. "archive_id": archive_id,
  2625. "filename": archive.filename,
  2626. "plates": [],
  2627. "is_multi_plate": False,
  2628. }
  2629. plate_indices.sort()
  2630. # Parse model_settings.config for plate names + object assignments
  2631. # Plate names are stored with plater_id and plater_name keys
  2632. plate_names = {} # plater_id -> name
  2633. plate_object_ids: dict[int, list[str]] = {}
  2634. object_names_by_id: dict[str, str] = {}
  2635. if "Metadata/model_settings.config" in namelist:
  2636. try:
  2637. model_content = zf.read("Metadata/model_settings.config").decode()
  2638. model_root = ET.fromstring(model_content)
  2639. # Build object ID -> name map
  2640. for obj_elem in model_root.findall(".//object"):
  2641. obj_id = obj_elem.get("id")
  2642. if not obj_id:
  2643. continue
  2644. name_meta = obj_elem.find("metadata[@key='name']")
  2645. obj_name = name_meta.get("value") if name_meta is not None else None
  2646. if obj_name:
  2647. object_names_by_id[obj_id] = obj_name
  2648. for plate_elem in model_root.findall(".//plate"):
  2649. plater_id = None
  2650. plater_name = None
  2651. for meta in plate_elem.findall("metadata"):
  2652. key = meta.get("key")
  2653. value = meta.get("value")
  2654. if key == "plater_id" and value:
  2655. try:
  2656. plater_id = int(value)
  2657. except ValueError:
  2658. pass # Skip plate with non-numeric plater_id
  2659. elif key == "plater_name" and value:
  2660. plater_name = value.strip()
  2661. if plater_id is not None and plater_name:
  2662. plate_names[plater_id] = plater_name
  2663. if plater_id is not None:
  2664. for instance_elem in plate_elem.findall("model_instance"):
  2665. for inst_meta in instance_elem.findall("metadata"):
  2666. if inst_meta.get("key") == "object_id":
  2667. obj_id = inst_meta.get("value")
  2668. if not obj_id:
  2669. continue
  2670. plate_object_ids.setdefault(plater_id, [])
  2671. if obj_id not in plate_object_ids[plater_id]:
  2672. plate_object_ids[plater_id].append(obj_id)
  2673. except Exception:
  2674. pass # model_settings.config parsing is optional
  2675. # Parse slice_info.config for plate metadata
  2676. plate_metadata = {} # plate_index -> {filaments, prediction, weight, name, objects}
  2677. if "Metadata/slice_info.config" in namelist:
  2678. content = zf.read("Metadata/slice_info.config").decode()
  2679. root = ET.fromstring(content)
  2680. for plate_elem in root.findall(".//plate"):
  2681. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  2682. # Get plate index from metadata
  2683. plate_index = None
  2684. for meta in plate_elem.findall("metadata"):
  2685. key = meta.get("key")
  2686. value = meta.get("value")
  2687. if key == "index" and value:
  2688. try:
  2689. plate_index = int(value)
  2690. except ValueError:
  2691. pass # Skip plate with non-numeric index
  2692. elif key == "prediction" and value:
  2693. try:
  2694. plate_info["prediction"] = int(value)
  2695. except ValueError:
  2696. pass # Skip non-numeric print time prediction
  2697. elif key == "weight" and value:
  2698. try:
  2699. plate_info["weight"] = float(value)
  2700. except ValueError:
  2701. pass # Skip non-numeric filament weight
  2702. # Get filaments used in this plate
  2703. for filament_elem in plate_elem.findall("filament"):
  2704. filament_id = filament_elem.get("id")
  2705. filament_type = filament_elem.get("type", "")
  2706. filament_color = filament_elem.get("color", "")
  2707. used_g = filament_elem.get("used_g", "0")
  2708. used_m = filament_elem.get("used_m", "0")
  2709. try:
  2710. used_grams = float(used_g)
  2711. except (ValueError, TypeError):
  2712. used_grams = 0
  2713. if used_grams > 0 and filament_id:
  2714. plate_info["filaments"].append(
  2715. {
  2716. "slot_id": int(filament_id),
  2717. "type": filament_type,
  2718. "color": filament_color,
  2719. "used_grams": round(used_grams, 1),
  2720. "used_meters": float(used_m) if used_m else 0,
  2721. }
  2722. )
  2723. # Sort filaments by slot ID
  2724. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  2725. # Collect all object names on this plate
  2726. for obj_elem in plate_elem.findall("object"):
  2727. obj_name = obj_elem.get("name")
  2728. if obj_name and obj_name not in plate_info["objects"]:
  2729. plate_info["objects"].append(obj_name)
  2730. # Set plate name: prefer custom name from model_settings.config,
  2731. # fall back to first object name if no custom name was set
  2732. if plate_index is not None:
  2733. custom_name = plate_names.get(plate_index)
  2734. if custom_name:
  2735. plate_info["name"] = custom_name
  2736. else:
  2737. # Fall back to first object name as hint
  2738. if plate_info["objects"]:
  2739. plate_info["name"] = plate_info["objects"][0]
  2740. plate_metadata[plate_index] = plate_info
  2741. # Parse plate_*.json for object lists when slice_info is missing
  2742. plate_json_objects: dict[int, list[str]] = {}
  2743. for name in namelist:
  2744. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  2745. if not match:
  2746. continue
  2747. try:
  2748. plate_index = int(match.group(1))
  2749. except ValueError:
  2750. continue
  2751. try:
  2752. payload = json.loads(zf.read(name).decode())
  2753. bbox_objects = payload.get("bbox_objects", [])
  2754. names = []
  2755. for obj in bbox_objects:
  2756. obj_name = obj.get("name") if isinstance(obj, dict) else None
  2757. if obj_name and obj_name not in names:
  2758. names.append(obj_name)
  2759. if names:
  2760. plate_json_objects[plate_index] = names
  2761. except Exception:
  2762. continue
  2763. # Build plate list
  2764. for idx in plate_indices:
  2765. meta = plate_metadata.get(idx, {})
  2766. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  2767. objects = meta.get("objects", [])
  2768. if not objects:
  2769. objects = plate_json_objects.get(idx, [])
  2770. if not objects and plate_object_ids.get(idx):
  2771. objects = [
  2772. object_names_by_id.get(obj_id, f"Object {obj_id}") for obj_id in plate_object_ids.get(idx, [])
  2773. ]
  2774. plate_name = meta.get("name")
  2775. if not plate_name:
  2776. plate_name = plate_names.get(idx)
  2777. if not plate_name and objects:
  2778. plate_name = objects[0]
  2779. plates.append(
  2780. {
  2781. "index": idx,
  2782. "name": plate_name,
  2783. "objects": objects,
  2784. "object_count": len(objects),
  2785. "has_thumbnail": has_thumbnail,
  2786. "thumbnail_url": f"/api/v1/archives/{archive_id}/plate-thumbnail/{idx}"
  2787. if has_thumbnail
  2788. else None,
  2789. "print_time_seconds": meta.get("prediction"),
  2790. "filament_used_grams": meta.get("weight"),
  2791. "filaments": meta.get("filaments", []),
  2792. }
  2793. )
  2794. except Exception as e:
  2795. logger.warning("Failed to parse plates from archive %s: %s", archive_id, e)
  2796. # Has gcode iff the plate list was built from .gcode filenames (as opposed
  2797. # to the JSON/PNG fallback for source-only 3MF projects). Callers that need
  2798. # to preview gcode — the viewer, skip-objects — can gate on this instead of
  2799. # 404-ing on every plate request.
  2800. has_gcode = bool(gcode_files)
  2801. # SliceModal pre-check signal — see library.py for rationale.
  2802. source_printer_model: str | None = None
  2803. try:
  2804. with zipfile.ZipFile(file_path, "r") as zf:
  2805. source_printer_model = extract_source_printer_model_from_3mf(zf)
  2806. except (zipfile.BadZipFile, OSError):
  2807. pass
  2808. return {
  2809. "archive_id": archive_id,
  2810. "filename": archive.filename,
  2811. "plates": plates,
  2812. "is_multi_plate": len(plates) > 1,
  2813. "has_gcode": has_gcode,
  2814. "source_printer_model": source_printer_model,
  2815. }
  2816. @router.get("/{archive_id}/plate-thumbnail/{plate_index}")
  2817. async def get_plate_thumbnail(
  2818. archive_id: int,
  2819. plate_index: int,
  2820. db: AsyncSession = Depends(get_db),
  2821. _: None = RequireCameraStreamTokenIfAuthEnabled,
  2822. ):
  2823. """Get the thumbnail image for a specific plate.
  2824. Requires a stream token query param (?token=xxx) when auth is enabled.
  2825. """
  2826. service = ArchiveService(db)
  2827. archive = await service.get_archive(archive_id)
  2828. if not archive:
  2829. raise HTTPException(404, "Archive not found")
  2830. file_path = settings.base_dir / archive.file_path
  2831. if not file_path.is_file():
  2832. raise HTTPException(404, "Archive file not found")
  2833. try:
  2834. with zipfile.ZipFile(file_path, "r") as zf:
  2835. thumb_path = f"Metadata/plate_{plate_index}.png"
  2836. if thumb_path in zf.namelist():
  2837. data = zf.read(thumb_path)
  2838. return Response(content=data, media_type="image/png")
  2839. except Exception:
  2840. pass # Fall through to 404 if archive is unreadable or thumbnail missing
  2841. raise HTTPException(404, f"Thumbnail for plate {plate_index} not found")
  2842. async def _try_preview_slice_filaments(
  2843. db: AsyncSession,
  2844. *,
  2845. kind: str,
  2846. source_id: int,
  2847. plate_id: int,
  2848. file_path: Path,
  2849. request_id: str | None = None,
  2850. bundle_id: str | None = None,
  2851. printer_name: str | None = None,
  2852. process_name: str | None = None,
  2853. filament_names: list[str] | None = None,
  2854. ) -> list[dict] | None:
  2855. """Run a preview slice via the user's configured sidecar so the filament
  2856. list endpoint can return real per-plate filaments for unsliced project
  2857. files. Returns ``None`` on any failure — the caller falls back to the
  2858. painted-face heuristic. ``request_id`` flows through to the sidecar
  2859. for live progress on the SliceModal's inline spinner + toast.
  2860. Bundle context (id + preset names) is forwarded to the preview helper
  2861. so the preview can mirror the real-print profile triplet when supplied
  2862. — see ``slice_preview.get_preview_filaments`` for the full contract.
  2863. """
  2864. from backend.app.api.routes.settings import get_setting
  2865. from backend.app.services.slice_preview import get_preview_filaments
  2866. preferred = (await get_setting(db, "preferred_slicer")) or "bambu_studio"
  2867. if preferred == "orcaslicer":
  2868. configured = await get_setting(db, "orcaslicer_api_url")
  2869. api_url = (configured or settings.slicer_api_url).strip()
  2870. elif preferred == "bambu_studio":
  2871. configured = await get_setting(db, "bambu_studio_api_url")
  2872. api_url = (configured or settings.bambu_studio_api_url).strip()
  2873. else:
  2874. return None
  2875. if not api_url:
  2876. return None
  2877. try:
  2878. file_bytes = file_path.read_bytes()
  2879. except OSError:
  2880. return None
  2881. return await get_preview_filaments(
  2882. kind=kind,
  2883. source_id=source_id,
  2884. plate_id=plate_id,
  2885. file_bytes=file_bytes,
  2886. file_name=file_path.name,
  2887. api_url=api_url,
  2888. request_id=request_id,
  2889. bundle_id=bundle_id,
  2890. printer_name=printer_name,
  2891. process_name=process_name,
  2892. filament_names=filament_names,
  2893. )
  2894. @router.get("/{archive_id}/filament-requirements")
  2895. async def get_filament_requirements(
  2896. archive_id: int,
  2897. plate_id: int | None = None,
  2898. request_id: str | None = None,
  2899. bundle_id: str | None = None,
  2900. printer_name: str | None = None,
  2901. process_name: str | None = None,
  2902. filament_names: str | None = None,
  2903. db: AsyncSession = Depends(get_db),
  2904. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  2905. ):
  2906. """Get filament requirements from the archived 3MF file.
  2907. Returns the filaments used in this print with their slot IDs, types, colors,
  2908. and usage amounts. This can be compared with current AMS state before reprinting.
  2909. Args:
  2910. archive_id: The archive ID
  2911. plate_id: Optional plate index to filter filaments for (for multi-plate files)
  2912. bundle_id / printer_name / process_name / filament_names: Optional
  2913. bundle context. When all four are supplied, the preview slice
  2914. (run for unsliced project files) uses ``slice_with_bundle``
  2915. against the named preset triplet instead of the embedded-
  2916. settings fallback. ``filament_names`` is comma- or semicolon-
  2917. separated.
  2918. """
  2919. import defusedxml.ElementTree as ET
  2920. service = ArchiveService(db)
  2921. archive = await service.get_archive(archive_id)
  2922. if not archive:
  2923. raise HTTPException(404, "Archive not found")
  2924. file_path = settings.base_dir / archive.file_path
  2925. if not file_path.is_file():
  2926. raise HTTPException(404, "Archive file not found")
  2927. filaments = []
  2928. try:
  2929. with zipfile.ZipFile(file_path, "r") as zf:
  2930. # Parse slice_info.config for filament requirements
  2931. if "Metadata/slice_info.config" in zf.namelist():
  2932. content = zf.read("Metadata/slice_info.config").decode()
  2933. root = ET.fromstring(content)
  2934. # If plate_id is specified, find filaments for that specific plate
  2935. if plate_id is not None:
  2936. # Find the plate element with matching index
  2937. for plate_elem in root.findall(".//plate"):
  2938. plate_index = None
  2939. for meta in plate_elem.findall("metadata"):
  2940. if meta.get("key") == "index":
  2941. try:
  2942. plate_index = int(meta.get("value", "0"))
  2943. except ValueError:
  2944. pass # Skip plate with non-numeric index metadata
  2945. break
  2946. if plate_index == plate_id:
  2947. # Extract filaments from this plate element
  2948. for filament_elem in plate_elem.findall("filament"):
  2949. filament_id = filament_elem.get("id")
  2950. filament_type = filament_elem.get("type", "")
  2951. filament_color = filament_elem.get("color", "")
  2952. used_g = filament_elem.get("used_g", "0")
  2953. used_m = filament_elem.get("used_m", "0")
  2954. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2955. try:
  2956. used_grams = float(used_g)
  2957. except (ValueError, TypeError):
  2958. used_grams = 0
  2959. if used_grams > 0 and filament_id:
  2960. filaments.append(
  2961. {
  2962. "slot_id": int(filament_id),
  2963. "type": filament_type,
  2964. "color": filament_color,
  2965. "used_grams": round(used_grams, 1),
  2966. "used_meters": float(used_m) if used_m else 0,
  2967. "tray_info_idx": tray_info_idx,
  2968. "used_in_plate": True,
  2969. }
  2970. )
  2971. break
  2972. else:
  2973. # No plate_id specified - extract all filaments with used_g > 0
  2974. # This is the legacy behavior for single-plate files
  2975. for filament_elem in root.findall(".//filament"):
  2976. filament_id = filament_elem.get("id")
  2977. filament_type = filament_elem.get("type", "")
  2978. filament_color = filament_elem.get("color", "")
  2979. used_g = filament_elem.get("used_g", "0")
  2980. used_m = filament_elem.get("used_m", "0")
  2981. tray_info_idx = filament_elem.get("tray_info_idx", "")
  2982. # Only include filaments that are actually used
  2983. try:
  2984. used_grams = float(used_g)
  2985. except (ValueError, TypeError):
  2986. used_grams = 0
  2987. if used_grams > 0 and filament_id:
  2988. filaments.append(
  2989. {
  2990. "slot_id": int(filament_id),
  2991. "type": filament_type,
  2992. "color": filament_color,
  2993. "used_grams": round(used_grams, 1),
  2994. "used_meters": float(used_m) if used_m else 0,
  2995. "tray_info_idx": tray_info_idx,
  2996. "used_in_plate": True,
  2997. }
  2998. )
  2999. # Unsliced project files: see library.py for full rationale.
  3000. # Return the FULL project_settings.config slot list with a
  3001. # used_in_plate flag derived from the preview slice; the
  3002. # CLI needs every slot pre-filled to avoid silent default
  3003. # substitution.
  3004. if not filaments:
  3005. project_filaments = extract_project_filaments_from_3mf(zf)
  3006. used_slot_ids: set[int] = set()
  3007. if project_filaments and plate_id is not None:
  3008. parsed_filament_names: list[str] | None = None
  3009. if filament_names:
  3010. parsed_filament_names = [
  3011. n.strip() for n in filament_names.replace(";", ",").split(",") if n.strip()
  3012. ] or None
  3013. preview = await _try_preview_slice_filaments(
  3014. db,
  3015. kind="archive",
  3016. source_id=archive_id,
  3017. plate_id=plate_id,
  3018. file_path=file_path,
  3019. request_id=request_id,
  3020. bundle_id=bundle_id,
  3021. printer_name=printer_name,
  3022. process_name=process_name,
  3023. filament_names=parsed_filament_names,
  3024. )
  3025. if preview is not None:
  3026. used_slot_ids = {f["slot_id"] for f in preview}
  3027. fallback_all_used = not used_slot_ids
  3028. for f in project_filaments:
  3029. f["used_in_plate"] = fallback_all_used or f["slot_id"] in used_slot_ids
  3030. filaments = project_filaments
  3031. # Sort by slot ID
  3032. filaments.sort(key=lambda x: x["slot_id"])
  3033. # Enrich with nozzle mapping for dual-nozzle printers
  3034. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  3035. if nozzle_mapping:
  3036. for filament in filaments:
  3037. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  3038. except Exception as e:
  3039. logger.warning("Failed to parse filament requirements from archive %s: %s", archive_id, e)
  3040. return {
  3041. "archive_id": archive_id,
  3042. "filename": archive.filename,
  3043. "plate_id": plate_id,
  3044. "filaments": filaments,
  3045. }
  3046. @router.post("/{archive_id}/slice", status_code=202)
  3047. async def slice_archive(
  3048. archive_id: int,
  3049. request: SliceRequest,
  3050. db: AsyncSession = Depends(get_db),
  3051. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.LIBRARY_UPLOAD),
  3052. ):
  3053. """Enqueue a slice job for an archive's source. Returns 202 + job_id;
  3054. the slice runs in the background, the caller polls `GET /slice-jobs/{id}`.
  3055. Source preference: ``source_3mf_path`` (the un-sliced project file the
  3056. user originally sent to slice) → ``file_path`` (the sliced 3MF/gcode that
  3057. actually printed).
  3058. """
  3059. from backend.app.api.routes.library import slice_and_persist_as_archive
  3060. from backend.app.core.database import async_session
  3061. from backend.app.services.slice_dispatch import (
  3062. http_exception_to_job_error,
  3063. slice_dispatch,
  3064. )
  3065. archive = await db.get(PrintArchive, archive_id)
  3066. if archive is None:
  3067. raise HTTPException(status_code=404, detail="Archive not found")
  3068. src_relative = archive.source_3mf_path or archive.file_path
  3069. if not src_relative:
  3070. raise HTTPException(
  3071. status_code=400,
  3072. detail="Archive has no source file to slice",
  3073. )
  3074. src_path = Path(settings.base_dir) / src_relative
  3075. if not src_path.exists():
  3076. raise HTTPException(status_code=404, detail="Archive source file missing on disk")
  3077. raw_filename = archive.filename or src_path.name
  3078. src_lower = raw_filename.lower()
  3079. if not (
  3080. src_lower.endswith(".stl")
  3081. or src_lower.endswith(".3mf")
  3082. or src_lower.endswith(".step")
  3083. or src_lower.endswith(".stp")
  3084. ):
  3085. raise HTTPException(
  3086. status_code=400,
  3087. detail="Archive's source file must be STL, 3MF, or STEP to slice",
  3088. )
  3089. # Match the library route: derive the sliced output's filename from
  3090. # `print_name` when set, so the new archive row's display name lines
  3091. # up with the source's display.
  3092. src_ext = Path(raw_filename).suffix.lower() or ".3mf"
  3093. src_filename = (
  3094. f"{archive.print_name.strip()}{src_ext}" if archive.print_name and archive.print_name.strip() else raw_filename
  3095. )
  3096. model_bytes = src_path.read_bytes()
  3097. archive_id_local = archive.id
  3098. user_id = current_user.id if current_user else None
  3099. async def _run(job_id: int):
  3100. async with async_session() as task_db:
  3101. # Re-fetch the source archive on the background-task session.
  3102. src_archive = await task_db.get(PrintArchive, archive_id_local)
  3103. if src_archive is None:
  3104. raise http_exception_to_job_error(
  3105. HTTPException(status_code=404, detail="Archive disappeared during slice")
  3106. )
  3107. try:
  3108. response = await slice_and_persist_as_archive(
  3109. task_db,
  3110. model_bytes=model_bytes,
  3111. model_filename=src_filename,
  3112. request=request,
  3113. source_archive=src_archive,
  3114. current_user_id=user_id,
  3115. job_id=job_id,
  3116. )
  3117. except HTTPException as exc:
  3118. raise http_exception_to_job_error(exc) from exc
  3119. return response.model_dump()
  3120. job = await slice_dispatch.enqueue(
  3121. kind="archive",
  3122. source_id=archive.id,
  3123. source_name=archive.print_name or archive.filename or f"archive {archive.id}",
  3124. run=_run,
  3125. )
  3126. return {
  3127. "job_id": job.id,
  3128. "status": job.status,
  3129. "status_url": f"/api/v1/slice-jobs/{job.id}",
  3130. }
  3131. @router.post("/{archive_id}/reprint")
  3132. async def reprint_archive(
  3133. archive_id: int,
  3134. printer_id: int,
  3135. body: ReprintRequest | None = None,
  3136. db: AsyncSession = Depends(get_db),
  3137. auth_result: tuple[User | None, bool] = Depends(
  3138. require_ownership_permission(
  3139. Permission.ARCHIVES_REPRINT_ALL,
  3140. Permission.ARCHIVES_REPRINT_OWN,
  3141. )
  3142. ),
  3143. ):
  3144. """Dispatch an archived 3MF file for send/start on a printer."""
  3145. from backend.app.models.printer import Printer
  3146. from backend.app.services.background_dispatch import DispatchEnqueueRejected, background_dispatch
  3147. from backend.app.services.printer_manager import printer_manager
  3148. user, can_modify_all = auth_result
  3149. # Use defaults if no body provided
  3150. if body is None:
  3151. body = ReprintRequest()
  3152. # Get archive
  3153. service = ArchiveService(db)
  3154. archive = await service.get_archive(archive_id)
  3155. if not archive:
  3156. raise HTTPException(404, "Archive not found")
  3157. # Ownership check
  3158. if not can_modify_all:
  3159. if archive.created_by_id != user.id:
  3160. raise HTTPException(403, "You can only reprint your own archives")
  3161. # Get printer
  3162. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3163. printer = result.scalar_one_or_none()
  3164. if not printer:
  3165. raise HTTPException(404, "Printer not found")
  3166. # Check printer is connected
  3167. if not printer_manager.is_connected(printer_id):
  3168. raise HTTPException(400, "Printer is not connected")
  3169. if not archive.file_path:
  3170. raise HTTPException(
  3171. 404,
  3172. "No 3MF file available for this archive. "
  3173. "The file could not be downloaded from the printer when the print was recorded.",
  3174. )
  3175. # Validate archive file exists
  3176. file_path = settings.base_dir / archive.file_path
  3177. if not file_path.is_file():
  3178. raise HTTPException(404, "Archive file not found")
  3179. plate_name = body.plate_name
  3180. if not plate_name and body.plate_id is not None:
  3181. plate_name = f"Plate {body.plate_id}"
  3182. dispatch_source_name = archive.filename
  3183. if plate_name:
  3184. dispatch_source_name = f"{archive.filename} • {plate_name}"
  3185. try:
  3186. dispatch_result = await background_dispatch.dispatch_reprint_archive(
  3187. archive_id=archive_id,
  3188. archive_name=dispatch_source_name,
  3189. printer_id=printer_id,
  3190. printer_name=printer.name,
  3191. options=body.model_dump(exclude_none=True),
  3192. requested_by_user_id=user.id if user else None,
  3193. requested_by_username=user.username if user else None,
  3194. )
  3195. except DispatchEnqueueRejected as e:
  3196. raise HTTPException(status_code=409, detail=str(e)) from e
  3197. logger.info(
  3198. "Dispatched reprint archive %s for printer %s (dispatch_job_id=%s, dispatch_position=%s)",
  3199. archive_id,
  3200. printer_id,
  3201. dispatch_result["dispatch_job_id"],
  3202. dispatch_result["dispatch_position"],
  3203. )
  3204. return {
  3205. "status": "dispatched",
  3206. "printer_id": printer_id,
  3207. "archive_id": archive_id,
  3208. "filename": archive.filename,
  3209. "dispatch_job_id": dispatch_result["dispatch_job_id"],
  3210. "dispatch_position": dispatch_result["dispatch_position"],
  3211. }
  3212. # =============================================================================
  3213. # Project Page API
  3214. # =============================================================================
  3215. @router.get("/{archive_id}/project-page")
  3216. async def get_project_page(
  3217. archive_id: int,
  3218. db: AsyncSession = Depends(get_db),
  3219. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3220. ):
  3221. """Get the project page data from the 3MF file."""
  3222. from backend.app.schemas.archive import ProjectPageResponse
  3223. from backend.app.services.archive import ProjectPageParser
  3224. service = ArchiveService(db)
  3225. archive = await service.get_archive(archive_id)
  3226. if not archive:
  3227. raise HTTPException(404, "Archive not found")
  3228. file_path = settings.base_dir / archive.file_path
  3229. if not file_path.is_file():
  3230. raise HTTPException(404, "Archive file not found")
  3231. parser = ProjectPageParser(file_path)
  3232. data = parser.parse(archive_id)
  3233. return ProjectPageResponse(**data)
  3234. @router.patch("/{archive_id}/project-page")
  3235. async def update_project_page(
  3236. archive_id: int,
  3237. update_data: dict,
  3238. db: AsyncSession = Depends(get_db),
  3239. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  3240. ):
  3241. """Update project page metadata in the 3MF file."""
  3242. from backend.app.services.archive import ProjectPageParser
  3243. service = ArchiveService(db)
  3244. archive = await service.get_archive(archive_id)
  3245. if not archive:
  3246. raise HTTPException(404, "Archive not found")
  3247. file_path = settings.base_dir / archive.file_path
  3248. if not file_path.is_file():
  3249. raise HTTPException(404, "Archive file not found")
  3250. parser = ProjectPageParser(file_path)
  3251. success = parser.update_metadata(update_data)
  3252. if not success:
  3253. raise HTTPException(500, "Failed to update project page")
  3254. # Return updated data
  3255. data = parser.parse(archive_id)
  3256. return data
  3257. @router.get("/{archive_id}/project-image/{image_path:path}")
  3258. async def get_project_image(
  3259. archive_id: int,
  3260. image_path: str,
  3261. db: AsyncSession = Depends(get_db),
  3262. _: None = RequireCameraStreamTokenIfAuthEnabled,
  3263. ):
  3264. """Get an image from the 3MF project page.
  3265. Requires a stream token query param (?token=xxx) when auth is enabled.
  3266. """
  3267. from backend.app.services.archive import ProjectPageParser
  3268. service = ArchiveService(db)
  3269. archive = await service.get_archive(archive_id)
  3270. if not archive:
  3271. raise HTTPException(404, "Archive not found")
  3272. file_path = settings.base_dir / archive.file_path
  3273. if not file_path.is_file():
  3274. raise HTTPException(404, "Archive file not found")
  3275. parser = ProjectPageParser(file_path)
  3276. result = parser.get_image(image_path)
  3277. if not result:
  3278. raise HTTPException(404, "Image not found in 3MF file")
  3279. image_data, content_type = result
  3280. return Response(
  3281. content=image_data,
  3282. media_type=content_type,
  3283. headers={"Cache-Control": "max-age=3600"},
  3284. )
  3285. # =============================================================================
  3286. # Source 3MF API (Original Project Files)
  3287. # =============================================================================
  3288. @router.post("/{archive_id}/source")
  3289. async def upload_source_3mf(
  3290. archive_id: int,
  3291. file: UploadFile = File(...),
  3292. db: AsyncSession = Depends(get_db),
  3293. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  3294. ):
  3295. """Upload the original source 3MF project file for an archive."""
  3296. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3297. archive = result.scalar_one_or_none()
  3298. if not archive:
  3299. raise HTTPException(404, "Archive not found")
  3300. if not file.filename or not file.filename.endswith(".3mf"):
  3301. raise HTTPException(400, "File must be a .3mf file")
  3302. # Get archive directory and create source subdirectory
  3303. file_path = settings.base_dir / archive.file_path
  3304. archive_dir = file_path.parent
  3305. source_dir = archive_dir / "source"
  3306. source_dir.mkdir(exist_ok=True)
  3307. # Delete old source file if exists
  3308. if archive.source_3mf_path:
  3309. old_source_path = settings.base_dir / archive.source_3mf_path
  3310. if old_source_path.exists():
  3311. old_source_path.unlink()
  3312. # Save the source 3MF file - preserve original filename, strip directory components
  3313. source_filename = _safe_filename(file.filename)
  3314. source_path = source_dir / source_filename
  3315. content = await file.read()
  3316. # #1401: validate zip header on source 3MF uploads too — source files
  3317. # are uploaded for reprint and slicing, so an invalid one breaks the
  3318. # same downstream paths as a bad sliced file.
  3319. from backend.app.api.routes.library import validate_print_file_upload
  3320. validate_print_file_upload(file.filename, content)
  3321. source_path.write_bytes(content)
  3322. # Update archive with source path (relative to base_dir)
  3323. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3324. await db.commit()
  3325. await db.refresh(archive)
  3326. return {
  3327. "status": "uploaded",
  3328. "source_3mf_path": archive.source_3mf_path,
  3329. "filename": source_filename,
  3330. }
  3331. @router.get("/{archive_id}/source")
  3332. async def download_source_3mf(
  3333. archive_id: int,
  3334. db: AsyncSession = Depends(get_db),
  3335. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3336. ):
  3337. """Download the source 3MF project file."""
  3338. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3339. archive = result.scalar_one_or_none()
  3340. if not archive:
  3341. raise HTTPException(404, "Archive not found")
  3342. if not archive.source_3mf_path:
  3343. raise HTTPException(404, "No source 3MF attached to this archive")
  3344. source_path = settings.base_dir / archive.source_3mf_path
  3345. if not source_path.exists():
  3346. raise HTTPException(404, "Source 3MF file not found on disk")
  3347. # Use the actual filename from the path
  3348. filename = source_path.name
  3349. return FileResponse(
  3350. path=source_path,
  3351. filename=filename,
  3352. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3353. )
  3354. @router.get("/{archive_id}/source/{filename}")
  3355. async def download_source_3mf_for_slicer(
  3356. archive_id: int,
  3357. filename: str,
  3358. db: AsyncSession = Depends(get_db),
  3359. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3360. ):
  3361. """Download source 3MF with filename in URL."""
  3362. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3363. archive = result.scalar_one_or_none()
  3364. if not archive:
  3365. raise HTTPException(404, "Archive not found")
  3366. if not archive.source_3mf_path:
  3367. raise HTTPException(404, "No source 3MF attached to this archive")
  3368. source_path = settings.base_dir / archive.source_3mf_path
  3369. if not source_path.exists():
  3370. raise HTTPException(404, "Source 3MF file not found on disk")
  3371. return FileResponse(
  3372. path=source_path,
  3373. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3374. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3375. )
  3376. @router.post("/{archive_id}/source-slicer-token")
  3377. async def create_source_slicer_token(
  3378. archive_id: int,
  3379. db: AsyncSession = Depends(get_db),
  3380. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3381. ):
  3382. """Create a short-lived download token for opening source 3MF in slicer."""
  3383. from backend.app.core.auth import create_slicer_download_token
  3384. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3385. archive = result.scalar_one_or_none()
  3386. if not archive:
  3387. raise HTTPException(404, "Archive not found")
  3388. if not archive.source_3mf_path:
  3389. raise HTTPException(404, "No source 3MF attached to this archive")
  3390. token = await create_slicer_download_token("source", archive_id)
  3391. return {"token": token}
  3392. @router.get("/{archive_id}/source-dl/{token}/{filename}")
  3393. async def download_source_3mf_for_slicer_with_token(
  3394. archive_id: int,
  3395. token: str,
  3396. filename: str,
  3397. db: AsyncSession = Depends(get_db),
  3398. ):
  3399. """Download source 3MF using a slicer download token.
  3400. Token-authenticated (no auth headers needed). The token is short-lived
  3401. and single-use, created by POST /{archive_id}/source-slicer-token.
  3402. """
  3403. from backend.app.core.auth import verify_slicer_download_token
  3404. if not await verify_slicer_download_token(token, "source", archive_id):
  3405. raise HTTPException(403, "Invalid or expired download token")
  3406. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3407. archive = result.scalar_one_or_none()
  3408. if not archive:
  3409. raise HTTPException(404, "Archive not found")
  3410. if not archive.source_3mf_path:
  3411. raise HTTPException(404, "No source 3MF attached to this archive")
  3412. source_path = settings.base_dir / archive.source_3mf_path
  3413. if not source_path.exists():
  3414. raise HTTPException(404, "Source 3MF file not found on disk")
  3415. return FileResponse(
  3416. path=source_path,
  3417. filename=filename if filename.endswith(".3mf") else f"{filename}.3mf",
  3418. media_type="application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  3419. )
  3420. @router.post("/upload-source")
  3421. async def upload_source_3mf_by_name(
  3422. file: UploadFile = File(...),
  3423. print_name: str = Query(None, description="Match archive by print name"),
  3424. db: AsyncSession = Depends(get_db),
  3425. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_ALL),
  3426. ):
  3427. """Upload source 3MF and match to archive by print name.
  3428. This endpoint is designed for slicer post-processing scripts.
  3429. It finds the most recent archive matching the print name and attaches the source.
  3430. """
  3431. if not file.filename or not file.filename.endswith(".3mf"):
  3432. raise HTTPException(400, "File must be a .3mf file")
  3433. safe_filename = _safe_filename(file.filename)
  3434. # Derive print name from filename if not provided
  3435. if not print_name:
  3436. # Remove .3mf extension and common suffixes
  3437. print_name = safe_filename.rsplit(".3mf", 1)[0]
  3438. # Remove _source suffix if present
  3439. if print_name.endswith("_source"):
  3440. print_name = print_name[:-7]
  3441. # Find matching archive - try exact match first, then fuzzy
  3442. result = await db.execute(
  3443. select(PrintArchive)
  3444. .where(PrintArchive.print_name == print_name)
  3445. .order_by(PrintArchive.created_at.desc())
  3446. .limit(1)
  3447. )
  3448. archive = result.scalar_one_or_none()
  3449. if not archive:
  3450. # Try matching filename without .gcode.3mf
  3451. result = await db.execute(
  3452. select(PrintArchive)
  3453. .where(PrintArchive.filename.like(f"{print_name}%"))
  3454. .order_by(PrintArchive.created_at.desc())
  3455. .limit(1)
  3456. )
  3457. archive = result.scalar_one_or_none()
  3458. if not archive:
  3459. # Try case-insensitive partial match on print_name
  3460. result = await db.execute(
  3461. select(PrintArchive)
  3462. .where(PrintArchive.print_name.ilike(f"%{print_name}%"))
  3463. .order_by(PrintArchive.created_at.desc())
  3464. .limit(1)
  3465. )
  3466. archive = result.scalar_one_or_none()
  3467. if not archive:
  3468. raise HTTPException(404, f"No archive found matching '{print_name}'")
  3469. # Get archive directory and create source subdirectory
  3470. file_path = settings.base_dir / archive.file_path
  3471. archive_dir = file_path.parent
  3472. source_dir = archive_dir / "source"
  3473. source_dir.mkdir(exist_ok=True)
  3474. # Delete old source file if exists
  3475. if archive.source_3mf_path:
  3476. old_source_path = settings.base_dir / archive.source_3mf_path
  3477. if old_source_path.exists():
  3478. old_source_path.unlink()
  3479. # Save the source 3MF file - preserve original filename, strip directory components
  3480. source_filename = safe_filename
  3481. source_path = source_dir / source_filename
  3482. content = await file.read()
  3483. # #1401: same zip-header check as the other upload routes — the
  3484. # match-by-name endpoint is used by slicer post-processing scripts,
  3485. # so a misconfigured script is exactly how a bad 3MF would slip in.
  3486. from backend.app.api.routes.library import validate_print_file_upload
  3487. validate_print_file_upload(file.filename, content)
  3488. source_path.write_bytes(content)
  3489. # Update archive with source path
  3490. archive.source_3mf_path = str(source_path.relative_to(settings.base_dir))
  3491. await db.commit()
  3492. await db.refresh(archive)
  3493. return {
  3494. "status": "uploaded",
  3495. "archive_id": archive.id,
  3496. "archive_name": archive.print_name or archive.filename,
  3497. "source_3mf_path": archive.source_3mf_path,
  3498. "filename": source_filename,
  3499. }
  3500. @router.delete("/{archive_id}/source")
  3501. async def delete_source_3mf(
  3502. archive_id: int,
  3503. db: AsyncSession = Depends(get_db),
  3504. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  3505. ):
  3506. """Delete the source 3MF project file from an archive."""
  3507. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3508. archive = result.scalar_one_or_none()
  3509. if not archive:
  3510. raise HTTPException(404, "Archive not found")
  3511. if not archive.source_3mf_path:
  3512. raise HTTPException(404, "No source 3MF attached to this archive")
  3513. # Delete the file
  3514. source_path = settings.base_dir / archive.source_3mf_path
  3515. if source_path.exists():
  3516. source_path.unlink()
  3517. # Clear the path in database
  3518. archive.source_3mf_path = None
  3519. await db.commit()
  3520. return {"status": "deleted"}
  3521. # =============================================================================
  3522. # F3D API (Fusion 360 Design Files)
  3523. # =============================================================================
  3524. @router.post("/{archive_id}/f3d")
  3525. async def upload_f3d(
  3526. archive_id: int,
  3527. file: UploadFile = File(...),
  3528. db: AsyncSession = Depends(get_db),
  3529. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_UPDATE_OWN),
  3530. ):
  3531. """Upload a Fusion 360 design file for an archive."""
  3532. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3533. archive = result.scalar_one_or_none()
  3534. if not archive:
  3535. raise HTTPException(404, "Archive not found")
  3536. if not file.filename or not file.filename.endswith(".f3d"):
  3537. raise HTTPException(400, "File must be a .f3d file")
  3538. # Get archive directory and create f3d subdirectory
  3539. file_path = settings.base_dir / archive.file_path
  3540. archive_dir = file_path.parent
  3541. f3d_dir = archive_dir / "f3d"
  3542. f3d_dir.mkdir(exist_ok=True)
  3543. # Delete old F3D file if exists
  3544. if archive.f3d_path:
  3545. old_f3d_path = settings.base_dir / archive.f3d_path
  3546. if old_f3d_path.exists():
  3547. old_f3d_path.unlink()
  3548. # Save the F3D file - preserve original filename, strip directory components
  3549. f3d_filename = _safe_filename(file.filename)
  3550. f3d_path = f3d_dir / f3d_filename
  3551. content = await file.read()
  3552. f3d_path.write_bytes(content)
  3553. # Update archive with F3D path (relative to base_dir)
  3554. archive.f3d_path = str(f3d_path.relative_to(settings.base_dir))
  3555. await db.commit()
  3556. await db.refresh(archive)
  3557. return {
  3558. "status": "uploaded",
  3559. "f3d_path": archive.f3d_path,
  3560. "filename": f3d_filename,
  3561. }
  3562. @router.get("/{archive_id}/f3d")
  3563. async def download_f3d(
  3564. archive_id: int,
  3565. db: AsyncSession = Depends(get_db),
  3566. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_READ),
  3567. ):
  3568. """Download the Fusion 360 design file."""
  3569. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3570. archive = result.scalar_one_or_none()
  3571. if not archive:
  3572. raise HTTPException(404, "Archive not found")
  3573. if not archive.f3d_path:
  3574. raise HTTPException(404, "No F3D file attached to this archive")
  3575. f3d_path = settings.base_dir / archive.f3d_path
  3576. if not f3d_path.exists():
  3577. raise HTTPException(404, "F3D file not found on disk")
  3578. # Use the actual filename from the path
  3579. filename = f3d_path.name
  3580. return FileResponse(
  3581. path=f3d_path,
  3582. filename=filename,
  3583. media_type="application/octet-stream",
  3584. )
  3585. @router.delete("/{archive_id}/f3d")
  3586. async def delete_f3d(
  3587. archive_id: int,
  3588. db: AsyncSession = Depends(get_db),
  3589. _: User | None = RequirePermissionIfAuthEnabled(Permission.ARCHIVES_DELETE_OWN),
  3590. ):
  3591. """Delete the Fusion 360 design file from an archive."""
  3592. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3593. archive = result.scalar_one_or_none()
  3594. if not archive:
  3595. raise HTTPException(404, "Archive not found")
  3596. if not archive.f3d_path:
  3597. raise HTTPException(404, "No F3D file attached to this archive")
  3598. # Delete the file
  3599. f3d_path = settings.base_dir / archive.f3d_path
  3600. if f3d_path.exists():
  3601. f3d_path.unlink()
  3602. # Clear the path in database
  3603. archive.f3d_path = None
  3604. await db.commit()
  3605. return {"status": "deleted"}