archives.py 170 KB

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