archives.py 190 KB

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