archives.py 163 KB

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