archives.py 228 KB

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