main.py 234 KB

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