main.py 243 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222
  1. import asyncio
  2. import logging
  3. import mimetypes as _mimetypes
  4. import os
  5. import posixpath
  6. import time
  7. from contextlib import asynccontextmanager
  8. from datetime import datetime, timedelta, timezone
  9. from logging.handlers import RotatingFileHandler
  10. from urllib.parse import urlparse
  11. from fastapi import FastAPI
  12. from fastapi.responses import FileResponse
  13. from fastapi.staticfiles import StaticFiles
  14. from sqlalchemy import delete, or_, select, text
  15. from backend.app.api.routes import (
  16. ams_history,
  17. api_keys,
  18. archive_purge,
  19. archives,
  20. auth,
  21. background_dispatch as background_dispatch_routes,
  22. bug_report,
  23. camera,
  24. cloud,
  25. discovery,
  26. external_links,
  27. filaments,
  28. firmware,
  29. github_backup,
  30. groups,
  31. inventory,
  32. kprofiles,
  33. library,
  34. library_trash,
  35. local_backup,
  36. local_presets,
  37. maintenance,
  38. makerworld,
  39. metrics,
  40. mfa,
  41. notification_templates,
  42. notifications,
  43. obico,
  44. pending_uploads,
  45. print_log,
  46. print_queue,
  47. printers,
  48. projects,
  49. settings as settings_routes,
  50. slice_jobs,
  51. slicer_presets,
  52. smart_plugs,
  53. spoolbuddy,
  54. spoolman,
  55. support,
  56. system,
  57. updates,
  58. user_notifications,
  59. users,
  60. virtual_printers,
  61. webhook,
  62. websocket,
  63. )
  64. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  65. from backend.app.api.routes.support import init_debug_logging
  66. from backend.app.core.config import APP_VERSION, settings as app_settings
  67. from backend.app.core.database import async_session, engine, init_db
  68. from backend.app.core.websocket import ws_manager
  69. from backend.app.models.smart_plug import SmartPlug
  70. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  71. from backend.app.services.archive_purge import archive_purge_service
  72. from backend.app.services.background_dispatch import background_dispatch
  73. from backend.app.services.bambu_ftp import (
  74. FileNotOnPrinterError,
  75. cache_3mf_download,
  76. clear_3mf_cache,
  77. download_file_async,
  78. get_cached_3mf,
  79. get_ftp_retry_settings,
  80. with_ftp_retry,
  81. )
  82. from backend.app.services.bambu_mqtt import PrinterState
  83. from backend.app.services.github_backup import github_backup_service
  84. from backend.app.services.homeassistant import homeassistant_service
  85. from backend.app.services.library_trash import library_trash_service
  86. from backend.app.services.local_backup import local_backup_service
  87. from backend.app.services.mqtt_relay import mqtt_relay
  88. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  89. from backend.app.services.notification_service import notification_service
  90. from backend.app.services.obico_detection import obico_detection_service
  91. from backend.app.services.print_scheduler import scheduler as print_scheduler
  92. from backend.app.services.printer_manager import (
  93. init_printer_connections,
  94. parse_plate_id,
  95. printer_manager,
  96. printer_state_to_dict,
  97. )
  98. from backend.app.services.smart_plug_manager import smart_plug_manager
  99. from backend.app.services.spool_assignment_notifications import (
  100. notify_missing_spool_assignments_on_print_start,
  101. )
  102. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  103. from backend.app.services.spoolman_tracking import (
  104. cleanup_tracking as _cleanup_spoolman_tracking,
  105. report_usage as _report_spoolman_usage,
  106. store_print_data as _store_spoolman_print_data,
  107. )
  108. from backend.app.services.tasmota import tasmota_service
  109. # =============================================================================
  110. # Dependency Check - runs before other imports to give helpful error messages
  111. # =============================================================================
  112. def _start_error_server(missing_packages: list):
  113. """Start a minimal HTTP server to display dependency errors in browser."""
  114. import os
  115. import signal
  116. from http.server import BaseHTTPRequestHandler, HTTPServer
  117. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  118. html = f"""<!DOCTYPE html>
  119. <html>
  120. <head>
  121. <title>Bambuddy - Setup Required</title>
  122. <style>
  123. body {{
  124. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  125. background: #0f172a; color: #e2e8f0;
  126. display: flex; justify-content: center; align-items: center;
  127. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  128. }}
  129. .container {{
  130. background: #1e293b; border-radius: 12px; padding: 40px;
  131. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  132. }}
  133. h1 {{ color: #f87171; margin-bottom: 10px; }}
  134. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  135. .packages {{
  136. background: #0f172a; border-radius: 8px; padding: 20px;
  137. margin: 20px 0; text-align: left;
  138. }}
  139. .packages ul {{ margin: 0; padding-left: 20px; }}
  140. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  141. .command {{
  142. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  143. margin: 15px 0; font-family: monospace; color: #4ade80;
  144. text-align: left; overflow-x: auto;
  145. }}
  146. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  147. </style>
  148. </head>
  149. <body>
  150. <div class="container">
  151. <h1>Setup Required</h1>
  152. <h2>Missing Python packages</h2>
  153. <div class="packages"><ul>{packages_html}</ul></div>
  154. <p>To fix, run this command on your server:</p>
  155. <div class="command">pip install -r requirements.txt</div>
  156. <p>Or if using a virtual environment:</p>
  157. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  158. <p class="note">After installing, restart Bambuddy:<br>
  159. <code>sudo systemctl restart bambuddy</code></p>
  160. </div>
  161. </body>
  162. </html>"""
  163. class ErrorHandler(BaseHTTPRequestHandler):
  164. def do_GET(self):
  165. self.send_response(503)
  166. self.send_header("Content-type", "text/html")
  167. self.end_headers()
  168. self.wfile.write(html.encode())
  169. def log_message(self, format, *args):
  170. print(f"[Error Server] {args[0]}")
  171. port = int(os.environ.get("PORT", 8000))
  172. print(f"\nStarting error server on http://0.0.0.0:{port}")
  173. print("Visit this URL in your browser to see the error details.\n")
  174. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  175. def shutdown(signum, frame):
  176. print("\nShutting down error server...")
  177. raise SystemExit(0)
  178. signal.signal(signal.SIGTERM, shutdown)
  179. signal.signal(signal.SIGINT, shutdown)
  180. server.serve_forever()
  181. def check_dependencies():
  182. """Check that all required packages are installed."""
  183. missing = []
  184. # Map of import name -> package name (for pip install)
  185. required = {
  186. "jwt": "PyJWT",
  187. "fastapi": "fastapi",
  188. "uvicorn": "uvicorn",
  189. "sqlalchemy": "sqlalchemy",
  190. "aiosqlite": "aiosqlite",
  191. "pydantic": "pydantic",
  192. "paho.mqtt": "paho-mqtt",
  193. }
  194. for module, package in required.items():
  195. try:
  196. __import__(module)
  197. except ImportError:
  198. missing.append(package)
  199. if missing:
  200. print("\n" + "=" * 60)
  201. print("ERROR: Missing required Python packages!")
  202. print("=" * 60)
  203. print(f"\nMissing packages: {', '.join(missing)}")
  204. print("\nTo fix, run:")
  205. print(" pip install -r requirements.txt")
  206. print("\nOr if using a virtual environment:")
  207. print(" ./venv/bin/pip install -r requirements.txt")
  208. print("=" * 60 + "\n")
  209. _start_error_server(missing)
  210. check_dependencies()
  211. # =============================================================================
  212. # Import settings first for logging configuration
  213. # Configure logging based on settings
  214. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  215. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  216. log_level = getattr(logging, log_level_str, logging.INFO)
  217. # Trace ID column ([-] when no request scope is active — startup, MQTT
  218. # callbacks, scheduled tasks not chained from a request — so the column
  219. # stays visually aligned and missing values are obvious in grep). See
  220. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  221. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  222. # Create root logger
  223. root_logger = logging.getLogger()
  224. root_logger.setLevel(log_level)
  225. # Trace-ID injection: this filter populates record.trace_id from the
  226. # per-request ContextVar so the format string above can reference it.
  227. # Attached to each HANDLER (not the root logger) because Python's
  228. # logging semantics only invoke a logger's filters on records that
  229. # *originated* at that logger — records propagated up from child
  230. # loggers (every named logger in the app) never trigger root's filter.
  231. # Putting it on the handlers means every record any handler emits gets
  232. # trace_id injected just before the formatter runs, regardless of which
  233. # logger created the record. Without this, the formatter raises
  234. # KeyError on every child-logger record and the record is silently
  235. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  236. # partially" bug we hit. See backend/app/core/trace.py for the
  237. # ContextVar the filter reads.
  238. from backend.app.core.trace import TraceIDFilter
  239. _trace_id_filter = TraceIDFilter()
  240. # Console handler - always enabled
  241. console_handler = logging.StreamHandler()
  242. console_handler.setLevel(log_level)
  243. console_handler.setFormatter(logging.Formatter(log_format))
  244. console_handler.addFilter(_trace_id_filter)
  245. root_logger.addHandler(console_handler)
  246. # File handler - only in production or if explicitly enabled
  247. if app_settings.log_to_file:
  248. log_file = app_settings.log_dir / "bambuddy.log"
  249. file_handler = RotatingFileHandler(
  250. log_file,
  251. maxBytes=5 * 1024 * 1024, # 5MB
  252. backupCount=3,
  253. encoding="utf-8",
  254. )
  255. file_handler.setLevel(log_level)
  256. file_handler.setFormatter(logging.Formatter(log_format))
  257. file_handler.addFilter(_trace_id_filter)
  258. root_logger.addHandler(file_handler)
  259. logging.info("Logging to file: %s", log_file)
  260. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  261. # access logger with propagate=False by default, so without this attach
  262. # there is no on-disk record of which endpoint triggered a server-state
  263. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  264. # for exactly this reason. Filtered to write methods only
  265. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  266. # frontend don't churn the rotation window faster than it's useful.
  267. from backend.app.core.logging_filters import (
  268. CancelledPoolNoiseFilter,
  269. WriteRequestsOnlyFilter,
  270. )
  271. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  272. uvicorn_access_logger.addHandler(file_handler)
  273. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  274. # Uvicorn's access logger has propagate=False (its own default), so the
  275. # root-attached TraceIDFilter never sees these records. Attach a
  276. # second instance directly so HTTP access lines carry the same trace
  277. # ID column as the application logs they correlate with.
  278. uvicorn_access_logger.addFilter(TraceIDFilter())
  279. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  280. # BaseHTTPMiddleware cancelling the inner task scope on client
  281. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  282. # underlying transaction leak; this filter only suppresses the residual
  283. # log records that pre-existing pools still emit during their cleanup.
  284. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  285. # Reduce noise from third-party libraries in production
  286. if not app_settings.debug:
  287. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  288. logging.getLogger("httpcore").setLevel(logging.WARNING)
  289. logging.getLogger("httpx").setLevel(logging.WARNING)
  290. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  291. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  292. # Track active prints: {(printer_id, filename): archive_id}
  293. _active_prints: dict[tuple[int, str], int] = {}
  294. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  295. # {(printer_id, filename): archive_id}
  296. _expected_prints: dict[tuple[int, str], int] = {}
  297. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  298. # Used by usage tracker to map 3MF slots to physical AMS trays
  299. _print_ams_mappings: dict[int, list[int]] = {}
  300. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  301. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  302. _last_progress_milestone: dict[int, int] = {}
  303. # Track whether first layer complete notification has been sent for current print
  304. _first_layer_notified: dict[int, bool] = {}
  305. # Track HMS errors that have been notified: {printer_id: set of error codes}
  306. # This prevents sending duplicate notifications for the same error
  307. _notified_hms_errors: dict[int, set[str]] = {}
  308. # Track when HMS errors were last seen: {printer_id: timestamp}
  309. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  310. _hms_last_seen: dict[int, float] = {}
  311. _HMS_CLEAR_GRACE_SECONDS = 30.0
  312. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  313. # Used for snapshot-diff detection at print completion
  314. _timelapse_baselines: dict[int, set[str]] = {}
  315. # Track printers waiting for bed to cool after print completion.
  316. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  317. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  318. _bed_cool_waiters: dict[int, dict] = {}
  319. # Track printers where the user explicitly stopped the print from the queue UI.
  320. # When on_print_complete fires with status "failed" for these printers we treat it
  321. # as "cancelled" (stopped by user) so the correct notification email is sent.
  322. _user_stopped_printers: set[int] = set()
  323. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  324. # when status="failed" to label the print's failure_reason in archives.
  325. #
  326. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  327. # which is wrong on two counts:
  328. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  329. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  330. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  331. # the public wiki) as part of its user-cancel sequence. Matching on the module
  332. # alone caused user-cancellations to be archived as "Layer shift" failures.
  333. # We now match by full short code only — anything not in this map leaves
  334. # failure_reason=None rather than guessing.
  335. _HMS_FAILURE_REASONS: dict[str, str] = {
  336. # Layer shift / step loss
  337. "0300_4057": "Layer shift",
  338. "0300_4068": "Layer shift",
  339. "0300_800C": "Layer shift",
  340. # Filament runout (printer-side & per-AMS-slot)
  341. "0300_8004": "Filament runout",
  342. "0700_8011": "Filament runout",
  343. "0701_8011": "Filament runout",
  344. "0702_8011": "Filament runout",
  345. "0703_8011": "Filament runout",
  346. "0704_8011": "Filament runout",
  347. "0705_8011": "Filament runout",
  348. "0706_8011": "Filament runout",
  349. "0707_8011": "Filament runout",
  350. "07FF_8011": "Filament runout",
  351. # Clogged nozzle / extruder
  352. "0300_4006": "Clogged nozzle",
  353. "0300_8016": "Clogged nozzle",
  354. "0300_801C": "Clogged nozzle",
  355. "0700_8003": "Clogged nozzle",
  356. "0700_8007": "Clogged nozzle",
  357. "0700_8013": "Clogged nozzle",
  358. "0701_8003": "Clogged nozzle",
  359. "0701_8007": "Clogged nozzle",
  360. "0701_8013": "Clogged nozzle",
  361. "0702_8003": "Clogged nozzle",
  362. }
  363. def _hms_short_code(attr: int, code: int | str) -> str:
  364. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  365. if isinstance(code, str):
  366. code_int = int(code.replace("0x", ""), 16) if code else 0
  367. else:
  368. code_int = int(code or 0)
  369. attr_int = int(attr or 0)
  370. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  371. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  372. """Derive a human-readable failure_reason for an archived print.
  373. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  374. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  375. no HMS code matches (don't guess — null is honest).
  376. """
  377. if status in ("aborted", "cancelled"):
  378. return "User cancelled"
  379. if status != "failed":
  380. return None
  381. for err in hms_errors or []:
  382. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  383. if short_code in _HMS_FAILURE_REASONS:
  384. return _HMS_FAILURE_REASONS[short_code]
  385. return None
  386. # Track created_by_id for expected prints so the user email can be sent even when
  387. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  388. # {(printer_id, filename): created_by_id}
  389. _expected_print_creators: dict[tuple[int, str], int] = {}
  390. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  391. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  392. # updates for the same printer in quick succession (~30 ms apart, observed in
  393. # the wild on H2D + dual AMS).
  394. #
  395. # Without this serialisation, two concurrent on_ams_change callbacks each read
  396. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  397. # the second commit hits
  398. # IntegrityError: duplicate key value violates unique constraint
  399. # "spool_assignment_printer_id_ams_id_tray_id_key"
  400. # SQLite's WAL serial-write semantics had been silently swallowing the race
  401. # until optional Postgres support landed (asyncpg allows true concurrent
  402. # transactions and surfaces the constraint violation).
  403. #
  404. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  405. # assign) are inside the lock. The Spoolman sync block further down stays
  406. # concurrent because it's network-bound and idempotent.
  407. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  408. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  409. """Return the per-printer assignment lock, creating it on first use."""
  410. lock = _ams_assignment_locks.get(printer_id)
  411. if lock is None:
  412. lock = asyncio.Lock()
  413. _ams_assignment_locks[printer_id] = lock
  414. return lock
  415. # TTL for expected-print entries: evict registrations older than this to prevent
  416. # unbounded growth when a print is registered but never starts (e.g. printer
  417. # disconnect, app restart, print started from the printer panel).
  418. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  419. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  420. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  421. # Cleanup loop interval
  422. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  423. _expected_prints_cleanup_task: asyncio.Task | None = None
  424. async def _get_plug_energy(plug, db) -> dict | None:
  425. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  426. For HA plugs, configures the service with current settings from DB.
  427. For MQTT plugs, returns data from the subscription service.
  428. For REST plugs, polls the status URL with JSON path extraction.
  429. """
  430. if plug.plug_type == "homeassistant":
  431. from backend.app.api.routes.settings import get_homeassistant_settings
  432. ha_settings = await get_homeassistant_settings(db)
  433. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  434. return await homeassistant_service.get_energy(plug)
  435. elif plug.plug_type == "mqtt":
  436. # MQTT plugs report "today" energy, not lifetime total
  437. # For per-print tracking, we use "today" as the counter (resets at midnight)
  438. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  439. if mqtt_data:
  440. return {
  441. "power": mqtt_data.power,
  442. "today": mqtt_data.energy,
  443. "total": mqtt_data.energy, # Use today as total for per-print calculations
  444. }
  445. return None
  446. elif plug.plug_type == "rest":
  447. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  448. return await rest_smart_plug_service.get_energy(plug)
  449. else:
  450. return await tasmota_service.get_energy(plug)
  451. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  452. """Capture the smart plug lifetime counter on the archive at print start.
  453. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  454. tracking survives a backend restart mid-print. The print-end handler reads
  455. this value back from the DB and computes the delta against the current
  456. plug counter.
  457. """
  458. _logger = logging.getLogger(__name__)
  459. try:
  460. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  461. plug = plug_result.scalar_one_or_none()
  462. if not plug:
  463. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  464. return False
  465. energy = await _get_plug_energy(plug, db)
  466. if not energy or energy.get("total") is None:
  467. _logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  468. return False
  469. archive.energy_start_kwh = float(energy["total"])
  470. await db.commit()
  471. _logger.info(
  472. "[ENERGY] Recorded starting energy%s for archive %s: %s kWh",
  473. f" ({context})" if context else "",
  474. archive.id,
  475. energy["total"],
  476. )
  477. return True
  478. except Exception as e:
  479. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  480. return False
  481. def register_expected_print(
  482. printer_id: int,
  483. filename: str,
  484. archive_id: int,
  485. ams_mapping: list[int] | None = None,
  486. created_by_id: int | None = None,
  487. ):
  488. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  489. # Store with multiple filename variations to catch different naming patterns
  490. _expected_prints[(printer_id, filename)] = archive_id
  491. # Also store without .3mf extension if present
  492. if filename.endswith(".3mf"):
  493. base = filename[:-4]
  494. _expected_prints[(printer_id, base)] = archive_id
  495. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  496. # Store AMS mapping for usage tracking at print completion
  497. if ams_mapping is not None:
  498. _print_ams_mappings[archive_id] = ams_mapping
  499. # Store created_by_id so the user start email can be sent even when the archive
  500. # itself has no created_by_id (e.g. library-file-based queue prints)
  501. if created_by_id is not None:
  502. _expected_print_creators[(printer_id, filename)] = created_by_id
  503. if filename.endswith(".3mf"):
  504. base = filename[:-4]
  505. _expected_print_creators[(printer_id, base)] = created_by_id
  506. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  507. # Record registration time for TTL-based eviction
  508. _registered_at = time.monotonic()
  509. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  510. if filename.endswith(".3mf"):
  511. base = filename[:-4]
  512. _expected_print_registered_at[(printer_id, base)] = _registered_at
  513. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  514. logging.getLogger(__name__).info(
  515. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}"
  516. )
  517. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  518. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  519. stored_ams_mapping = data.get("ams_mapping")
  520. if not stored_ams_mapping and archive_id:
  521. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  522. return stored_ams_mapping
  523. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  524. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  525. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity.
  526. The short code used for the hms_errors.py lookup table is 'MMMM_EEEE' — module
  527. from attr bits 16-31, error from the numeric part of code. Falls back to the raw
  528. short code when no description is on file. Returns None for an empty list so
  529. callers can leave error_message unset.
  530. """
  531. if not hms_errors:
  532. return None
  533. from backend.app.services.hms_errors import get_error_description
  534. parts: list[str] = []
  535. for err in hms_errors:
  536. try:
  537. code_str = str(err.get("code", "")).replace("0x", "")
  538. error_num = int(code_str, 16) if code_str else 0
  539. module_num = (int(err.get("attr", 0)) >> 16) & 0xFFFF
  540. short_code = f"{module_num:04X}_{error_num:04X}"
  541. except (TypeError, ValueError):
  542. continue
  543. description = get_error_description(short_code)
  544. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  545. return "; ".join(parts) if parts else None
  546. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  547. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  548. print completes successfully. Gated to status=='completed': failed, cancelled
  549. and aborted prints do not count as usage. Caller is responsible for committing
  550. the session. No-op when the queue item has no linked library file (e.g. reprints
  551. from an archive). See #1008."""
  552. if queue_status != "completed" or item.library_file_id is None:
  553. return
  554. from backend.app.models.library import LibraryFile
  555. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  556. if lib_file is None:
  557. return
  558. lib_file.print_count = (lib_file.print_count or 0) + 1
  559. lib_file.last_printed_at = datetime.now(timezone.utc)
  560. def mark_printer_stopped_by_user(printer_id: int) -> None:
  561. """Mark that the active print on this printer was stopped by the user from the queue UI.
  562. When on_print_complete fires with status 'failed' for a printer in this set we
  563. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  564. rather than a 'print failed' notification.
  565. """
  566. _user_stopped_printers.add(printer_id)
  567. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  568. _last_status_broadcast: dict[int, str] = {}
  569. # Track printers where we've updated nozzle_count
  570. _nozzle_count_updated: set[int] = set()
  571. async def on_printer_status_change(printer_id: int, state: PrinterState):
  572. """Handle printer status changes - broadcast via WebSocket."""
  573. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  574. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  575. temps = state.temperatures or {}
  576. nozzle_temp = round(temps.get("nozzle", 0))
  577. bed_temp = round(temps.get("bed", 0))
  578. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  579. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  580. # Auto-detect dual-nozzle printers from MQTT temperature data
  581. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  582. _nozzle_count_updated.add(printer_id)
  583. # Update nozzle_count in database
  584. async with async_session() as db:
  585. from backend.app.models.printer import Printer
  586. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  587. printer = result.scalar_one_or_none()
  588. if printer and printer.nozzle_count != 2:
  589. printer.nozzle_count = 2
  590. await db.commit()
  591. logging.getLogger(__name__).info(
  592. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  593. )
  594. # Include target temps for heating phase detection
  595. bed_target = round(temps.get("bed_target", 0))
  596. nozzle_target = round(temps.get("nozzle_target", 0))
  597. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  598. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  599. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  600. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  601. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  602. ams_tray_key = (
  603. tuple(
  604. (t.get("id"), t.get("tray_type", ""), t.get("state"))
  605. for a in (state.raw_data.get("ams") or [])
  606. for t in a.get("tray", [])
  607. )
  608. if state.raw_data
  609. else ()
  610. )
  611. status_key = (
  612. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  613. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  614. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  615. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  616. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  617. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}"
  618. )
  619. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  620. try:
  621. printer_info = printer_manager.get_printer(printer_id)
  622. if printer_info:
  623. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  624. except Exception:
  625. pass # Don't fail status callback if MQTT fails
  626. if _last_status_broadcast.get(printer_id) == status_key:
  627. return # No change, skip WebSocket broadcast
  628. _last_status_broadcast[printer_id] = status_key
  629. # Check for progress milestone notifications (25%, 50%, 75%)
  630. progress = state.progress or 0
  631. is_printing = state.state in ("RUNNING", "PRINTING")
  632. if is_printing and progress > 0:
  633. # Determine which milestone we've reached
  634. current_milestone = 0
  635. if progress >= 75:
  636. current_milestone = 75
  637. elif progress >= 50:
  638. current_milestone = 50
  639. elif progress >= 25:
  640. current_milestone = 25
  641. last_milestone = _last_progress_milestone.get(printer_id, 0)
  642. # If we've crossed a new milestone, send notification
  643. if current_milestone > last_milestone:
  644. _last_progress_milestone[printer_id] = current_milestone
  645. try:
  646. async with async_session() as db:
  647. from backend.app.models.printer import Printer
  648. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  649. printer = result.scalar_one_or_none()
  650. printer_name = printer.name if printer else f"Printer {printer_id}"
  651. filename = state.subtask_name or state.gcode_file or "Unknown"
  652. # remaining_time is in minutes, convert to seconds for notification
  653. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  654. # Capture camera snapshot for notification image attachment
  655. image_data = await _capture_snapshot_for_notification(
  656. printer_id, printer, logging.getLogger(__name__)
  657. )
  658. await notification_service.on_print_progress(
  659. printer_id,
  660. printer_name,
  661. filename,
  662. current_milestone,
  663. db,
  664. remaining_time_seconds,
  665. image_data=image_data,
  666. )
  667. except Exception as e:
  668. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  669. elif progress < 5:
  670. # Reset milestone tracking when print restarts or new print begins
  671. _last_progress_milestone[printer_id] = 0
  672. _first_layer_notified[printer_id] = False
  673. # HMS error codes that should not trigger notifications even though they
  674. # have known descriptions (e.g. user-initiated actions, not real errors).
  675. _HMS_NOTIFICATION_SUPPRESS = {
  676. "0500_400E", # Printing was cancelled (user action, not an error)
  677. }
  678. # Check for new HMS errors and send notifications
  679. current_hms_errors = getattr(state, "hms_errors", []) or []
  680. if current_hms_errors:
  681. # Build set of current error codes (using attr for uniqueness)
  682. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  683. previously_notified = _notified_hms_errors.get(printer_id, set())
  684. # Find new errors that haven't been notified yet
  685. new_error_codes = current_error_codes - previously_notified
  686. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  687. _notified_hms_errors[printer_id] = current_error_codes
  688. _hms_last_seen[printer_id] = time.time()
  689. if new_error_codes:
  690. # Get the actual new errors for the notification
  691. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  692. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  693. try:
  694. async with async_session() as db:
  695. from backend.app.models.printer import Printer
  696. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  697. printer = result.scalar_one_or_none()
  698. printer_name = printer.name if printer else f"Printer {printer_id}"
  699. # Format error details for notification
  700. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  701. module_names = {
  702. 0x03: "Print/Task",
  703. 0x05: "Nozzle/Extruder",
  704. 0x07: "AMS/Filament",
  705. 0x0C: "Motion Controller",
  706. 0x12: "Chamber",
  707. }
  708. from backend.app.services.hms_errors import get_error_description
  709. # Capture camera snapshot once for all error notifications
  710. error_image_data = await _capture_snapshot_for_notification(
  711. printer_id, printer, logging.getLogger(__name__)
  712. )
  713. sent_count = 0
  714. for error in new_errors:
  715. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  716. # Build short code like "0700_8010"
  717. # Mask to 16 bits to handle printers that send larger values
  718. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  719. error_code_masked = error_code_int & 0xFFFF
  720. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  721. # Only notify for errors with known descriptions — printers
  722. # send many undocumented/phantom codes that aren't real errors.
  723. description = get_error_description(short_code)
  724. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  725. continue
  726. error_type = f"{module_name} Error"
  727. error_detail = description
  728. await notification_service.on_printer_error(
  729. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  730. )
  731. sent_count += 1
  732. if sent_count:
  733. logging.getLogger(__name__).info(
  734. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  735. )
  736. # Also publish to MQTT relay
  737. printer_info = printer_manager.get_printer(printer_id)
  738. if printer_info:
  739. errors_data = [
  740. {
  741. "code": e.code,
  742. "attr": e.attr,
  743. "module": e.module,
  744. "severity": e.severity,
  745. }
  746. for e in new_errors
  747. ]
  748. await mqtt_relay.on_printer_error(
  749. printer_id, printer_info.name, printer_info.serial_number, errors_data
  750. )
  751. except Exception as e:
  752. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  753. else:
  754. # No HMS errors — only clear tracking after a grace period to prevent
  755. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  756. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  757. # on/off every few seconds as conditions fluctuate around thresholds.
  758. if printer_id in _notified_hms_errors:
  759. last_seen = _hms_last_seen.get(printer_id, 0)
  760. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  761. _notified_hms_errors.pop(printer_id, None)
  762. _hms_last_seen.pop(printer_id, None)
  763. await ws_manager.send_printer_status(
  764. printer_id,
  765. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  766. )
  767. def _is_bambu_uuid(tray_uuid: str) -> bool:
  768. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  769. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  770. async def on_ams_change(printer_id: int, ams_data: list):
  771. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  772. logger = logging.getLogger(__name__)
  773. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  774. # on_print_complete may pop _active_sessions during our awaits (#880).
  775. from backend.app.services.usage_tracker import _active_sessions
  776. _print_active = printer_id in _active_sessions
  777. # MQTT relay - publish AMS change
  778. try:
  779. printer_info = printer_manager.get_printer(printer_id)
  780. if printer_info:
  781. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  782. except Exception:
  783. pass # Don't fail AMS callback if MQTT fails
  784. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  785. # This ensures frontend gets immediate updates when AMS slots are configured
  786. try:
  787. state = printer_manager.get_status(printer_id)
  788. if state:
  789. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  790. await ws_manager.send_printer_status(
  791. printer_id,
  792. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  793. )
  794. except Exception as e:
  795. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  796. from backend.app.utils.color_utils import colors_similar as _colors_similar
  797. # Auto-unlink spool assignments with stale fingerprints
  798. try:
  799. async with async_session() as db:
  800. from sqlalchemy.orm import selectinload
  801. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  802. from backend.app.models.spool import Spool as _Spool
  803. from backend.app.models.spool_assignment import SpoolAssignment as SA
  804. result = await db.execute(
  805. select(SA)
  806. .where(SA.printer_id == printer_id)
  807. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  808. )
  809. stale = []
  810. for assignment in result.scalars().all():
  811. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  812. if assignment.ams_id == 255:
  813. ps = printer_manager.get_status(printer_id)
  814. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  815. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  816. current_tray = None
  817. for vt in vt_tray_raw:
  818. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  819. current_tray = vt
  820. break
  821. if not current_tray:
  822. # vt_tray data may not have arrived yet — keep assignment
  823. continue
  824. else:
  825. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  826. if not current_tray:
  827. logger.info(
  828. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  829. assignment.spool_id,
  830. assignment.ams_id,
  831. assignment.tray_id,
  832. )
  833. stale.append(assignment) # Slot empty
  834. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  835. # A Bambu Lab spool is in this slot — check if it's the same spool
  836. # that's currently assigned. If yes, keep the assignment (avoids
  837. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  838. # the printer's filament preset on every startup).
  839. tray_uuid = current_tray.get("tray_uuid", "")
  840. tag_uid = current_tray.get("tag_uid", "")
  841. spool = assignment.spool
  842. spool_matches = False
  843. if spool:
  844. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  845. spool.tag_uid
  846. and tag_uid
  847. and tag_uid != "0000000000000000"
  848. and spool.tag_uid.upper() == tag_uid.upper()
  849. ):
  850. spool_matches = True
  851. if spool_matches:
  852. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  853. cur_color = current_tray.get("tray_color", "")
  854. cur_type = current_tray.get("tray_type", "")
  855. fp_color = assignment.fingerprint_color or ""
  856. fp_type = assignment.fingerprint_type or ""
  857. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  858. assignment.fingerprint_color = cur_color
  859. assignment.fingerprint_type = cur_type
  860. logger.debug(
  861. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  862. assignment.spool_id,
  863. assignment.ams_id,
  864. assignment.tray_id,
  865. )
  866. continue
  867. # Different BL spool or unrecognized — unlink so auto-assign can match
  868. logger.info(
  869. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  870. assignment.spool_id,
  871. assignment.ams_id,
  872. assignment.tray_id,
  873. tray_uuid,
  874. )
  875. stale.append(assignment)
  876. else:
  877. cur_color = current_tray.get("tray_color", "")
  878. cur_type = current_tray.get("tray_type", "")
  879. cur_state = current_tray.get("state")
  880. fp_color = assignment.fingerprint_color or ""
  881. fp_type = assignment.fingerprint_type or ""
  882. # SpoolBuddy pre-config replay: fingerprint_type empty means
  883. # the slot was empty when the user pre-assigned via SpoolBuddy
  884. # (the firmware drops ams_filament_setting on empty slots, so
  885. # MQTT was deferred). The moment any filament gets inserted
  886. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  887. # reconfigured spool — fire the deferred configuration.
  888. # The "loaded" signal is `state == 11` (Bambu's "filament fed
  889. # to extruder" code), NOT tray_type — 3rd-party spools without
  890. # readable RFID report state=11 but tray_type="" because the
  891. # AMS sensor reads no filament metadata. Requiring a non-empty
  892. # tray_type would lock out the exact users this feature targets.
  893. if not fp_type.strip() and cur_state == 11 and assignment.spool:
  894. try:
  895. from backend.app.api.routes.inventory import (
  896. apply_spool_to_slot_via_mqtt,
  897. )
  898. await apply_spool_to_slot_via_mqtt(
  899. db=db,
  900. current_user=None,
  901. spool=assignment.spool,
  902. printer_id=printer_id,
  903. ams_id=assignment.ams_id,
  904. tray_id=assignment.tray_id,
  905. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  906. current_tray_type=cur_type,
  907. )
  908. logger.info(
  909. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  910. assignment.spool_id,
  911. printer_id,
  912. assignment.ams_id,
  913. assignment.tray_id,
  914. )
  915. except Exception:
  916. logger.exception(
  917. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  918. assignment.spool_id,
  919. printer_id,
  920. assignment.ams_id,
  921. assignment.tray_id,
  922. )
  923. assignment.fingerprint_color = cur_color
  924. assignment.fingerprint_type = cur_type
  925. continue
  926. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  927. # Fingerprint mismatch — but check if tray now matches the
  928. # assigned spool (e.g. auto-configure changed the tray).
  929. spool = assignment.spool
  930. if spool:
  931. spool_color = (spool.rgba or "FFFFFFFF").upper()
  932. spool_type = (spool.material or "").upper()
  933. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  934. logger.info(
  935. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  936. assignment.spool_id,
  937. assignment.ams_id,
  938. assignment.tray_id,
  939. )
  940. assignment.fingerprint_color = cur_color
  941. assignment.fingerprint_type = cur_type
  942. continue
  943. logger.info(
  944. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  945. assignment.spool_id,
  946. assignment.ams_id,
  947. assignment.tray_id,
  948. cur_color,
  949. cur_type,
  950. fp_color,
  951. fp_type,
  952. spool.rgba if spool else "?",
  953. spool.material if spool else "?",
  954. )
  955. stale.append(assignment) # Spool changed
  956. for a in stale:
  957. await db.delete(a)
  958. if stale:
  959. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  960. # Commit any changes (stale deletions and/or fingerprint updates)
  961. await db.commit()
  962. except Exception as e:
  963. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  964. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  965. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  966. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  967. # "no existing assignment" for the same (printer, ams, tray) and race to
  968. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  969. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  970. # bug stayed latent there. See _ams_assignment_locks comment for details.
  971. try:
  972. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  973. from backend.app.api.routes.settings import get_setting
  974. from backend.app.models.spool import Spool
  975. from backend.app.models.spool_assignment import SpoolAssignment as SA
  976. from backend.app.services.spool_tag_matcher import (
  977. auto_assign_spool,
  978. create_spool_from_tray,
  979. find_matching_untagged_spool,
  980. get_spool_by_tag,
  981. is_bambu_tag,
  982. is_valid_tag,
  983. link_tag_to_inventory_spool,
  984. )
  985. _spoolman_on = await get_setting(db, "spoolman_enabled")
  986. if not _spoolman_on or _spoolman_on.lower() != "true":
  987. for ams_unit in ams_data:
  988. if not isinstance(ams_unit, dict):
  989. continue
  990. ams_id = int(ams_unit.get("id", 0))
  991. for tray in ams_unit.get("tray", []):
  992. if not isinstance(tray, dict):
  993. continue
  994. tray_id = int(tray.get("id", 0))
  995. tag_uid = tray.get("tag_uid", "")
  996. tray_uuid = tray.get("tray_uuid", "")
  997. tray_info_idx = tray.get("tray_info_idx", "")
  998. if not tray.get("tray_type"):
  999. continue # Empty slot
  1000. # Check if assignment already exists for this slot
  1001. existing = await db.execute(
  1002. select(SA)
  1003. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  1004. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  1005. )
  1006. existing_assignment = existing.scalar_one_or_none()
  1007. if existing_assignment:
  1008. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  1009. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  1010. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  1011. # Skip during active prints: the usage tracker handles deduction
  1012. # precisely via 3MF data on print completion. Without this guard the
  1013. # AMS remain% SET and the usage tracker ADD both fire from the same
  1014. # MQTT message, doubling the deduction (#880).
  1015. if _print_active:
  1016. continue
  1017. remain_raw = tray.get("remain")
  1018. if (
  1019. remain_raw is not None
  1020. and existing_assignment.spool
  1021. and not existing_assignment.spool.weight_locked
  1022. ):
  1023. try:
  1024. remain_val = int(remain_raw)
  1025. except (TypeError, ValueError):
  1026. remain_val = -1
  1027. if 1 <= remain_val <= 100:
  1028. lw = existing_assignment.spool.label_weight or 1000
  1029. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1030. current_used = existing_assignment.spool.weight_used or 0
  1031. if new_used > current_used + 1:
  1032. logger.info(
  1033. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  1034. existing_assignment.spool_id,
  1035. current_used,
  1036. new_used,
  1037. remain_val,
  1038. )
  1039. existing_assignment.spool.weight_used = new_used
  1040. await db.commit()
  1041. continue
  1042. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  1043. # BL spool with RFID tag: auto-match → inventory match → auto-create
  1044. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  1045. if not spool:
  1046. # Try matching an untagged inventory spool (same material/color)
  1047. spool = await find_matching_untagged_spool(db, tray)
  1048. if spool:
  1049. await link_tag_to_inventory_spool(db, spool, tray)
  1050. else:
  1051. spool = await create_spool_from_tray(db, tray)
  1052. await auto_assign_spool(
  1053. printer_id,
  1054. ams_id,
  1055. tray_id,
  1056. spool,
  1057. printer_manager,
  1058. db,
  1059. tray_info_idx=tray_info_idx,
  1060. )
  1061. await db.commit()
  1062. await ws_manager.broadcast(
  1063. {
  1064. "type": "spool_auto_assigned",
  1065. "printer_id": printer_id,
  1066. "ams_id": ams_id,
  1067. "tray_id": tray_id,
  1068. "spool_id": spool.id,
  1069. }
  1070. )
  1071. logger.info(
  1072. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  1073. spool.id,
  1074. printer_id,
  1075. ams_id,
  1076. tray_id,
  1077. )
  1078. elif is_valid_tag(tag_uid, tray_uuid):
  1079. # Non-BL spool with some tag — let user choose
  1080. await ws_manager.broadcast(
  1081. {
  1082. "type": "unknown_tag",
  1083. "printer_id": printer_id,
  1084. "ams_id": ams_id,
  1085. "tray_id": tray_id,
  1086. "tag_uid": tag_uid,
  1087. "tray_uuid": tray_uuid,
  1088. }
  1089. )
  1090. else:
  1091. # No tag at all — let user choose from inventory
  1092. await ws_manager.broadcast(
  1093. {
  1094. "type": "unknown_tag",
  1095. "printer_id": printer_id,
  1096. "ams_id": ams_id,
  1097. "tray_id": tray_id,
  1098. "tag_uid": "",
  1099. "tray_uuid": "",
  1100. }
  1101. )
  1102. except Exception as e:
  1103. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  1104. try:
  1105. async with async_session() as db:
  1106. from backend.app.api.routes.settings import get_setting
  1107. from backend.app.models.printer import Printer
  1108. # Check if Spoolman is enabled
  1109. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1110. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  1111. return
  1112. # Check sync mode
  1113. sync_mode = await get_setting(db, "spoolman_sync_mode")
  1114. if sync_mode and sync_mode != "auto":
  1115. return # Only sync on auto mode
  1116. # Check if weight sync is disabled
  1117. disable_weight_sync_str = await get_setting(db, "spoolman_disable_weight_sync")
  1118. disable_weight_sync = disable_weight_sync_str and disable_weight_sync_str.lower() == "true"
  1119. # Get Spoolman URL
  1120. spoolman_url = await get_setting(db, "spoolman_url")
  1121. if not spoolman_url:
  1122. return
  1123. # Get or create Spoolman client
  1124. client = await get_spoolman_client()
  1125. if not client:
  1126. client = await init_spoolman_client(spoolman_url)
  1127. # Check if Spoolman is reachable
  1128. if not await client.health_check():
  1129. logger.warning("Spoolman not reachable at %s", spoolman_url)
  1130. return
  1131. # Get printer name for location
  1132. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1133. printer = result.scalar_one_or_none()
  1134. printer_name = printer.name if printer else f"Printer {printer_id}"
  1135. # OPTIMIZATION: Fetch all spools once before processing trays
  1136. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  1137. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  1138. try:
  1139. cached_spools = await client.get_spools()
  1140. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  1141. except Exception as e:
  1142. logger.error(
  1143. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  1144. printer_id,
  1145. e,
  1146. )
  1147. return
  1148. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  1149. from sqlalchemy.orm import selectinload
  1150. from backend.app.models.spool_assignment import SpoolAssignment
  1151. inventory_weights: dict[tuple[int, int], float] = {}
  1152. try:
  1153. assign_result = await db.execute(
  1154. select(SpoolAssignment)
  1155. .options(selectinload(SpoolAssignment.spool))
  1156. .where(SpoolAssignment.printer_id == printer_id)
  1157. )
  1158. for assignment in assign_result.scalars().all():
  1159. spool = assignment.spool
  1160. if spool and spool.label_weight > 0:
  1161. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  1162. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  1163. except Exception as e:
  1164. logger.debug("Could not load inventory weights for printer %s: %s", printer_id, e)
  1165. # Sync each AMS tray, tracking UUIDs and spool IDs for cleanup
  1166. synced = 0
  1167. current_tray_uuids: set[str] = set()
  1168. synced_spool_ids: set[int] = set()
  1169. for ams_unit in ams_data:
  1170. ams_id = int(ams_unit.get("id", 0))
  1171. trays = ams_unit.get("tray", [])
  1172. for tray_data in trays:
  1173. tray = client.parse_ams_tray(ams_id, tray_data)
  1174. if not tray:
  1175. continue # Empty tray
  1176. # Track this spool's UUID as currently present in the AMS
  1177. spool_tag = (
  1178. tray.tray_uuid
  1179. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  1180. else tray.tag_uid
  1181. )
  1182. if spool_tag:
  1183. current_tray_uuids.add(spool_tag.upper())
  1184. try:
  1185. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  1186. result = await client.sync_ams_tray(
  1187. tray,
  1188. printer_name,
  1189. disable_weight_sync=disable_weight_sync,
  1190. cached_spools=cached_spools,
  1191. inventory_remaining=inv_remaining,
  1192. )
  1193. if result:
  1194. synced += 1
  1195. if result.get("id"):
  1196. synced_spool_ids.add(result["id"])
  1197. # If a new spool was created, add it to the cache
  1198. # so subsequent trays can find it if they reference the same tag
  1199. # Check if this spool already exists in cache
  1200. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  1201. if not spool_exists:
  1202. cached_spools.append(result)
  1203. logger.debug(
  1204. "[Printer %s] Added newly created spool %s to cache",
  1205. printer_id,
  1206. result["id"],
  1207. )
  1208. except Exception as e:
  1209. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  1210. if synced > 0:
  1211. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  1212. # Clear location for spools no longer in this printer's AMS
  1213. try:
  1214. cleared = await client.clear_location_for_removed_spools(
  1215. printer_name, current_tray_uuids, cached_spools=cached_spools, synced_spool_ids=synced_spool_ids
  1216. )
  1217. if cleared > 0:
  1218. logger.info("Auto-cleared location for %s spools removed from printer %s", cleared, printer_id)
  1219. except Exception as e:
  1220. logger.error("Error clearing locations for removed spools on printer %s: %s", printer_id, e)
  1221. except Exception as e:
  1222. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  1223. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  1224. """Capture a camera snapshot for notification image attachment.
  1225. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  1226. Uses: external camera > buffered frame > fresh capture.
  1227. """
  1228. if not printer:
  1229. return None
  1230. try:
  1231. from backend.app.api.routes.settings import get_setting
  1232. async with async_session() as db:
  1233. capture_enabled = await get_setting(db, "capture_finish_photo")
  1234. if capture_enabled is not None and capture_enabled.lower() != "true":
  1235. return None
  1236. # Try external camera first
  1237. if printer.external_camera_enabled and printer.external_camera_url:
  1238. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  1239. from backend.app.services.external_camera import capture_frame
  1240. frame_data = await capture_frame(
  1241. printer.external_camera_url,
  1242. printer.external_camera_type or "mjpeg",
  1243. snapshot_url=printer.external_camera_snapshot_url,
  1244. )
  1245. if frame_data and len(frame_data) <= 2_500_000:
  1246. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  1247. return _apply_camera_rotation(frame_data, printer, logger)
  1248. # Try buffered frame from active stream
  1249. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1250. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1251. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  1252. buffered_frame = get_buffered_frame(printer_id)
  1253. if (active_for_printer or active_chamber) and buffered_frame:
  1254. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  1255. if len(buffered_frame) <= 2_500_000:
  1256. return _apply_camera_rotation(buffered_frame, printer, logger)
  1257. # Fresh capture from printer camera
  1258. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  1259. from backend.app.services.camera import capture_camera_frame_bytes
  1260. frame_data = await capture_camera_frame_bytes(
  1261. printer.ip_address, printer.access_code, printer.model, timeout=15
  1262. )
  1263. if frame_data and len(frame_data) <= 2_500_000:
  1264. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  1265. return _apply_camera_rotation(frame_data, printer, logger)
  1266. except Exception as e:
  1267. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  1268. return None
  1269. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  1270. """Apply camera rotation to snapshot image if configured."""
  1271. rotation = getattr(printer, "camera_rotation", 0)
  1272. if not rotation or rotation == 0:
  1273. return image_data
  1274. try:
  1275. from io import BytesIO
  1276. from PIL import Image
  1277. img = Image.open(BytesIO(image_data))
  1278. # PIL rotate is counter-clockwise, so negate for clockwise rotation
  1279. img = img.rotate(-rotation, expand=True)
  1280. buf = BytesIO()
  1281. img.save(buf, format="JPEG", quality=90)
  1282. rotated = buf.getvalue()
  1283. logger.info("[SNAPSHOT] Applied %d° rotation: %s → %s bytes", rotation, len(image_data), len(rotated))
  1284. return rotated
  1285. except Exception as e:
  1286. logger.warning("[SNAPSHOT] Failed to apply rotation: %s", e)
  1287. return image_data
  1288. async def _send_print_start_notification(
  1289. printer_id: int,
  1290. data: dict,
  1291. archive_data: dict | None = None,
  1292. logger=None,
  1293. ):
  1294. """Helper to send print start notification with optional archive data."""
  1295. if logger is None:
  1296. logger = logging.getLogger(__name__)
  1297. try:
  1298. async with async_session() as db:
  1299. from backend.app.models.printer import Printer
  1300. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1301. printer = result.scalar_one_or_none()
  1302. printer_name = printer.name if printer else f"Printer {printer_id}"
  1303. # Capture camera snapshot for notification image attachment
  1304. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  1305. if image_data:
  1306. if archive_data is None:
  1307. archive_data = {}
  1308. archive_data["image_data"] = image_data
  1309. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  1310. # Send user-specific email notification for print start
  1311. if archive_data and archive_data.get("created_by_id"):
  1312. await notification_service.send_user_print_email(
  1313. event_type="user_print_start",
  1314. created_by_id=archive_data["created_by_id"],
  1315. printer_name=printer_name,
  1316. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  1317. db=db,
  1318. )
  1319. except Exception as e:
  1320. logger.warning("Notification on_print_start failed: %s", e)
  1321. async def _dispatch_user_print_email(
  1322. status: str,
  1323. created_by_id: int | None,
  1324. printer_name: str,
  1325. filename: str,
  1326. db,
  1327. ) -> None:
  1328. """Send a user-specific print-completion email based on print status.
  1329. Maps the normalised print status to the correct event type and delegates
  1330. to :meth:`NotificationService.send_user_print_email`. A single helper
  1331. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  1332. "stopped"`` dispatch block at every call site.
  1333. Does nothing if *created_by_id* is ``None``.
  1334. """
  1335. if created_by_id is None:
  1336. return
  1337. if status == "completed":
  1338. event_type = "user_print_complete"
  1339. elif status == "failed":
  1340. event_type = "user_print_failed"
  1341. elif status in ("stopped", "aborted", "cancelled"):
  1342. event_type = "user_print_stopped"
  1343. else:
  1344. return
  1345. await notification_service.send_user_print_email(
  1346. event_type=event_type,
  1347. created_by_id=created_by_id,
  1348. printer_name=printer_name,
  1349. filename=filename,
  1350. db=db,
  1351. )
  1352. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  1353. """Extract printable objects from an archive's 3MF file and store in printer state."""
  1354. try:
  1355. from backend.app.services.archive import extract_printable_objects_from_3mf
  1356. file_path = app_settings.base_dir / archive.file_path
  1357. if file_path.is_file() and str(file_path).endswith(".3mf"):
  1358. with open(file_path, "rb") as f:
  1359. threemf_data = f.read()
  1360. # Extract with positions for UI overlay
  1361. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  1362. if printable_objects:
  1363. client = printer_manager.get_client(printer_id)
  1364. if client:
  1365. client.state.printable_objects = printable_objects
  1366. client.state.printable_objects_bbox_all = bbox_all
  1367. client.state.skipped_objects = []
  1368. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  1369. except Exception as e:
  1370. logger.debug("Failed to extract printable objects from archive: %s", e)
  1371. async def on_print_start(printer_id: int, data: dict):
  1372. """Handle print start - archive the 3MF file immediately."""
  1373. logger = logging.getLogger(__name__)
  1374. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  1375. # Clear any stale user-stopped flag from previous print cycles
  1376. _user_stopped_printers.discard(printer_id)
  1377. # Cancel any active bed cooldown waiter for this printer
  1378. if _bed_cool_waiters.pop(printer_id, None):
  1379. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  1380. # Clear cached cover images so the new print's thumbnail is fetched fresh
  1381. from backend.app.api.routes.printers import clear_cover_cache
  1382. clear_cover_cache(printer_id)
  1383. await ws_manager.send_print_start(printer_id, data)
  1384. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  1385. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  1386. # MQTT relay - publish print start
  1387. try:
  1388. printer_info = printer_manager.get_printer(printer_id)
  1389. if printer_info:
  1390. await mqtt_relay.on_print_start(
  1391. printer_id,
  1392. printer_info.name,
  1393. printer_info.serial_number,
  1394. data.get("filename", ""),
  1395. data.get("subtask_name", ""),
  1396. )
  1397. except Exception:
  1398. pass # Don't fail print start callback if MQTT fails
  1399. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  1400. try:
  1401. async with async_session() as db:
  1402. from backend.app.api.routes.settings import get_setting
  1403. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1404. if not _spoolman_on or _spoolman_on.lower() != "true":
  1405. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  1406. await usage_on_print_start(printer_id, data, printer_manager, db=db)
  1407. except Exception as e:
  1408. logger.warning("Usage tracker on_print_start failed: %s", e)
  1409. # Track if notification was sent (to avoid sending twice)
  1410. notification_sent = False
  1411. # Smart plug automation: turn on plug when print starts
  1412. try:
  1413. async with async_session() as db:
  1414. await smart_plug_manager.on_print_start(printer_id, db)
  1415. except Exception as e:
  1416. logger.warning("Smart plug on_print_start failed: %s", e)
  1417. async with async_session() as db:
  1418. from backend.app.models.printer import Printer
  1419. from backend.app.services.bambu_ftp import list_files_async
  1420. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1421. printer = result.scalar_one_or_none()
  1422. # Plate detection check - pause if objects detected on build plate
  1423. logger.info(
  1424. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  1425. )
  1426. if printer and printer.plate_detection_enabled:
  1427. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  1428. try:
  1429. from backend.app.services.plate_detection import check_plate_empty
  1430. # Build ROI tuple from printer settings if available
  1431. roi = None
  1432. if all(
  1433. [
  1434. printer.plate_detection_roi_x is not None,
  1435. printer.plate_detection_roi_y is not None,
  1436. printer.plate_detection_roi_w is not None,
  1437. printer.plate_detection_roi_h is not None,
  1438. ]
  1439. ):
  1440. roi = (
  1441. printer.plate_detection_roi_x,
  1442. printer.plate_detection_roi_y,
  1443. printer.plate_detection_roi_w,
  1444. printer.plate_detection_roi_h,
  1445. )
  1446. # Auto-turn on chamber light if it's off for better detection
  1447. light_was_off = False
  1448. client = printer_manager.get_client(printer_id)
  1449. if client and client.state:
  1450. light_was_off = not client.state.chamber_light
  1451. if light_was_off:
  1452. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  1453. client.set_chamber_light(True)
  1454. # Wait for light to physically turn on and camera to adjust exposure
  1455. await asyncio.sleep(2.5)
  1456. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  1457. plate_result = await check_plate_empty(
  1458. printer_id=printer_id,
  1459. ip_address=printer.ip_address,
  1460. access_code=printer.access_code,
  1461. model=printer.model,
  1462. include_debug_image=False,
  1463. external_camera_url=printer.external_camera_url,
  1464. external_camera_type=printer.external_camera_type,
  1465. use_external=printer.external_camera_enabled,
  1466. roi=roi,
  1467. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  1468. )
  1469. # Restore chamber light to original state
  1470. if light_was_off and client:
  1471. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  1472. client.set_chamber_light(False)
  1473. if not plate_result.needs_calibration and not plate_result.is_empty:
  1474. # Objects detected - pause the print!
  1475. logger.warning(
  1476. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  1477. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  1478. )
  1479. client = printer_manager.get_client(printer_id)
  1480. if client:
  1481. client.pause_print()
  1482. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  1483. # Send notification about plate not empty
  1484. await ws_manager.broadcast(
  1485. {
  1486. "type": "plate_not_empty",
  1487. "printer_id": printer_id,
  1488. "printer_name": printer.name,
  1489. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  1490. }
  1491. )
  1492. # Also send push notification
  1493. try:
  1494. await notification_service.on_plate_not_empty(
  1495. printer_id=printer_id,
  1496. printer_name=printer.name,
  1497. db=db,
  1498. difference_percent=plate_result.difference_percent,
  1499. )
  1500. except Exception as notif_err:
  1501. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  1502. else:
  1503. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  1504. except Exception as plate_err:
  1505. # Don't block print on plate detection errors
  1506. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  1507. if not printer:
  1508. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  1509. if not notification_sent:
  1510. await _send_print_start_notification(printer_id, data, logger=logger)
  1511. return
  1512. if not printer.auto_archive:
  1513. # auto-archive disabled — check if there's an expected print (dispatched
  1514. # by BamBuddy via queue/reprint) that already has an archive to promote.
  1515. # If so, fall through to the expected-print handling below so the archive
  1516. # is tracked in _active_prints and usage tracking works at completion.
  1517. _fn = data.get("filename", "")
  1518. _sn = data.get("subtask_name", "")
  1519. _check_keys: list[tuple[int, str]] = []
  1520. if _sn:
  1521. _check_keys += [
  1522. (printer_id, _sn),
  1523. (printer_id, f"{_sn}.3mf"),
  1524. (printer_id, f"{_sn}.gcode.3mf"),
  1525. ]
  1526. if _fn:
  1527. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  1528. _check_keys.append((printer_id, _base_fn))
  1529. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  1530. _check_keys += [
  1531. (printer_id, _no_archive_base),
  1532. (printer_id, f"{_no_archive_base}.3mf"),
  1533. ]
  1534. _has_expected = any(k in _expected_prints for k in _check_keys)
  1535. if not _has_expected:
  1536. # No expected print — truly external print (started from slicer/touchscreen)
  1537. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  1538. if not notification_sent:
  1539. _no_archive_creator: int | None = None
  1540. for _key in _check_keys:
  1541. _expected_prints.pop(_key, None)
  1542. _expected_print_registered_at.pop(_key, None)
  1543. popped_creator = _expected_print_creators.pop(_key, None)
  1544. if _no_archive_creator is None:
  1545. _no_archive_creator = popped_creator
  1546. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  1547. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  1548. return
  1549. else:
  1550. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  1551. # Get the filename and subtask_name
  1552. filename = data.get("filename", "")
  1553. subtask_name = data.get("subtask_name", "")
  1554. # MQTT subtask_id uniquely identifies a print job on the printer. When
  1555. # present, it lets us match an archive across a backend restart (#972):
  1556. # same id → same print → resume the existing row instead of cancelling
  1557. # it and recreating from scratch (which loses started_at). Treat "0"
  1558. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  1559. raw_mqtt = data.get("raw_data") or {}
  1560. subtask_id = raw_mqtt.get("subtask_id")
  1561. if subtask_id is not None:
  1562. subtask_id = str(subtask_id).strip()
  1563. if subtask_id in ("", "0"):
  1564. subtask_id = None
  1565. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  1566. # Skip calibration prints — internal printer files should not be archived
  1567. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  1568. if filename and filename.startswith("/usr/"):
  1569. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  1570. if not notification_sent:
  1571. await _send_print_start_notification(printer_id, data, logger=logger)
  1572. return
  1573. if not filename and not subtask_name:
  1574. # Send notification without archive data (no filename)
  1575. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  1576. if not notification_sent:
  1577. await _send_print_start_notification(printer_id, data, logger=logger)
  1578. return
  1579. # Check if this is an expected print from reprint/scheduled
  1580. # Build list of possible keys to check
  1581. expected_keys = []
  1582. if subtask_name:
  1583. expected_keys.append((printer_id, subtask_name))
  1584. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  1585. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1586. if filename:
  1587. fname = filename.split("/")[-1] if "/" in filename else filename
  1588. expected_keys.append((printer_id, fname))
  1589. # Strip extensions to match
  1590. base = fname.replace(".gcode", "").replace(".3mf", "")
  1591. expected_keys.append((printer_id, base))
  1592. expected_keys.append((printer_id, f"{base}.3mf"))
  1593. expected_archive_id = None
  1594. for key in expected_keys:
  1595. expected_archive_id = _expected_prints.pop(key, None)
  1596. _expected_print_registered_at.pop(key, None)
  1597. if expected_archive_id:
  1598. # Clean up other possible keys for this print
  1599. for other_key in expected_keys:
  1600. _expected_prints.pop(other_key, None)
  1601. _expected_print_registered_at.pop(other_key, None)
  1602. break
  1603. if expected_archive_id:
  1604. # This is a reprint/scheduled print - use existing archive, don't create new one
  1605. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  1606. from backend.app.models.archive import PrintArchive
  1607. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  1608. archive = result.scalar_one_or_none()
  1609. if archive:
  1610. # Update archive status to printing
  1611. archive.status = "printing"
  1612. archive.started_at = datetime.now(timezone.utc)
  1613. if subtask_id and not archive.subtask_id:
  1614. archive.subtask_id = subtask_id
  1615. await db.commit()
  1616. # Track as active print
  1617. _active_prints[(printer_id, archive.filename)] = archive.id
  1618. if subtask_name:
  1619. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1620. # Inject ams_mapping into usage tracker session — the session was created
  1621. # before expected-print promotion, so it may have ams_mapping=None when
  1622. # the MQTT request topic subscription failed (common on P1S/A1).
  1623. _stored_map = _print_ams_mappings.get(expected_archive_id)
  1624. if _stored_map:
  1625. try:
  1626. from backend.app.services.usage_tracker import _active_sessions
  1627. _ut_session = _active_sessions.get(printer_id)
  1628. if _ut_session and not _ut_session.ams_mapping:
  1629. _ut_session.ams_mapping = _stored_map
  1630. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  1631. except Exception:
  1632. pass
  1633. # Set up energy tracking (#941: persist start on archive row)
  1634. await _record_energy_start(archive, printer_id, db, context="expected-print")
  1635. await ws_manager.send_archive_updated(
  1636. {
  1637. "id": archive.id,
  1638. "status": "printing",
  1639. }
  1640. )
  1641. # Send notification with archive data (reprint/scheduled)
  1642. if not notification_sent:
  1643. # Use archive's created_by_id; fall back to the creator registered via
  1644. # register_expected_print (handles library-file-based queue items where
  1645. # the freshly-created archive has no created_by_id yet).
  1646. # Pop ALL matching keys so no stale entries remain in the dict.
  1647. fallback_creator = None
  1648. for key in expected_keys:
  1649. popped = _expected_print_creators.pop(key, None)
  1650. if fallback_creator is None:
  1651. fallback_creator = popped
  1652. archive_data = {
  1653. "print_time_seconds": archive.print_time_seconds,
  1654. "created_by_id": archive.created_by_id or fallback_creator,
  1655. }
  1656. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1657. # Extract printable objects from the archived 3MF file
  1658. _load_objects_from_archive(archive, printer_id, logger)
  1659. # Store Spoolman tracking data for per-filament usage reporting
  1660. try:
  1661. await _store_spoolman_print_data(
  1662. printer_id,
  1663. archive.id,
  1664. archive.file_path,
  1665. db,
  1666. printer_manager,
  1667. ams_mapping=_get_start_ams_mapping(data, archive.id),
  1668. )
  1669. except Exception as e:
  1670. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1671. return # Skip creating a new archive
  1672. # Check if there's already a "printing" archive for this printer/file
  1673. # This prevents duplicates when backend restarts during an active print
  1674. from backend.app.models.archive import PrintArchive
  1675. existing_archive: PrintArchive | None = None
  1676. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  1677. # across a backend restart for the same print, so this is the most
  1678. # reliable way to reattach. We also accept a previously stale-cancelled
  1679. # archive here so users upgrading mid-print get revived when the row
  1680. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  1681. if subtask_id:
  1682. by_id = await db.execute(
  1683. select(PrintArchive)
  1684. .where(PrintArchive.printer_id == printer_id)
  1685. .where(PrintArchive.subtask_id == subtask_id)
  1686. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  1687. .order_by(PrintArchive.created_at.desc())
  1688. .limit(1)
  1689. )
  1690. candidate = by_id.scalar_one_or_none()
  1691. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  1692. existing_archive = candidate
  1693. # Fallback match: name-based lookup. Kept as-is for prints whose
  1694. # subtask_id is missing ("0" / local / non-cloud prints).
  1695. if existing_archive is None:
  1696. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  1697. existing = await db.execute(
  1698. select(PrintArchive)
  1699. .where(PrintArchive.printer_id == printer_id)
  1700. .where(PrintArchive.status == "printing")
  1701. .where(
  1702. or_(
  1703. PrintArchive.print_name == check_name,
  1704. PrintArchive.filename.in_(
  1705. [
  1706. f"{check_name}.3mf",
  1707. f"{check_name}.gcode.3mf",
  1708. ]
  1709. ),
  1710. )
  1711. )
  1712. .order_by(PrintArchive.created_at.desc())
  1713. .limit(1)
  1714. )
  1715. existing_archive = existing.scalar_one_or_none()
  1716. if existing_archive:
  1717. # subtask_id match → always resume, regardless of age. Same print,
  1718. # just a backend restart. Revive if it was previously stale-cancelled.
  1719. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  1720. if subtask_match:
  1721. if existing_archive.status == "cancelled":
  1722. logger.warning(
  1723. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  1724. existing_archive.id,
  1725. subtask_id,
  1726. )
  1727. existing_archive.status = "printing"
  1728. existing_archive.failure_reason = None
  1729. await db.commit()
  1730. else:
  1731. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  1732. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1733. if existing_archive.energy_start_kwh is None:
  1734. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  1735. if not notification_sent:
  1736. archive_data = {
  1737. "print_time_seconds": existing_archive.print_time_seconds,
  1738. "created_by_id": existing_archive.created_by_id,
  1739. }
  1740. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1741. _load_objects_from_archive(existing_archive, printer_id, logger)
  1742. return
  1743. # Name-match only: fall back to the legacy 4h staleness heuristic.
  1744. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  1745. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  1746. logger.warning(
  1747. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  1748. f"marking as cancelled and creating new archive"
  1749. )
  1750. existing_archive.status = "cancelled"
  1751. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  1752. await db.commit()
  1753. # Fall through to create new archive (don't return)
  1754. _existing_archive = None # Clear so we don't use stale archive
  1755. else:
  1756. logger.info(
  1757. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  1758. )
  1759. # Track this as the active print
  1760. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1761. # Attach subtask_id retroactively so future restarts can resume
  1762. if subtask_id and not existing_archive.subtask_id:
  1763. existing_archive.subtask_id = subtask_id
  1764. await db.commit()
  1765. # Also set up energy tracking if not already tracked (#941: persisted column)
  1766. if existing_archive.energy_start_kwh is None:
  1767. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  1768. # Send notification with archive data (existing archive)
  1769. if not notification_sent:
  1770. archive_data = {
  1771. "print_time_seconds": existing_archive.print_time_seconds,
  1772. "created_by_id": existing_archive.created_by_id,
  1773. }
  1774. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1775. # Extract printable objects from the archived 3MF file
  1776. _load_objects_from_archive(existing_archive, printer_id, logger)
  1777. return
  1778. # Build list of possible 3MF filenames to try
  1779. possible_names = []
  1780. # Bambu printers typically store files as "Name.gcode.3mf"
  1781. # The subtask_name is usually the best source for the filename
  1782. if subtask_name:
  1783. # Try common Bambu naming patterns
  1784. possible_names.append(f"{subtask_name}.gcode.3mf")
  1785. possible_names.append(f"{subtask_name}.3mf")
  1786. # Try original filename with .3mf extension
  1787. if filename:
  1788. # Extract just the filename part, not the full path
  1789. fname = filename.split("/")[-1] if "/" in filename else filename
  1790. if fname.endswith(".3mf"):
  1791. possible_names.append(fname)
  1792. elif fname.endswith(".gcode"):
  1793. base = fname.rsplit(".", 1)[0]
  1794. possible_names.append(f"{base}.gcode.3mf")
  1795. possible_names.append(f"{base}.3mf")
  1796. else:
  1797. possible_names.append(f"{fname}.gcode.3mf")
  1798. possible_names.append(f"{fname}.3mf")
  1799. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1800. space_variants = []
  1801. for name in possible_names:
  1802. if " " in name:
  1803. space_variants.append(name.replace(" ", "_"))
  1804. possible_names.extend(space_variants)
  1805. # Remove duplicates while preserving order
  1806. seen = set()
  1807. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  1808. logger.info("Trying filenames: %s", possible_names)
  1809. # Try to find and download the 3MF file
  1810. temp_path = None
  1811. downloaded_filename = None
  1812. # Cache check: cover endpoint may have already pulled this 3MF during
  1813. # the print (frontend opens the card and shows the thumbnail) — reuse
  1814. # that file instead of re-downloading 36MB over the same FTP link that
  1815. # just served it (#972). The cache keys on a normalized filename so
  1816. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  1817. for try_filename in possible_names:
  1818. if not try_filename.endswith(".3mf"):
  1819. continue
  1820. cached = get_cached_3mf(printer_id, try_filename)
  1821. if cached:
  1822. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  1823. temp_path = cached
  1824. downloaded_filename = try_filename
  1825. break
  1826. # Get FTP retry settings
  1827. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1828. for try_filename in possible_names if not downloaded_filename else []:
  1829. if not try_filename.endswith(".3mf"):
  1830. continue
  1831. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  1832. # printers, so try it first — deferring it to last cost #972's reporter
  1833. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  1834. # landing on the path that actually had the file.
  1835. remote_paths = [
  1836. f"/{try_filename}",
  1837. f"/cache/{try_filename}",
  1838. f"/model/{try_filename}",
  1839. f"/data/{try_filename}",
  1840. f"/data/Metadata/{try_filename}",
  1841. ]
  1842. temp_path = app_settings.archive_dir / "temp" / try_filename
  1843. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1844. for remote_path in remote_paths:
  1845. logger.debug("Trying FTP download: %s", remote_path)
  1846. try:
  1847. if ftp_retry_enabled:
  1848. downloaded = await with_ftp_retry(
  1849. download_file_async,
  1850. printer.ip_address,
  1851. printer.access_code,
  1852. remote_path,
  1853. temp_path,
  1854. timeout=ftp_timeout,
  1855. socket_timeout=ftp_timeout,
  1856. printer_model=printer.model,
  1857. max_retries=ftp_retry_count,
  1858. retry_delay=ftp_retry_delay,
  1859. operation_name=f"Download 3MF from {remote_path}",
  1860. non_retry_exceptions=(FileNotOnPrinterError,),
  1861. )
  1862. else:
  1863. downloaded = await download_file_async(
  1864. printer.ip_address,
  1865. printer.access_code,
  1866. remote_path,
  1867. temp_path,
  1868. timeout=ftp_timeout,
  1869. socket_timeout=ftp_timeout,
  1870. printer_model=printer.model,
  1871. )
  1872. if downloaded:
  1873. downloaded_filename = try_filename
  1874. logger.info("Downloaded: %s", remote_path)
  1875. # Populate shared cache so the cover endpoint (if it
  1876. # runs next) doesn't refetch the same 36MB over FTP.
  1877. cache_3mf_download(printer_id, try_filename, temp_path)
  1878. break
  1879. except FileNotOnPrinterError:
  1880. # 550 — file isn't at this path. Advance to next candidate
  1881. # without burning the retry budget.
  1882. logger.debug("3MF not at %s (550), trying next path", remote_path)
  1883. except Exception as e:
  1884. logger.debug("FTP download failed for %s: %s", remote_path, e)
  1885. if downloaded_filename:
  1886. break
  1887. # If still not found, try listing directories to find matching file
  1888. # Different printer models use different directory structures
  1889. if not downloaded_filename and (filename or subtask_name):
  1890. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  1891. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  1892. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  1893. for search_dir in search_dirs:
  1894. if downloaded_filename:
  1895. break
  1896. try:
  1897. dir_files = await list_files_async(
  1898. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  1899. )
  1900. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  1901. if threemf_files:
  1902. logger.info(
  1903. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  1904. )
  1905. for f in dir_files:
  1906. if f.get("is_directory"):
  1907. continue
  1908. fname = f.get("name", "")
  1909. # Normalize both for comparison (spaces and underscores are equivalent)
  1910. fname_normalized = fname.lower().replace(" ", "_")
  1911. search_normalized = search_term.replace(" ", "_")
  1912. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  1913. logger.info("Found matching file in %s: %s", search_dir, fname)
  1914. temp_path = app_settings.archive_dir / "temp" / fname
  1915. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1916. remote_full_path = posixpath.join(search_dir, fname)
  1917. if ftp_retry_enabled:
  1918. downloaded = await with_ftp_retry(
  1919. download_file_async,
  1920. printer.ip_address,
  1921. printer.access_code,
  1922. remote_full_path,
  1923. temp_path,
  1924. timeout=ftp_timeout,
  1925. socket_timeout=ftp_timeout,
  1926. printer_model=printer.model,
  1927. max_retries=ftp_retry_count,
  1928. retry_delay=ftp_retry_delay,
  1929. operation_name=f"Download 3MF from {remote_full_path}",
  1930. )
  1931. else:
  1932. downloaded = await download_file_async(
  1933. printer.ip_address,
  1934. printer.access_code,
  1935. remote_full_path,
  1936. temp_path,
  1937. timeout=ftp_timeout,
  1938. socket_timeout=ftp_timeout,
  1939. printer_model=printer.model,
  1940. )
  1941. if downloaded:
  1942. downloaded_filename = fname
  1943. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  1944. cache_3mf_download(printer_id, fname, temp_path)
  1945. break
  1946. except Exception as e:
  1947. logger.debug("Failed to list %s: %s", search_dir, e)
  1948. # Validate the downloaded 3MF actually matches the plate that's running
  1949. # (#1204): subtask_name lags across consecutive plates of the same model,
  1950. # so the first FTP candidate (built from subtask_name) can land on the
  1951. # previous plate's still-resident upload. Cross-check the slice_info
  1952. # plate index against the plate parsed from gcode_file (always fresh —
  1953. # it's the field whose change triggered this callback).
  1954. if downloaded_filename and temp_path:
  1955. expected_plate = parse_plate_id(filename)
  1956. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  1957. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  1958. logger.warning(
  1959. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  1960. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  1961. downloaded_filename,
  1962. actual_plate,
  1963. expected_plate,
  1964. subtask_name,
  1965. )
  1966. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  1967. retry_succeeded = False
  1968. if corrected_subtask and corrected_subtask != subtask_name:
  1969. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  1970. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  1971. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  1972. for remote_path in (
  1973. f"/{try_filename}",
  1974. f"/cache/{try_filename}",
  1975. f"/model/{try_filename}",
  1976. f"/data/{try_filename}",
  1977. f"/data/Metadata/{try_filename}",
  1978. ):
  1979. try:
  1980. if ftp_retry_enabled:
  1981. downloaded = await with_ftp_retry(
  1982. download_file_async,
  1983. printer.ip_address,
  1984. printer.access_code,
  1985. remote_path,
  1986. retry_temp_path,
  1987. timeout=ftp_timeout,
  1988. socket_timeout=ftp_timeout,
  1989. printer_model=printer.model,
  1990. max_retries=ftp_retry_count,
  1991. retry_delay=ftp_retry_delay,
  1992. operation_name=f"Re-download 3MF from {remote_path}",
  1993. non_retry_exceptions=(FileNotOnPrinterError,),
  1994. )
  1995. else:
  1996. downloaded = await download_file_async(
  1997. printer.ip_address,
  1998. printer.access_code,
  1999. remote_path,
  2000. retry_temp_path,
  2001. timeout=ftp_timeout,
  2002. socket_timeout=ftp_timeout,
  2003. printer_model=printer.model,
  2004. )
  2005. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  2006. logger.info(
  2007. "[CALLBACK] Re-download succeeded with corrected name %s "
  2008. "(plate %s) — replacing wrong file",
  2009. try_filename,
  2010. expected_plate,
  2011. )
  2012. try:
  2013. temp_path.unlink(missing_ok=True)
  2014. except OSError:
  2015. pass
  2016. temp_path = retry_temp_path
  2017. downloaded_filename = try_filename
  2018. subtask_name = corrected_subtask
  2019. cache_3mf_download(printer_id, try_filename, temp_path)
  2020. retry_succeeded = True
  2021. break
  2022. elif downloaded:
  2023. # Wrong plate again — discard and keep trying
  2024. try:
  2025. retry_temp_path.unlink(missing_ok=True)
  2026. except OSError:
  2027. pass
  2028. except FileNotOnPrinterError:
  2029. continue
  2030. except Exception as e:
  2031. logger.debug("Re-download failed for %s: %s", remote_path, e)
  2032. if retry_succeeded:
  2033. break
  2034. # If the retry didn't find a matching file, drop the wrong 3MF
  2035. # so the no-3MF fallback below creates an archive whose name
  2036. # at least reflects the right plate.
  2037. if not retry_succeeded:
  2038. logger.warning(
  2039. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  2040. expected_plate,
  2041. )
  2042. try:
  2043. temp_path.unlink(missing_ok=True)
  2044. except OSError:
  2045. pass
  2046. temp_path = None
  2047. downloaded_filename = None
  2048. # Override the stale subtask_name so the fallback archive's
  2049. # print_name reflects the correct plate. Prefer the swapped
  2050. # name when we have one; otherwise let filename win.
  2051. if corrected_subtask:
  2052. subtask_name = corrected_subtask
  2053. else:
  2054. subtask_name = ""
  2055. if not downloaded_filename or not temp_path:
  2056. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  2057. # Create a fallback archive without 3MF data so the print is still tracked
  2058. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  2059. try:
  2060. from backend.app.models.archive import PrintArchive
  2061. # Derive print name from subtask_name or filename
  2062. print_name = subtask_name or filename
  2063. if print_name:
  2064. # Clean up the name (remove extensions, path parts)
  2065. print_name = print_name.split("/")[-1]
  2066. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  2067. else:
  2068. print_name = "Unknown Print"
  2069. # Recover estimated print time from MQTT (best-effort for notifications)
  2070. fallback_print_time = None
  2071. mqtt_remaining = data.get("remaining_time")
  2072. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  2073. fallback_print_time = int(mqtt_remaining)
  2074. if fallback_print_time is None:
  2075. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  2076. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  2077. fallback_print_time = int(mc_remaining * 60)
  2078. # Create minimal archive entry
  2079. fallback_archive = PrintArchive(
  2080. printer_id=printer_id,
  2081. filename=filename or f"{print_name}.3mf",
  2082. file_path="", # Empty - no 3MF file available
  2083. file_size=0,
  2084. print_name=print_name,
  2085. print_time_seconds=fallback_print_time,
  2086. status="printing",
  2087. started_at=datetime.now(timezone.utc),
  2088. subtask_id=subtask_id,
  2089. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  2090. )
  2091. db.add(fallback_archive)
  2092. await db.commit()
  2093. await db.refresh(fallback_archive)
  2094. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  2095. # Start timelapse session if external camera is enabled
  2096. if printer.external_camera_enabled and printer.external_camera_url:
  2097. from backend.app.services.layer_timelapse import start_session
  2098. start_session(
  2099. printer_id,
  2100. fallback_archive.id,
  2101. printer.external_camera_url,
  2102. printer.external_camera_type or "mjpeg",
  2103. snapshot_url=printer.external_camera_snapshot_url,
  2104. )
  2105. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, fallback_archive.id)
  2106. # Track as active print
  2107. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  2108. if filename:
  2109. _active_prints[(printer_id, filename)] = fallback_archive.id
  2110. if subtask_name:
  2111. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  2112. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  2113. # Record starting energy if smart plug available (#941: persisted column)
  2114. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  2115. # Send WebSocket notification
  2116. await ws_manager.send_archive_created(
  2117. {
  2118. "id": fallback_archive.id,
  2119. "printer_id": fallback_archive.printer_id,
  2120. "filename": fallback_archive.filename,
  2121. "print_name": fallback_archive.print_name,
  2122. "status": fallback_archive.status,
  2123. }
  2124. )
  2125. # MQTT relay - publish archive created
  2126. try:
  2127. await mqtt_relay.on_archive_created(
  2128. archive_id=fallback_archive.id,
  2129. print_name=fallback_archive.print_name,
  2130. printer_name=printer.name,
  2131. status=fallback_archive.status,
  2132. )
  2133. except Exception:
  2134. pass # Don't fail if MQTT fails
  2135. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  2136. try:
  2137. await _store_spoolman_print_data(
  2138. printer_id,
  2139. fallback_archive.id,
  2140. fallback_archive.file_path,
  2141. db,
  2142. printer_manager,
  2143. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  2144. )
  2145. except Exception as e:
  2146. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  2147. # Send notification without archive data (file not found)
  2148. if not notification_sent:
  2149. await _send_print_start_notification(printer_id, data, logger=logger)
  2150. return
  2151. except Exception as e:
  2152. logger.error("Failed to create fallback archive: %s", e)
  2153. # Send notification without archive data (file not found)
  2154. if not notification_sent:
  2155. await _send_print_start_notification(printer_id, data, logger=logger)
  2156. return
  2157. try:
  2158. # Archive the file with status "printing"
  2159. service = ArchiveService(db)
  2160. archive = await service.archive_print(
  2161. printer_id=printer_id,
  2162. source_file=temp_path,
  2163. print_data={**data, "status": "printing"},
  2164. subtask_id=subtask_id,
  2165. )
  2166. if archive:
  2167. # Track this active print (use both original filename and downloaded filename)
  2168. _active_prints[(printer_id, downloaded_filename)] = archive.id
  2169. if filename and filename != downloaded_filename:
  2170. _active_prints[(printer_id, filename)] = archive.id
  2171. if subtask_name:
  2172. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  2173. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  2174. # Start timelapse session if external camera is enabled
  2175. if printer.external_camera_enabled and printer.external_camera_url:
  2176. from backend.app.services.layer_timelapse import start_session
  2177. start_session(
  2178. printer_id,
  2179. archive.id,
  2180. printer.external_camera_url,
  2181. printer.external_camera_type or "mjpeg",
  2182. snapshot_url=printer.external_camera_snapshot_url,
  2183. )
  2184. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, archive.id)
  2185. # Record starting energy from smart plug if available (#941: persisted column)
  2186. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  2187. await ws_manager.send_archive_created(
  2188. {
  2189. "id": archive.id,
  2190. "printer_id": archive.printer_id,
  2191. "filename": archive.filename,
  2192. "print_name": archive.print_name,
  2193. "status": archive.status,
  2194. }
  2195. )
  2196. # MQTT relay - publish archive created
  2197. try:
  2198. await mqtt_relay.on_archive_created(
  2199. archive_id=archive.id,
  2200. print_name=archive.print_name,
  2201. printer_name=printer.name,
  2202. status=archive.status,
  2203. )
  2204. except Exception:
  2205. pass # Don't fail if MQTT fails
  2206. # Send notification with archive data (new archive created)
  2207. if not notification_sent:
  2208. archive_data = {
  2209. "print_time_seconds": archive.print_time_seconds,
  2210. "created_by_id": archive.created_by_id,
  2211. }
  2212. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2213. # Extract printable objects for skip object functionality
  2214. try:
  2215. from backend.app.services.archive import extract_printable_objects_from_3mf
  2216. with open(temp_path, "rb") as f:
  2217. threemf_data = f.read()
  2218. # Extract with positions for UI overlay
  2219. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  2220. threemf_data, include_positions=True
  2221. )
  2222. if printable_objects:
  2223. # Store objects in printer state
  2224. client = printer_manager.get_client(printer_id)
  2225. if client:
  2226. client.state.printable_objects = printable_objects
  2227. client.state.printable_objects_bbox_all = bbox_all
  2228. client.state.skipped_objects = [] # Reset skipped objects for new print
  2229. logger.info(
  2230. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  2231. )
  2232. except Exception as e:
  2233. logger.debug("Failed to extract printable objects: %s", e)
  2234. # Store Spoolman tracking data for per-filament usage reporting
  2235. try:
  2236. await _store_spoolman_print_data(
  2237. printer_id,
  2238. archive.id,
  2239. archive.file_path,
  2240. db,
  2241. printer_manager,
  2242. ams_mapping=_get_start_ams_mapping(data, archive.id),
  2243. )
  2244. except Exception as e:
  2245. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  2246. # Capture timelapse file baseline for snapshot-diff on completion
  2247. try:
  2248. baseline_files, _ = await _list_timelapse_videos(printer)
  2249. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  2250. logger.info(
  2251. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  2252. len(_timelapse_baselines[printer_id]),
  2253. printer_id,
  2254. )
  2255. except Exception as e:
  2256. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  2257. finally:
  2258. # Keep temp_path around until print completes so the cover endpoint
  2259. # can reuse it (#972). Cache eviction in on_print_complete deletes
  2260. # the file. If the cache entry was evicted early (file vanished),
  2261. # clean up any stragglers here to avoid leaking disk on retries.
  2262. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  2263. if temp_path and temp_path.exists() and cached_now != temp_path:
  2264. temp_path.unlink()
  2265. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  2266. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  2267. """List video files from printer's timelapse directory.
  2268. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  2269. Returns (video_files, found_path) where video_files is a list of file dicts
  2270. and found_path is the directory where they were found, or ([], None).
  2271. """
  2272. from backend.app.services.bambu_ftp import list_files_async
  2273. logger = logging.getLogger(__name__)
  2274. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  2275. try:
  2276. found_files = await list_files_async(
  2277. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  2278. )
  2279. if found_files:
  2280. video_files = [
  2281. f
  2282. for f in found_files
  2283. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  2284. ]
  2285. if video_files:
  2286. return video_files, timelapse_path
  2287. except Exception as e:
  2288. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  2289. continue
  2290. return [], None
  2291. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  2292. """
  2293. Scan for timelapse with retries using a snapshot-diff approach.
  2294. Instead of picking the "most recent by mtime" (unreliable when the printer
  2295. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  2296. waiting, then look for any NEW filename that appears after each delay.
  2297. If baseline_names is provided (captured at print start), it is used directly.
  2298. Otherwise falls back to taking a baseline at completion time (best-effort
  2299. for prints started before app restart).
  2300. Falls back to name-matching (print name contained in MP4 filename) if no
  2301. new file appears after all retries.
  2302. """
  2303. from pathlib import Path
  2304. logger = logging.getLogger(__name__)
  2305. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  2306. try:
  2307. async with async_session() as db:
  2308. from backend.app.models.printer import Printer
  2309. service = ArchiveService(db)
  2310. archive = await service.get_archive(archive_id)
  2311. if not archive:
  2312. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  2313. return
  2314. if archive.timelapse_path:
  2315. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  2316. return
  2317. if not archive.printer_id:
  2318. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  2319. return
  2320. if baseline_names is not None:
  2321. # Use pre-captured baseline from print start (no race condition)
  2322. logger.info(
  2323. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  2324. len(baseline_names),
  2325. archive_id,
  2326. )
  2327. else:
  2328. # Fallback: take baseline now (e.g. app restarted mid-print)
  2329. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2330. printer = result.scalar_one_or_none()
  2331. if not printer:
  2332. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  2333. return
  2334. baseline_files, _ = await _list_timelapse_videos(printer)
  2335. baseline_names = {f.get("name", "") for f in baseline_files}
  2336. logger.info(
  2337. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  2338. len(baseline_names),
  2339. archive_id,
  2340. )
  2341. # Derive base_name for name-matching fallback
  2342. base_name = Path(archive.filename).stem if archive.filename else ""
  2343. if base_name.endswith(".gcode"):
  2344. base_name = base_name[:-6]
  2345. except Exception as e:
  2346. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  2347. return
  2348. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  2349. retry_delays = [5, 10, 20, 30]
  2350. for attempt, delay in enumerate(retry_delays, 1):
  2351. logger.info(
  2352. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  2353. attempt,
  2354. len(retry_delays),
  2355. delay,
  2356. archive_id,
  2357. )
  2358. await asyncio.sleep(delay)
  2359. try:
  2360. async with async_session() as db:
  2361. from backend.app.models.printer import Printer
  2362. from backend.app.services.bambu_ftp import download_file_bytes_async
  2363. service = ArchiveService(db)
  2364. archive = await service.get_archive(archive_id)
  2365. if not archive:
  2366. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  2367. return
  2368. if archive.timelapse_path:
  2369. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  2370. return
  2371. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2372. printer = result.scalar_one_or_none()
  2373. if not printer:
  2374. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  2375. return
  2376. video_files, found_path = await _list_timelapse_videos(printer)
  2377. if not video_files:
  2378. logger.info("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  2379. continue
  2380. logger.info("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  2381. for f in video_files[:5]:
  2382. logger.info("[TIMELAPSE] - %s", f.get("name"))
  2383. # Find files that are NEW (not in baseline snapshot)
  2384. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  2385. if new_files:
  2386. # Pick the first new file (there should typically be exactly one)
  2387. target = new_files[0]
  2388. file_name = target.get("name")
  2389. remote_path = target.get("path") or f"/timelapse/{file_name}"
  2390. logger.info(
  2391. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  2392. attempt,
  2393. file_name,
  2394. archive_id,
  2395. )
  2396. timelapse_data = await download_file_bytes_async(
  2397. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2398. )
  2399. if timelapse_data:
  2400. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  2401. if success:
  2402. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  2403. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2404. return
  2405. else:
  2406. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  2407. else:
  2408. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  2409. else:
  2410. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  2411. except Exception as e:
  2412. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  2413. # --- Phase 3: Fallback — try name matching against all files ---
  2414. if base_name:
  2415. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  2416. try:
  2417. async with async_session() as db:
  2418. from backend.app.models.printer import Printer
  2419. from backend.app.services.bambu_ftp import download_file_bytes_async
  2420. service = ArchiveService(db)
  2421. archive = await service.get_archive(archive_id)
  2422. if not archive or archive.timelapse_path:
  2423. return
  2424. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2425. printer = result.scalar_one_or_none()
  2426. if not printer:
  2427. return
  2428. video_files, found_path = await _list_timelapse_videos(printer)
  2429. for f in video_files:
  2430. fname = f.get("name", "")
  2431. if base_name.lower() in fname.lower():
  2432. remote_path = f.get("path") or f"/timelapse/{fname}"
  2433. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  2434. timelapse_data = await download_file_bytes_async(
  2435. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  2436. )
  2437. if timelapse_data:
  2438. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  2439. if success:
  2440. logger.info(
  2441. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  2442. )
  2443. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  2444. return
  2445. break # Only try the first name match
  2446. except Exception as e:
  2447. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  2448. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  2449. async def on_print_complete(printer_id: int, data: dict):
  2450. """Handle print completion - update the archive status."""
  2451. import time
  2452. logger = logging.getLogger(__name__)
  2453. start_time = time.time()
  2454. def log_timing(section: str):
  2455. elapsed = time.time() - start_time
  2456. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  2457. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  2458. # Drop the 3MF download cache for this printer (#972). The print is over,
  2459. # nothing else legitimately needs the bytes; keeping them would only risk
  2460. # handing a stale file to the next print if it reuses the same name.
  2461. clear_3mf_cache(printer_id)
  2462. try:
  2463. ws_data = {
  2464. "status": data.get("status"),
  2465. "filename": data.get("filename"),
  2466. "subtask_name": data.get("subtask_name"),
  2467. "timelapse_was_active": data.get("timelapse_was_active"),
  2468. }
  2469. await ws_manager.send_print_complete(printer_id, ws_data)
  2470. log_timing("WebSocket send_print_complete")
  2471. except Exception as e:
  2472. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  2473. # Capture user info before clearing (needed for print log entry)
  2474. _print_user_info = printer_manager.get_current_print_user(printer_id)
  2475. # Clear current print user tracking (Issue #206)
  2476. printer_manager.clear_current_print_user(printer_id)
  2477. # If the user explicitly stopped this print from the queue UI the printer will
  2478. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  2479. # correct "print stopped" notification/email is sent instead of a failure alert.
  2480. _raw_status = data.get("status", "completed")
  2481. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  2482. logger.info(
  2483. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  2484. _raw_status,
  2485. printer_id,
  2486. )
  2487. data = {**data, "status": "cancelled"}
  2488. _user_stopped_printers.discard(printer_id)
  2489. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  2490. # may have left material on the bed: a user can cancel ten hours into a
  2491. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  2492. # touchscreen-stop reports `aborted` rather than `cancelled` because
  2493. # `_user_stopped_printers` is only populated when the user stops via the
  2494. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  2495. # which auto-dispatched the next queued print onto a fouled bed two seconds
  2496. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  2497. # Auto Off power cycles and Bambuddy restarts.
  2498. _final_status = data.get("status", "completed")
  2499. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  2500. printer_manager.set_awaiting_plate_clear(printer_id, True)
  2501. # MQTT relay - publish print complete
  2502. try:
  2503. printer_info = printer_manager.get_printer(printer_id)
  2504. if printer_info:
  2505. await mqtt_relay.on_print_complete(
  2506. printer_id,
  2507. printer_info.name,
  2508. printer_info.serial_number,
  2509. data.get("filename", ""),
  2510. data.get("subtask_name", ""),
  2511. data.get("status", "completed"),
  2512. )
  2513. except Exception:
  2514. pass # Don't fail print complete callback if MQTT fails
  2515. filename = data.get("filename", "")
  2516. subtask_name = data.get("subtask_name", "")
  2517. if not filename and not subtask_name:
  2518. logger.warning("Print complete without filename or subtask_name")
  2519. return
  2520. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  2521. # Build list of possible keys to try (matching how they were registered in on_print_start)
  2522. possible_keys = []
  2523. # Try subtask_name variations first (most reliable for matching)
  2524. if subtask_name:
  2525. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  2526. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  2527. possible_keys.append((printer_id, subtask_name))
  2528. # Try filename variations
  2529. if filename:
  2530. # Extract just the filename if it's a path
  2531. fname = filename.split("/")[-1] if "/" in filename else filename
  2532. if fname.endswith(".3mf"):
  2533. possible_keys.append((printer_id, fname))
  2534. elif fname.endswith(".gcode"):
  2535. base_name = fname.rsplit(".", 1)[0]
  2536. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  2537. possible_keys.append((printer_id, f"{base_name}.3mf"))
  2538. possible_keys.append((printer_id, fname))
  2539. else:
  2540. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  2541. possible_keys.append((printer_id, f"{fname}.3mf"))
  2542. possible_keys.append((printer_id, fname))
  2543. # Also try full path versions
  2544. if filename.endswith(".3mf"):
  2545. possible_keys.append((printer_id, filename))
  2546. elif filename.endswith(".gcode"):
  2547. base_name = filename.rsplit(".", 1)[0]
  2548. possible_keys.append((printer_id, f"{base_name}.3mf"))
  2549. possible_keys.append((printer_id, filename))
  2550. else:
  2551. possible_keys.append((printer_id, f"{filename}.3mf"))
  2552. possible_keys.append((printer_id, filename))
  2553. # Find the archive for this print
  2554. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  2555. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  2556. archive_id = None
  2557. for key in possible_keys:
  2558. archive_id = _active_prints.pop(key, None)
  2559. if archive_id:
  2560. logger.info("Found archive %s with key %s", archive_id, key)
  2561. # Also clean up any other keys pointing to this archive
  2562. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  2563. for k in keys_to_remove:
  2564. _active_prints.pop(k, None)
  2565. break
  2566. if not archive_id:
  2567. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  2568. async with async_session() as db:
  2569. from backend.app.models.archive import PrintArchive
  2570. # Try matching by subtask_name (stored as print_name) first
  2571. if subtask_name:
  2572. result = await db.execute(
  2573. select(PrintArchive)
  2574. .where(PrintArchive.printer_id == printer_id)
  2575. .where(PrintArchive.status == "printing")
  2576. .where(
  2577. or_(
  2578. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  2579. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  2580. )
  2581. )
  2582. .order_by(PrintArchive.created_at.desc())
  2583. .limit(1)
  2584. )
  2585. archive = result.scalar_one_or_none()
  2586. if archive:
  2587. archive_id = archive.id
  2588. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  2589. # Also try by filename
  2590. if not archive_id and filename:
  2591. result = await db.execute(
  2592. select(PrintArchive)
  2593. .where(PrintArchive.printer_id == printer_id)
  2594. .where(PrintArchive.filename == filename)
  2595. .where(PrintArchive.status == "printing")
  2596. .order_by(PrintArchive.created_at.desc())
  2597. .limit(1)
  2598. )
  2599. archive = result.scalar_one_or_none()
  2600. if archive:
  2601. archive_id = archive.id
  2602. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374)
  2603. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S)
  2604. # auto-start files found in root on power cycle, causing ghost prints.
  2605. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  2606. try:
  2607. if subtask_name:
  2608. async with async_session() as db:
  2609. from backend.app.models.printer import Printer
  2610. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2611. printer = result.scalar_one_or_none()
  2612. if printer:
  2613. from backend.app.services.bambu_ftp import delete_file_async
  2614. # Try both .3mf and .gcode extensions — the printer may have either
  2615. for ext in (".3mf", ".gcode"):
  2616. remote_path = f"/{subtask_name}{ext}"
  2617. # Retry up to 3 times — the printer may still lock the filesystem briefly after a print ends
  2618. for attempt in range(1, 4):
  2619. try:
  2620. delete_result = await delete_file_async(
  2621. printer.ip_address,
  2622. printer.access_code,
  2623. remote_path,
  2624. printer_model=printer.model,
  2625. )
  2626. if delete_result:
  2627. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  2628. break
  2629. except Exception as e:
  2630. delete_result = False
  2631. logger.warning(
  2632. "SD card cleanup attempt %d/3 raised for %s: %s",
  2633. attempt,
  2634. remote_path,
  2635. e,
  2636. )
  2637. if not delete_result and attempt < 3:
  2638. await asyncio.sleep(2)
  2639. elif not delete_result:
  2640. logger.warning(
  2641. "SD card cleanup failed after 3 attempts for %s (file may linger on SD card)",
  2642. remote_path,
  2643. )
  2644. except Exception as e:
  2645. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  2646. log_timing("SD card cleanup")
  2647. # Update queue item status early — must run before the archive_id early-return
  2648. # so queue items don't get stuck in "printing" when archive lookup fails.
  2649. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  2650. queue_item_id = None
  2651. queue_status = None
  2652. queue_auto_off = False
  2653. try:
  2654. from backend.app.core.database import run_with_retry
  2655. from backend.app.models.print_queue import PrintQueueItem
  2656. async def _update_queue_status(db):
  2657. nonlocal queue_item_id, queue_status, queue_auto_off
  2658. result = await db.execute(
  2659. select(PrintQueueItem)
  2660. .where(PrintQueueItem.printer_id == printer_id)
  2661. .where(PrintQueueItem.status == "printing")
  2662. )
  2663. printing_items = list(result.scalars().all())
  2664. if len(printing_items) > 1:
  2665. logger.warning(
  2666. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  2667. printer_id,
  2668. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  2669. )
  2670. item = printing_items[0] if printing_items else None
  2671. if item:
  2672. queue_status = data.get("status", "completed")
  2673. # MQTT sends "aborted" for cancelled prints; normalise to
  2674. # "cancelled" so it matches the queue schema Literal.
  2675. if queue_status == "aborted":
  2676. queue_status = "cancelled"
  2677. item.status = queue_status
  2678. item.completed_at = datetime.now(timezone.utc)
  2679. if queue_status == "failed" and not item.error_message:
  2680. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  2681. # Bump usage counters on the source library file so admins can
  2682. # sort by "last printed" and (eventually) auto-purge stale
  2683. # files — #1008.
  2684. await _bump_library_file_usage_if_completed(db, item, queue_status)
  2685. await db.commit()
  2686. queue_item_id = item.id
  2687. queue_auto_off = item.auto_off_after
  2688. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  2689. await run_with_retry(_update_queue_status, label="queue status update")
  2690. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  2691. # their own sessions and have their own error handling — no retry needed.
  2692. if queue_item_id is not None:
  2693. # MQTT relay - publish queue job completed
  2694. try:
  2695. printer_info = printer_manager.get_printer(printer_id)
  2696. await mqtt_relay.on_queue_job_completed(
  2697. job_id=queue_item_id,
  2698. filename=filename or subtask_name,
  2699. printer_id=printer_id,
  2700. printer_name=printer_info.name if printer_info else "Unknown",
  2701. status=queue_status,
  2702. )
  2703. except Exception:
  2704. pass # Don't fail if MQTT fails
  2705. # Check if queue is now empty and send notification
  2706. try:
  2707. from sqlalchemy import func as sa_func
  2708. async with async_session() as db:
  2709. count_result = await db.execute(
  2710. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  2711. )
  2712. pending_count = count_result.scalar() or 0
  2713. if pending_count == 0:
  2714. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  2715. completed_result = await db.execute(
  2716. select(sa_func.count(PrintQueueItem.id)).where(
  2717. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  2718. PrintQueueItem.completed_at >= today_start,
  2719. )
  2720. )
  2721. completed_count = completed_result.scalar() or 1
  2722. await notification_service.on_queue_completed(
  2723. completed_count=completed_count,
  2724. db=db,
  2725. )
  2726. except Exception:
  2727. pass # Don't fail if notification fails
  2728. # Handle auto_off_after - power off printer if requested (after cooldown)
  2729. if queue_auto_off:
  2730. async with async_session() as db:
  2731. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2732. plugs = list(result.scalars().all())
  2733. enabled_plugs = [p for p in plugs if p.enabled]
  2734. if enabled_plugs:
  2735. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  2736. async def cooldown_and_poweroff(pid: int, plug_ids: list[int]):
  2737. # Wait for nozzle to cool down
  2738. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  2739. # Re-fetch plugs in new session and turn off each one
  2740. async with async_session() as new_db:
  2741. for plug_id in plug_ids:
  2742. try:
  2743. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  2744. p = result.scalar_one_or_none()
  2745. if p and p.enabled:
  2746. service = await smart_plug_manager.get_service_for_plug(p, new_db)
  2747. success = await service.turn_off(p)
  2748. if success:
  2749. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  2750. else:
  2751. logger.warning("Failed to power off plug '%s' for printer %s", p.name, pid)
  2752. except Exception as e:
  2753. logger.warning("Failed to power off plug %s for printer %s: %s", plug_id, pid, e)
  2754. asyncio.create_task(cooldown_and_poweroff(printer_id, [p.id for p in enabled_plugs]))
  2755. except Exception as e:
  2756. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  2757. log_timing("Queue item update")
  2758. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  2759. # Must run before archive_id early-return so it fires for all prints (including
  2760. # prints started from BambuStudio/touchscreen that have no archive).
  2761. if data.get("status") == "completed":
  2762. try:
  2763. from backend.app.api.routes.settings import get_setting
  2764. async with async_session() as db:
  2765. threshold_str = await get_setting(db, "bed_cooled_threshold")
  2766. threshold = float(threshold_str) if threshold_str else 35.0
  2767. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  2768. async with async_session() as db:
  2769. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  2770. if providers:
  2771. _bed_cool_waiters[printer_id] = {
  2772. "threshold": threshold,
  2773. "filename": filename or subtask_name or "",
  2774. "registered_at": time.time(),
  2775. }
  2776. logger.info(
  2777. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  2778. printer_id,
  2779. threshold,
  2780. )
  2781. else:
  2782. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  2783. except Exception as e:
  2784. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  2785. # --- Track filament consumption (must run before archive_id early-return so usage
  2786. # is recorded even when auto-archive is disabled) ---
  2787. usage_results: list[dict] = []
  2788. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  2789. stored_ams_mapping = data.get("ams_mapping")
  2790. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  2791. if not stored_ams_mapping and archive_id:
  2792. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  2793. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  2794. try:
  2795. async with async_session() as db:
  2796. from backend.app.api.routes.settings import get_setting
  2797. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2798. if not _spoolman_on or _spoolman_on.lower() != "true":
  2799. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  2800. async with async_session() as db:
  2801. usage_results = await usage_on_print_complete(
  2802. printer_id,
  2803. data,
  2804. printer_manager,
  2805. db,
  2806. archive_id=archive_id,
  2807. ams_mapping=stored_ams_mapping,
  2808. )
  2809. if usage_results:
  2810. await ws_manager.broadcast(
  2811. {
  2812. "type": "spool_usage_logged",
  2813. "printer_id": printer_id,
  2814. "usage": usage_results,
  2815. }
  2816. )
  2817. log_timing("Usage tracker")
  2818. except Exception as e:
  2819. logger.warning("Usage tracker on_print_complete failed: %s", e)
  2820. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  2821. if archive_id:
  2822. if data.get("status") == "completed":
  2823. try:
  2824. await _report_spoolman_usage(printer_id, archive_id)
  2825. log_timing("Spoolman usage report")
  2826. except Exception as e:
  2827. logger.warning("Spoolman usage reporting failed: %s", e)
  2828. else:
  2829. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  2830. try:
  2831. async with async_session() as db:
  2832. await _cleanup_spoolman_tracking(
  2833. printer_id,
  2834. archive_id,
  2835. db,
  2836. last_layer_num=data.get("last_layer_num"),
  2837. last_progress=data.get("last_progress"),
  2838. )
  2839. except Exception as e:
  2840. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  2841. log_timing("Filament usage tracking")
  2842. if not archive_id:
  2843. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  2844. # Still send print-complete/failed/stopped notifications even without an archive.
  2845. # Try to enrich with queue/library-file data so user-specific emails work too.
  2846. async def _notify_no_archive():
  2847. try:
  2848. async with async_session() as db:
  2849. from backend.app.models.library import LibraryFile
  2850. from backend.app.models.print_queue import PrintQueueItem
  2851. from backend.app.models.printer import Printer
  2852. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2853. printer_obj = result.scalar_one_or_none()
  2854. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  2855. # Try to find the most-recent queue item for this printer so we can
  2856. # recover created_by_id and estimated print time.
  2857. # NOTE: By the time this task runs the queue item status has already
  2858. # been updated to a terminal state (completed/failed/cancelled), so
  2859. # we look for recently-completed items (within the last 5 minutes).
  2860. no_archive_data: dict | None = None
  2861. try:
  2862. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  2863. q_result = await db.execute(
  2864. select(PrintQueueItem)
  2865. .where(PrintQueueItem.printer_id == printer_id)
  2866. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  2867. .where(PrintQueueItem.completed_at >= cutoff)
  2868. .order_by(PrintQueueItem.completed_at.desc())
  2869. .limit(1)
  2870. )
  2871. queue_item = q_result.scalar_one_or_none()
  2872. if queue_item:
  2873. no_archive_data = {"created_by_id": queue_item.created_by_id}
  2874. # Pull estimated time from library file when available
  2875. if queue_item.library_file_id:
  2876. lib_result = await db.execute(
  2877. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  2878. )
  2879. lib_file = lib_result.scalar_one_or_none()
  2880. if lib_file and lib_file.print_time_seconds:
  2881. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  2882. except Exception as lookup_err:
  2883. logger.debug(
  2884. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  2885. )
  2886. # Enrich with usage tracker results (captured in enclosing scope)
  2887. if usage_results:
  2888. if no_archive_data is None:
  2889. no_archive_data = {}
  2890. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  2891. if total_from_usage > 0:
  2892. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  2893. no_archive_data["usage_results"] = usage_results
  2894. # Try MQTT remaining_time for print duration when no queue/library data
  2895. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  2896. mqtt_remaining = data.get("remaining_time")
  2897. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  2898. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  2899. ps = data.get("status", "completed")
  2900. logger.info(
  2901. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  2902. )
  2903. await notification_service.on_print_complete(
  2904. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  2905. )
  2906. # Send user-specific email if we have a created_by_id
  2907. if no_archive_data and no_archive_data.get("created_by_id"):
  2908. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  2909. await _dispatch_user_print_email(
  2910. ps,
  2911. no_archive_data["created_by_id"],
  2912. p_name,
  2913. raw_filename,
  2914. db,
  2915. )
  2916. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  2917. except Exception as e:
  2918. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  2919. task = asyncio.create_task(_notify_no_archive())
  2920. task.add_done_callback(lambda _t: None)
  2921. return
  2922. log_timing("Archive lookup")
  2923. # Update archive status
  2924. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  2925. try:
  2926. async with async_session() as db:
  2927. service = ArchiveService(db)
  2928. status = data.get("status", "completed")
  2929. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  2930. if hms_errors:
  2931. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  2932. failure_reason = derive_failure_reason(status, hms_errors)
  2933. if failure_reason:
  2934. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  2935. elif status == "failed" and hms_errors:
  2936. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  2937. await service.update_archive_status(
  2938. archive_id,
  2939. status=status,
  2940. completed_at=(
  2941. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  2942. ),
  2943. failure_reason=failure_reason,
  2944. )
  2945. logger.info(
  2946. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  2947. )
  2948. await ws_manager.send_archive_updated(
  2949. {
  2950. "id": archive_id,
  2951. "status": status,
  2952. }
  2953. )
  2954. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  2955. # MQTT relay - publish archive updated
  2956. try:
  2957. await mqtt_relay.on_archive_updated(
  2958. archive_id=archive_id,
  2959. print_name=filename or subtask_name,
  2960. status=status,
  2961. )
  2962. except Exception:
  2963. pass # Don't fail if MQTT fails
  2964. except Exception as e:
  2965. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  2966. # Continue with other operations even if archive update fails
  2967. log_timing("Archive status update")
  2968. # Write independent print log entry (separate table, never touches archives)
  2969. try:
  2970. async with async_session() as db:
  2971. from backend.app.models.archive import PrintArchive
  2972. from backend.app.services.print_log import write_log_entry
  2973. archive = await db.get(PrintArchive, archive_id)
  2974. if archive:
  2975. # Back-fill created_by_id on reprint (#730): reprint reuses the
  2976. # source archive row rather than creating a new one, so an
  2977. # archive that was auto-created from a printer-initiated
  2978. # print (created_by_id=NULL) would otherwise stay unattributed
  2979. # forever. When we have a print-session user AND the archive
  2980. # has no attribution yet, credit the current user. Never
  2981. # overwrite an existing attribution — the original uploader
  2982. # keeps ownership.
  2983. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  2984. if archive.created_by_id is None and _print_user_id is not None:
  2985. archive.created_by_id = _print_user_id
  2986. p_info = printer_manager.get_printer(printer_id)
  2987. await write_log_entry(
  2988. db,
  2989. status=data.get("status", "completed"),
  2990. print_name=archive.print_name,
  2991. printer_name=p_info.name if p_info else None,
  2992. printer_id=printer_id,
  2993. started_at=archive.started_at,
  2994. completed_at=archive.completed_at,
  2995. filament_type=archive.filament_type,
  2996. filament_color=archive.filament_color,
  2997. filament_used_grams=archive.filament_used_grams,
  2998. thumbnail_path=archive.thumbnail_path,
  2999. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  3000. )
  3001. await db.commit()
  3002. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  3003. except Exception as e:
  3004. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  3005. log_timing("Print log entry")
  3006. # Run slow operations as background tasks to avoid blocking the event loop
  3007. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  3008. async def _background_energy_calculation():
  3009. """Calculate and save energy usage in background.
  3010. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  3011. backend restart no longer loses per-print energy data).
  3012. """
  3013. try:
  3014. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  3015. async with async_session() as db:
  3016. from backend.app.models.archive import PrintArchive
  3017. archive = await db.get(PrintArchive, archive_id)
  3018. if archive is None:
  3019. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  3020. return
  3021. starting_kwh = archive.energy_start_kwh
  3022. if starting_kwh is None:
  3023. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  3024. return
  3025. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3026. plug = plug_result.scalar_one_or_none()
  3027. if plug is None:
  3028. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  3029. return
  3030. energy = await _get_plug_energy(plug, db)
  3031. logger.info("[ENERGY-BG] Energy response: %s", energy)
  3032. if not energy or energy.get("total") is None:
  3033. logger.warning("[ENERGY-BG] No 'total' in energy response")
  3034. return
  3035. energy_used = round(energy["total"] - starting_kwh, 4)
  3036. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  3037. if energy_used < 0:
  3038. logger.warning(
  3039. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  3040. archive_id,
  3041. starting_kwh,
  3042. energy["total"],
  3043. )
  3044. return
  3045. from backend.app.api.routes.settings import get_setting
  3046. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  3047. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  3048. archive.energy_kwh = energy_used
  3049. archive.energy_cost = round(energy_used * cost_per_kwh, 3)
  3050. await db.commit()
  3051. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, archive.energy_cost)
  3052. except Exception as e:
  3053. logger.warning("[ENERGY-BG] Failed: %s", e)
  3054. async def _background_finish_photo() -> str | None:
  3055. """Capture finish photo in background. Returns photo filename if captured."""
  3056. try:
  3057. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  3058. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3059. async with async_session() as db:
  3060. from backend.app.api.routes.settings import get_setting
  3061. capture_enabled = await get_setting(db, "capture_finish_photo")
  3062. if capture_enabled is None or capture_enabled.lower() == "true":
  3063. from backend.app.models.printer import Printer
  3064. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3065. printer = result.scalar_one_or_none()
  3066. if printer and archive_id:
  3067. from backend.app.models.archive import PrintArchive
  3068. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3069. archive = result.scalar_one_or_none()
  3070. if archive:
  3071. import uuid
  3072. from datetime import datetime
  3073. from pathlib import Path
  3074. if archive.file_path:
  3075. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  3076. else:
  3077. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  3078. archive_dir = app_settings.archive_dir / str(archive.id)
  3079. photo_filename = None
  3080. # Check for external camera first
  3081. if printer.external_camera_enabled and printer.external_camera_url:
  3082. logger.info("[PHOTO-BG] Using external camera")
  3083. from backend.app.services.external_camera import capture_frame
  3084. frame_data = await capture_frame(
  3085. printer.external_camera_url,
  3086. printer.external_camera_type or "mjpeg",
  3087. snapshot_url=printer.external_camera_snapshot_url,
  3088. )
  3089. if frame_data:
  3090. photos_dir = archive_dir / "photos"
  3091. photos_dir.mkdir(parents=True, exist_ok=True)
  3092. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  3093. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  3094. photo_path = photos_dir / photo_filename
  3095. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  3096. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  3097. else:
  3098. # Check if camera stream is active - use buffered frame to avoid freeze
  3099. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  3100. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3101. active_chamber_for_printer = [
  3102. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  3103. ]
  3104. buffered_frame = get_buffered_frame(printer_id)
  3105. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  3106. # Use frame from active stream
  3107. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  3108. photos_dir = archive_dir / "photos"
  3109. photos_dir.mkdir(parents=True, exist_ok=True)
  3110. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  3111. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  3112. photo_path = photos_dir / photo_filename
  3113. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  3114. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  3115. else:
  3116. # No active stream - capture new frame
  3117. from backend.app.services.camera import capture_finish_photo
  3118. photo_filename = await capture_finish_photo(
  3119. printer_id=printer_id,
  3120. ip_address=printer.ip_address,
  3121. access_code=printer.access_code,
  3122. model=printer.model,
  3123. archive_dir=archive_dir,
  3124. )
  3125. if photo_filename:
  3126. photos = archive.photos or []
  3127. photos.append(photo_filename)
  3128. archive.photos = photos
  3129. await db.commit()
  3130. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  3131. return photo_filename
  3132. return None
  3133. except Exception as e:
  3134. logger.warning("[PHOTO-BG] Failed: %s", e)
  3135. return None
  3136. asyncio.create_task(_background_energy_calculation())
  3137. # Photo capture task - result will be used by notifications
  3138. photo_task = asyncio.create_task(_background_finish_photo())
  3139. log_timing("Background tasks scheduled (energy, photo)")
  3140. # Also run smart plug, notifications, and maintenance as background tasks
  3141. print_status = data.get("status", "completed")
  3142. async def _background_smart_plug():
  3143. """Handle smart plug automation in background."""
  3144. try:
  3145. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  3146. async with async_session() as db:
  3147. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  3148. logger.info("[AUTO-OFF-BG] Completed")
  3149. except Exception as e:
  3150. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  3151. async def _background_notifications(finish_photo_filename: str | None = None):
  3152. """Send print complete notifications in background."""
  3153. try:
  3154. logger.info(
  3155. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  3156. )
  3157. async with async_session() as db:
  3158. from backend.app.models.archive import PrintArchive
  3159. from backend.app.models.printer import Printer
  3160. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3161. printer = result.scalar_one_or_none()
  3162. printer_name = printer.name if printer else f"Printer {printer_id}"
  3163. archive_data = None
  3164. if archive_id:
  3165. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3166. archive = archive_result.scalar_one_or_none()
  3167. if archive:
  3168. # Actual elapsed time from started_at/completed_at when both are
  3169. # populated (every terminal status sets completed_at after #1198).
  3170. # Falls back to None so the notification path can decide whether to
  3171. # render the slicer estimate as a last resort.
  3172. actual_time_seconds = None
  3173. if archive.started_at and archive.completed_at:
  3174. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  3175. if elapsed > 0:
  3176. actual_time_seconds = int(elapsed)
  3177. archive_data = {
  3178. "print_time_seconds": archive.print_time_seconds,
  3179. "actual_time_seconds": actual_time_seconds,
  3180. "actual_filament_grams": archive.filament_used_grams,
  3181. "failure_reason": archive.failure_reason,
  3182. "created_by_id": archive.created_by_id,
  3183. }
  3184. # Scale filament usage for partial prints
  3185. if print_status != "completed" and archive.filament_used_grams:
  3186. progress = data.get("progress") or 0
  3187. scale = max(0.0, min(progress / 100.0, 1.0))
  3188. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  3189. archive_data["progress"] = progress
  3190. # Pass per-slot data from archive.extra_data
  3191. if archive.extra_data and archive.extra_data.get("filament_slots"):
  3192. slots = archive.extra_data["filament_slots"]
  3193. if print_status != "completed":
  3194. scale = max(0.0, min((data.get("progress") or 0) / 100.0, 1.0))
  3195. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  3196. archive_data["filament_slots"] = slots
  3197. # Enrich filament_grams from usage_results when archive has no 3MF data
  3198. if not archive_data.get("actual_filament_grams") and usage_results:
  3199. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  3200. if total_from_usage > 0:
  3201. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  3202. # Pass usage tracker results for AMS slot info in notifications
  3203. if usage_results:
  3204. archive_data["usage_results"] = usage_results
  3205. # Add finish photo URL and image bytes if available
  3206. if finish_photo_filename:
  3207. from backend.app.api.routes.settings import get_setting
  3208. external_url = await get_setting(db, "external_url")
  3209. if external_url:
  3210. external_url = external_url.rstrip("/")
  3211. archive_data["finish_photo_url"] = (
  3212. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  3213. )
  3214. else:
  3215. # Fallback to relative URL (won't work for external services)
  3216. archive_data["finish_photo_url"] = (
  3217. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  3218. )
  3219. # Read finish photo bytes for image attachment (e.g. Pushover)
  3220. try:
  3221. from pathlib import Path
  3222. photo_path = (
  3223. app_settings.base_dir
  3224. / Path(archive.file_path).parent
  3225. / "photos"
  3226. / finish_photo_filename
  3227. )
  3228. if photo_path.exists():
  3229. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3230. if len(photo_bytes) <= 2_500_000:
  3231. archive_data["image_data"] = photo_bytes
  3232. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3233. else:
  3234. logger.warning(
  3235. f"[NOTIFY-BG] Finish photo too large for attachment: "
  3236. f"{len(photo_bytes)} bytes"
  3237. )
  3238. except Exception as e:
  3239. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3240. await notification_service.on_print_complete(
  3241. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  3242. )
  3243. # Send user-specific email notification
  3244. if archive_data:
  3245. created_by_id = archive_data.get("created_by_id")
  3246. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  3247. await _dispatch_user_print_email(
  3248. print_status,
  3249. created_by_id,
  3250. printer_name,
  3251. raw_filename,
  3252. db,
  3253. )
  3254. logger.info("[NOTIFY-BG] Completed")
  3255. except Exception as e:
  3256. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  3257. async def _background_maintenance_check():
  3258. """Check for maintenance due in background."""
  3259. if print_status != "completed":
  3260. return
  3261. try:
  3262. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  3263. async with async_session() as db:
  3264. from backend.app.models.printer import Printer
  3265. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3266. printer = result.scalar_one_or_none()
  3267. printer_name = printer.name if printer else f"Printer {printer_id}"
  3268. await ensure_default_types(db)
  3269. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  3270. items_needing_attention = [
  3271. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  3272. for item in overview.maintenance_items
  3273. if item.enabled and (item.is_due or item.is_warning)
  3274. ]
  3275. if items_needing_attention:
  3276. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  3277. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  3278. # MQTT relay - publish maintenance alerts
  3279. for item in items_needing_attention:
  3280. try:
  3281. await mqtt_relay.on_maintenance_alert(
  3282. printer_id=printer_id,
  3283. printer_name=printer_name,
  3284. maintenance_type=item["name"],
  3285. current_value=0, # Not easily available here
  3286. threshold=0, # Not easily available here
  3287. )
  3288. except Exception:
  3289. pass # Don't fail if MQTT fails
  3290. else:
  3291. logger.info("[MAINT-BG] Completed (no items need attention)")
  3292. except Exception as e:
  3293. logger.warning("[MAINT-BG] Failed: %s", e)
  3294. asyncio.create_task(_background_smart_plug())
  3295. asyncio.create_task(_background_maintenance_check())
  3296. # Notification task waits for photo capture to complete first (with timeout)
  3297. async def _photo_then_notify():
  3298. """Wait for photo capture, then send notification with photo URL."""
  3299. finish_photo = None
  3300. try:
  3301. finish_photo = await asyncio.wait_for(photo_task, timeout=45)
  3302. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  3303. except TimeoutError:
  3304. logger.warning("[PHOTO-NOTIFY] Photo capture timed out after 45s, sending notification without photo")
  3305. except Exception as e:
  3306. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  3307. try:
  3308. await _background_notifications(finish_photo)
  3309. except Exception as e:
  3310. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  3311. asyncio.create_task(_photo_then_notify())
  3312. # Stitch external camera layer timelapse if session was active
  3313. print_status = data.get("status", "completed")
  3314. async def _background_layer_timelapse():
  3315. """Stitch layer timelapse and attach to archive."""
  3316. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  3317. try:
  3318. if print_status == "completed":
  3319. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  3320. timelapse_path = await tl_complete(printer_id)
  3321. if timelapse_path and archive_id:
  3322. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  3323. async with async_session() as db:
  3324. service = ArchiveService(db)
  3325. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  3326. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  3327. # Clean up the temp file
  3328. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  3329. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  3330. elif timelapse_path:
  3331. # Timelapse created but no archive - just clean up
  3332. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  3333. else:
  3334. # Print failed or cancelled - cancel timelapse session
  3335. cancel_session(printer_id)
  3336. logger.info(
  3337. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  3338. )
  3339. except Exception as e:
  3340. logger.warning("[LAYER-TL] Failed: %s", e)
  3341. # Try to cancel session on error
  3342. try:
  3343. cancel_session(printer_id)
  3344. except Exception:
  3345. pass # Best-effort timelapse session cancellation on error
  3346. asyncio.create_task(_background_layer_timelapse())
  3347. log_timing("All background tasks scheduled")
  3348. # Auto-scan for timelapse if recording was active during the print
  3349. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  3350. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  3351. # Schedule timelapse scan as background task with retries
  3352. # The printer needs time to encode the video after print completion
  3353. baseline = _timelapse_baselines.pop(printer_id, None)
  3354. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id, baseline))
  3355. log_timing("Timelapse scan scheduled")
  3356. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  3357. # AMS sensor history recording
  3358. _ams_history_task: asyncio.Task | None = None
  3359. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  3360. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  3361. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  3362. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  3363. _ams_alarm_cooldown: dict[str, datetime] = {}
  3364. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  3365. async def record_ams_history():
  3366. """Background task to record AMS humidity and temperature data."""
  3367. logger = logging.getLogger(__name__)
  3368. # Wait a short time for MQTT connections to establish on startup
  3369. await asyncio.sleep(10)
  3370. while True:
  3371. try:
  3372. from backend.app.models.ams_history import AMSSensorHistory
  3373. from backend.app.models.printer import Printer
  3374. from backend.app.models.settings import Settings
  3375. async with async_session() as db:
  3376. # Get all active printers
  3377. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  3378. printers = result.scalars().all()
  3379. # Get alarm thresholds from settings
  3380. humidity_threshold = 60.0 # Default: fair threshold
  3381. temp_threshold = 35.0 # Default: fair threshold
  3382. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  3383. setting = result.scalar_one_or_none()
  3384. if setting:
  3385. try:
  3386. humidity_threshold = float(setting.value)
  3387. except (ValueError, TypeError):
  3388. pass # Keep default threshold if stored value is invalid
  3389. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  3390. setting = result.scalar_one_or_none()
  3391. if setting:
  3392. try:
  3393. temp_threshold = float(setting.value)
  3394. except (ValueError, TypeError):
  3395. pass # Keep default threshold if stored value is invalid
  3396. recorded_count = 0
  3397. for printer in printers:
  3398. # Get current state from printer manager
  3399. state = printer_manager.get_status(printer.id)
  3400. if not state or not state.connected or not state.raw_data:
  3401. continue # Skip disconnected printers - don't use stale data
  3402. raw_data = state.raw_data
  3403. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  3404. continue
  3405. # Record data for each AMS unit
  3406. for ams_data in raw_data["ams"]:
  3407. ams_id = int(ams_data.get("id", 0))
  3408. # Get humidity (prefer humidity_raw)
  3409. humidity_raw = ams_data.get("humidity_raw")
  3410. humidity_idx = ams_data.get("humidity")
  3411. humidity = None
  3412. if humidity_raw is not None:
  3413. try:
  3414. humidity = float(humidity_raw)
  3415. except (ValueError, TypeError):
  3416. pass # Skip unparseable humidity; will try fallback
  3417. if humidity is None and humidity_idx is not None:
  3418. try:
  3419. humidity = float(humidity_idx)
  3420. except (ValueError, TypeError):
  3421. pass # Skip unparseable humidity index value
  3422. # Get temperature
  3423. temperature = None
  3424. temp_str = ams_data.get("temp")
  3425. if temp_str is not None:
  3426. try:
  3427. temperature = float(temp_str)
  3428. except (ValueError, TypeError):
  3429. pass # Skip unparseable temperature value
  3430. # Skip if no data
  3431. if humidity is None and temperature is None:
  3432. continue
  3433. # Record the data point
  3434. history = AMSSensorHistory(
  3435. printer_id=printer.id,
  3436. ams_id=ams_id,
  3437. humidity=humidity,
  3438. humidity_raw=float(humidity_raw) if humidity_raw else None,
  3439. temperature=temperature,
  3440. )
  3441. db.add(history)
  3442. recorded_count += 1
  3443. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  3444. is_ams_ht = ams_id >= 128
  3445. if is_ams_ht:
  3446. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  3447. else:
  3448. ams_label = f"AMS-{chr(65 + ams_id)}"
  3449. # Check humidity alarm (only if above threshold)
  3450. if humidity is not None and humidity > humidity_threshold:
  3451. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  3452. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  3453. now = datetime.now(timezone.utc)
  3454. if (
  3455. last_alarm is None
  3456. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  3457. ):
  3458. _ams_alarm_cooldown[cooldown_key] = now
  3459. logger.info(
  3460. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  3461. )
  3462. try:
  3463. # Call different notification method based on AMS type
  3464. if is_ams_ht:
  3465. await notification_service.on_ams_ht_humidity_high(
  3466. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  3467. )
  3468. else:
  3469. await notification_service.on_ams_humidity_high(
  3470. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  3471. )
  3472. except Exception as e:
  3473. logger.warning("Failed to send humidity alarm: %s", e)
  3474. # Check temperature alarm (only if above threshold)
  3475. if temperature is not None and temperature > temp_threshold:
  3476. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  3477. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  3478. now = datetime.now(timezone.utc)
  3479. if (
  3480. last_alarm is None
  3481. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  3482. ):
  3483. _ams_alarm_cooldown[cooldown_key] = now
  3484. logger.info(
  3485. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  3486. )
  3487. try:
  3488. # Call different notification method based on AMS type
  3489. if is_ams_ht:
  3490. await notification_service.on_ams_ht_temperature_high(
  3491. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  3492. )
  3493. else:
  3494. await notification_service.on_ams_temperature_high(
  3495. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  3496. )
  3497. except Exception as e:
  3498. logger.warning("Failed to send temperature alarm: %s", e)
  3499. await db.commit()
  3500. if recorded_count > 0:
  3501. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  3502. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  3503. global _ams_cleanup_counter
  3504. _ams_cleanup_counter += 1
  3505. if _ams_cleanup_counter >= 288:
  3506. _ams_cleanup_counter = 0
  3507. # Get retention days from settings
  3508. from backend.app.models.settings import Settings
  3509. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  3510. setting = result.scalar_one_or_none()
  3511. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  3512. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  3513. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  3514. await db.commit()
  3515. if result.rowcount > 0:
  3516. logger.info(
  3517. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  3518. )
  3519. # Wait until next recording interval
  3520. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  3521. except asyncio.CancelledError:
  3522. break
  3523. except Exception as e:
  3524. logger.warning("AMS history recording failed: %s", e)
  3525. await asyncio.sleep(60) # Wait a bit before retrying
  3526. def start_ams_history_recording():
  3527. """Start the AMS history recording background task."""
  3528. global _ams_history_task
  3529. if _ams_history_task is None:
  3530. _ams_history_task = asyncio.create_task(record_ams_history())
  3531. logging.getLogger(__name__).info("AMS history recording started")
  3532. def stop_ams_history_recording():
  3533. """Stop the AMS history recording background task."""
  3534. global _ams_history_task
  3535. if _ams_history_task:
  3536. _ams_history_task.cancel()
  3537. _ams_history_task = None
  3538. logging.getLogger(__name__).info("AMS history recording stopped")
  3539. # Printer runtime tracking
  3540. _runtime_tracking_task: asyncio.Task | None = None
  3541. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  3542. async def track_printer_runtime():
  3543. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  3544. logger = logging.getLogger(__name__)
  3545. # Wait for MQTT connections to establish on startup
  3546. await asyncio.sleep(15)
  3547. while True:
  3548. try:
  3549. from backend.app.models.printer import Printer
  3550. # Fetch printer IDs in a short-lived read-only session
  3551. async with async_session() as db:
  3552. result = await db.execute(
  3553. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  3554. Printer.is_active.is_(True)
  3555. )
  3556. )
  3557. printer_rows = result.all()
  3558. now = datetime.now(timezone.utc)
  3559. updated_count = 0
  3560. # Update each printer in its own short session to minimise write-lock
  3561. # hold time and avoid blocking critical commits like queue status
  3562. # updates (#897).
  3563. for pid, pname, runtime_secs, last_update in printer_rows:
  3564. state = printer_manager.get_status(pid)
  3565. if not state:
  3566. logger.debug("[%s] Runtime tracking: no state available", pname)
  3567. continue
  3568. if not state.connected:
  3569. logger.debug("[%s] Runtime tracking: not connected", pname)
  3570. continue
  3571. needs_commit = False
  3572. new_runtime = runtime_secs
  3573. new_last_update = last_update
  3574. if state.state in ("RUNNING", "PAUSE"):
  3575. if last_update:
  3576. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  3577. elapsed = (now - lu).total_seconds()
  3578. if elapsed > 0:
  3579. new_runtime = runtime_secs + int(elapsed)
  3580. updated_count += 1
  3581. needs_commit = True
  3582. logger.debug(
  3583. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  3584. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  3585. )
  3586. else:
  3587. needs_commit = True
  3588. logger.debug("[%s] Runtime tracking: first active detection", pname)
  3589. new_last_update = now
  3590. else:
  3591. if last_update is not None:
  3592. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  3593. new_last_update = None
  3594. needs_commit = True
  3595. if needs_commit:
  3596. try:
  3597. async with async_session() as db:
  3598. result = await db.execute(select(Printer).where(Printer.id == pid))
  3599. printer = result.scalar_one_or_none()
  3600. if printer:
  3601. printer.runtime_seconds = new_runtime
  3602. printer.last_runtime_update = new_last_update
  3603. await db.commit()
  3604. except Exception as e:
  3605. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  3606. if updated_count > 0:
  3607. logger.debug("Updated runtime for %s printer(s)", updated_count)
  3608. except asyncio.CancelledError:
  3609. logger.info("Runtime tracking cancelled")
  3610. break
  3611. except Exception as e:
  3612. logger.warning("Runtime tracking failed: %s", e)
  3613. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  3614. def start_runtime_tracking():
  3615. """Start the printer runtime tracking background task."""
  3616. global _runtime_tracking_task
  3617. if _runtime_tracking_task is None:
  3618. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  3619. logging.getLogger(__name__).info("Printer runtime tracking started")
  3620. def stop_runtime_tracking():
  3621. """Stop the printer runtime tracking background task."""
  3622. global _runtime_tracking_task
  3623. if _runtime_tracking_task:
  3624. _runtime_tracking_task.cancel()
  3625. _runtime_tracking_task = None
  3626. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  3627. # SpoolBuddy device watchdog
  3628. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  3629. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  3630. async def _spoolbuddy_watchdog_loop():
  3631. """Periodic check for SpoolBuddy devices that have gone offline."""
  3632. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  3633. while True:
  3634. try:
  3635. await spoolbuddy_watchdog()
  3636. except asyncio.CancelledError:
  3637. break
  3638. except Exception as e:
  3639. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  3640. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  3641. def start_spoolbuddy_watchdog():
  3642. global _spoolbuddy_watchdog_task
  3643. if _spoolbuddy_watchdog_task is None:
  3644. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  3645. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  3646. def stop_spoolbuddy_watchdog():
  3647. global _spoolbuddy_watchdog_task
  3648. if _spoolbuddy_watchdog_task:
  3649. _spoolbuddy_watchdog_task.cancel()
  3650. _spoolbuddy_watchdog_task = None
  3651. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  3652. # Camera stream orphan cleanup
  3653. _camera_cleanup_task: asyncio.Task | None = None
  3654. CAMERA_CLEANUP_INTERVAL = 60
  3655. async def _camera_cleanup_loop():
  3656. """Periodically clean up orphaned ffmpeg processes."""
  3657. from backend.app.api.routes.camera import cleanup_orphaned_streams
  3658. while True:
  3659. try:
  3660. await cleanup_orphaned_streams()
  3661. except asyncio.CancelledError:
  3662. break
  3663. except Exception as e:
  3664. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  3665. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  3666. def start_camera_cleanup():
  3667. global _camera_cleanup_task
  3668. if _camera_cleanup_task is None:
  3669. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  3670. logging.getLogger(__name__).info("Camera stream cleanup started")
  3671. def stop_camera_cleanup():
  3672. global _camera_cleanup_task
  3673. if _camera_cleanup_task:
  3674. _camera_cleanup_task.cancel()
  3675. _camera_cleanup_task = None
  3676. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  3677. # ---------------------------------------------------------------------------
  3678. # Expected-print TTL eviction
  3679. # ---------------------------------------------------------------------------
  3680. def _evict_stale_expected_prints() -> None:
  3681. """Remove entries from _expected_prints / _expected_print_creators that are
  3682. older than _EXPECTED_PRINT_TTL_SECONDS.
  3683. This prevents unbounded growth when a print is registered (via
  3684. register_expected_print) but on_print_start never fires — e.g. because the
  3685. printer disconnects, the app restarts, or the print is started directly from
  3686. the printer panel without going through the queue.
  3687. """
  3688. # Use monotonic time so the TTL is unaffected by system clock adjustments
  3689. # (e.g. NTP sync, DST changes).
  3690. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  3691. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  3692. if not stale_keys:
  3693. return
  3694. evicted_archive_ids: set[int] = set()
  3695. for key in stale_keys:
  3696. archive_id = _expected_prints.pop(key, None)
  3697. if archive_id is not None:
  3698. evicted_archive_ids.add(archive_id)
  3699. _expected_print_creators.pop(key, None)
  3700. _expected_print_registered_at.pop(key, None)
  3701. # Also clean up _print_ams_mappings for archive_ids that have no remaining
  3702. # live keys in _expected_prints (i.e. all variants were just evicted).
  3703. live_archive_ids = set(_expected_prints.values())
  3704. for archive_id in evicted_archive_ids:
  3705. if archive_id not in live_archive_ids:
  3706. _print_ams_mappings.pop(archive_id, None)
  3707. logging.getLogger(__name__).info(
  3708. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  3709. )
  3710. async def _expected_prints_cleanup_loop() -> None:
  3711. """Background task: periodically evict stale expected-print entries."""
  3712. while True:
  3713. try:
  3714. _evict_stale_expected_prints()
  3715. except asyncio.CancelledError:
  3716. raise
  3717. except Exception as e:
  3718. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  3719. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  3720. def start_expected_prints_cleanup() -> None:
  3721. global _expected_prints_cleanup_task
  3722. if _expected_prints_cleanup_task is None:
  3723. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  3724. logging.getLogger(__name__).info("Expected prints cleanup started")
  3725. def stop_expected_prints_cleanup() -> None:
  3726. global _expected_prints_cleanup_task
  3727. if _expected_prints_cleanup_task:
  3728. _expected_prints_cleanup_task.cancel()
  3729. _expected_prints_cleanup_task = None
  3730. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  3731. # ---------------------------------------------------------------------------
  3732. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  3733. # ---------------------------------------------------------------------------
  3734. _auth_cleanup_task: asyncio.Task | None = None
  3735. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  3736. async def _run_auth_cleanup() -> None:
  3737. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  3738. from backend.app.core.database import async_session
  3739. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  3740. from backend.app.models.user_totp import UserTOTP
  3741. now = datetime.now(timezone.utc)
  3742. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  3743. try:
  3744. async with async_session() as db:
  3745. stale_cutoff = now - timedelta(hours=1)
  3746. result = await db.execute(
  3747. select(UserTOTP).where(
  3748. UserTOTP.is_enabled.is_(False),
  3749. UserTOTP.created_at < stale_cutoff,
  3750. )
  3751. )
  3752. stale_records = result.scalars().all()
  3753. if stale_records:
  3754. for rec in stale_records:
  3755. await db.delete(rec)
  3756. await db.commit()
  3757. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  3758. except Exception as e:
  3759. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  3760. # Remove expired revoked-JTI entries (they are no longer needed once the
  3761. # original token's exp has passed — the token would be rejected by JWT
  3762. # signature verification regardless).
  3763. try:
  3764. async with async_session() as db:
  3765. await db.execute(
  3766. delete(AuthEphemeralToken).where(
  3767. AuthEphemeralToken.token_type == "revoked_jti",
  3768. AuthEphemeralToken.expires_at < now,
  3769. )
  3770. )
  3771. await db.commit()
  3772. except Exception as e:
  3773. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  3774. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  3775. # Events outside this window can never affect rate-limit decisions — they only
  3776. # consume DB space. Use the same window constant as the rate limiter so the
  3777. # two are always in sync.
  3778. try:
  3779. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  3780. async with async_session() as db:
  3781. await db.execute(
  3782. delete(AuthRateLimitEvent).where(
  3783. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  3784. )
  3785. )
  3786. await db.commit()
  3787. except Exception as e:
  3788. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  3789. async def _auth_cleanup_loop() -> None:
  3790. """Periodic background task: run auth cleanup every hour."""
  3791. while True:
  3792. try:
  3793. await _run_auth_cleanup()
  3794. except asyncio.CancelledError:
  3795. break
  3796. except Exception as e:
  3797. logging.warning("Auth cleanup loop error: %s", e)
  3798. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  3799. def start_auth_cleanup() -> None:
  3800. global _auth_cleanup_task
  3801. if _auth_cleanup_task is None:
  3802. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  3803. logging.getLogger(__name__).info("Auth periodic cleanup started")
  3804. def stop_auth_cleanup() -> None:
  3805. global _auth_cleanup_task
  3806. if _auth_cleanup_task:
  3807. _auth_cleanup_task.cancel()
  3808. _auth_cleanup_task = None
  3809. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  3810. @asynccontextmanager
  3811. async def lifespan(app: FastAPI):
  3812. # Startup
  3813. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  3814. # anything else can spawn tasks that might trip it.
  3815. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  3816. install_proactor_reset_filter()
  3817. await init_db()
  3818. # Register an app-scoped httpx client for Bambu Cloud services so
  3819. # per-request BambuCloudService instances reuse the same connection pool
  3820. # (important for routes like /cloud/filament-info that chain many
  3821. # get_setting_detail calls). The shared client stores no region/token
  3822. # state, so the per-request ownership pattern that fixed the region-bleed
  3823. # bug is preserved.
  3824. import httpx as _httpx
  3825. from backend.app.services.bambu_cloud import set_shared_http_client
  3826. from backend.app.services.makerworld import (
  3827. set_shared_http_client as set_shared_makerworld_http_client,
  3828. )
  3829. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  3830. set_shared_http_client(_shared_cloud_http_client)
  3831. # Reuse the same connection pool for MakerWorld — different host, same
  3832. # keep-alive pool saves a TLS handshake per request.
  3833. set_shared_makerworld_http_client(_shared_cloud_http_client)
  3834. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  3835. # This can happen when a print was cancelled mid-print on versions before this fix.
  3836. try:
  3837. async with async_session() as db:
  3838. from backend.app.models.print_queue import PrintQueueItem
  3839. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  3840. aborted_items = result.scalars().all()
  3841. if aborted_items:
  3842. for item in aborted_items:
  3843. item.status = "cancelled"
  3844. await db.commit()
  3845. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  3846. except Exception as e:
  3847. logging.warning("Failed to fix aborted queue items: %s", e)
  3848. # Restore debug logging state from previous session
  3849. await init_debug_logging()
  3850. # Set up printer manager callbacks
  3851. loop = asyncio.get_event_loop()
  3852. printer_manager.set_event_loop(loop)
  3853. printer_manager.set_status_change_callback(on_printer_status_change)
  3854. printer_manager.set_print_start_callback(on_print_start)
  3855. printer_manager.set_print_complete_callback(on_print_complete)
  3856. printer_manager.set_ams_change_callback(on_ams_change)
  3857. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  3858. await printer_manager.load_awaiting_plate_clear_from_db()
  3859. # Layer change callback for external camera timelapse
  3860. async def on_layer_change(printer_id: int, layer_num: int):
  3861. """Capture timelapse frame on layer change + first layer notification."""
  3862. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  3863. await tl_layer_change(printer_id, layer_num)
  3864. # First layer complete notification (layer_num >= 2 means layer 1 is done)
  3865. if 2 <= layer_num <= 5 and not _first_layer_notified.get(printer_id, False):
  3866. _first_layer_notified[printer_id] = True
  3867. try:
  3868. async with async_session() as db:
  3869. from backend.app.models.printer import Printer
  3870. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3871. printer = result.scalar_one_or_none()
  3872. if not printer:
  3873. return
  3874. printer_name = printer.name
  3875. client = printer_manager.get_client(printer_id)
  3876. state = client.state if client else None
  3877. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  3878. total_layers = state.total_layers if state else 0
  3879. image_data = await _capture_snapshot_for_notification(
  3880. printer_id, printer, logging.getLogger(__name__)
  3881. )
  3882. await notification_service.on_first_layer_complete(
  3883. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  3884. )
  3885. except Exception as e:
  3886. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  3887. printer_manager.set_layer_change_callback(on_layer_change)
  3888. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  3889. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  3890. waiter = _bed_cool_waiters.get(printer_id)
  3891. if not waiter:
  3892. return
  3893. threshold = waiter["threshold"]
  3894. if bed_temp > threshold:
  3895. return
  3896. # Bed is at or below threshold — fire notification and remove waiter
  3897. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  3898. if not waiter_info:
  3899. return # Another callback already handled it
  3900. bed_cool_logger = logging.getLogger(__name__)
  3901. bed_cool_logger.info(
  3902. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  3903. bed_temp,
  3904. printer_id,
  3905. threshold,
  3906. )
  3907. try:
  3908. printer_info = printer_manager.get_printer(printer_id)
  3909. p_name = printer_info.name if printer_info else "Unknown"
  3910. async with async_session() as db:
  3911. await notification_service.on_bed_cooled(
  3912. printer_id=printer_id,
  3913. printer_name=p_name,
  3914. bed_temp=bed_temp,
  3915. threshold=threshold,
  3916. filename=waiter_info["filename"],
  3917. db=db,
  3918. )
  3919. except Exception as e:
  3920. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  3921. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  3922. # Initialize MQTT relay from settings
  3923. async with async_session() as db:
  3924. from backend.app.api.routes.settings import get_setting
  3925. mqtt_settings = {
  3926. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  3927. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  3928. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  3929. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  3930. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  3931. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  3932. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  3933. }
  3934. await mqtt_relay.configure(mqtt_settings)
  3935. # Restore MQTT smart plug subscriptions
  3936. if mqtt_settings.get("mqtt_enabled"):
  3937. from backend.app.models.smart_plug import SmartPlug
  3938. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  3939. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  3940. mqtt_plugs = result.scalars().all()
  3941. restored = 0
  3942. for plug in mqtt_plugs:
  3943. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  3944. restored += 1
  3945. if restored:
  3946. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  3947. # Connect to all active printers
  3948. async with async_session() as db:
  3949. await init_printer_connections(db)
  3950. # Auto-connect to Spoolman if enabled
  3951. async with async_session() as db:
  3952. from backend.app.api.routes.settings import get_setting
  3953. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3954. spoolman_url = await get_setting(db, "spoolman_url")
  3955. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  3956. try:
  3957. client = await init_spoolman_client(spoolman_url)
  3958. if await client.health_check():
  3959. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  3960. # Ensure the 'tag' extra field exists for RFID/UUID storage
  3961. await client.ensure_tag_extra_field()
  3962. else:
  3963. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  3964. except Exception as e:
  3965. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  3966. # Start the print scheduler
  3967. asyncio.create_task(print_scheduler.run())
  3968. # Start background dispatch worker for send/start operations
  3969. await background_dispatch.start()
  3970. # Start the smart plug scheduler for time-based on/off
  3971. smart_plug_manager.start_scheduler()
  3972. # Resume any pending auto-offs that were interrupted by restart
  3973. await smart_plug_manager.resume_pending_auto_offs()
  3974. # Start the notification digest scheduler
  3975. notification_service.start_digest_scheduler()
  3976. # Start the GitHub backup scheduler
  3977. await github_backup_service.start_scheduler()
  3978. # Start the local backup scheduler
  3979. await local_backup_service.start_scheduler()
  3980. await obico_detection_service.start()
  3981. # Start the library trash sweeper (#1008)
  3982. await library_trash_service.start_scheduler()
  3983. # Start the archive auto-purge sweeper (#1008 follow-up)
  3984. await archive_purge_service.start_scheduler()
  3985. # Start AMS history recording
  3986. start_ams_history_recording()
  3987. # Start printer runtime tracking
  3988. start_runtime_tracking()
  3989. # Start SpoolBuddy device watchdog
  3990. start_spoolbuddy_watchdog()
  3991. # Start camera stream orphan cleanup
  3992. start_camera_cleanup()
  3993. # Start expected-print TTL eviction (prevents memory leak when prints are
  3994. # registered but on_print_start never fires)
  3995. start_expected_prints_cleanup()
  3996. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  3997. start_auth_cleanup()
  3998. # Initialize virtual printer manager and sync from DB
  3999. from backend.app.services.virtual_printer import virtual_printer_manager
  4000. virtual_printer_manager.set_session_factory(async_session)
  4001. virtual_printer_manager.set_printer_manager(printer_manager)
  4002. try:
  4003. await virtual_printer_manager.sync_from_db()
  4004. logging.info("Virtual printer manager synced from database")
  4005. except Exception as e:
  4006. logging.warning("Failed to sync virtual printers: %s", e)
  4007. yield
  4008. # Shutdown
  4009. print_scheduler.stop()
  4010. await background_dispatch.stop()
  4011. smart_plug_manager.stop_scheduler()
  4012. notification_service.stop_digest_scheduler()
  4013. github_backup_service.stop_scheduler()
  4014. local_backup_service.stop_scheduler()
  4015. library_trash_service.stop_scheduler()
  4016. archive_purge_service.stop_scheduler()
  4017. obico_detection_service.stop()
  4018. stop_ams_history_recording()
  4019. stop_runtime_tracking()
  4020. stop_spoolbuddy_watchdog()
  4021. stop_camera_cleanup()
  4022. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  4023. # cleanly rather than waiting on a queue that nothing will ever fill.
  4024. try:
  4025. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  4026. await shutdown_all_broadcasters()
  4027. except Exception as e:
  4028. logging.warning("Failed to shut down camera broadcasters: %s", e)
  4029. stop_expected_prints_cleanup()
  4030. stop_auth_cleanup()
  4031. printer_manager.disconnect_all()
  4032. await close_spoolman_client()
  4033. # Stop all virtual printer services
  4034. await virtual_printer_manager.stop_all()
  4035. await mqtt_smart_plug_service.disconnect(timeout=2)
  4036. await mqtt_relay.disconnect(timeout=2)
  4037. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  4038. set_shared_http_client(None)
  4039. set_shared_makerworld_http_client(None)
  4040. await _shared_cloud_http_client.aclose()
  4041. # Checkpoint WAL (SQLite only) and close all database connections
  4042. from backend.app.core.db_dialect import is_sqlite
  4043. if is_sqlite():
  4044. try:
  4045. async with engine.begin() as conn:
  4046. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  4047. logging.info("WAL checkpoint completed")
  4048. except Exception as e:
  4049. logging.warning("WAL checkpoint failed: %s", e)
  4050. await engine.dispose()
  4051. app = FastAPI(
  4052. title=app_settings.app_name,
  4053. description="Archive and manage Bambu Lab 3MF files",
  4054. version=APP_VERSION,
  4055. lifespan=lifespan,
  4056. )
  4057. # =============================================================================
  4058. # Authentication Middleware - Secures ALL API routes by default
  4059. # =============================================================================
  4060. # Public routes that don't require authentication even when auth is enabled
  4061. PUBLIC_API_ROUTES = {
  4062. # Auth routes needed before/during login
  4063. "/api/v1/auth/status",
  4064. "/api/v1/auth/login",
  4065. "/api/v1/auth/setup", # Needed for initial setup and recovery
  4066. # Advanced auth status needed for login page
  4067. "/api/v1/auth/advanced-auth/status",
  4068. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  4069. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  4070. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  4071. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  4072. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  4073. # OIDC routes that must be reachable without a JWT
  4074. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  4075. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  4076. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  4077. # Version check for updates (no sensitive data)
  4078. "/api/v1/updates/version",
  4079. # Metrics endpoint handles its own prometheus_token authentication
  4080. "/api/v1/metrics",
  4081. }
  4082. # Route prefixes that are public (for routes with dynamic segments)
  4083. PUBLIC_API_PREFIXES = [
  4084. # WebSocket connections handle their own auth
  4085. "/api/v1/ws",
  4086. # OIDC authorize redirects — include provider_id in path
  4087. "/api/v1/auth/oidc/authorize/",
  4088. ]
  4089. # Route patterns that are public (read-only display data)
  4090. # These are checked with "in path" - needed because browsers load images/videos
  4091. # via <img src> and <video src> which don't include Authorization headers
  4092. PUBLIC_API_PATTERNS = [
  4093. # Thumbnails
  4094. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  4095. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  4096. # Images and media
  4097. "/photos/", # /archives/{id}/photos/{filename}
  4098. "/project-image/", # /archives/{id}/project-image/{path}
  4099. "/qrcode", # /archives/{id}/qrcode
  4100. "/timelapse", # /archives/{id}/timelapse (video)
  4101. "/cover", # /printers/{id}/cover
  4102. "/icon", # /external-links/{id}/icon
  4103. # Camera (streams loaded via <img> tag)
  4104. "/camera/stream", # /printers/{id}/camera/stream
  4105. "/camera/snapshot", # /printers/{id}/camera/snapshot
  4106. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  4107. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  4108. # download token in the URL path instead.
  4109. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  4110. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  4111. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  4112. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  4113. ]
  4114. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  4115. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  4116. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  4117. Format: comma-separated list of ``scheme://host[:port]`` origins.
  4118. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  4119. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  4120. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  4121. Invalid entries are dropped with a warning rather than failing startup, so
  4122. a typo in one origin doesn't take the whole deployment down.
  4123. """
  4124. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  4125. if not raw:
  4126. return ()
  4127. valid: list[str] = []
  4128. for item in raw.split(","):
  4129. candidate = item.strip()
  4130. if not candidate:
  4131. continue
  4132. try:
  4133. parsed = urlparse(candidate)
  4134. except ValueError as e:
  4135. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  4136. continue
  4137. if parsed.scheme not in ("http", "https"):
  4138. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  4139. continue
  4140. if not parsed.netloc:
  4141. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  4142. continue
  4143. if parsed.path and parsed.path != "/":
  4144. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  4145. continue
  4146. if parsed.query or parsed.fragment:
  4147. _security_headers_logger.warning(
  4148. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  4149. )
  4150. continue
  4151. if "*" in parsed.netloc:
  4152. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  4153. continue
  4154. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  4155. if valid:
  4156. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  4157. return tuple(valid)
  4158. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  4159. def _frame_ancestors(default_value: str) -> str:
  4160. """Compose the ``frame-ancestors`` CSP directive (#1191).
  4161. ``default_value`` is the strict directive used when the operator has not
  4162. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  4163. docs) or ``'self'`` (gcode-viewer, served same-origin). When trusted origins
  4164. are configured, ``'self'`` is always included so same-origin embedding never
  4165. breaks even if an operator forgets to add their own origin to the list.
  4166. """
  4167. if _TRUSTED_FRAME_ORIGINS:
  4168. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  4169. return f"frame-ancestors {default_value};"
  4170. @app.middleware("http")
  4171. async def security_headers_middleware(request, call_next):
  4172. """Add standard HTTP security headers to every response."""
  4173. response = await call_next(request)
  4174. response.headers["X-Content-Type-Options"] = "nosniff"
  4175. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  4176. # browsers honour CSP frame-ancestors instead, and the legacy
  4177. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  4178. # When operators have explicitly allowlisted trusted frame origins (#1191
  4179. # — typically Home Assistant on a different port), drop X-Frame-Options
  4180. # and let the CSP-side frame-ancestors directive govern embedding.
  4181. if not _TRUSTED_FRAME_ORIGINS:
  4182. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  4183. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  4184. # Content-Security-Policy for the React SPA.
  4185. # Notes:
  4186. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  4187. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  4188. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  4189. # - media-src blob:: timelapse video player uses Blob URLs.
  4190. # - font-src data:: some icon fonts are embedded as data URIs.
  4191. if request.url.path.startswith("/gcode-viewer"):
  4192. # The gcode viewer is embedded in an iframe served by this same origin,
  4193. # so frame-ancestors must allow 'self'. prettygcode.js also uses eval()
  4194. # internally, so script-src needs 'unsafe-eval'.
  4195. response.headers["Content-Security-Policy"] = (
  4196. "default-src 'self'; "
  4197. "script-src 'self' 'unsafe-eval'; "
  4198. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
  4199. "img-src 'self' data: blob:; "
  4200. "media-src 'self' blob:; "
  4201. "connect-src 'self' ws: wss:; "
  4202. "font-src 'self' data: https://fonts.gstatic.com; "
  4203. "object-src 'none'; "
  4204. "base-uri 'self'; "
  4205. "frame-src 'self' http: https:; " + _frame_ancestors("'self'")
  4206. )
  4207. elif request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  4208. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  4209. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  4210. # default CSP would render a blank page.
  4211. response.headers["Content-Security-Policy"] = (
  4212. "default-src 'self'; "
  4213. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  4214. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  4215. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  4216. "connect-src 'self'; "
  4217. "font-src 'self' data: https://fonts.gstatic.com; "
  4218. "worker-src 'self' blob:; "
  4219. "object-src 'none'; "
  4220. "base-uri 'self'; " + _frame_ancestors("'none'")
  4221. )
  4222. else:
  4223. response.headers["Content-Security-Policy"] = (
  4224. "default-src 'self'; "
  4225. "script-src 'self'; "
  4226. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
  4227. "img-src 'self' data: blob:; "
  4228. "media-src 'self' blob:; "
  4229. "connect-src 'self' ws: wss:; "
  4230. "font-src 'self' data: https://fonts.gstatic.com; "
  4231. "object-src 'none'; "
  4232. "base-uri 'self'; "
  4233. "frame-src 'self' http: https:; " + _frame_ancestors("'none'")
  4234. )
  4235. if request.url.scheme == "https":
  4236. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  4237. return response
  4238. @app.middleware("http")
  4239. async def auth_middleware(request, call_next):
  4240. """Enforce authentication on all API routes when auth is enabled.
  4241. This middleware provides defense-in-depth by checking auth at the API gateway level,
  4242. regardless of whether individual routes have auth dependencies.
  4243. """
  4244. from starlette.responses import JSONResponse
  4245. path = request.url.path
  4246. # Only apply to API routes
  4247. if not path.startswith("/api/"):
  4248. return await call_next(request)
  4249. # Allow public routes
  4250. if path in PUBLIC_API_ROUTES:
  4251. return await call_next(request)
  4252. # Allow public prefixes
  4253. for prefix in PUBLIC_API_PREFIXES:
  4254. if path.startswith(prefix):
  4255. return await call_next(request)
  4256. # Allow public patterns (read-only display data like thumbnails)
  4257. for pattern in PUBLIC_API_PATTERNS:
  4258. if pattern in path:
  4259. return await call_next(request)
  4260. # Check if auth is enabled
  4261. try:
  4262. async with async_session() as db:
  4263. from backend.app.core.auth import is_auth_enabled
  4264. auth_enabled = await is_auth_enabled(db)
  4265. if not auth_enabled:
  4266. # Auth disabled, allow all requests
  4267. return await call_next(request)
  4268. except Exception:
  4269. # If we can't check auth status, allow request (fail open for DB issues)
  4270. return await call_next(request)
  4271. # Auth is enabled - require valid token
  4272. auth_header = request.headers.get("Authorization")
  4273. x_api_key = request.headers.get("X-API-Key")
  4274. # Check for API key auth first
  4275. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  4276. # API key authentication - let the request through to be validated by route handler
  4277. # API keys are validated per-route since they have different permission levels
  4278. return await call_next(request)
  4279. # Check for JWT auth
  4280. if not auth_header or not auth_header.startswith("Bearer "):
  4281. return JSONResponse(
  4282. status_code=401,
  4283. content={"detail": "Authentication required"},
  4284. headers={"WWW-Authenticate": "Bearer"},
  4285. )
  4286. # Validate JWT token
  4287. import jwt
  4288. try:
  4289. from backend.app.core.auth import (
  4290. ALGORITHM,
  4291. SECRET_KEY,
  4292. _is_token_fresh,
  4293. get_user_by_username,
  4294. is_jti_revoked,
  4295. )
  4296. token = auth_header.replace("Bearer ", "")
  4297. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  4298. username = payload.get("sub")
  4299. if not username:
  4300. raise ValueError("No username in token")
  4301. jti = payload.get("jti")
  4302. if not jti:
  4303. raise ValueError("No jti in token")
  4304. iat = payload.get("iat")
  4305. # Reject revoked tokens (defense-in-depth gateway check)
  4306. if await is_jti_revoked(jti):
  4307. return JSONResponse(
  4308. status_code=401,
  4309. content={"detail": "Token has been revoked"},
  4310. headers={"WWW-Authenticate": "Bearer"},
  4311. )
  4312. # Verify user exists, is active, and token is still fresh (L-R8-A)
  4313. async with async_session() as db:
  4314. user = await get_user_by_username(db, username)
  4315. if not user or not user.is_active:
  4316. return JSONResponse(
  4317. status_code=401,
  4318. content={"detail": "User not found or inactive"},
  4319. headers={"WWW-Authenticate": "Bearer"},
  4320. )
  4321. if not _is_token_fresh(iat, user):
  4322. return JSONResponse(
  4323. status_code=401,
  4324. content={"detail": "Token no longer valid"},
  4325. headers={"WWW-Authenticate": "Bearer"},
  4326. )
  4327. except jwt.ExpiredSignatureError:
  4328. return JSONResponse(
  4329. status_code=401,
  4330. content={"detail": "Token has expired"},
  4331. headers={"WWW-Authenticate": "Bearer"},
  4332. )
  4333. except (jwt.InvalidTokenError, ValueError, Exception):
  4334. return JSONResponse(
  4335. status_code=401,
  4336. content={"detail": "Invalid token"},
  4337. headers={"WWW-Authenticate": "Bearer"},
  4338. )
  4339. return await call_next(request)
  4340. @app.middleware("http")
  4341. async def trace_id_middleware(request, call_next):
  4342. """Stamp every HTTP request with a trace ID and echo it back.
  4343. Decorated AFTER auth_middleware on purpose: Starlette stacks
  4344. @app.middleware decorators LIFO, so the last-decorated runs first
  4345. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  4346. which means auth-middleware log lines (and every line emitted on the
  4347. way down to and back from the route handler) all carry the same
  4348. trace ID. If we put it before auth, auth's logs would be stamped
  4349. with the *previous* request's ID — useless for correlation.
  4350. Honours an inbound ``X-Trace-Id`` header so callers running their
  4351. own tracing can correlate their span IDs with our log lines, but
  4352. only if the value passes the whitelist gate in
  4353. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  4354. rejected (too long, contains control chars, etc.) silently triggers
  4355. a freshly minted server-side ID rather than failing the request.
  4356. The minted (or echoed) ID is set on a ContextVar so that every log
  4357. record emitted during the request — application logs *and* uvicorn's
  4358. access log — carries it via TraceIDFilter, and is also written to
  4359. the ``X-Trace-Id`` response header so clients can pin a server-side
  4360. log search to the exact request they made.
  4361. """
  4362. from backend.app.core.trace import (
  4363. generate_trace_id,
  4364. normalise_inbound_trace_id,
  4365. trace_id_var,
  4366. )
  4367. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  4368. trace_id = inbound if inbound is not None else generate_trace_id()
  4369. token = trace_id_var.set(trace_id)
  4370. try:
  4371. response = await call_next(request)
  4372. finally:
  4373. # Reset the ContextVar so a record emitted in a totally
  4374. # unrelated background task that just happens to inherit this
  4375. # context doesn't keep referencing this request's ID forever.
  4376. # In practice ContextVar.reset is best-effort under asyncio
  4377. # task-spawn semantics, but the cost is one attribute write so
  4378. # we may as well do it.
  4379. trace_id_var.reset(token)
  4380. response.headers["X-Trace-Id"] = trace_id
  4381. return response
  4382. # API routes
  4383. app.include_router(auth.router, prefix=app_settings.api_prefix)
  4384. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  4385. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  4386. app.include_router(users.router, prefix=app_settings.api_prefix)
  4387. app.include_router(groups.router, prefix=app_settings.api_prefix)
  4388. app.include_router(printers.router, prefix=app_settings.api_prefix)
  4389. app.include_router(archives.router, prefix=app_settings.api_prefix)
  4390. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  4391. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  4392. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  4393. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  4394. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  4395. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  4396. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  4397. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  4398. app.include_router(background_dispatch_routes.router, prefix=app_settings.api_prefix)
  4399. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  4400. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  4401. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  4402. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  4403. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  4404. app.include_router(updates.router, prefix=app_settings.api_prefix)
  4405. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  4406. app.include_router(camera.router, prefix=app_settings.api_prefix)
  4407. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  4408. app.include_router(projects.router, prefix=app_settings.api_prefix)
  4409. app.include_router(library.router, prefix=app_settings.api_prefix)
  4410. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  4411. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  4412. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  4413. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  4414. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  4415. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  4416. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  4417. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  4418. app.include_router(system.router, prefix=app_settings.api_prefix)
  4419. app.include_router(support.router, prefix=app_settings.api_prefix)
  4420. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  4421. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  4422. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  4423. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  4424. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  4425. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  4426. app.include_router(obico.router, prefix=app_settings.api_prefix)
  4427. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  4428. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  4429. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  4430. # Serve static files (React build)
  4431. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  4432. app.mount(
  4433. "/assets",
  4434. StaticFiles(directory=app_settings.static_dir / "assets"),
  4435. name="assets",
  4436. )
  4437. if (app_settings.static_dir / "img").exists():
  4438. app.mount(
  4439. "/img",
  4440. StaticFiles(directory=app_settings.static_dir / "img"),
  4441. name="img",
  4442. )
  4443. if (app_settings.static_dir / "icons").exists():
  4444. app.mount(
  4445. "/icons",
  4446. StaticFiles(directory=app_settings.static_dir / "icons"),
  4447. name="icons",
  4448. )
  4449. @app.get("/")
  4450. async def serve_frontend():
  4451. """Serve the React frontend."""
  4452. index_file = app_settings.static_dir / "index.html"
  4453. if index_file.exists():
  4454. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  4455. return {
  4456. "message": "Bambuddy API",
  4457. "docs": "/docs",
  4458. "frontend": "Build and place React app in /static directory",
  4459. }
  4460. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  4461. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  4462. # forever, but the HTML wrapping it is the only file that knows which hash
  4463. # is current. Without explicit cache-control headers Chromium decides
  4464. # heuristically (typically 10% of the time since Last-Modified) and on
  4465. # long-running kiosks happily serves stale HTML across browser restarts.
  4466. # That stale HTML references an old bundle hash, the old bundle is also
  4467. # in the disk cache, and the user ends up running pre-update JS forever
  4468. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  4469. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  4470. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  4471. @app.get("/health")
  4472. async def health_check():
  4473. """Health check endpoint."""
  4474. return {"status": "healthy"}
  4475. @app.get("/manifest.json")
  4476. async def serve_manifest():
  4477. """Serve PWA manifest."""
  4478. manifest_file = app_settings.static_dir / "manifest.json"
  4479. if manifest_file.exists():
  4480. return FileResponse(manifest_file, media_type="application/manifest+json")
  4481. return {"error": "Manifest not found"}
  4482. @app.get("/sw.js")
  4483. async def serve_service_worker():
  4484. """Serve service worker."""
  4485. sw_file = app_settings.static_dir / "sw.js"
  4486. if sw_file.exists():
  4487. return FileResponse(
  4488. sw_file,
  4489. media_type="application/javascript",
  4490. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  4491. )
  4492. return {"error": "Service worker not found"}
  4493. @app.get("/sw-register.js")
  4494. async def serve_sw_register():
  4495. """Serve the service-worker registration bootstrap script.
  4496. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  4497. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  4498. """
  4499. reg_file = app_settings.static_dir / "sw-register.js"
  4500. if reg_file.exists():
  4501. return FileResponse(reg_file, media_type="application/javascript")
  4502. return {"error": "sw-register.js not found"}
  4503. # ── GCode viewer static files ────────────────────────────────────────────────
  4504. # Served via explicit routes so ordering is guaranteed (app.mount() loses
  4505. # to the /{full_path:path} catch-all in some Starlette versions).
  4506. _gcode_viewer_dir = (app_settings.static_dir.parent / "gcode_viewer").resolve()
  4507. def _gcode_viewer_response(rel: str) -> FileResponse:
  4508. from fastapi import HTTPException as _HTTPException
  4509. safe = (_gcode_viewer_dir / rel).resolve()
  4510. if not safe.is_relative_to(_gcode_viewer_dir):
  4511. raise _HTTPException(status_code=403)
  4512. if safe.is_file():
  4513. mt, _ = _mimetypes.guess_type(str(safe))
  4514. return FileResponse(str(safe), media_type=mt or "application/octet-stream")
  4515. raise _HTTPException(status_code=404)
  4516. @app.get("/gcode-viewer/")
  4517. async def serve_gcode_viewer_index() -> FileResponse:
  4518. """Raw PrettyGCode viewer for the iframe. The bare ``/gcode-viewer``
  4519. (no trailing slash) intentionally falls through to the SPA catch-all so a
  4520. full-page reload re-enters the React layout instead of serving the iframe
  4521. contents standalone."""
  4522. return _gcode_viewer_response("index.html")
  4523. @app.get("/gcode-viewer/{file_path:path}")
  4524. async def serve_gcode_viewer_file(file_path: str) -> FileResponse:
  4525. return _gcode_viewer_response(file_path)
  4526. # Catch-all route for React Router (must be last)
  4527. @app.get("/{full_path:path}")
  4528. async def serve_spa(full_path: str):
  4529. """Serve React app for client-side routing."""
  4530. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  4531. if full_path.startswith("api/"):
  4532. from fastapi import HTTPException
  4533. raise HTTPException(status_code=404, detail="Not found")
  4534. index_file = app_settings.static_dir / "index.html"
  4535. if index_file.exists():
  4536. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  4537. return {"error": "Frontend not built"}