archives.py 210 KB

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