notification_service.py 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  1. """Notification service for sending push notifications via various providers."""
  2. import asyncio
  3. import html
  4. import json
  5. import logging
  6. import re
  7. import smtplib
  8. from datetime import datetime, timedelta, timezone
  9. from email.mime.image import MIMEImage
  10. from email.mime.multipart import MIMEMultipart
  11. from email.mime.text import MIMEText
  12. from typing import Any
  13. from urllib.parse import quote
  14. import httpx
  15. from sqlalchemy import select
  16. from sqlalchemy.ext.asyncio import AsyncSession
  17. from backend.app.models.notification import NotificationDigestQueue, NotificationLog, NotificationProvider
  18. from backend.app.models.notification_template import NotificationTemplate
  19. from backend.app.services.print_confirmation import one_tap_url
  20. logger = logging.getLogger(__name__)
  21. # Honest User-Agent — matches the convention used by every other outbound
  22. # httpx client in the codebase (bambu_cloud, makerworld, firmware_check,
  23. # inventory). Previously this client leaked python-httpx/<version>, which
  24. # was both inconsistent with the rest of the project and a more obvious
  25. # bot signature for upstream WAFs.
  26. _USER_AGENT = "Bambuddy/1.0 (+https://github.com/maziggy/bambuddy)"
  27. def _looks_like_cloudflare_challenge(response: httpx.Response) -> bool:
  28. """Return True if ``response`` looks like a Cloudflare mitigation
  29. interstitial (JS challenge / managed challenge / block page) rather
  30. than a legitimate response passed through Cloudflare.
  31. Self-hosted servers behind Cloudflare (Tunnel, "Bot Fight Mode", or
  32. "Under Attack" mode) intercept non-browser clients at the edge and
  33. return a challenge HTML page instead of forwarding to the origin —
  34. so we never reach the user's actual ntfy / webhook backend.
  35. Cloudflare cannot be defeated from a Python client; the user has to
  36. add a security-skip rule on their side. We detect the shape so the
  37. UI can tell them that, instead of dumping the raw HTML.
  38. Detection deliberately does NOT rely on ``Server: cloudflare`` alone
  39. — Cloudflare adds that header to every response it proxies (success
  40. AND legitimate origin errors), so a real 401 "wrong token" from a
  41. CF-fronted ntfy would false-positive into a misleading "your CF is
  42. blocking" message. Reliable signals: the ``cf-mitigated`` header
  43. (set only when CF actively mitigates) and the challenge body shape.
  44. """
  45. if response.headers.get("cf-mitigated"):
  46. return True
  47. content_type = (response.headers.get("content-type") or "").lower()
  48. if "html" not in content_type:
  49. return False
  50. body = (response.text or "")[:1024].lower()
  51. # "Just a moment..." is Cloudflare's universal challenge-page title
  52. # (managed challenge, JS challenge, Under Attack mode). Combined with
  53. # an HTML content-type this is unambiguous — no legitimate ntfy or
  54. # webhook backend returns HTML with that title. ``cf-chl-*`` and
  55. # ``challenge-platform`` cover newer / non-default CF templates.
  56. return "just a moment" in body or "cf-chl-bypass" in body or "cf-chl-opt" in body or "challenge-platform" in body
  57. def _assert_safe_provider_url(url: str, *, label: str) -> str | None:
  58. """Validate a provider URL taken from user-supplied config.
  59. Returns an error message on rejection, or None when the URL is
  60. acceptable — the ``_send_*`` methods return ``tuple[bool, str]`` rather
  61. than raising, so a message is more useful here than an exception.
  62. Uses the LAN-service policy: self-hosting ntfy, Bark, Gotify or a webhook
  63. receiver on the home LAN is normal and must keep working, so loopback and
  64. RFC-1918 stay permitted. Cloud-metadata endpoints, numeric-encoded IPs and
  65. non-HTTP schemes are rejected.
  66. """
  67. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  68. try:
  69. assert_safe_lan_service_url(url, label=label)
  70. except ValueError as exc:
  71. return str(exc)
  72. return None
  73. def _opaque_http_failure(response: httpx.Response, *, label: str) -> str:
  74. """Failure message for a provider whose destination host the user supplies.
  75. The response body is deliberately **not** returned to the caller. Provider
  76. URLs are configurable by anyone holding ``NOTIFICATIONS_CREATE`` — which
  77. the default Operators group carries and which does not imply
  78. ``SETTINGS_UPDATE`` — and ``POST /notifications/test-config`` accepts a URL
  79. straight from the request body without persisting anything. Echoing the
  80. response body there turned an intended "does my webhook work?" check into
  81. an authenticated read primitive against any host the Bambuddy process can
  82. reach, including services that are not exposed to the network at all.
  83. Providers whose host Bambuddy hardcodes (Pushover, Telegram, CallMeBot)
  84. keep returning the upstream body — there is no trust boundary to cross
  85. when the destination cannot be influenced.
  86. The body is logged at debug level, where it stays available to whoever
  87. already administers the host without being handed back over the API.
  88. """
  89. logger.debug(
  90. "%s delivery failed with HTTP %s; body: %s",
  91. label,
  92. response.status_code,
  93. (response.text or "")[:200],
  94. )
  95. return f"HTTP {response.status_code} from the configured {label} (see server logs at debug level for details)"
  96. class NotificationService:
  97. """Service for sending notifications through various providers."""
  98. def __init__(self):
  99. self._http_client: httpx.AsyncClient | None = None
  100. self._template_cache: dict[str, NotificationTemplate] = {}
  101. self._digest_scheduler_task: asyncio.Task | None = None
  102. self._last_digest_check: str = "" # "HH:MM" to avoid duplicate checks
  103. async def _get_client(self) -> httpx.AsyncClient:
  104. """Get or create HTTP client.
  105. The connect timeout is deliberately far shorter than the rest. A flat
  106. 30 s meant that when a site's internet went down, every alarm spent a
  107. full 30 s inside ``connect`` — longer than SQLite's 15 s
  108. ``busy_timeout`` — and any other task that wanted to write during that
  109. window failed with "database is locked" (#2770). Reaching a host either
  110. works in a couple of seconds or is not going to; sending the body is the
  111. part that legitimately takes time, so read/write keep the old 30 s and
  112. an image upload on a slow uplink is unaffected.
  113. """
  114. if self._http_client is None or self._http_client.is_closed:
  115. self._http_client = httpx.AsyncClient(
  116. timeout=httpx.Timeout(30.0, connect=5.0),
  117. headers={"User-Agent": _USER_AGENT},
  118. )
  119. return self._http_client
  120. async def close(self):
  121. """Close HTTP client."""
  122. if self._http_client and not self._http_client.is_closed:
  123. await self._http_client.aclose()
  124. def _is_in_quiet_hours(self, provider: NotificationProvider) -> bool:
  125. """Check if current time is within provider's quiet hours."""
  126. if not provider.quiet_hours_enabled:
  127. return False
  128. if not provider.quiet_hours_start or not provider.quiet_hours_end:
  129. return False
  130. try:
  131. now = datetime.now()
  132. current_time = now.hour * 60 + now.minute
  133. start_parts = provider.quiet_hours_start.split(":")
  134. end_parts = provider.quiet_hours_end.split(":")
  135. start_minutes = int(start_parts[0]) * 60 + int(start_parts[1])
  136. end_minutes = int(end_parts[0]) * 60 + int(end_parts[1])
  137. # Handle overnight quiet hours (e.g., 22:00 to 07:00)
  138. if start_minutes > end_minutes:
  139. # Quiet hours span midnight
  140. return current_time >= start_minutes or current_time < end_minutes
  141. else:
  142. # Same day quiet hours
  143. return start_minutes <= current_time < end_minutes
  144. except (ValueError, TypeError, AttributeError):
  145. logger.warning("Invalid quiet hours format for provider %s", provider.name)
  146. return False
  147. async def _get_template(self, db: AsyncSession, event_type: str) -> NotificationTemplate | None:
  148. """Get a notification template by event type.
  149. ``no_autoflush`` for the same reason as ``_get_providers_for_event``:
  150. this read runs before the provider is contacted, and must not be the
  151. thing that opens a write transaction on the caller's session (#2770).
  152. """
  153. # Check cache first
  154. if event_type in self._template_cache:
  155. return self._template_cache[event_type]
  156. with db.no_autoflush:
  157. result = await db.execute(select(NotificationTemplate).where(NotificationTemplate.event_type == event_type))
  158. template = result.scalar_one_or_none()
  159. if template:
  160. self._template_cache[event_type] = template
  161. return template
  162. def _render_template(self, template_str: str, variables: dict[str, Any]) -> str:
  163. """Render a template string with variables. Missing variables become empty."""
  164. result = template_str
  165. for key, value in variables.items():
  166. result = result.replace("{" + key + "}", str(value) if value is not None else "")
  167. # Remove any remaining unreplaced placeholders
  168. result = re.sub(r"\{[a-z_]+\}", "", result)
  169. return result
  170. async def _format_eta(self, seconds: int | None, db: AsyncSession) -> str:
  171. """Format ETA as wall-clock time, respecting user's time_format setting."""
  172. if not seconds or seconds <= 0:
  173. return "Unknown"
  174. from backend.app.api.routes.settings import get_setting
  175. eta_time = datetime.now() + timedelta(seconds=seconds)
  176. time_format = await get_setting(db, "time_format")
  177. if time_format == "12h":
  178. return eta_time.strftime("%I:%M %p").lstrip("0")
  179. # Default to 24h for "24h", "system", or unset
  180. return eta_time.strftime("%H:%M")
  181. def _format_duration(self, seconds: int | None) -> str:
  182. """Format duration in seconds to human-readable string."""
  183. if seconds is None:
  184. return "Unknown"
  185. hours = seconds // 3600
  186. minutes = (seconds % 3600) // 60
  187. if hours > 0:
  188. return f"{hours}h {minutes}m"
  189. return f"{minutes}m"
  190. def _clean_filename(self, filename: str) -> str:
  191. """Extract filename and remove file extensions."""
  192. import os
  193. # Strip path prefix (e.g., /data/Metadata/plate_5.gcode -> plate_5.gcode)
  194. filename = os.path.basename(filename)
  195. # Remove common extensions
  196. if filename.endswith(".gcode.3mf"):
  197. return filename[:-10]
  198. elif filename.endswith(".gcode"):
  199. return filename[:-6]
  200. elif filename.endswith(".3mf"):
  201. return filename[:-4]
  202. return filename
  203. async def _build_message_from_template(
  204. self, db: AsyncSession, event_type: str, variables: dict[str, Any]
  205. ) -> tuple[str, str]:
  206. """Build notification title and body from template."""
  207. # Add common variables
  208. variables["timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M")
  209. variables["app_name"] = "Bambuddy"
  210. template = await self._get_template(db, event_type)
  211. if not template:
  212. # Fallback to simple message
  213. logger.warning("Template not found for event type: %s", event_type)
  214. return event_type.replace("_", " ").title(), str(variables)
  215. title = self._render_template(template.title_template, variables)
  216. body = self._render_template(template.body_template, variables)
  217. return title, body
  218. async def send_test_notification(
  219. self, provider_type: str, config: dict[str, Any], db: AsyncSession | None = None
  220. ) -> tuple[bool, str]:
  221. """Send a test notification to verify configuration."""
  222. if db:
  223. title, message = await self._build_message_from_template(db, "test", {})
  224. else:
  225. title = "Bambuddy Test"
  226. message = "This is a test notification. If you see this, notifications are working!"
  227. try:
  228. if provider_type == "callmebot":
  229. return await self._send_callmebot(config, f"{title}\n{message}")
  230. elif provider_type == "ntfy":
  231. return await self._send_ntfy(config, title, message)
  232. elif provider_type == "pushover":
  233. return await self._send_pushover(config, title, message)
  234. elif provider_type == "telegram":
  235. return await self._send_telegram(config, f"*{title}*\n{message}")
  236. elif provider_type == "email":
  237. return await self._send_email(config, title, message)
  238. elif provider_type == "discord":
  239. return await self._send_discord(config, title, message)
  240. elif provider_type == "webhook":
  241. return await self._send_webhook(config, title, message)
  242. elif provider_type == "homeassistant":
  243. return await self._send_homeassistant(config, title, message, db=db)
  244. elif provider_type == "bark":
  245. return await self._send_bark(config, title, message)
  246. else:
  247. return False, f"Unknown provider type: {provider_type}"
  248. except Exception as e:
  249. logger.exception("Error sending test notification via %s", provider_type)
  250. return False, str(e)
  251. async def _send_callmebot(self, config: dict, message: str) -> tuple[bool, str]:
  252. """Send notification via CallMeBot (WhatsApp)."""
  253. phone = config.get("phone", "").strip()
  254. apikey = config.get("apikey", "").strip()
  255. if not phone or not apikey:
  256. return False, "Phone number and API key are required"
  257. # URL encode the message
  258. encoded_message = quote(message)
  259. url = f"https://api.callmebot.com/whatsapp.php?phone={phone}&text={encoded_message}&apikey={apikey}"
  260. client = await self._get_client()
  261. response = await client.get(url)
  262. if response.status_code == 200:
  263. return True, "Message sent successfully"
  264. else:
  265. return False, f"HTTP {response.status_code}: {response.text[:200]}"
  266. async def _send_bark(self, config: dict, title: str, message: str, url: str | None = None) -> tuple[bool, str]:
  267. """Send notification via Bark, the self-hostable iOS push service (#1495).
  268. POSTs JSON to {server}/push. Defaults to the official api.day.app
  269. relay; a self-hosted bark-server works by overriding the server URL.
  270. ``url`` opens on tap — the outcome confirmation (#1898) deep-links
  271. into the archive's confirmation dialog with it.
  272. """
  273. server = (config.get("server") or "https://api.day.app").strip().rstrip("/")
  274. device_key = (config.get("device_key") or "").strip()
  275. if not device_key:
  276. return False, "Device key is required"
  277. url_error = _assert_safe_provider_url(server, label="Bark server URL")
  278. if url_error:
  279. return False, url_error
  280. payload: dict[str, Any] = {
  281. "device_key": device_key,
  282. "title": title,
  283. "body": message,
  284. }
  285. group = (config.get("group") or "").strip()
  286. if group:
  287. payload["group"] = group
  288. sound = (config.get("sound") or "").strip()
  289. if sound:
  290. payload["sound"] = sound
  291. level = (config.get("level") or "").strip()
  292. if level in ("active", "timeSensitive", "critical", "passive"):
  293. payload["level"] = level
  294. if url:
  295. payload["url"] = url
  296. client = await self._get_client()
  297. response = await client.post(f"{server}/push", json=payload)
  298. if response.status_code == 200:
  299. # bark-server can report failures inside an HTTP 200 body
  300. # ({"code": 400, "message": ...}), so the status alone isn't proof.
  301. try:
  302. body = response.json()
  303. except ValueError:
  304. body = None
  305. if isinstance(body, dict) and body.get("code") not in (200, None):
  306. # Only the numeric code is echoed. A server chosen by the caller
  307. # controls this body too, so the free-text message is a (narrow)
  308. # read channel of the same kind _opaque_http_failure closes.
  309. logger.debug("Bark reported error %s: %s", body.get("code"), str(body.get("message"))[:200])
  310. return False, f"Bark error {body.get('code')} (see server logs at debug level for details)"
  311. return True, "Message sent successfully"
  312. return False, _opaque_http_failure(response, label="Bark server")
  313. async def _send_ntfy(
  314. self,
  315. config: dict,
  316. title: str,
  317. message: str,
  318. image_data: bytes | None = None,
  319. event_type: str | None = None,
  320. actions: str | None = None,
  321. ) -> tuple[bool, str]:
  322. """Send notification via ntfy.
  323. ``actions`` is a pre-built value for ntfy's Actions header (simple
  324. format), used by the outcome-confirmation event (#1898) to put
  325. one-tap Good/Reject buttons directly into the push notification.
  326. """
  327. server = config.get("server", "https://ntfy.sh").rstrip("/")
  328. topic = config.get("topic", "").strip()
  329. auth_token = config.get("auth_token", "").strip()
  330. if not topic:
  331. return False, "Topic is required"
  332. url_error = _assert_safe_provider_url(server, label="ntfy server URL")
  333. if url_error:
  334. return False, url_error
  335. url = f"{server}/{topic}"
  336. # ntfy reads Title/Message from HTTP headers. httpx enforces ASCII
  337. # for str header values, but printer names and filenames can contain
  338. # non-ASCII characters (e.g. accented letters, CJK). Passing bytes
  339. # bypasses the ASCII check — ntfy handles UTF-8 headers correctly.
  340. headers: dict[str, str | bytes] = {"Title": title.encode("utf-8")}
  341. # Per-event Priority header (#990). Only set when the user has
  342. # explicitly mapped this event to a 1-5 value; otherwise fall through
  343. # to the ntfy server's default so existing setups stay unchanged.
  344. #
  345. # The map is keyed by the provider's toggle column ("on_print_failed"),
  346. # because that is what the dialog builds its rows from -- but every
  347. # sender is called with the bare event name ("print_failed"), so the
  348. # lookup used to miss for every real notification and hit only in tests
  349. # that called this method with the prefixed name (issue #3139). Both
  350. # spellings are accepted, which also leaves stored configs untouched.
  351. event_priorities = config.get("event_priorities") or {}
  352. if event_type and isinstance(event_priorities, dict):
  353. raw = event_priorities.get(event_type)
  354. if raw is None and not event_type.startswith("on_"):
  355. raw = event_priorities.get(f"on_{event_type}")
  356. try:
  357. priority = int(raw) if raw is not None else None
  358. except (TypeError, ValueError):
  359. priority = None
  360. if priority is not None and 1 <= priority <= 5:
  361. headers["Priority"] = str(priority)
  362. if auth_token:
  363. headers["Authorization"] = f"Bearer {auth_token}"
  364. if actions:
  365. headers["Actions"] = actions
  366. client = await self._get_client()
  367. if image_data:
  368. # ntfy supports image attachments via multipart form-data.
  369. # HTTP headers cannot contain newlines, but ntfy interprets
  370. # literal \n (backslash-n) as newlines in the Message header.
  371. headers["Filename"] = "photo.jpg"
  372. headers["Message"] = message.replace("\n", "\\n").encode("utf-8")
  373. response = await client.put(url, content=image_data, headers=headers)
  374. if response.status_code == 400 and "attachments not allowed" in response.text:
  375. # Server has attachments disabled — retry without the image
  376. headers.pop("Filename", None)
  377. headers.pop("Message", None)
  378. response = await client.post(url, content=message.encode("utf-8"), headers=headers)
  379. else:
  380. response = await client.post(url, content=message.encode("utf-8"), headers=headers)
  381. if response.status_code in (200, 204):
  382. return True, "Message sent successfully"
  383. if _looks_like_cloudflare_challenge(response):
  384. return False, (
  385. f"HTTP {response.status_code} — ntfy server is behind a Cloudflare "
  386. "challenge. Bambuddy was served the JS challenge page instead of "
  387. "reaching ntfy. Cloudflare cannot be solved from a backend; add a "
  388. "Cloudflare security-skip rule for this hostname, disable Bot "
  389. "Fight Mode, or front the server with Cloudflare Access using a "
  390. "service token. (#1534)"
  391. )
  392. return False, _opaque_http_failure(response, label="ntfy server")
  393. async def _send_pushover(
  394. self,
  395. config: dict,
  396. title: str,
  397. message: str,
  398. image_data: bytes | None = None,
  399. url: str | None = None,
  400. url_title: str | None = None,
  401. ) -> tuple[bool, str]:
  402. """Send notification via Pushover.
  403. Args:
  404. config: Provider configuration with user_key, app_token, priority
  405. title: Notification title
  406. message: Notification body
  407. image_data: Optional JPEG image bytes to attach (max 2.5MB)
  408. url: Optional supplementary URL shown under the message
  409. url_title: Optional label for that URL
  410. """
  411. user_key = config.get("user_key", "").strip()
  412. app_token = config.get("app_token", "").strip()
  413. try:
  414. priority = int(config.get("priority", 0))
  415. except (TypeError, ValueError):
  416. priority = 0
  417. if not user_key or not app_token:
  418. return False, "User key and app token are required"
  419. api_url = "https://api.pushover.net/1/messages.json"
  420. data = {
  421. "token": app_token,
  422. "user": user_key,
  423. "title": title,
  424. "message": message,
  425. "priority": priority,
  426. }
  427. if url:
  428. data["url"] = url
  429. if url_title:
  430. data["url_title"] = url_title
  431. # Emergency priority (2) keeps re-alerting until acknowledged, so
  432. # Pushover *requires* retry (how often, >= 30s) and expire (when to
  433. # give up, <= 10800s). Without them the API rejects the message. Only
  434. # send them at priority 2 — Pushover ignores them at other priorities.
  435. if priority == 2:
  436. try:
  437. retry = int(config.get("retry", 60))
  438. except (TypeError, ValueError):
  439. retry = 60
  440. try:
  441. expire = int(config.get("expire", 3600))
  442. except (TypeError, ValueError):
  443. expire = 3600
  444. data["retry"] = max(30, min(retry, 10800))
  445. data["expire"] = max(30, min(expire, 10800))
  446. client = await self._get_client()
  447. if image_data:
  448. # Pushover supports image attachments via multipart form-data
  449. files = {"attachment": ("photo.jpg", image_data, "image/jpeg")}
  450. response = await client.post(api_url, data=data, files=files)
  451. else:
  452. response = await client.post(api_url, data=data)
  453. if response.status_code == 200:
  454. return True, "Message sent successfully"
  455. else:
  456. try:
  457. error_data = response.json()
  458. errors = error_data.get("errors", [])
  459. return False, f"Pushover error: {', '.join(errors)}"
  460. except Exception:
  461. return False, f"HTTP {response.status_code}: {response.text[:200]}"
  462. async def _send_telegram(
  463. self,
  464. config: dict,
  465. message: str,
  466. image_data: bytes | None = None,
  467. buttons: list[dict] | None = None,
  468. link_preview: bool = True,
  469. ) -> tuple[bool, str]:
  470. """Send notification via Telegram bot.
  471. ``buttons`` is one row of inline URL buttons (``{"text", "url"}``
  472. entries), used by the outcome-confirmation event (#1898) to put
  473. one-tap Good/Reject under the message. ``link_preview=False`` asks
  474. Telegram not to fetch the first URL in the text for a preview card.
  475. """
  476. bot_token = config.get("bot_token", "").strip()
  477. chat_id = config.get("chat_id", "").strip()
  478. if not bot_token or not chat_id:
  479. return False, "Bot token and chat ID are required"
  480. # Optional forum topic (#1518). Telegram expects message_thread_id as an
  481. # integer in the JSON sendMessage body — a string 400s there even though
  482. # the multipart sendPhoto call below would happily accept one. Coerce it
  483. # once, up front, so both call sites agree and a bad value fails loudly
  484. # instead of silently breaking only the text notifications.
  485. thread_id_raw = str(config.get("message_thread_id") or "").strip()
  486. message_thread_id: int | None = None
  487. if thread_id_raw:
  488. try:
  489. message_thread_id = int(thread_id_raw)
  490. except ValueError:
  491. return False, f"Invalid message thread ID: {thread_id_raw!r} is not a number"
  492. # Escape underscores in the message body so Telegram Markdown
  493. # parsing doesn't break on job names like "A1_plate_8" or error
  494. # codes like "0300_0001". The title is already wrapped in *bold*
  495. # markers, so only escape after the first newline.
  496. if "\n" in message:
  497. title_part, body_part = message.split("\n", 1)
  498. body_part = body_part.replace("_", "\\_")
  499. message = f"{title_part}\n{body_part}"
  500. client = await self._get_client()
  501. async def _post(with_buttons: bool):
  502. if image_data:
  503. # Use sendPhoto to attach the thumbnail with the caption
  504. url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
  505. form: dict[str, Any] = {"chat_id": chat_id, "caption": message, "parse_mode": "Markdown"}
  506. if message_thread_id is not None:
  507. form["message_thread_id"] = message_thread_id
  508. if with_buttons:
  509. # Multipart form fields are strings — reply_markup goes JSON-encoded.
  510. form["reply_markup"] = json.dumps({"inline_keyboard": [buttons]})
  511. return await client.post(
  512. url,
  513. data=form,
  514. files={"photo": ("photo.jpg", image_data, "image/jpeg")},
  515. )
  516. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  517. payload: dict[str, Any] = {
  518. "chat_id": chat_id,
  519. "text": message,
  520. "parse_mode": "Markdown",
  521. }
  522. if not link_preview:
  523. payload["disable_web_page_preview"] = True
  524. if message_thread_id is not None:
  525. payload["message_thread_id"] = message_thread_id
  526. if with_buttons:
  527. payload["reply_markup"] = {"inline_keyboard": [buttons]}
  528. return await client.post(url, json=payload)
  529. def _failure(resp) -> str | None:
  530. """What Telegram objected to, or None when the send went through."""
  531. if resp.status_code != 200:
  532. return f"HTTP {resp.status_code}: {resp.text[:200]}"
  533. result = resp.json()
  534. if result.get("ok"):
  535. return None
  536. return f"Telegram error: {result.get('description', 'Unknown error')}"
  537. response = await _post(bool(buttons))
  538. failure = _failure(response)
  539. if failure and buttons:
  540. # Telegram validates every inline-keyboard URL and refuses the whole
  541. # send when one of them is not a URL it accepts — which is what an
  542. # install without a public external_url produces for the #1898
  543. # verdict links. Dropping the buttons is survivable; dropping the
  544. # message the user is waiting for is not.
  545. logger.warning("Telegram refused the message with inline buttons (%s); retrying without them", failure)
  546. response = await _post(False)
  547. failure = _failure(response)
  548. if failure:
  549. return False, failure
  550. return True, "Message sent successfully"
  551. async def _send_email(
  552. self,
  553. config: dict,
  554. subject: str,
  555. body: str,
  556. image_data: bytes | None = None,
  557. finish_photo_url: str | None = None,
  558. ) -> tuple[bool, str]:
  559. """Send notification via email (SMTP).
  560. Inline finish-photo embed is opt-in via the template: when the rendered
  561. ``body`` contains the substituted ``{finish_photo_url}`` value AND the
  562. finish-photo bytes are present, the message is built as
  563. ``multipart/related`` wrapping a ``multipart/alternative`` (plain + HTML)
  564. plus an inline ``MIMEImage`` with ``Content-ID: <bambuddy-finish-photo>``.
  565. The HTML part replaces the URL with ``<img src="cid:...">``; the plain-
  566. text part keeps the URL as a clickable link. When the template doesn't
  567. reference ``{finish_photo_url}`` (or image bytes aren't available), the
  568. original single-part text shape is used — no attachment, no surprise
  569. inline image (#1792).
  570. """
  571. smtp_server = config.get("smtp_server", "").strip()
  572. smtp_port = int(config.get("smtp_port", 587))
  573. username = config.get("username", "").strip()
  574. password = config.get("password", "").strip()
  575. from_email = config.get("from_email", "").strip()
  576. to_email = config.get("to_email", "").strip()
  577. # Security: "starttls" (port 587), "ssl" (port 465), "none" (port 25)
  578. security = config.get("security", "starttls")
  579. # Authentication: "true" or "false"
  580. auth_enabled = config.get("auth_enabled", "true").lower() == "true"
  581. if not all([smtp_server, from_email, to_email]):
  582. return False, "SMTP server, from email, and to email are required"
  583. if auth_enabled and not all([username, password]):
  584. return False, "Username and password are required when authentication is enabled"
  585. # Template-driven: only inline-embed when the user's template explicitly
  586. # referenced {finish_photo_url} (so the URL appears in the rendered body)
  587. # AND the photo bytes are available. Falls back to text-only otherwise.
  588. inline_photo = bool(image_data and finish_photo_url and finish_photo_url in body)
  589. try:
  590. if inline_photo:
  591. # multipart/related → (multipart/alternative → text, html) + inline image
  592. msg = MIMEMultipart("related")
  593. msg["From"] = from_email
  594. msg["To"] = to_email
  595. msg["Subject"] = f"[Bambuddy] {subject}"
  596. alt = MIMEMultipart("alternative")
  597. alt.attach(MIMEText(body, "plain"))
  598. # Build HTML body: escape the rendered body, then swap the
  599. # escaped URL substring for an inline <img> referencing the
  600. # MIMEImage we attach below. Done AFTER escape so the cid: URL
  601. # we inject isn't re-escaped.
  602. escaped_body = html.escape(body).replace("\n", "<br>\n")
  603. escaped_url = html.escape(finish_photo_url)
  604. img_tag = (
  605. '<img src="cid:bambuddy-finish-photo" '
  606. 'alt="Printer camera snapshot" '
  607. 'style="max-width:100%;height:auto;border:1px solid #ddd;border-radius:4px;">'
  608. )
  609. html_body = f"<html><body><p>{escaped_body.replace(escaped_url, img_tag)}</p></body></html>"
  610. alt.attach(MIMEText(html_body, "html"))
  611. msg.attach(alt)
  612. img = MIMEImage(image_data, _subtype="jpeg")
  613. # Angle-bracketed Content-ID per RFC 2392, referenced from HTML
  614. # without the brackets via ``cid:bambuddy-finish-photo``.
  615. img.add_header("Content-ID", "<bambuddy-finish-photo>")
  616. img.add_header("Content-Disposition", "inline", filename="finish-photo.jpg")
  617. msg.attach(img)
  618. else:
  619. msg = MIMEMultipart()
  620. msg["From"] = from_email
  621. msg["To"] = to_email
  622. msg["Subject"] = f"[Bambuddy] {subject}"
  623. msg.attach(MIMEText(body, "plain"))
  624. # smtplib is synchronous and blocking: a wedged / greylisting /
  625. # firewall-dropped relay leaves recv() stuck. Two problems, two
  626. # fixes (#2572):
  627. # 1. No timeout — smtplib defaults to the global socket timeout,
  628. # which this app never sets, so a stuck relay blocks forever.
  629. # Pass an explicit timeout to every connect.
  630. # 2. Run on the event loop — a stuck (or merely slow) send freezes
  631. # every other coroutine, including a DB session a caller is
  632. # holding open across this notification. Offload to a worker
  633. # thread so the loop stays live and the connection is released
  634. # on schedule.
  635. smtp_timeout = 30.0
  636. msg_str = msg.as_string()
  637. def _blocking_send() -> None:
  638. if security == "ssl":
  639. # Direct SSL connection (typically port 465)
  640. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=smtp_timeout)
  641. elif security == "starttls":
  642. # STARTTLS upgrade (typically port 587)
  643. server = smtplib.SMTP(smtp_server, smtp_port, timeout=smtp_timeout)
  644. server.starttls()
  645. else:
  646. # No encryption (typically port 25) - use with caution
  647. server = smtplib.SMTP(smtp_server, smtp_port, timeout=smtp_timeout)
  648. try:
  649. if auth_enabled:
  650. server.login(username, password)
  651. server.sendmail(from_email, to_email, msg_str)
  652. finally:
  653. # quit() in finally so a send error doesn't leak the socket.
  654. try:
  655. server.quit()
  656. except Exception: # noqa: BLE001 — closing a broken connection is best-effort
  657. pass
  658. await asyncio.to_thread(_blocking_send)
  659. return True, "Email sent successfully"
  660. except smtplib.SMTPAuthenticationError:
  661. return False, "SMTP authentication failed - check username/password"
  662. except smtplib.SMTPException as e:
  663. return False, f"SMTP error: {str(e)}"
  664. except Exception as e:
  665. return False, f"Email error: {str(e)}"
  666. async def _send_discord(
  667. self, config: dict, title: str, message: str, image_data: bytes | None = None
  668. ) -> tuple[bool, str]:
  669. """Send notification via Discord webhook."""
  670. webhook_url = config.get("webhook_url", "").strip()
  671. if not webhook_url:
  672. return False, "Webhook URL is required"
  673. if not (
  674. webhook_url.startswith("https://discord.com/api/webhooks/")
  675. or webhook_url.startswith("https://discordapp.com/api/webhooks/")
  676. ):
  677. return False, "Invalid Discord webhook URL"
  678. # Discord embed format for nicer messages
  679. embed = {
  680. "title": title,
  681. "description": message,
  682. "color": 0x00AE42, # Bambu green
  683. }
  684. client = await self._get_client()
  685. if image_data:
  686. # Attach image via multipart form-data and reference in embed
  687. embed["image"] = {"url": "attachment://photo.jpg"}
  688. payload = {"embeds": [embed]}
  689. response = await client.post(
  690. webhook_url,
  691. data={"payload_json": json.dumps(payload)},
  692. files={"files[0]": ("photo.jpg", image_data, "image/jpeg")},
  693. )
  694. else:
  695. response = await client.post(webhook_url, json={"embeds": [embed]})
  696. if response.status_code in (200, 204):
  697. return True, "Message sent successfully"
  698. else:
  699. return False, f"HTTP {response.status_code}: {response.text[:200]}"
  700. async def _send_webhook(
  701. self,
  702. config: dict,
  703. title: str,
  704. message: str,
  705. image_data: bytes | None = None,
  706. event_type: str | None = None,
  707. variables: dict | None = None,
  708. ) -> tuple[bool, str]:
  709. """Send notification via generic webhook (POST JSON).
  710. Supports two payload formats:
  711. - generic: Custom field names with timestamp/source metadata + structured event data
  712. - slack: Slack/Mattermost compatible format (just {"text": "..."})
  713. """
  714. webhook_url = config.get("webhook_url", "").strip()
  715. auth_header = config.get("auth_header", "").strip()
  716. payload_format = config.get("payload_format", "generic").strip()
  717. if not webhook_url:
  718. return False, "Webhook URL is required"
  719. url_error = _assert_safe_provider_url(webhook_url, label="Webhook URL")
  720. if url_error:
  721. return False, url_error
  722. # Build payload based on format
  723. if payload_format == "slack":
  724. # Slack/Mattermost format - just text field
  725. data = {"text": f"*{title}*\n{message}"}
  726. if event_type == "print_confirm_request":
  727. # Slack and Mattermost fetch every URL in the text to build
  728. # preview cards, and the outcome prompt (#1898) is the one
  729. # message whose links are single-use capabilities — that fetch
  730. # would be a machine answering the operator's question. Off
  731. # here for the same reason Telegram's preview is.
  732. #
  733. # Only here: the slack payload never attaches image bytes (the
  734. # base64 attach below is generic-format only), so unfurling is
  735. # the only way a {finish_photo_url} in a print_complete body
  736. # can render as a photo in the channel. Switching it off for
  737. # every event would quietly take that away with no setting to
  738. # get it back.
  739. data["unfurl_links"] = False
  740. data["unfurl_media"] = False
  741. else:
  742. # Generic format with custom field names
  743. custom_field_title = config.get("field_title", "title").strip() or "title"
  744. custom_field_message = config.get("field_message", "message").strip() or "message"
  745. data = {
  746. custom_field_title: title,
  747. custom_field_message: message,
  748. "timestamp": datetime.now().isoformat(),
  749. "source": "Bambuddy",
  750. }
  751. # For generic format, include structured event data for automation tools
  752. if payload_format != "slack":
  753. if event_type:
  754. data["event"] = event_type
  755. if variables:
  756. for key, value in variables.items():
  757. if key not in data: # Don't overwrite title/message/timestamp/source
  758. data[key] = value
  759. # Attach base64-encoded image when available (generic format only)
  760. if image_data and payload_format != "slack":
  761. import base64
  762. data["image"] = base64.b64encode(image_data).decode("ascii")
  763. headers = {"Content-Type": "application/json"}
  764. if auth_header:
  765. # Support "Bearer token" or just "token" format
  766. if " " in auth_header:
  767. headers["Authorization"] = auth_header
  768. else:
  769. headers["Authorization"] = f"Bearer {auth_header}"
  770. client = await self._get_client()
  771. try:
  772. response = await client.post(webhook_url, json=data, headers=headers)
  773. if response.status_code in (200, 201, 202, 204):
  774. return True, "Webhook delivered successfully"
  775. else:
  776. return False, _opaque_http_failure(response, label="webhook endpoint")
  777. except Exception as e:
  778. return False, f"Webhook error: {str(e)}"
  779. async def _send_homeassistant(
  780. self, config: dict, title: str, message: str, db: AsyncSession | None = None
  781. ) -> tuple[bool, str]:
  782. """Send notification via Home Assistant.
  783. Uses the globally configured HA URL/token from settings.
  784. Defaults to persistent_notification/create, but supports
  785. custom services via config["service"] (e.g. notify.mobile_app_myphone).
  786. """
  787. # Get HA connection settings from global config
  788. ha_url = ""
  789. ha_token = ""
  790. if db:
  791. from backend.app.api.routes.settings import get_homeassistant_settings
  792. try:
  793. ha_settings = await get_homeassistant_settings(db)
  794. ha_url = ha_settings.get("ha_url", "")
  795. ha_token = ha_settings.get("ha_token", "")
  796. except Exception as e:
  797. logger.warning("Failed to read HA settings from database: %s", e)
  798. else:
  799. # Fallback: read directly from environment if no DB session
  800. import os
  801. ha_url = os.environ.get("HA_URL", "")
  802. ha_token = os.environ.get("HA_TOKEN", "")
  803. if not ha_url or not ha_token:
  804. return False, (
  805. "Home Assistant is not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  806. )
  807. # Determine which HA service to call - Default: persistent_notification.create
  808. service = (config.get("service") or "").strip()
  809. if service:
  810. # Allow in different forms:
  811. # - notify.mobile_app_<device>
  812. # - notify/mobile_app_<device>
  813. # - api/services/notify/mobile_app_<device>
  814. service_str = service.lstrip("/")
  815. if service_str.startswith("api/services/"):
  816. endpoint = service_str
  817. elif "/" in service_str:
  818. endpoint = f"api/services/{service_str}"
  819. elif "." in service_str:
  820. domain, svc = service_str.split(".", 1)
  821. endpoint = f"api/services/{domain}/{svc}"
  822. else:
  823. return False, (
  824. "Invalid Home Assistant service name. Use e.g. 'notify.mobile_app_yourdevice' or 'notify/your_service'."
  825. )
  826. if not re.match(r"^api/services/[a-zA-Z0-9_]+/[a-zA-Z0-9_]+$", endpoint):
  827. return False, (
  828. "Invalid Home Assistant service name. Domain and service must only contain letters, numbers, and underscores."
  829. )
  830. else:
  831. endpoint = "api/services/persistent_notification/create"
  832. url = f"{ha_url.rstrip('/')}/{endpoint}"
  833. headers = {
  834. "Authorization": f"Bearer {ha_token}",
  835. "Content-Type": "application/json",
  836. }
  837. payload = {
  838. "title": title,
  839. "message": message,
  840. }
  841. # Optional custom service-data (#1441), forwarded as HA's nested "data"
  842. # object so mobile-app push options (priority, ttl, channel, group, ...)
  843. # reach the notify service. Only included when configured — the default
  844. # persistent_notification.create schema rejects unknown keys.
  845. raw_data = config.get("data")
  846. if raw_data:
  847. if isinstance(raw_data, str):
  848. try:
  849. parsed_data = json.loads(raw_data)
  850. except json.JSONDecodeError as e:
  851. return False, f"Invalid JSON in the Data field: {e}"
  852. else:
  853. parsed_data = raw_data
  854. if not isinstance(parsed_data, dict):
  855. return False, 'The Data field must be a JSON object, e.g. {"priority": "high", "ttl": 0}'
  856. if parsed_data:
  857. payload["data"] = parsed_data
  858. client = await self._get_client()
  859. response = await client.post(url, json=payload, headers=headers)
  860. if response.status_code in (200, 201):
  861. return True, "Notification sent via Home Assistant"
  862. elif response.status_code == 401:
  863. return False, "Home Assistant authentication failed - check your token"
  864. else:
  865. # ha_url comes from global settings (SETTINGS_UPDATE, admin-only), so
  866. # this is a narrower channel than the per-request provider URLs — but
  867. # it lands in the same NOTIFICATIONS_CREATE-gated test response, so it
  868. # gets the same treatment.
  869. return False, _opaque_http_failure(response, label="Home Assistant endpoint")
  870. async def _send_to_provider(
  871. self,
  872. provider: NotificationProvider,
  873. title: str,
  874. message: str,
  875. db: AsyncSession | None = None,
  876. image_data: bytes | None = None,
  877. event_type: str | None = None,
  878. variables: dict | None = None,
  879. ) -> tuple[bool, str]:
  880. """Send notification to a specific provider."""
  881. # Check quiet hours
  882. if self._is_in_quiet_hours(provider):
  883. logger.info("Skipping notification to %s - quiet hours active", provider.name)
  884. return True, "Skipped - quiet hours"
  885. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  886. try:
  887. if provider.provider_type == "callmebot":
  888. return await self._send_callmebot(config, f"{title}\n{message}")
  889. elif provider.provider_type == "ntfy":
  890. # Outcome confirmation (#1898): render the verdict capability
  891. # links as one-tap buttons on the notification itself. http so
  892. # no browser needs to open; POST because that is the method
  893. # that records — a GET only opens the confirmation page, which
  894. # is what keeps unfurlers from answering the prompt.
  895. # clear=true dismisses the notification once a button was tapped.
  896. ntfy_actions = None
  897. good_url = (variables or {}).get("good_url")
  898. reject_url = (variables or {}).get("reject_url")
  899. # Buttons need absolute URLs; without a configured external_url
  900. # the links are relative, and the body's deep link into the
  901. # archive has to do.
  902. if (
  903. event_type == "print_confirm_request"
  904. and good_url
  905. and reject_url
  906. and good_url.startswith("http")
  907. and reject_url.startswith("http")
  908. ):
  909. ntfy_actions = (
  910. f"http, Good, {good_url}, method=POST, clear=true; "
  911. f"http, Reject, {reject_url}, method=POST, clear=true"
  912. )
  913. return await self._send_ntfy(
  914. config, title, message, image_data=image_data, event_type=event_type, actions=ntfy_actions
  915. )
  916. elif provider.provider_type == "pushover":
  917. # Outcome confirmation (#1898): Pushover has no arbitrary
  918. # buttons, but supports one supplementary URL — deep-link into
  919. # the archive's confirmation dialog.
  920. supplement_url = None
  921. supplement_url_title = None
  922. _confirm_url = (variables or {}).get("confirm_url")
  923. if event_type == "print_confirm_request" and _confirm_url and _confirm_url.startswith("http"):
  924. supplement_url = _confirm_url
  925. supplement_url_title = "Confirm print outcome"
  926. return await self._send_pushover(
  927. config, title, message, image_data=image_data, url=supplement_url, url_title=supplement_url_title
  928. )
  929. elif provider.provider_type == "telegram":
  930. # Outcome confirmation (#1898): inline URL buttons under the
  931. # message — one tap records the verdict via the capability
  932. # link. Same absolute-URL requirement as the ntfy actions.
  933. # Telegram has no way to POST, so this is the one affordance
  934. # that opens a browser, and it is the one that gets the one-tap
  935. # marker: the page submits itself only for a URL that came off
  936. # a button. Telegram does not fetch inline-keyboard URLs and
  937. # nothing else can read them, so the marker never reaches a
  938. # scanner — which is the difference between this and trusting
  939. # the User-Agent.
  940. tg_buttons = None
  941. _tg_good = (variables or {}).get("good_url")
  942. _tg_reject = (variables or {}).get("reject_url")
  943. if (
  944. event_type == "print_confirm_request"
  945. and _tg_good
  946. and _tg_reject
  947. and _tg_good.startswith("http")
  948. and _tg_reject.startswith("http")
  949. ):
  950. tg_buttons = [
  951. {"text": "\U0001f44d Good", "url": one_tap_url(_tg_good)},
  952. {"text": "\U0001f44e Reject", "url": one_tap_url(_tg_reject)},
  953. ]
  954. # Telegram's servers GET the first URL in the text to build a
  955. # preview card. An outcome prompt whose edited body still
  956. # carries {good_url} would have that fetch answer the question
  957. # before the operator saw it, so the preview is off for this
  958. # event. Only for this one, for the same reason as the Slack
  959. # unfurl in _send_webhook: when the finish photo is too large to attach,
  960. # the preview is how a {finish_photo_url} in a print_complete
  961. # body still shows up as a photo in the chat.
  962. return await self._send_telegram(
  963. config,
  964. f"*{title}*\n{message}",
  965. image_data=image_data,
  966. buttons=tg_buttons,
  967. link_preview=event_type != "print_confirm_request",
  968. )
  969. elif provider.provider_type == "email":
  970. # finish_photo_url is pulled from the rendered template variables
  971. # so _send_email can detect whether the template referenced the
  972. # URL and inline-embed the photo only in that case.
  973. finish_photo_url = (variables or {}).get("finish_photo_url")
  974. return await self._send_email(
  975. config, title, message, image_data=image_data, finish_photo_url=finish_photo_url
  976. )
  977. elif provider.provider_type == "discord":
  978. return await self._send_discord(config, title, message, image_data=image_data)
  979. elif provider.provider_type == "webhook":
  980. return await self._send_webhook(
  981. config, title, message, image_data=image_data, event_type=event_type, variables=variables
  982. )
  983. elif provider.provider_type == "homeassistant":
  984. return await self._send_homeassistant(config, title, message, db=db)
  985. elif provider.provider_type == "bark":
  986. # Outcome confirmation (#1898): Bark opens one URL on tap —
  987. # deep-link into the confirmation dialog, like Pushover.
  988. bark_url = None
  989. _bark_confirm = (variables or {}).get("confirm_url")
  990. if event_type == "print_confirm_request" and _bark_confirm and _bark_confirm.startswith("http"):
  991. bark_url = _bark_confirm
  992. return await self._send_bark(config, title, message, url=bark_url)
  993. else:
  994. return False, f"Unknown provider type: {provider.provider_type}"
  995. except Exception as e:
  996. logger.exception("Error sending notification via %s", provider.provider_type)
  997. return False, str(e)
  998. async def _update_provider_status(
  999. self, db: AsyncSession, provider_id: int, success: bool, error: str | None = None
  1000. ):
  1001. """Update provider status after sending notification."""
  1002. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  1003. provider = result.scalar_one_or_none()
  1004. if provider:
  1005. if success:
  1006. provider.last_success = datetime.now(timezone.utc)
  1007. else:
  1008. provider.last_error = error
  1009. provider.last_error_at = datetime.now(timezone.utc)
  1010. await db.commit()
  1011. async def _get_providers_for_event(
  1012. self,
  1013. db: AsyncSession,
  1014. event_field: str,
  1015. printer_id: int | None = None,
  1016. ) -> list[NotificationProvider]:
  1017. """Get all enabled providers that want a specific event type.
  1018. Runs under ``no_autoflush`` (#2770). Callers routinely hold pending
  1019. writes when they raise an event — the AMS sensor loop does
  1020. ``db.add(history)`` and only commits after the alarms have gone out — and
  1021. without this, autoflush satisfies this SELECT by writing those rows,
  1022. which opens a write transaction on SQLite. The provider is then contacted
  1023. over the network with that transaction still open, so a site whose
  1024. internet is down holds the single SQLite writer for the whole connect
  1025. timeout and unrelated background tasks fail with "database is locked".
  1026. Deferring the flush costs nothing here: providers are committed rows, so
  1027. a pending change in the caller's session cannot be one this query wants.
  1028. """
  1029. # Build the query dynamically based on event field
  1030. query = select(NotificationProvider).where(
  1031. NotificationProvider.enabled.is_(True),
  1032. getattr(NotificationProvider, event_field).is_(True),
  1033. )
  1034. if printer_id is not None:
  1035. query = query.where(
  1036. (NotificationProvider.printer_id.is_(None)) | (NotificationProvider.printer_id == printer_id)
  1037. )
  1038. with db.no_autoflush:
  1039. result = await db.execute(query)
  1040. return list(result.scalars().all())
  1041. async def _log_notification(
  1042. self,
  1043. db: AsyncSession,
  1044. provider_id: int,
  1045. event_type: str,
  1046. title: str,
  1047. message: str,
  1048. success: bool,
  1049. error_message: str | None = None,
  1050. printer_id: int | None = None,
  1051. printer_name: str | None = None,
  1052. ):
  1053. """Create a log entry for a sent notification."""
  1054. try:
  1055. log = NotificationLog(
  1056. provider_id=provider_id,
  1057. event_type=event_type,
  1058. title=title,
  1059. message=message,
  1060. success=success,
  1061. error_message=error_message,
  1062. printer_id=printer_id,
  1063. printer_name=printer_name,
  1064. )
  1065. db.add(log)
  1066. await db.commit()
  1067. except Exception as e:
  1068. logger.warning("Failed to log notification: %s", e)
  1069. # Don't fail the notification just because logging failed
  1070. async def _send_to_providers(
  1071. self,
  1072. providers: list[NotificationProvider],
  1073. title: str,
  1074. message: str,
  1075. db: AsyncSession,
  1076. event_type: str = "unknown",
  1077. printer_id: int | None = None,
  1078. printer_name: str | None = None,
  1079. force_immediate: bool = False,
  1080. image_data: bytes | None = None,
  1081. variables: dict | None = None,
  1082. ):
  1083. """Send notification to multiple providers and log the results.
  1084. All notifications are always sent immediately. If digest mode is enabled,
  1085. the notification is ALSO queued for the daily digest summary.
  1086. """
  1087. for provider in providers:
  1088. try:
  1089. # Always send notification immediately
  1090. success, error = await self._send_to_provider(
  1091. provider, title, message, db, image_data=image_data, event_type=event_type, variables=variables
  1092. )
  1093. # Also queue for digest if enabled (digest is a summary, not a queue)
  1094. if provider.daily_digest_enabled and provider.daily_digest_time:
  1095. await self._queue_for_digest(
  1096. provider=provider,
  1097. event_type=event_type,
  1098. title=title,
  1099. message=message,
  1100. db=db,
  1101. printer_id=printer_id,
  1102. printer_name=printer_name,
  1103. )
  1104. await self._update_provider_status(db, provider.id, success, error if not success else None)
  1105. await self._log_notification(
  1106. db=db,
  1107. provider_id=provider.id,
  1108. event_type=event_type,
  1109. title=title,
  1110. message=message,
  1111. success=success,
  1112. error_message=error if not success else None,
  1113. printer_id=printer_id,
  1114. printer_name=printer_name,
  1115. )
  1116. if success:
  1117. logger.info("Sent notification via %s", provider.name)
  1118. else:
  1119. logger.warning("Failed to send notification via %s: %s", provider.name, error)
  1120. except Exception as e:
  1121. logger.exception("Error sending notification via %s", provider.name)
  1122. await self._update_provider_status(db, provider.id, False, str(e))
  1123. await self._log_notification(
  1124. db=db,
  1125. provider_id=provider.id,
  1126. event_type=event_type,
  1127. title=title,
  1128. message=message,
  1129. success=False,
  1130. error_message=str(e),
  1131. printer_id=printer_id,
  1132. printer_name=printer_name,
  1133. )
  1134. async def on_app_message(
  1135. self,
  1136. db: AsyncSession,
  1137. *,
  1138. sender: str,
  1139. title: str,
  1140. message: str,
  1141. url: str | None = None,
  1142. ) -> int:
  1143. """A message another application sends through Bambuddy.
  1144. Goes to every enabled channel with "Messages from connected apps" on,
  1145. through the same path as Bambuddy's own events: quiet hours, the daily
  1146. digest and the log (whose event type names the sender). The text is
  1147. the app's own; a link, when given, is appended so every channel type
  1148. carries it. Returns how many channels it was handed to.
  1149. """
  1150. providers = await self._get_providers_for_event(db, "on_app_message")
  1151. if not providers:
  1152. return 0
  1153. body = f"{message}\n{url}" if url else message
  1154. await self._send_to_providers(providers, title, body, db, event_type=f"app:{sender}"[:50])
  1155. return len(providers)
  1156. async def on_print_start(
  1157. self,
  1158. printer_id: int,
  1159. printer_name: str,
  1160. data: dict,
  1161. db: AsyncSession,
  1162. archive_data: dict | None = None,
  1163. ):
  1164. """Handle print start event - send notifications to relevant providers.
  1165. Args:
  1166. printer_id: The printer ID
  1167. printer_name: The printer name
  1168. data: MQTT event data with filename, subtask_name, remaining_time, raw_data
  1169. db: Database session
  1170. archive_data: Optional archive data with print_time_seconds from 3MF parsing
  1171. """
  1172. logger.info("on_print_start called for printer %s (%s)", printer_id, printer_name)
  1173. providers = await self._get_providers_for_event(db, "on_print_start", printer_id)
  1174. if not providers:
  1175. logger.info("No notification providers configured for print_start event on printer %s", printer_id)
  1176. return
  1177. # Use subtask_name (project name) if available, otherwise use filename
  1178. subtask_name = data.get("subtask_name")
  1179. if subtask_name:
  1180. # Replace underscores with spaces for readability
  1181. filename = subtask_name.replace("_", " ")
  1182. else:
  1183. filename = self._clean_filename(data.get("filename", "Unknown"))
  1184. # Priority for estimated_time:
  1185. # 1. Archive's print_time_seconds from 3MF parsing (most reliable)
  1186. # 2. MQTT remaining_time (may be 0 at print start)
  1187. # 3. raw_data mc_remaining_time
  1188. estimated_time = None
  1189. # Try archive data first (from 3MF parsing - most reliable)
  1190. if archive_data and archive_data.get("print_time_seconds"):
  1191. estimated_time = archive_data["print_time_seconds"]
  1192. logger.debug("Using print_time_seconds from archive: %s", estimated_time)
  1193. # Fall back to MQTT remaining_time
  1194. if estimated_time is None:
  1195. estimated_time = data.get("remaining_time")
  1196. if estimated_time:
  1197. logger.debug("Using remaining_time from MQTT: %s", estimated_time)
  1198. # Last resort: raw_data mc_remaining_time (in minutes, convert to seconds)
  1199. if estimated_time is None:
  1200. raw_time = data.get("raw_data", {}).get("mc_remaining_time")
  1201. if raw_time:
  1202. estimated_time = raw_time * 60
  1203. logger.debug("Using mc_remaining_time from raw_data: %s", estimated_time)
  1204. time_str = self._format_duration(estimated_time)
  1205. eta_str = await self._format_eta(estimated_time, db)
  1206. variables = {
  1207. "printer": printer_name,
  1208. "filename": filename,
  1209. "estimated_time": time_str,
  1210. "eta": eta_str,
  1211. }
  1212. # Extract image data for providers that support attachments (e.g. Pushover)
  1213. image_data = None
  1214. if archive_data:
  1215. image_data = archive_data.get("image_data")
  1216. logger.info("Found %s providers for print_start: %s", len(providers), [p.name for p in providers])
  1217. title, message = await self._build_message_from_template(db, "print_start", variables)
  1218. await self._send_to_providers(
  1219. providers,
  1220. title,
  1221. message,
  1222. db,
  1223. "print_start",
  1224. printer_id,
  1225. printer_name,
  1226. image_data=image_data,
  1227. variables=variables,
  1228. )
  1229. async def on_print_complete(
  1230. self,
  1231. printer_id: int,
  1232. printer_name: str,
  1233. status: str,
  1234. data: dict,
  1235. db: AsyncSession,
  1236. archive_data: dict | None = None,
  1237. ):
  1238. """Handle print complete event - send notifications to relevant providers."""
  1239. logger.info("on_print_complete called for printer %s (%s), status=%s", printer_id, printer_name, status)
  1240. # Determine event type based on status
  1241. if status == "completed":
  1242. event_field = "on_print_complete"
  1243. event_type = "print_complete"
  1244. elif status in ("failed",):
  1245. event_field = "on_print_failed"
  1246. event_type = "print_failed"
  1247. elif status in ("aborted", "stopped", "cancelled"):
  1248. event_field = "on_print_stopped"
  1249. event_type = "print_stopped"
  1250. else:
  1251. logger.warning("Unknown print status '%s', defaulting to on_print_complete", status)
  1252. event_field = "on_print_complete"
  1253. event_type = "print_complete"
  1254. providers = await self._get_providers_for_event(db, event_field, printer_id)
  1255. if not providers:
  1256. logger.info("No notification providers configured for %s event on printer %s", event_field, printer_id)
  1257. return
  1258. # Use subtask_name (project name) if available, otherwise use filename
  1259. subtask_name = data.get("subtask_name")
  1260. if subtask_name:
  1261. filename = subtask_name.replace("_", " ")
  1262. else:
  1263. filename = self._clean_filename(data.get("filename", "Unknown"))
  1264. variables = {
  1265. "printer": printer_name,
  1266. "filename": filename,
  1267. "duration": "Unknown",
  1268. "filament_grams": "Unknown",
  1269. "reason": "Unknown",
  1270. }
  1271. if archive_data:
  1272. # {{duration}} on completion / failure / stopped events is the *actual*
  1273. # elapsed time (#1198). Slicer-estimated print_time_seconds is only used
  1274. # as a last-resort fallback when timestamps weren't recorded.
  1275. duration_seconds = archive_data.get("actual_time_seconds") or archive_data.get("print_time_seconds")
  1276. if duration_seconds:
  1277. variables["duration"] = self._format_duration(duration_seconds)
  1278. if archive_data.get("actual_filament_grams"):
  1279. variables["filament_grams"] = f"{archive_data['actual_filament_grams']:.1f}"
  1280. if status == "failed" and archive_data.get("failure_reason"):
  1281. variables["reason"] = archive_data["failure_reason"]
  1282. if archive_data.get("finish_photo_url"):
  1283. variables["finish_photo_url"] = archive_data["finish_photo_url"]
  1284. # Build per-slot breakdown string with AMS info when available
  1285. if archive_data.get("usage_results"):
  1286. parts = []
  1287. for u in archive_data["usage_results"]:
  1288. ams_id = u.get("ams_id", 0)
  1289. tray_id = u.get("tray_id", 0)
  1290. material = u.get("material", "Unknown") or "Unknown"
  1291. used = u.get("weight_used", 0)
  1292. if ams_id >= 128:
  1293. slot_label = "Ext"
  1294. else:
  1295. slot_label = f"AMS-{chr(65 + ams_id)} T{tray_id + 1}"
  1296. parts.append(f"{slot_label} {material}: {used:.1f}g")
  1297. variables["filament_details"] = " | ".join(parts)
  1298. elif archive_data.get("filament_slots"):
  1299. parts = []
  1300. for slot in archive_data["filament_slots"]:
  1301. ftype = slot.get("type", "Unknown") or "Unknown"
  1302. used = slot.get("used_g", 0)
  1303. parts.append(f"{ftype}: {used:.1f}g")
  1304. variables["filament_details"] = " | ".join(parts)
  1305. # Add progress for partial prints
  1306. if archive_data.get("progress") is not None:
  1307. variables["progress"] = str(archive_data["progress"])
  1308. # Extract image data for providers that support attachments (e.g. Pushover)
  1309. image_data = None
  1310. if archive_data:
  1311. image_data = archive_data.get("image_data")
  1312. logger.info("Found %s providers for %s: %s", len(providers), event_field, [p.name for p in providers])
  1313. title, message = await self._build_message_from_template(db, event_type, variables)
  1314. await self._send_to_providers(
  1315. providers,
  1316. title,
  1317. message,
  1318. db,
  1319. event_type,
  1320. printer_id,
  1321. printer_name,
  1322. image_data=image_data,
  1323. variables=variables,
  1324. )
  1325. async def on_print_confirm_request(
  1326. self,
  1327. printer_id: int,
  1328. printer_name: str,
  1329. data: dict,
  1330. db: AsyncSession,
  1331. archive_data: dict | None = None,
  1332. good_url: str | None = None,
  1333. reject_url: str | None = None,
  1334. confirm_url: str | None = None,
  1335. ):
  1336. """Ask for a post-print outcome verdict (#1898).
  1337. Fires only for completed prints whose queue item opted in — the
  1338. provider-level toggle exists to mute a channel, not to enable the
  1339. feature. good_url / reject_url are the one-tap capability links
  1340. (rendered as ntfy action buttons), confirm_url deep-links into the
  1341. archive's confirmation dialog in the web UI.
  1342. """
  1343. providers = await self._get_providers_for_event(db, "on_print_confirm_request", printer_id)
  1344. if not providers:
  1345. return
  1346. subtask_name = data.get("subtask_name")
  1347. if subtask_name:
  1348. filename = subtask_name.replace("_", " ")
  1349. else:
  1350. filename = self._clean_filename(data.get("filename", "Unknown"))
  1351. variables = {"printer": printer_name, "filename": filename}
  1352. if good_url:
  1353. variables["good_url"] = good_url
  1354. if reject_url:
  1355. variables["reject_url"] = reject_url
  1356. if confirm_url:
  1357. variables["confirm_url"] = confirm_url
  1358. image_data = None
  1359. if archive_data:
  1360. if archive_data.get("finish_photo_url"):
  1361. variables["finish_photo_url"] = archive_data["finish_photo_url"]
  1362. image_data = archive_data.get("image_data")
  1363. title, message = await self._build_message_from_template(db, "print_confirm_request", variables)
  1364. await self._send_to_providers(
  1365. providers,
  1366. title,
  1367. message,
  1368. db,
  1369. "print_confirm_request",
  1370. printer_id,
  1371. printer_name,
  1372. image_data=image_data,
  1373. variables=variables,
  1374. )
  1375. async def on_print_progress(
  1376. self,
  1377. printer_id: int,
  1378. printer_name: str,
  1379. filename: str,
  1380. progress: int,
  1381. db: AsyncSession,
  1382. remaining_time: int | None = None,
  1383. image_data: bytes | None = None,
  1384. ):
  1385. """Handle print progress milestone (25%, 50%, 75%)."""
  1386. providers = await self._get_providers_for_event(db, "on_print_progress", printer_id)
  1387. if not providers:
  1388. return
  1389. eta_str = await self._format_eta(remaining_time, db)
  1390. variables = {
  1391. "printer": printer_name,
  1392. "filename": self._clean_filename(filename),
  1393. "progress": str(progress),
  1394. "remaining_time": self._format_duration(remaining_time) if remaining_time else "Unknown",
  1395. "eta": eta_str,
  1396. }
  1397. title, message = await self._build_message_from_template(db, "print_progress", variables)
  1398. await self._send_to_providers(
  1399. providers,
  1400. title,
  1401. message,
  1402. db,
  1403. "print_progress",
  1404. printer_id,
  1405. printer_name,
  1406. image_data=image_data,
  1407. variables=variables,
  1408. )
  1409. async def on_print_missing_spool_assignment(
  1410. self,
  1411. printer_id: int,
  1412. printer_name: str,
  1413. missing_slots: list[dict[str, str]],
  1414. db: AsyncSession,
  1415. ):
  1416. """Handle print-start event when required trays are missing spool assignments."""
  1417. if not missing_slots:
  1418. return
  1419. providers = await self._get_providers_for_event(db, "on_print_missing_spool_assignment", printer_id)
  1420. if not providers:
  1421. return
  1422. missing_slot_names = ", ".join(slot.get("slot", "Unknown") for slot in missing_slots)
  1423. detail_lines = []
  1424. for slot in missing_slots:
  1425. slot_name = slot.get("slot", "Unknown")
  1426. profile = slot.get("profile", "Unknown")
  1427. detail_lines.append(f"- {slot_name}: {profile}")
  1428. missing_profile_details = "\n".join(detail_lines)
  1429. variables = {
  1430. "printer": printer_name,
  1431. "missing_slots": missing_slot_names,
  1432. "missing_slot_details": missing_profile_details,
  1433. }
  1434. title, message = await self._build_message_from_template(db, "print_missing_spool_assignment", variables)
  1435. await self._send_to_providers(
  1436. providers,
  1437. title,
  1438. message,
  1439. db,
  1440. "print_missing_spool_assignment",
  1441. printer_id,
  1442. printer_name,
  1443. force_immediate=True,
  1444. variables=variables,
  1445. )
  1446. async def on_billing_charge_failed(
  1447. self,
  1448. printer_id: int,
  1449. printer_name: str,
  1450. filename: str,
  1451. archive_id: int | None,
  1452. error: str,
  1453. db: AsyncSession,
  1454. ) -> None:
  1455. """Notify providers that a terminal print could not be charged."""
  1456. providers = await self._get_providers_for_event(db, "on_billing_charge_failed", printer_id)
  1457. if not providers:
  1458. return
  1459. variables = {
  1460. "printer": printer_name,
  1461. "filename": self._clean_filename(filename),
  1462. "archive_id": str(archive_id) if archive_id is not None else "Unknown",
  1463. "error": error,
  1464. }
  1465. title, message = await self._build_message_from_template(db, "billing_charge_failed", variables)
  1466. await self._send_to_providers(
  1467. providers,
  1468. title,
  1469. message,
  1470. db,
  1471. "billing_charge_failed",
  1472. printer_id,
  1473. printer_name,
  1474. force_immediate=True,
  1475. variables=variables,
  1476. )
  1477. async def on_printer_offline(self, printer_id: int, printer_name: str, db: AsyncSession):
  1478. """Handle printer offline event."""
  1479. providers = await self._get_providers_for_event(db, "on_printer_offline", printer_id)
  1480. if not providers:
  1481. return
  1482. variables = {"printer": printer_name}
  1483. title, message = await self._build_message_from_template(db, "printer_offline", variables)
  1484. await self._send_to_providers(
  1485. providers, title, message, db, "printer_offline", printer_id, printer_name, variables=variables
  1486. )
  1487. async def on_printer_error(
  1488. self,
  1489. printer_id: int,
  1490. printer_name: str,
  1491. error_type: str,
  1492. db: AsyncSession,
  1493. error_detail: str | None = None,
  1494. image_data: bytes | None = None,
  1495. ):
  1496. """Handle printer error event (AMS issues, etc.)."""
  1497. providers = await self._get_providers_for_event(db, "on_printer_error", printer_id)
  1498. if not providers:
  1499. return
  1500. variables = {
  1501. "printer": printer_name,
  1502. "error_type": error_type,
  1503. "error_detail": error_detail or "No details available",
  1504. }
  1505. title, message = await self._build_message_from_template(db, "printer_error", variables)
  1506. await self._send_to_providers(
  1507. providers,
  1508. title,
  1509. message,
  1510. db,
  1511. "printer_error",
  1512. printer_id,
  1513. printer_name,
  1514. image_data=image_data,
  1515. variables=variables,
  1516. )
  1517. async def on_ai_failure_detection(
  1518. self,
  1519. printer_id: int,
  1520. printer_name: str,
  1521. task_name: str,
  1522. confidence: float,
  1523. action: str,
  1524. db: AsyncSession,
  1525. image_data: bytes | None = None,
  1526. ):
  1527. """Handle AI failure-detection event (Obico spaghetti / print-failure ML).
  1528. Split out of on_printer_error (#1794) so a user can subscribe to AI
  1529. alerts without also being paged for every HMS hardware code.
  1530. """
  1531. providers = await self._get_providers_for_event(db, "on_ai_failure_detection", printer_id)
  1532. if not providers:
  1533. return
  1534. variables = {
  1535. "printer": printer_name,
  1536. "task_name": task_name or "current job",
  1537. "confidence": f"{confidence:.2f}",
  1538. "action": action,
  1539. }
  1540. title, message = await self._build_message_from_template(db, "ai_failure_detection", variables)
  1541. await self._send_to_providers(
  1542. providers,
  1543. title,
  1544. message,
  1545. db,
  1546. "ai_failure_detection",
  1547. printer_id,
  1548. printer_name,
  1549. image_data=image_data,
  1550. variables=variables,
  1551. )
  1552. async def on_plate_not_empty(
  1553. self,
  1554. printer_id: int,
  1555. printer_name: str,
  1556. db: AsyncSession,
  1557. difference_percent: float | None = None,
  1558. ):
  1559. """Handle plate not empty event - objects detected on build plate before print."""
  1560. providers = await self._get_providers_for_event(db, "on_plate_not_empty", printer_id)
  1561. if not providers:
  1562. return
  1563. variables = {
  1564. "printer": printer_name,
  1565. "difference_percent": f"{difference_percent:.1f}" if difference_percent else "N/A",
  1566. }
  1567. title, message = await self._build_message_from_template(db, "plate_not_empty", variables)
  1568. await self._send_to_providers(
  1569. providers,
  1570. title,
  1571. message,
  1572. db,
  1573. "plate_not_empty",
  1574. printer_id,
  1575. printer_name,
  1576. force_immediate=True,
  1577. variables=variables,
  1578. )
  1579. async def on_plate_clear_required(
  1580. self,
  1581. printer_id: int,
  1582. printer_name: str,
  1583. db: AsyncSession,
  1584. ):
  1585. """Handle plate-clear-required event — a print ended and the queue is gated (#2525).
  1586. Distinct from ``on_plate_not_empty``, which is the camera check *before* a
  1587. print starts. This one fires on the rising edge of the Bambuddy-side
  1588. awaiting-plate-clear flag, i.e. whenever a print reaches a terminal state
  1589. and the next queued job can't dispatch until someone confirms the bed is
  1590. free. Off by default on every provider: it lands at the same moment as the
  1591. print-complete notification, so opting in is a deliberate choice.
  1592. """
  1593. providers = await self._get_providers_for_event(db, "on_plate_clear_required", printer_id)
  1594. if not providers:
  1595. return
  1596. variables = {"printer": printer_name}
  1597. title, message = await self._build_message_from_template(db, "plate_clear_required", variables)
  1598. await self._send_to_providers(
  1599. providers,
  1600. title,
  1601. message,
  1602. db,
  1603. "plate_clear_required",
  1604. printer_id,
  1605. printer_name,
  1606. variables=variables,
  1607. )
  1608. async def on_filament_low(
  1609. self,
  1610. printer_id: int,
  1611. printer_name: str,
  1612. slot: int,
  1613. remaining_percent: int,
  1614. db: AsyncSession,
  1615. color: str | None = None,
  1616. ):
  1617. """Handle low filament event."""
  1618. providers = await self._get_providers_for_event(db, "on_filament_low", printer_id)
  1619. if not providers:
  1620. return
  1621. variables = {
  1622. "printer": printer_name,
  1623. "slot": str(slot),
  1624. "remaining_percent": str(remaining_percent),
  1625. "color": color or "",
  1626. }
  1627. title, message = await self._build_message_from_template(db, "filament_low", variables)
  1628. await self._send_to_providers(
  1629. providers, title, message, db, "filament_low", printer_id, printer_name, variables=variables
  1630. )
  1631. async def on_maintenance_due(
  1632. self,
  1633. printer_id: int,
  1634. printer_name: str,
  1635. maintenance_items: list[dict],
  1636. db: AsyncSession,
  1637. ):
  1638. """Handle maintenance due event - sends notification when maintenance is due or warning."""
  1639. if not maintenance_items:
  1640. return
  1641. providers = await self._get_providers_for_event(db, "on_maintenance_due", printer_id)
  1642. if not providers:
  1643. logger.info("No notification providers configured for maintenance_due event on printer %s", printer_id)
  1644. return
  1645. # Format maintenance items list
  1646. items_list = []
  1647. for item in maintenance_items:
  1648. status = "OVERDUE" if item.get("is_due") else "Soon"
  1649. items_list.append(f"- {item['name']} ({status})")
  1650. items_str = "\n".join(items_list)
  1651. variables = {
  1652. "printer": printer_name,
  1653. "items": items_str,
  1654. }
  1655. logger.info("Found %s providers for maintenance_due: %s", len(providers), [p.name for p in providers])
  1656. title, message = await self._build_message_from_template(db, "maintenance_due", variables)
  1657. await self._send_to_providers(
  1658. providers, title, message, db, "maintenance_due", printer_id, printer_name, variables=variables
  1659. )
  1660. async def on_ams_humidity_high(
  1661. self,
  1662. printer_id: int,
  1663. printer_name: str,
  1664. ams_label: str,
  1665. humidity: float,
  1666. threshold: float,
  1667. db: AsyncSession,
  1668. ):
  1669. """Handle AMS high humidity alarm event. Always sends immediately (bypasses digest)."""
  1670. providers = await self._get_providers_for_event(db, "on_ams_humidity_high", printer_id)
  1671. if not providers:
  1672. return
  1673. variables = {
  1674. "printer": printer_name,
  1675. "ams_label": ams_label,
  1676. "humidity": f"{humidity:.0f}",
  1677. "threshold": f"{threshold:.0f}",
  1678. }
  1679. title, message = await self._build_message_from_template(db, "ams_humidity_high", variables)
  1680. # Alarms always send immediately, bypassing digest mode
  1681. await self._send_to_providers(
  1682. providers,
  1683. title,
  1684. message,
  1685. db,
  1686. "ams_humidity_high",
  1687. printer_id,
  1688. printer_name,
  1689. force_immediate=True,
  1690. variables=variables,
  1691. )
  1692. async def on_ams_temperature_high(
  1693. self,
  1694. printer_id: int,
  1695. printer_name: str,
  1696. ams_label: str,
  1697. temperature: float,
  1698. threshold: float,
  1699. db: AsyncSession,
  1700. ):
  1701. """Handle AMS high temperature alarm event. Always sends immediately (bypasses digest)."""
  1702. providers = await self._get_providers_for_event(db, "on_ams_temperature_high", printer_id)
  1703. if not providers:
  1704. return
  1705. variables = {
  1706. "printer": printer_name,
  1707. "ams_label": ams_label,
  1708. "temperature": f"{temperature:.1f}",
  1709. "threshold": f"{threshold:.1f}",
  1710. }
  1711. title, message = await self._build_message_from_template(db, "ams_temperature_high", variables)
  1712. # Alarms always send immediately, bypassing digest mode
  1713. await self._send_to_providers(
  1714. providers,
  1715. title,
  1716. message,
  1717. db,
  1718. "ams_temperature_high",
  1719. printer_id,
  1720. printer_name,
  1721. force_immediate=True,
  1722. variables=variables,
  1723. )
  1724. async def on_ams_drying_suspended(
  1725. self,
  1726. printer_id: int,
  1727. printer_name: str,
  1728. ams_label: str,
  1729. humidity: float,
  1730. threshold: float,
  1731. cycles: int,
  1732. db: AsyncSession,
  1733. ):
  1734. """Handle automatic drying giving up on one AMS unit (#2770).
  1735. Sent immediately rather than folded into a digest: it reports that
  1736. Bambuddy has STOPPED doing something, and a report of inaction that
  1737. arrives with tomorrow's summary has already cost the user a day.
  1738. """
  1739. providers = await self._get_providers_for_event(db, "on_ams_drying_suspended", printer_id)
  1740. if not providers:
  1741. return
  1742. variables = {
  1743. "printer": printer_name,
  1744. "ams_label": ams_label,
  1745. "humidity": f"{humidity:.0f}",
  1746. "threshold": f"{threshold:.0f}",
  1747. "cycles": str(cycles),
  1748. }
  1749. title, message = await self._build_message_from_template(db, "ams_drying_suspended", variables)
  1750. await self._send_to_providers(
  1751. providers,
  1752. title,
  1753. message,
  1754. db,
  1755. "ams_drying_suspended",
  1756. printer_id,
  1757. printer_name,
  1758. force_immediate=True,
  1759. variables=variables,
  1760. )
  1761. async def on_ams_ht_humidity_high(
  1762. self,
  1763. printer_id: int,
  1764. printer_name: str,
  1765. ams_label: str,
  1766. humidity: float,
  1767. threshold: float,
  1768. db: AsyncSession,
  1769. ):
  1770. """Handle AMS-HT high humidity alarm event. Always sends immediately (bypasses digest)."""
  1771. providers = await self._get_providers_for_event(db, "on_ams_ht_humidity_high", printer_id)
  1772. if not providers:
  1773. return
  1774. variables = {
  1775. "printer": printer_name,
  1776. "ams_label": ams_label,
  1777. "humidity": f"{humidity:.0f}",
  1778. "threshold": f"{threshold:.0f}",
  1779. }
  1780. # Use the same template as regular AMS (can create separate templates later if needed)
  1781. title, message = await self._build_message_from_template(db, "ams_humidity_high", variables)
  1782. # Alarms always send immediately, bypassing digest mode
  1783. await self._send_to_providers(
  1784. providers,
  1785. title,
  1786. message,
  1787. db,
  1788. "ams_ht_humidity_high",
  1789. printer_id,
  1790. printer_name,
  1791. force_immediate=True,
  1792. variables=variables,
  1793. )
  1794. async def on_ams_ht_temperature_high(
  1795. self,
  1796. printer_id: int,
  1797. printer_name: str,
  1798. ams_label: str,
  1799. temperature: float,
  1800. threshold: float,
  1801. db: AsyncSession,
  1802. ):
  1803. """Handle AMS-HT high temperature alarm event. Always sends immediately (bypasses digest)."""
  1804. providers = await self._get_providers_for_event(db, "on_ams_ht_temperature_high", printer_id)
  1805. if not providers:
  1806. return
  1807. variables = {
  1808. "printer": printer_name,
  1809. "ams_label": ams_label,
  1810. "temperature": f"{temperature:.1f}",
  1811. "threshold": f"{threshold:.1f}",
  1812. }
  1813. # Use the same template as regular AMS (can create separate templates later if needed)
  1814. title, message = await self._build_message_from_template(db, "ams_temperature_high", variables)
  1815. # Alarms always send immediately, bypassing digest mode
  1816. await self._send_to_providers(
  1817. providers,
  1818. title,
  1819. message,
  1820. db,
  1821. "ams_ht_temperature_high",
  1822. printer_id,
  1823. printer_name,
  1824. force_immediate=True,
  1825. variables=variables,
  1826. )
  1827. async def on_bed_cooled(
  1828. self,
  1829. printer_id: int,
  1830. printer_name: str,
  1831. bed_temp: float,
  1832. threshold: float,
  1833. filename: str,
  1834. db: AsyncSession,
  1835. ):
  1836. """Handle bed cooled event - bed temperature dropped below threshold after print."""
  1837. providers = await self._get_providers_for_event(db, "on_bed_cooled", printer_id)
  1838. if not providers:
  1839. return
  1840. variables = {
  1841. "printer": printer_name,
  1842. "bed_temp": f"{bed_temp:.0f}",
  1843. "threshold": f"{threshold:.0f}",
  1844. "filename": self._clean_filename(filename) if filename else "Unknown",
  1845. }
  1846. title, message = await self._build_message_from_template(db, "bed_cooled", variables)
  1847. await self._send_to_providers(
  1848. providers, title, message, db, "bed_cooled", printer_id, printer_name, variables=variables
  1849. )
  1850. async def on_ha_sensor_alert(
  1851. self,
  1852. printer_id: int,
  1853. printer_name: str,
  1854. sensor_name: str,
  1855. state: str,
  1856. db: AsyncSession,
  1857. ):
  1858. """A Home Assistant sensor bound to a printer entered its alert state (#1148).
  1859. Sent immediately rather than folded into a digest: the case this exists
  1860. for is an enclosure door left open, which is only worth telling someone
  1861. about while they can still act on it.
  1862. """
  1863. providers = await self._get_providers_for_event(db, "on_ha_sensor_alert", printer_id)
  1864. if not providers:
  1865. return
  1866. variables = {
  1867. "printer": printer_name,
  1868. "sensor": sensor_name,
  1869. "state": state,
  1870. }
  1871. title, message = await self._build_message_from_template(db, "ha_sensor_alert", variables)
  1872. await self._send_to_providers(
  1873. providers,
  1874. title,
  1875. message,
  1876. db,
  1877. "ha_sensor_alert",
  1878. printer_id,
  1879. printer_name,
  1880. force_immediate=True,
  1881. variables=variables,
  1882. )
  1883. async def on_location_ha_sensor_alert(
  1884. self,
  1885. location_name: str,
  1886. sensor_name: str,
  1887. state: str,
  1888. db: AsyncSession,
  1889. ):
  1890. """A Home Assistant sensor bound to a storage location entered its alert state (#2824).
  1891. Sent immediately rather than folded into a digest, for the same reason
  1892. as on_ha_sensor_alert above: this is the "drybox went stale" case, only
  1893. worth acting on while the humidity/temperature is still climbing.
  1894. """
  1895. # Own column, not on_ha_sensor_alert (#2824): that one can be scoped to
  1896. # a single printer via provider.printer_id, and a location alert has no
  1897. # printer to scope by, so sharing it would leak drybox alerts to a
  1898. # provider narrowed to one printer's sensors.
  1899. providers = await self._get_providers_for_event(db, "on_location_ha_sensor_alert", None)
  1900. if not providers:
  1901. return
  1902. variables = {
  1903. "location": location_name,
  1904. "sensor": sensor_name,
  1905. "state": state,
  1906. }
  1907. title, message = await self._build_message_from_template(db, "location_ha_sensor_alert", variables)
  1908. await self._send_to_providers(
  1909. providers,
  1910. title,
  1911. message,
  1912. db,
  1913. "location_ha_sensor_alert",
  1914. force_immediate=True,
  1915. variables=variables,
  1916. )
  1917. async def on_first_layer_complete(
  1918. self,
  1919. printer_id: int,
  1920. printer_name: str,
  1921. filename: str,
  1922. total_layers: int,
  1923. db: AsyncSession,
  1924. image_data: bytes | None = None,
  1925. ):
  1926. """Handle first layer complete event."""
  1927. providers = await self._get_providers_for_event(db, "on_first_layer_complete", printer_id)
  1928. if not providers:
  1929. return
  1930. variables = {
  1931. "printer": printer_name,
  1932. "filename": self._clean_filename(filename),
  1933. "total_layers": str(total_layers),
  1934. }
  1935. title, message = await self._build_message_from_template(db, "first_layer_complete", variables)
  1936. await self._send_to_providers(
  1937. providers,
  1938. title,
  1939. message,
  1940. db,
  1941. "first_layer_complete",
  1942. printer_id,
  1943. printer_name,
  1944. image_data=image_data,
  1945. variables=variables,
  1946. )
  1947. def clear_template_cache(self):
  1948. """Clear the template cache. Call this when templates are updated."""
  1949. self._template_cache.clear()
  1950. async def send_user_print_email(
  1951. self,
  1952. event_type: str,
  1953. created_by_id: int | None,
  1954. printer_name: str,
  1955. filename: str,
  1956. db: AsyncSession,
  1957. ) -> None:
  1958. """Send a print event email notification to the user who submitted the job.
  1959. Args:
  1960. event_type: 'user_print_start', 'user_print_complete', 'user_print_failed', or 'user_print_stopped'
  1961. created_by_id: User ID who submitted the print job (from archive)
  1962. printer_name: Name of the printer
  1963. filename: Raw filename or subtask name
  1964. db: Database session
  1965. """
  1966. if created_by_id is None:
  1967. logger.debug("[EMAIL] Skipping user print email (%s): no created_by_id", event_type)
  1968. return
  1969. try:
  1970. # Check if advanced auth is enabled - required for user email notifications
  1971. from backend.app.models.settings import Settings
  1972. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  1973. setting = result.scalar_one_or_none()
  1974. if not setting or setting.value.lower() != "true":
  1975. logger.debug("[EMAIL] Skipping user print email (%s): advanced_auth not enabled", event_type)
  1976. return
  1977. # Check if user notifications are enabled (admin-controlled toggle)
  1978. notif_enabled_result = await db.execute(
  1979. select(Settings).where(Settings.key == "user_notifications_enabled")
  1980. )
  1981. notif_enabled_setting = notif_enabled_result.scalar_one_or_none()
  1982. if notif_enabled_setting and notif_enabled_setting.value.lower() == "false":
  1983. logger.debug("[EMAIL] Skipping user print email (%s): user_notifications_enabled is false", event_type)
  1984. return
  1985. # Check SMTP settings are configured - required for sending emails
  1986. from backend.app.services.email_service import get_smtp_settings, send_user_print_notification
  1987. smtp_settings = await get_smtp_settings(db)
  1988. if not smtp_settings:
  1989. logger.debug("[EMAIL] Skipping user print email (%s): SMTP settings not configured", event_type)
  1990. return
  1991. # Load user preferences
  1992. from backend.app.models.user import User
  1993. from backend.app.models.user_email_pref import UserEmailPreference
  1994. user_result = await db.execute(select(User).where(User.id == created_by_id))
  1995. user = user_result.scalar_one_or_none()
  1996. if user is None or not user.email:
  1997. logger.debug(
  1998. "[EMAIL] Skipping user print email (%s): user %s not found or has no email address",
  1999. event_type,
  2000. created_by_id,
  2001. )
  2002. return
  2003. # Load user's notification preferences
  2004. pref_result = await db.execute(
  2005. select(UserEmailPreference).where(UserEmailPreference.user_id == created_by_id)
  2006. )
  2007. pref = pref_result.scalar_one_or_none()
  2008. # Determine if this event type should be sent
  2009. should_send = False
  2010. if event_type == "user_print_start":
  2011. should_send = pref is None or pref.notify_print_start
  2012. elif event_type == "user_print_complete":
  2013. should_send = pref is None or pref.notify_print_complete
  2014. elif event_type == "user_print_failed":
  2015. should_send = pref is None or pref.notify_print_failed
  2016. elif event_type == "user_print_stopped":
  2017. should_send = pref is None or pref.notify_print_stopped
  2018. if not should_send:
  2019. logger.debug(
  2020. "[EMAIL] Skipping user print email (%s): user %s has notifications disabled for this event",
  2021. event_type,
  2022. created_by_id,
  2023. )
  2024. return
  2025. logger.info(
  2026. "[EMAIL] Sending user print email: event=%s, user=%s (%s), printer=%s, file=%s",
  2027. event_type,
  2028. user.username,
  2029. user.email,
  2030. printer_name,
  2031. filename,
  2032. )
  2033. # Build variables
  2034. variables = {
  2035. "printer": printer_name,
  2036. "filename": self._clean_filename(filename),
  2037. }
  2038. # Send the email
  2039. await send_user_print_notification(
  2040. db=db,
  2041. event_type=event_type,
  2042. user_email=user.email,
  2043. username=user.username,
  2044. variables=variables,
  2045. )
  2046. logger.info("[EMAIL] User print email sent: event=%s → %s", event_type, user.email)
  2047. except Exception as e:
  2048. logger.warning("Failed to send user print email notification: %s", e, exc_info=True)
  2049. # ==================== Queue Notifications ====================
  2050. async def on_queue_job_added(
  2051. self,
  2052. job_name: str,
  2053. target: str,
  2054. db: AsyncSession,
  2055. printer_id: int | None = None,
  2056. printer_name: str | None = None,
  2057. ):
  2058. """Handle queue job added event."""
  2059. providers = await self._get_providers_for_event(db, "on_queue_job_added", printer_id)
  2060. if not providers:
  2061. return
  2062. variables = {
  2063. "job_name": job_name,
  2064. "target": target, # e.g., "Printer1" or "Any X1C"
  2065. "printer": printer_name or target,
  2066. }
  2067. title, message = await self._build_message_from_template(db, "queue_job_added", variables)
  2068. await self._send_to_providers(
  2069. providers, title, message, db, "queue_job_added", printer_id, printer_name, variables=variables
  2070. )
  2071. async def on_queue_job_assigned(
  2072. self,
  2073. job_name: str,
  2074. printer_id: int,
  2075. printer_name: str,
  2076. target_model: str,
  2077. db: AsyncSession,
  2078. ):
  2079. """Handle model-based job assigned to printer event."""
  2080. providers = await self._get_providers_for_event(db, "on_queue_job_assigned", printer_id)
  2081. if not providers:
  2082. return
  2083. variables = {
  2084. "job_name": job_name,
  2085. "printer": printer_name,
  2086. "target_model": target_model,
  2087. }
  2088. title, message = await self._build_message_from_template(db, "queue_job_assigned", variables)
  2089. await self._send_to_providers(
  2090. providers, title, message, db, "queue_job_assigned", printer_id, printer_name, variables=variables
  2091. )
  2092. async def on_queue_job_started(
  2093. self,
  2094. job_name: str,
  2095. printer_id: int,
  2096. printer_name: str,
  2097. db: AsyncSession,
  2098. estimated_time: int | None = None,
  2099. ):
  2100. """Handle queue job started printing event."""
  2101. providers = await self._get_providers_for_event(db, "on_queue_job_started", printer_id)
  2102. if not providers:
  2103. return
  2104. eta_str = await self._format_eta(estimated_time, db)
  2105. variables = {
  2106. "job_name": job_name,
  2107. "printer": printer_name,
  2108. "estimated_time": self._format_duration(estimated_time),
  2109. "eta": eta_str,
  2110. }
  2111. title, message = await self._build_message_from_template(db, "queue_job_started", variables)
  2112. await self._send_to_providers(
  2113. providers, title, message, db, "queue_job_started", printer_id, printer_name, variables=variables
  2114. )
  2115. async def on_queue_job_waiting(
  2116. self,
  2117. job_name: str,
  2118. target_model: str,
  2119. waiting_reason: str,
  2120. db: AsyncSession,
  2121. ):
  2122. """Handle job waiting for filament event."""
  2123. providers = await self._get_providers_for_event(db, "on_queue_job_waiting", None)
  2124. if not providers:
  2125. return
  2126. variables = {
  2127. "job_name": job_name,
  2128. "target_model": target_model,
  2129. "waiting_reason": waiting_reason,
  2130. }
  2131. title, message = await self._build_message_from_template(db, "queue_job_waiting", variables)
  2132. await self._send_to_providers(providers, title, message, db, "queue_job_waiting", variables=variables)
  2133. async def on_queue_job_skipped(
  2134. self,
  2135. job_name: str,
  2136. printer_id: int,
  2137. printer_name: str,
  2138. reason: str,
  2139. db: AsyncSession,
  2140. ):
  2141. """Handle job skipped event (e.g., previous print failed)."""
  2142. providers = await self._get_providers_for_event(db, "on_queue_job_skipped", printer_id)
  2143. if not providers:
  2144. return
  2145. variables = {
  2146. "job_name": job_name,
  2147. "printer": printer_name,
  2148. "reason": reason,
  2149. }
  2150. title, message = await self._build_message_from_template(db, "queue_job_skipped", variables)
  2151. await self._send_to_providers(
  2152. providers, title, message, db, "queue_job_skipped", printer_id, printer_name, variables=variables
  2153. )
  2154. async def on_queue_job_failed(
  2155. self,
  2156. job_name: str,
  2157. printer_id: int | None,
  2158. printer_name: str | None,
  2159. reason: str,
  2160. db: AsyncSession,
  2161. ):
  2162. """Handle job failed to start event (upload error, etc.)."""
  2163. providers = await self._get_providers_for_event(db, "on_queue_job_failed", printer_id)
  2164. if not providers:
  2165. return
  2166. variables = {
  2167. "job_name": job_name,
  2168. "printer": printer_name or "Unknown",
  2169. "reason": reason,
  2170. }
  2171. title, message = await self._build_message_from_template(db, "queue_job_failed", variables)
  2172. await self._send_to_providers(
  2173. providers, title, message, db, "queue_job_failed", printer_id, printer_name, variables=variables
  2174. )
  2175. async def on_queue_completed(
  2176. self,
  2177. completed_count: int,
  2178. db: AsyncSession,
  2179. ):
  2180. """Handle all queue jobs completed event."""
  2181. providers = await self._get_providers_for_event(db, "on_queue_completed", None)
  2182. if not providers:
  2183. return
  2184. variables = {
  2185. "completed_count": str(completed_count),
  2186. }
  2187. title, message = await self._build_message_from_template(db, "queue_completed", variables)
  2188. await self._send_to_providers(providers, title, message, db, "queue_completed", variables=variables)
  2189. # ==================== Inventory Stock Alerts ====================
  2190. async def on_stock_reorder_alert(
  2191. self,
  2192. material: str,
  2193. brand: str | None,
  2194. stock_g: float,
  2195. rate_g_day: float,
  2196. days_left: int,
  2197. db: AsyncSession,
  2198. ):
  2199. """Fire when an inventory SKU reaches its reorder point."""
  2200. providers = await self._get_providers_for_event(db, "on_stock_reorder_alert", None)
  2201. if not providers:
  2202. return
  2203. variables = {
  2204. "material": material,
  2205. "brand": brand or "",
  2206. "stock_g": f"{stock_g:.0f}",
  2207. "rate_g_day": f"{rate_g_day:.1f}",
  2208. "days_left": str(days_left),
  2209. }
  2210. title, message = await self._build_message_from_template(db, "stock_reorder_alert", variables)
  2211. await self._send_to_providers(providers, title, message, db, "stock_reorder_alert", variables=variables)
  2212. async def on_stock_break_alert(
  2213. self,
  2214. material: str,
  2215. brand: str | None,
  2216. stock_g: float,
  2217. rate_g_day: float,
  2218. days_left: int,
  2219. lead_time_days: int,
  2220. db: AsyncSession,
  2221. ):
  2222. """Fire when a stock break is detected (stock runs out before lead time)."""
  2223. providers = await self._get_providers_for_event(db, "on_stock_break_alert", None)
  2224. if not providers:
  2225. return
  2226. variables = {
  2227. "material": material,
  2228. "brand": brand or "",
  2229. "stock_g": f"{stock_g:.0f}",
  2230. "rate_g_day": f"{rate_g_day:.1f}",
  2231. "days_left": str(days_left),
  2232. "lead_time_days": str(lead_time_days),
  2233. }
  2234. title, message = await self._build_message_from_template(db, "stock_break_alert", variables)
  2235. await self._send_to_providers(providers, title, message, db, "stock_break_alert", variables=variables)
  2236. async def _queue_for_digest(
  2237. self,
  2238. provider: NotificationProvider,
  2239. event_type: str,
  2240. title: str,
  2241. message: str,
  2242. db: AsyncSession,
  2243. printer_id: int | None = None,
  2244. printer_name: str | None = None,
  2245. ):
  2246. """Queue a notification for later delivery in the daily digest."""
  2247. try:
  2248. queue_entry = NotificationDigestQueue(
  2249. provider_id=provider.id,
  2250. event_type=event_type,
  2251. title=title,
  2252. message=message,
  2253. printer_id=printer_id,
  2254. printer_name=printer_name,
  2255. )
  2256. db.add(queue_entry)
  2257. await db.commit()
  2258. logger.info("Queued notification for digest: %s for provider %s", event_type, provider.name)
  2259. except Exception as e:
  2260. logger.warning("Failed to queue notification for digest: %s", e)
  2261. async def send_digest(self, provider_id: int):
  2262. """Send all queued notifications as a single digest for a provider."""
  2263. from backend.app.core.database import async_session
  2264. async with async_session() as db:
  2265. # Get the provider
  2266. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  2267. provider = result.scalar_one_or_none()
  2268. if not provider or not provider.enabled:
  2269. return
  2270. # Get all queued notifications for this provider
  2271. result = await db.execute(
  2272. select(NotificationDigestQueue)
  2273. .where(NotificationDigestQueue.provider_id == provider_id)
  2274. .order_by(NotificationDigestQueue.created_at)
  2275. )
  2276. queue_entries = list(result.scalars().all())
  2277. if not queue_entries:
  2278. logger.debug("No queued notifications for provider %s", provider.name)
  2279. return
  2280. # Build digest message
  2281. title = f"Daily Digest - {len(queue_entries)} Events"
  2282. # Group by event type
  2283. events_by_type: dict[str, list] = {}
  2284. for entry in queue_entries:
  2285. if entry.event_type not in events_by_type:
  2286. events_by_type[entry.event_type] = []
  2287. events_by_type[entry.event_type].append(entry)
  2288. # Format the digest body
  2289. body_parts = []
  2290. for event_type, entries in events_by_type.items():
  2291. event_label = event_type.replace("_", " ").title()
  2292. body_parts.append(f"== {event_label} ({len(entries)}) ==")
  2293. for entry in entries:
  2294. time_str = entry.created_at.strftime("%H:%M")
  2295. printer_info = f"[{entry.printer_name}] " if entry.printer_name else ""
  2296. body_parts.append(f" {time_str} {printer_info}{entry.title}")
  2297. body_parts.append("")
  2298. body = "\n".join(body_parts)
  2299. # Send the digest
  2300. success, error = await self._send_to_provider(provider, title, body, db)
  2301. # Log the digest
  2302. await self._log_notification(
  2303. db=db,
  2304. provider_id=provider.id,
  2305. event_type="daily_digest",
  2306. title=title,
  2307. message=body,
  2308. success=success,
  2309. error_message=error if not success else None,
  2310. )
  2311. # Clear the queue
  2312. for entry in queue_entries:
  2313. await db.delete(entry)
  2314. await db.commit()
  2315. if success:
  2316. logger.info("Sent daily digest with %s events to %s", len(queue_entries), provider.name)
  2317. else:
  2318. logger.warning("Failed to send daily digest to %s: %s", provider.name, error)
  2319. async def check_and_send_digests(self):
  2320. """Check all providers and send digests if it's their scheduled time."""
  2321. from backend.app.core.database import async_session
  2322. current_time = datetime.now().strftime("%H:%M")
  2323. # Avoid duplicate checks within the same minute
  2324. if current_time == self._last_digest_check:
  2325. return
  2326. self._last_digest_check = current_time
  2327. async with async_session() as db:
  2328. # Find all providers with digest enabled at this time
  2329. result = await db.execute(
  2330. select(NotificationProvider).where(
  2331. NotificationProvider.enabled.is_(True),
  2332. NotificationProvider.daily_digest_enabled.is_(True),
  2333. NotificationProvider.daily_digest_time == current_time,
  2334. )
  2335. )
  2336. providers = result.scalars().all()
  2337. for provider in providers:
  2338. try:
  2339. await self.send_digest(provider.id)
  2340. except Exception as e:
  2341. logger.error("Error sending digest for provider %s: %s", provider.id, e)
  2342. def start_digest_scheduler(self):
  2343. """Start the background scheduler for daily digest notifications."""
  2344. if self._digest_scheduler_task is None:
  2345. self._digest_scheduler_task = asyncio.create_task(self._digest_scheduler_loop())
  2346. logger.info("Notification digest scheduler started")
  2347. def stop_digest_scheduler(self):
  2348. """Stop the background scheduler for daily digests."""
  2349. if self._digest_scheduler_task:
  2350. self._digest_scheduler_task.cancel()
  2351. self._digest_scheduler_task = None
  2352. logger.info("Notification digest scheduler stopped")
  2353. async def _digest_scheduler_loop(self):
  2354. """Background loop that checks for scheduled digests every minute."""
  2355. while True:
  2356. try:
  2357. await self.check_and_send_digests()
  2358. except Exception as e:
  2359. logger.error("Error in digest scheduler: %s", e)
  2360. # Wait until the next minute
  2361. await asyncio.sleep(60)
  2362. # Global instance
  2363. notification_service = NotificationService()