notification_service.py 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642
  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. ) -> tuple[bool, str]:
  469. """Send notification via Telegram bot.
  470. ``buttons`` is one row of inline URL buttons (``{"text", "url"}``
  471. entries), used by the outcome-confirmation event (#1898) to put
  472. one-tap Good/Reject under the message.
  473. """
  474. bot_token = config.get("bot_token", "").strip()
  475. chat_id = config.get("chat_id", "").strip()
  476. if not bot_token or not chat_id:
  477. return False, "Bot token and chat ID are required"
  478. # Optional forum topic (#1518). Telegram expects message_thread_id as an
  479. # integer in the JSON sendMessage body — a string 400s there even though
  480. # the multipart sendPhoto call below would happily accept one. Coerce it
  481. # once, up front, so both call sites agree and a bad value fails loudly
  482. # instead of silently breaking only the text notifications.
  483. thread_id_raw = str(config.get("message_thread_id") or "").strip()
  484. message_thread_id: int | None = None
  485. if thread_id_raw:
  486. try:
  487. message_thread_id = int(thread_id_raw)
  488. except ValueError:
  489. return False, f"Invalid message thread ID: {thread_id_raw!r} is not a number"
  490. # Escape underscores in the message body so Telegram Markdown
  491. # parsing doesn't break on job names like "A1_plate_8" or error
  492. # codes like "0300_0001". The title is already wrapped in *bold*
  493. # markers, so only escape after the first newline.
  494. if "\n" in message:
  495. title_part, body_part = message.split("\n", 1)
  496. body_part = body_part.replace("_", "\\_")
  497. message = f"{title_part}\n{body_part}"
  498. client = await self._get_client()
  499. async def _post(with_buttons: bool):
  500. if image_data:
  501. # Use sendPhoto to attach the thumbnail with the caption
  502. url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
  503. form: dict[str, Any] = {"chat_id": chat_id, "caption": message, "parse_mode": "Markdown"}
  504. if message_thread_id is not None:
  505. form["message_thread_id"] = message_thread_id
  506. if with_buttons:
  507. # Multipart form fields are strings — reply_markup goes JSON-encoded.
  508. form["reply_markup"] = json.dumps({"inline_keyboard": [buttons]})
  509. return await client.post(
  510. url,
  511. data=form,
  512. files={"photo": ("photo.jpg", image_data, "image/jpeg")},
  513. )
  514. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  515. payload: dict[str, Any] = {
  516. "chat_id": chat_id,
  517. "text": message,
  518. "parse_mode": "Markdown",
  519. # Telegram's servers GET the first URL in the text to build a
  520. # preview card. The outcome prompt (#1898) carries single-use
  521. # verdict links in its body, so that fetch would answer the
  522. # question before the operator saw it. Bambuddy's messages are
  523. # status text; a preview card adds nothing to any of them.
  524. "disable_web_page_preview": True,
  525. }
  526. if message_thread_id is not None:
  527. payload["message_thread_id"] = message_thread_id
  528. if with_buttons:
  529. payload["reply_markup"] = {"inline_keyboard": [buttons]}
  530. return await client.post(url, json=payload)
  531. def _failure(resp) -> str | None:
  532. """What Telegram objected to, or None when the send went through."""
  533. if resp.status_code != 200:
  534. return f"HTTP {resp.status_code}: {resp.text[:200]}"
  535. result = resp.json()
  536. if result.get("ok"):
  537. return None
  538. return f"Telegram error: {result.get('description', 'Unknown error')}"
  539. response = await _post(bool(buttons))
  540. failure = _failure(response)
  541. if failure and buttons:
  542. # Telegram validates every inline-keyboard URL and refuses the whole
  543. # send when one of them is not a URL it accepts — which is what an
  544. # install without a public external_url produces for the #1898
  545. # verdict links. Dropping the buttons is survivable; dropping the
  546. # message the user is waiting for is not.
  547. logger.warning("Telegram refused the message with inline buttons (%s); retrying without them", failure)
  548. response = await _post(False)
  549. failure = _failure(response)
  550. if failure:
  551. return False, failure
  552. return True, "Message sent successfully"
  553. async def _send_email(
  554. self,
  555. config: dict,
  556. subject: str,
  557. body: str,
  558. image_data: bytes | None = None,
  559. finish_photo_url: str | None = None,
  560. ) -> tuple[bool, str]:
  561. """Send notification via email (SMTP).
  562. Inline finish-photo embed is opt-in via the template: when the rendered
  563. ``body`` contains the substituted ``{finish_photo_url}`` value AND the
  564. finish-photo bytes are present, the message is built as
  565. ``multipart/related`` wrapping a ``multipart/alternative`` (plain + HTML)
  566. plus an inline ``MIMEImage`` with ``Content-ID: <bambuddy-finish-photo>``.
  567. The HTML part replaces the URL with ``<img src="cid:...">``; the plain-
  568. text part keeps the URL as a clickable link. When the template doesn't
  569. reference ``{finish_photo_url}`` (or image bytes aren't available), the
  570. original single-part text shape is used — no attachment, no surprise
  571. inline image (#1792).
  572. """
  573. smtp_server = config.get("smtp_server", "").strip()
  574. smtp_port = int(config.get("smtp_port", 587))
  575. username = config.get("username", "").strip()
  576. password = config.get("password", "").strip()
  577. from_email = config.get("from_email", "").strip()
  578. to_email = config.get("to_email", "").strip()
  579. # Security: "starttls" (port 587), "ssl" (port 465), "none" (port 25)
  580. security = config.get("security", "starttls")
  581. # Authentication: "true" or "false"
  582. auth_enabled = config.get("auth_enabled", "true").lower() == "true"
  583. if not all([smtp_server, from_email, to_email]):
  584. return False, "SMTP server, from email, and to email are required"
  585. if auth_enabled and not all([username, password]):
  586. return False, "Username and password are required when authentication is enabled"
  587. # Template-driven: only inline-embed when the user's template explicitly
  588. # referenced {finish_photo_url} (so the URL appears in the rendered body)
  589. # AND the photo bytes are available. Falls back to text-only otherwise.
  590. inline_photo = bool(image_data and finish_photo_url and finish_photo_url in body)
  591. try:
  592. if inline_photo:
  593. # multipart/related → (multipart/alternative → text, html) + inline image
  594. msg = MIMEMultipart("related")
  595. msg["From"] = from_email
  596. msg["To"] = to_email
  597. msg["Subject"] = f"[Bambuddy] {subject}"
  598. alt = MIMEMultipart("alternative")
  599. alt.attach(MIMEText(body, "plain"))
  600. # Build HTML body: escape the rendered body, then swap the
  601. # escaped URL substring for an inline <img> referencing the
  602. # MIMEImage we attach below. Done AFTER escape so the cid: URL
  603. # we inject isn't re-escaped.
  604. escaped_body = html.escape(body).replace("\n", "<br>\n")
  605. escaped_url = html.escape(finish_photo_url)
  606. img_tag = (
  607. '<img src="cid:bambuddy-finish-photo" '
  608. 'alt="Printer camera snapshot" '
  609. 'style="max-width:100%;height:auto;border:1px solid #ddd;border-radius:4px;">'
  610. )
  611. html_body = f"<html><body><p>{escaped_body.replace(escaped_url, img_tag)}</p></body></html>"
  612. alt.attach(MIMEText(html_body, "html"))
  613. msg.attach(alt)
  614. img = MIMEImage(image_data, _subtype="jpeg")
  615. # Angle-bracketed Content-ID per RFC 2392, referenced from HTML
  616. # without the brackets via ``cid:bambuddy-finish-photo``.
  617. img.add_header("Content-ID", "<bambuddy-finish-photo>")
  618. img.add_header("Content-Disposition", "inline", filename="finish-photo.jpg")
  619. msg.attach(img)
  620. else:
  621. msg = MIMEMultipart()
  622. msg["From"] = from_email
  623. msg["To"] = to_email
  624. msg["Subject"] = f"[Bambuddy] {subject}"
  625. msg.attach(MIMEText(body, "plain"))
  626. # smtplib is synchronous and blocking: a wedged / greylisting /
  627. # firewall-dropped relay leaves recv() stuck. Two problems, two
  628. # fixes (#2572):
  629. # 1. No timeout — smtplib defaults to the global socket timeout,
  630. # which this app never sets, so a stuck relay blocks forever.
  631. # Pass an explicit timeout to every connect.
  632. # 2. Run on the event loop — a stuck (or merely slow) send freezes
  633. # every other coroutine, including a DB session a caller is
  634. # holding open across this notification. Offload to a worker
  635. # thread so the loop stays live and the connection is released
  636. # on schedule.
  637. smtp_timeout = 30.0
  638. msg_str = msg.as_string()
  639. def _blocking_send() -> None:
  640. if security == "ssl":
  641. # Direct SSL connection (typically port 465)
  642. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=smtp_timeout)
  643. elif security == "starttls":
  644. # STARTTLS upgrade (typically port 587)
  645. server = smtplib.SMTP(smtp_server, smtp_port, timeout=smtp_timeout)
  646. server.starttls()
  647. else:
  648. # No encryption (typically port 25) - use with caution
  649. server = smtplib.SMTP(smtp_server, smtp_port, timeout=smtp_timeout)
  650. try:
  651. if auth_enabled:
  652. server.login(username, password)
  653. server.sendmail(from_email, to_email, msg_str)
  654. finally:
  655. # quit() in finally so a send error doesn't leak the socket.
  656. try:
  657. server.quit()
  658. except Exception: # noqa: BLE001 — closing a broken connection is best-effort
  659. pass
  660. await asyncio.to_thread(_blocking_send)
  661. return True, "Email sent successfully"
  662. except smtplib.SMTPAuthenticationError:
  663. return False, "SMTP authentication failed - check username/password"
  664. except smtplib.SMTPException as e:
  665. return False, f"SMTP error: {str(e)}"
  666. except Exception as e:
  667. return False, f"Email error: {str(e)}"
  668. async def _send_discord(
  669. self, config: dict, title: str, message: str, image_data: bytes | None = None
  670. ) -> tuple[bool, str]:
  671. """Send notification via Discord webhook."""
  672. webhook_url = config.get("webhook_url", "").strip()
  673. if not webhook_url:
  674. return False, "Webhook URL is required"
  675. if not (
  676. webhook_url.startswith("https://discord.com/api/webhooks/")
  677. or webhook_url.startswith("https://discordapp.com/api/webhooks/")
  678. ):
  679. return False, "Invalid Discord webhook URL"
  680. # Discord embed format for nicer messages
  681. embed = {
  682. "title": title,
  683. "description": message,
  684. "color": 0x00AE42, # Bambu green
  685. }
  686. client = await self._get_client()
  687. if image_data:
  688. # Attach image via multipart form-data and reference in embed
  689. embed["image"] = {"url": "attachment://photo.jpg"}
  690. payload = {"embeds": [embed]}
  691. response = await client.post(
  692. webhook_url,
  693. data={"payload_json": json.dumps(payload)},
  694. files={"files[0]": ("photo.jpg", image_data, "image/jpeg")},
  695. )
  696. else:
  697. response = await client.post(webhook_url, json={"embeds": [embed]})
  698. if response.status_code in (200, 204):
  699. return True, "Message sent successfully"
  700. else:
  701. return False, f"HTTP {response.status_code}: {response.text[:200]}"
  702. async def _send_webhook(
  703. self,
  704. config: dict,
  705. title: str,
  706. message: str,
  707. image_data: bytes | None = None,
  708. event_type: str | None = None,
  709. variables: dict | None = None,
  710. ) -> tuple[bool, str]:
  711. """Send notification via generic webhook (POST JSON).
  712. Supports two payload formats:
  713. - generic: Custom field names with timestamp/source metadata + structured event data
  714. - slack: Slack/Mattermost compatible format (just {"text": "..."})
  715. """
  716. webhook_url = config.get("webhook_url", "").strip()
  717. auth_header = config.get("auth_header", "").strip()
  718. payload_format = config.get("payload_format", "generic").strip()
  719. if not webhook_url:
  720. return False, "Webhook URL is required"
  721. url_error = _assert_safe_provider_url(webhook_url, label="Webhook URL")
  722. if url_error:
  723. return False, url_error
  724. # Build payload based on format
  725. if payload_format == "slack":
  726. # Slack/Mattermost format - just text field
  727. data = {"text": f"*{title}*\n{message}"}
  728. if event_type == "print_confirm_request":
  729. # Slack and Mattermost fetch every URL in the text to build
  730. # preview cards, and the outcome prompt (#1898) is the one
  731. # message whose links are single-use capabilities — that fetch
  732. # would be a machine answering the operator's question. Off
  733. # here for the same reason Telegram's preview is.
  734. #
  735. # Only here: the slack payload never attaches image bytes (the
  736. # base64 attach below is generic-format only), so unfurling is
  737. # the only way a {finish_photo_url} in a print_complete body
  738. # can render as a photo in the channel. Switching it off for
  739. # every event would quietly take that away with no setting to
  740. # get it back.
  741. data["unfurl_links"] = False
  742. data["unfurl_media"] = False
  743. else:
  744. # Generic format with custom field names
  745. custom_field_title = config.get("field_title", "title").strip() or "title"
  746. custom_field_message = config.get("field_message", "message").strip() or "message"
  747. data = {
  748. custom_field_title: title,
  749. custom_field_message: message,
  750. "timestamp": datetime.now().isoformat(),
  751. "source": "Bambuddy",
  752. }
  753. # For generic format, include structured event data for automation tools
  754. if payload_format != "slack":
  755. if event_type:
  756. data["event"] = event_type
  757. if variables:
  758. for key, value in variables.items():
  759. if key not in data: # Don't overwrite title/message/timestamp/source
  760. data[key] = value
  761. # Attach base64-encoded image when available (generic format only)
  762. if image_data and payload_format != "slack":
  763. import base64
  764. data["image"] = base64.b64encode(image_data).decode("ascii")
  765. headers = {"Content-Type": "application/json"}
  766. if auth_header:
  767. # Support "Bearer token" or just "token" format
  768. if " " in auth_header:
  769. headers["Authorization"] = auth_header
  770. else:
  771. headers["Authorization"] = f"Bearer {auth_header}"
  772. client = await self._get_client()
  773. try:
  774. response = await client.post(webhook_url, json=data, headers=headers)
  775. if response.status_code in (200, 201, 202, 204):
  776. return True, "Webhook delivered successfully"
  777. else:
  778. return False, _opaque_http_failure(response, label="webhook endpoint")
  779. except Exception as e:
  780. return False, f"Webhook error: {str(e)}"
  781. async def _send_homeassistant(
  782. self, config: dict, title: str, message: str, db: AsyncSession | None = None
  783. ) -> tuple[bool, str]:
  784. """Send notification via Home Assistant.
  785. Uses the globally configured HA URL/token from settings.
  786. Defaults to persistent_notification/create, but supports
  787. custom services via config["service"] (e.g. notify.mobile_app_myphone).
  788. """
  789. # Get HA connection settings from global config
  790. ha_url = ""
  791. ha_token = ""
  792. if db:
  793. from backend.app.api.routes.settings import get_homeassistant_settings
  794. try:
  795. ha_settings = await get_homeassistant_settings(db)
  796. ha_url = ha_settings.get("ha_url", "")
  797. ha_token = ha_settings.get("ha_token", "")
  798. except Exception as e:
  799. logger.warning("Failed to read HA settings from database: %s", e)
  800. else:
  801. # Fallback: read directly from environment if no DB session
  802. import os
  803. ha_url = os.environ.get("HA_URL", "")
  804. ha_token = os.environ.get("HA_TOKEN", "")
  805. if not ha_url or not ha_token:
  806. return False, (
  807. "Home Assistant is not configured. Please set HA URL and token in Settings → Network → Home Assistant."
  808. )
  809. # Determine which HA service to call - Default: persistent_notification.create
  810. service = (config.get("service") or "").strip()
  811. if service:
  812. # Allow in different forms:
  813. # - notify.mobile_app_<device>
  814. # - notify/mobile_app_<device>
  815. # - api/services/notify/mobile_app_<device>
  816. service_str = service.lstrip("/")
  817. if service_str.startswith("api/services/"):
  818. endpoint = service_str
  819. elif "/" in service_str:
  820. endpoint = f"api/services/{service_str}"
  821. elif "." in service_str:
  822. domain, svc = service_str.split(".", 1)
  823. endpoint = f"api/services/{domain}/{svc}"
  824. else:
  825. return False, (
  826. "Invalid Home Assistant service name. Use e.g. 'notify.mobile_app_yourdevice' or 'notify/your_service'."
  827. )
  828. if not re.match(r"^api/services/[a-zA-Z0-9_]+/[a-zA-Z0-9_]+$", endpoint):
  829. return False, (
  830. "Invalid Home Assistant service name. Domain and service must only contain letters, numbers, and underscores."
  831. )
  832. else:
  833. endpoint = "api/services/persistent_notification/create"
  834. url = f"{ha_url.rstrip('/')}/{endpoint}"
  835. headers = {
  836. "Authorization": f"Bearer {ha_token}",
  837. "Content-Type": "application/json",
  838. }
  839. payload = {
  840. "title": title,
  841. "message": message,
  842. }
  843. # Optional custom service-data (#1441), forwarded as HA's nested "data"
  844. # object so mobile-app push options (priority, ttl, channel, group, ...)
  845. # reach the notify service. Only included when configured — the default
  846. # persistent_notification.create schema rejects unknown keys.
  847. raw_data = config.get("data")
  848. if raw_data:
  849. if isinstance(raw_data, str):
  850. try:
  851. parsed_data = json.loads(raw_data)
  852. except json.JSONDecodeError as e:
  853. return False, f"Invalid JSON in the Data field: {e}"
  854. else:
  855. parsed_data = raw_data
  856. if not isinstance(parsed_data, dict):
  857. return False, 'The Data field must be a JSON object, e.g. {"priority": "high", "ttl": 0}'
  858. if parsed_data:
  859. payload["data"] = parsed_data
  860. client = await self._get_client()
  861. response = await client.post(url, json=payload, headers=headers)
  862. if response.status_code in (200, 201):
  863. return True, "Notification sent via Home Assistant"
  864. elif response.status_code == 401:
  865. return False, "Home Assistant authentication failed - check your token"
  866. else:
  867. # ha_url comes from global settings (SETTINGS_UPDATE, admin-only), so
  868. # this is a narrower channel than the per-request provider URLs — but
  869. # it lands in the same NOTIFICATIONS_CREATE-gated test response, so it
  870. # gets the same treatment.
  871. return False, _opaque_http_failure(response, label="Home Assistant endpoint")
  872. async def _send_to_provider(
  873. self,
  874. provider: NotificationProvider,
  875. title: str,
  876. message: str,
  877. db: AsyncSession | None = None,
  878. image_data: bytes | None = None,
  879. event_type: str | None = None,
  880. variables: dict | None = None,
  881. ) -> tuple[bool, str]:
  882. """Send notification to a specific provider."""
  883. # Check quiet hours
  884. if self._is_in_quiet_hours(provider):
  885. logger.info("Skipping notification to %s - quiet hours active", provider.name)
  886. return True, "Skipped - quiet hours"
  887. config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
  888. try:
  889. if provider.provider_type == "callmebot":
  890. return await self._send_callmebot(config, f"{title}\n{message}")
  891. elif provider.provider_type == "ntfy":
  892. # Outcome confirmation (#1898): render the verdict capability
  893. # links as one-tap buttons on the notification itself. http so
  894. # no browser needs to open; POST because that is the method
  895. # that records — a GET only opens the confirmation page, which
  896. # is what keeps unfurlers from answering the prompt.
  897. # clear=true dismisses the notification once a button was tapped.
  898. ntfy_actions = None
  899. good_url = (variables or {}).get("good_url")
  900. reject_url = (variables or {}).get("reject_url")
  901. # Buttons need absolute URLs; without a configured external_url
  902. # the links are relative, and the body's deep link into the
  903. # archive has to do.
  904. if (
  905. event_type == "print_confirm_request"
  906. and good_url
  907. and reject_url
  908. and good_url.startswith("http")
  909. and reject_url.startswith("http")
  910. ):
  911. ntfy_actions = (
  912. f"http, Good, {good_url}, method=POST, clear=true; "
  913. f"http, Reject, {reject_url}, method=POST, clear=true"
  914. )
  915. return await self._send_ntfy(
  916. config, title, message, image_data=image_data, event_type=event_type, actions=ntfy_actions
  917. )
  918. elif provider.provider_type == "pushover":
  919. # Outcome confirmation (#1898): Pushover has no arbitrary
  920. # buttons, but supports one supplementary URL — deep-link into
  921. # the archive's confirmation dialog.
  922. supplement_url = None
  923. supplement_url_title = None
  924. _confirm_url = (variables or {}).get("confirm_url")
  925. if event_type == "print_confirm_request" and _confirm_url and _confirm_url.startswith("http"):
  926. supplement_url = _confirm_url
  927. supplement_url_title = "Confirm print outcome"
  928. return await self._send_pushover(
  929. config, title, message, image_data=image_data, url=supplement_url, url_title=supplement_url_title
  930. )
  931. elif provider.provider_type == "telegram":
  932. # Outcome confirmation (#1898): inline URL buttons under the
  933. # message — one tap records the verdict via the capability
  934. # link. Same absolute-URL requirement as the ntfy actions.
  935. # Telegram has no way to POST, so this is the one affordance
  936. # that opens a browser, and it is the one that gets the one-tap
  937. # marker: the page submits itself only for a URL that came off
  938. # a button. Telegram does not fetch inline-keyboard URLs and
  939. # nothing else can read them, so the marker never reaches a
  940. # scanner — which is the difference between this and trusting
  941. # the User-Agent.
  942. tg_buttons = None
  943. _tg_good = (variables or {}).get("good_url")
  944. _tg_reject = (variables or {}).get("reject_url")
  945. if (
  946. event_type == "print_confirm_request"
  947. and _tg_good
  948. and _tg_reject
  949. and _tg_good.startswith("http")
  950. and _tg_reject.startswith("http")
  951. ):
  952. tg_buttons = [
  953. {"text": "\U0001f44d Good", "url": one_tap_url(_tg_good)},
  954. {"text": "\U0001f44e Reject", "url": one_tap_url(_tg_reject)},
  955. ]
  956. return await self._send_telegram(
  957. config, f"*{title}*\n{message}", image_data=image_data, buttons=tg_buttons
  958. )
  959. elif provider.provider_type == "email":
  960. # finish_photo_url is pulled from the rendered template variables
  961. # so _send_email can detect whether the template referenced the
  962. # URL and inline-embed the photo only in that case.
  963. finish_photo_url = (variables or {}).get("finish_photo_url")
  964. return await self._send_email(
  965. config, title, message, image_data=image_data, finish_photo_url=finish_photo_url
  966. )
  967. elif provider.provider_type == "discord":
  968. return await self._send_discord(config, title, message, image_data=image_data)
  969. elif provider.provider_type == "webhook":
  970. return await self._send_webhook(
  971. config, title, message, image_data=image_data, event_type=event_type, variables=variables
  972. )
  973. elif provider.provider_type == "homeassistant":
  974. return await self._send_homeassistant(config, title, message, db=db)
  975. elif provider.provider_type == "bark":
  976. # Outcome confirmation (#1898): Bark opens one URL on tap —
  977. # deep-link into the confirmation dialog, like Pushover.
  978. bark_url = None
  979. _bark_confirm = (variables or {}).get("confirm_url")
  980. if event_type == "print_confirm_request" and _bark_confirm and _bark_confirm.startswith("http"):
  981. bark_url = _bark_confirm
  982. return await self._send_bark(config, title, message, url=bark_url)
  983. else:
  984. return False, f"Unknown provider type: {provider.provider_type}"
  985. except Exception as e:
  986. logger.exception("Error sending notification via %s", provider.provider_type)
  987. return False, str(e)
  988. async def _update_provider_status(
  989. self, db: AsyncSession, provider_id: int, success: bool, error: str | None = None
  990. ):
  991. """Update provider status after sending notification."""
  992. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  993. provider = result.scalar_one_or_none()
  994. if provider:
  995. if success:
  996. provider.last_success = datetime.now(timezone.utc)
  997. else:
  998. provider.last_error = error
  999. provider.last_error_at = datetime.now(timezone.utc)
  1000. await db.commit()
  1001. async def _get_providers_for_event(
  1002. self,
  1003. db: AsyncSession,
  1004. event_field: str,
  1005. printer_id: int | None = None,
  1006. ) -> list[NotificationProvider]:
  1007. """Get all enabled providers that want a specific event type.
  1008. Runs under ``no_autoflush`` (#2770). Callers routinely hold pending
  1009. writes when they raise an event — the AMS sensor loop does
  1010. ``db.add(history)`` and only commits after the alarms have gone out — and
  1011. without this, autoflush satisfies this SELECT by writing those rows,
  1012. which opens a write transaction on SQLite. The provider is then contacted
  1013. over the network with that transaction still open, so a site whose
  1014. internet is down holds the single SQLite writer for the whole connect
  1015. timeout and unrelated background tasks fail with "database is locked".
  1016. Deferring the flush costs nothing here: providers are committed rows, so
  1017. a pending change in the caller's session cannot be one this query wants.
  1018. """
  1019. # Build the query dynamically based on event field
  1020. query = select(NotificationProvider).where(
  1021. NotificationProvider.enabled.is_(True),
  1022. getattr(NotificationProvider, event_field).is_(True),
  1023. )
  1024. if printer_id is not None:
  1025. query = query.where(
  1026. (NotificationProvider.printer_id.is_(None)) | (NotificationProvider.printer_id == printer_id)
  1027. )
  1028. with db.no_autoflush:
  1029. result = await db.execute(query)
  1030. return list(result.scalars().all())
  1031. async def _log_notification(
  1032. self,
  1033. db: AsyncSession,
  1034. provider_id: int,
  1035. event_type: str,
  1036. title: str,
  1037. message: str,
  1038. success: bool,
  1039. error_message: str | None = None,
  1040. printer_id: int | None = None,
  1041. printer_name: str | None = None,
  1042. ):
  1043. """Create a log entry for a sent notification."""
  1044. try:
  1045. log = NotificationLog(
  1046. provider_id=provider_id,
  1047. event_type=event_type,
  1048. title=title,
  1049. message=message,
  1050. success=success,
  1051. error_message=error_message,
  1052. printer_id=printer_id,
  1053. printer_name=printer_name,
  1054. )
  1055. db.add(log)
  1056. await db.commit()
  1057. except Exception as e:
  1058. logger.warning("Failed to log notification: %s", e)
  1059. # Don't fail the notification just because logging failed
  1060. async def _send_to_providers(
  1061. self,
  1062. providers: list[NotificationProvider],
  1063. title: str,
  1064. message: str,
  1065. db: AsyncSession,
  1066. event_type: str = "unknown",
  1067. printer_id: int | None = None,
  1068. printer_name: str | None = None,
  1069. force_immediate: bool = False,
  1070. image_data: bytes | None = None,
  1071. variables: dict | None = None,
  1072. ):
  1073. """Send notification to multiple providers and log the results.
  1074. All notifications are always sent immediately. If digest mode is enabled,
  1075. the notification is ALSO queued for the daily digest summary.
  1076. """
  1077. for provider in providers:
  1078. try:
  1079. # Always send notification immediately
  1080. success, error = await self._send_to_provider(
  1081. provider, title, message, db, image_data=image_data, event_type=event_type, variables=variables
  1082. )
  1083. # Also queue for digest if enabled (digest is a summary, not a queue)
  1084. if provider.daily_digest_enabled and provider.daily_digest_time:
  1085. await self._queue_for_digest(
  1086. provider=provider,
  1087. event_type=event_type,
  1088. title=title,
  1089. message=message,
  1090. db=db,
  1091. printer_id=printer_id,
  1092. printer_name=printer_name,
  1093. )
  1094. await self._update_provider_status(db, provider.id, success, error if not success else None)
  1095. await self._log_notification(
  1096. db=db,
  1097. provider_id=provider.id,
  1098. event_type=event_type,
  1099. title=title,
  1100. message=message,
  1101. success=success,
  1102. error_message=error if not success else None,
  1103. printer_id=printer_id,
  1104. printer_name=printer_name,
  1105. )
  1106. if success:
  1107. logger.info("Sent notification via %s", provider.name)
  1108. else:
  1109. logger.warning("Failed to send notification via %s: %s", provider.name, error)
  1110. except Exception as e:
  1111. logger.exception("Error sending notification via %s", provider.name)
  1112. await self._update_provider_status(db, provider.id, False, str(e))
  1113. await self._log_notification(
  1114. db=db,
  1115. provider_id=provider.id,
  1116. event_type=event_type,
  1117. title=title,
  1118. message=message,
  1119. success=False,
  1120. error_message=str(e),
  1121. printer_id=printer_id,
  1122. printer_name=printer_name,
  1123. )
  1124. async def on_print_start(
  1125. self,
  1126. printer_id: int,
  1127. printer_name: str,
  1128. data: dict,
  1129. db: AsyncSession,
  1130. archive_data: dict | None = None,
  1131. ):
  1132. """Handle print start event - send notifications to relevant providers.
  1133. Args:
  1134. printer_id: The printer ID
  1135. printer_name: The printer name
  1136. data: MQTT event data with filename, subtask_name, remaining_time, raw_data
  1137. db: Database session
  1138. archive_data: Optional archive data with print_time_seconds from 3MF parsing
  1139. """
  1140. logger.info("on_print_start called for printer %s (%s)", printer_id, printer_name)
  1141. providers = await self._get_providers_for_event(db, "on_print_start", printer_id)
  1142. if not providers:
  1143. logger.info("No notification providers configured for print_start event on printer %s", printer_id)
  1144. return
  1145. # Use subtask_name (project name) if available, otherwise use filename
  1146. subtask_name = data.get("subtask_name")
  1147. if subtask_name:
  1148. # Replace underscores with spaces for readability
  1149. filename = subtask_name.replace("_", " ")
  1150. else:
  1151. filename = self._clean_filename(data.get("filename", "Unknown"))
  1152. # Priority for estimated_time:
  1153. # 1. Archive's print_time_seconds from 3MF parsing (most reliable)
  1154. # 2. MQTT remaining_time (may be 0 at print start)
  1155. # 3. raw_data mc_remaining_time
  1156. estimated_time = None
  1157. # Try archive data first (from 3MF parsing - most reliable)
  1158. if archive_data and archive_data.get("print_time_seconds"):
  1159. estimated_time = archive_data["print_time_seconds"]
  1160. logger.debug("Using print_time_seconds from archive: %s", estimated_time)
  1161. # Fall back to MQTT remaining_time
  1162. if estimated_time is None:
  1163. estimated_time = data.get("remaining_time")
  1164. if estimated_time:
  1165. logger.debug("Using remaining_time from MQTT: %s", estimated_time)
  1166. # Last resort: raw_data mc_remaining_time (in minutes, convert to seconds)
  1167. if estimated_time is None:
  1168. raw_time = data.get("raw_data", {}).get("mc_remaining_time")
  1169. if raw_time:
  1170. estimated_time = raw_time * 60
  1171. logger.debug("Using mc_remaining_time from raw_data: %s", estimated_time)
  1172. time_str = self._format_duration(estimated_time)
  1173. eta_str = await self._format_eta(estimated_time, db)
  1174. variables = {
  1175. "printer": printer_name,
  1176. "filename": filename,
  1177. "estimated_time": time_str,
  1178. "eta": eta_str,
  1179. }
  1180. # Extract image data for providers that support attachments (e.g. Pushover)
  1181. image_data = None
  1182. if archive_data:
  1183. image_data = archive_data.get("image_data")
  1184. logger.info("Found %s providers for print_start: %s", len(providers), [p.name for p in providers])
  1185. title, message = await self._build_message_from_template(db, "print_start", variables)
  1186. await self._send_to_providers(
  1187. providers,
  1188. title,
  1189. message,
  1190. db,
  1191. "print_start",
  1192. printer_id,
  1193. printer_name,
  1194. image_data=image_data,
  1195. variables=variables,
  1196. )
  1197. async def on_print_complete(
  1198. self,
  1199. printer_id: int,
  1200. printer_name: str,
  1201. status: str,
  1202. data: dict,
  1203. db: AsyncSession,
  1204. archive_data: dict | None = None,
  1205. ):
  1206. """Handle print complete event - send notifications to relevant providers."""
  1207. logger.info("on_print_complete called for printer %s (%s), status=%s", printer_id, printer_name, status)
  1208. # Determine event type based on status
  1209. if status == "completed":
  1210. event_field = "on_print_complete"
  1211. event_type = "print_complete"
  1212. elif status in ("failed",):
  1213. event_field = "on_print_failed"
  1214. event_type = "print_failed"
  1215. elif status in ("aborted", "stopped", "cancelled"):
  1216. event_field = "on_print_stopped"
  1217. event_type = "print_stopped"
  1218. else:
  1219. logger.warning("Unknown print status '%s', defaulting to on_print_complete", status)
  1220. event_field = "on_print_complete"
  1221. event_type = "print_complete"
  1222. providers = await self._get_providers_for_event(db, event_field, printer_id)
  1223. if not providers:
  1224. logger.info("No notification providers configured for %s event on printer %s", event_field, printer_id)
  1225. return
  1226. # Use subtask_name (project name) if available, otherwise use filename
  1227. subtask_name = data.get("subtask_name")
  1228. if subtask_name:
  1229. filename = subtask_name.replace("_", " ")
  1230. else:
  1231. filename = self._clean_filename(data.get("filename", "Unknown"))
  1232. variables = {
  1233. "printer": printer_name,
  1234. "filename": filename,
  1235. "duration": "Unknown",
  1236. "filament_grams": "Unknown",
  1237. "reason": "Unknown",
  1238. }
  1239. if archive_data:
  1240. # {{duration}} on completion / failure / stopped events is the *actual*
  1241. # elapsed time (#1198). Slicer-estimated print_time_seconds is only used
  1242. # as a last-resort fallback when timestamps weren't recorded.
  1243. duration_seconds = archive_data.get("actual_time_seconds") or archive_data.get("print_time_seconds")
  1244. if duration_seconds:
  1245. variables["duration"] = self._format_duration(duration_seconds)
  1246. if archive_data.get("actual_filament_grams"):
  1247. variables["filament_grams"] = f"{archive_data['actual_filament_grams']:.1f}"
  1248. if status == "failed" and archive_data.get("failure_reason"):
  1249. variables["reason"] = archive_data["failure_reason"]
  1250. if archive_data.get("finish_photo_url"):
  1251. variables["finish_photo_url"] = archive_data["finish_photo_url"]
  1252. # Build per-slot breakdown string with AMS info when available
  1253. if archive_data.get("usage_results"):
  1254. parts = []
  1255. for u in archive_data["usage_results"]:
  1256. ams_id = u.get("ams_id", 0)
  1257. tray_id = u.get("tray_id", 0)
  1258. material = u.get("material", "Unknown") or "Unknown"
  1259. used = u.get("weight_used", 0)
  1260. if ams_id >= 128:
  1261. slot_label = "Ext"
  1262. else:
  1263. slot_label = f"AMS-{chr(65 + ams_id)} T{tray_id + 1}"
  1264. parts.append(f"{slot_label} {material}: {used:.1f}g")
  1265. variables["filament_details"] = " | ".join(parts)
  1266. elif archive_data.get("filament_slots"):
  1267. parts = []
  1268. for slot in archive_data["filament_slots"]:
  1269. ftype = slot.get("type", "Unknown") or "Unknown"
  1270. used = slot.get("used_g", 0)
  1271. parts.append(f"{ftype}: {used:.1f}g")
  1272. variables["filament_details"] = " | ".join(parts)
  1273. # Add progress for partial prints
  1274. if archive_data.get("progress") is not None:
  1275. variables["progress"] = str(archive_data["progress"])
  1276. # Extract image data for providers that support attachments (e.g. Pushover)
  1277. image_data = None
  1278. if archive_data:
  1279. image_data = archive_data.get("image_data")
  1280. logger.info("Found %s providers for %s: %s", len(providers), event_field, [p.name for p in providers])
  1281. title, message = await self._build_message_from_template(db, event_type, variables)
  1282. await self._send_to_providers(
  1283. providers,
  1284. title,
  1285. message,
  1286. db,
  1287. event_type,
  1288. printer_id,
  1289. printer_name,
  1290. image_data=image_data,
  1291. variables=variables,
  1292. )
  1293. async def on_print_confirm_request(
  1294. self,
  1295. printer_id: int,
  1296. printer_name: str,
  1297. data: dict,
  1298. db: AsyncSession,
  1299. archive_data: dict | None = None,
  1300. good_url: str | None = None,
  1301. reject_url: str | None = None,
  1302. confirm_url: str | None = None,
  1303. ):
  1304. """Ask for a post-print outcome verdict (#1898).
  1305. Fires only for completed prints whose queue item opted in — the
  1306. provider-level toggle exists to mute a channel, not to enable the
  1307. feature. good_url / reject_url are the one-tap capability links
  1308. (rendered as ntfy action buttons), confirm_url deep-links into the
  1309. archive's confirmation dialog in the web UI.
  1310. """
  1311. providers = await self._get_providers_for_event(db, "on_print_confirm_request", printer_id)
  1312. if not providers:
  1313. return
  1314. subtask_name = data.get("subtask_name")
  1315. if subtask_name:
  1316. filename = subtask_name.replace("_", " ")
  1317. else:
  1318. filename = self._clean_filename(data.get("filename", "Unknown"))
  1319. variables = {"printer": printer_name, "filename": filename}
  1320. if good_url:
  1321. variables["good_url"] = good_url
  1322. if reject_url:
  1323. variables["reject_url"] = reject_url
  1324. if confirm_url:
  1325. variables["confirm_url"] = confirm_url
  1326. image_data = None
  1327. if archive_data:
  1328. if archive_data.get("finish_photo_url"):
  1329. variables["finish_photo_url"] = archive_data["finish_photo_url"]
  1330. image_data = archive_data.get("image_data")
  1331. title, message = await self._build_message_from_template(db, "print_confirm_request", variables)
  1332. await self._send_to_providers(
  1333. providers,
  1334. title,
  1335. message,
  1336. db,
  1337. "print_confirm_request",
  1338. printer_id,
  1339. printer_name,
  1340. image_data=image_data,
  1341. variables=variables,
  1342. )
  1343. async def on_print_progress(
  1344. self,
  1345. printer_id: int,
  1346. printer_name: str,
  1347. filename: str,
  1348. progress: int,
  1349. db: AsyncSession,
  1350. remaining_time: int | None = None,
  1351. image_data: bytes | None = None,
  1352. ):
  1353. """Handle print progress milestone (25%, 50%, 75%)."""
  1354. providers = await self._get_providers_for_event(db, "on_print_progress", printer_id)
  1355. if not providers:
  1356. return
  1357. eta_str = await self._format_eta(remaining_time, db)
  1358. variables = {
  1359. "printer": printer_name,
  1360. "filename": self._clean_filename(filename),
  1361. "progress": str(progress),
  1362. "remaining_time": self._format_duration(remaining_time) if remaining_time else "Unknown",
  1363. "eta": eta_str,
  1364. }
  1365. title, message = await self._build_message_from_template(db, "print_progress", variables)
  1366. await self._send_to_providers(
  1367. providers,
  1368. title,
  1369. message,
  1370. db,
  1371. "print_progress",
  1372. printer_id,
  1373. printer_name,
  1374. image_data=image_data,
  1375. variables=variables,
  1376. )
  1377. async def on_print_missing_spool_assignment(
  1378. self,
  1379. printer_id: int,
  1380. printer_name: str,
  1381. missing_slots: list[dict[str, str]],
  1382. db: AsyncSession,
  1383. ):
  1384. """Handle print-start event when required trays are missing spool assignments."""
  1385. if not missing_slots:
  1386. return
  1387. providers = await self._get_providers_for_event(db, "on_print_missing_spool_assignment", printer_id)
  1388. if not providers:
  1389. return
  1390. missing_slot_names = ", ".join(slot.get("slot", "Unknown") for slot in missing_slots)
  1391. detail_lines = []
  1392. for slot in missing_slots:
  1393. slot_name = slot.get("slot", "Unknown")
  1394. profile = slot.get("profile", "Unknown")
  1395. detail_lines.append(f"- {slot_name}: {profile}")
  1396. missing_profile_details = "\n".join(detail_lines)
  1397. variables = {
  1398. "printer": printer_name,
  1399. "missing_slots": missing_slot_names,
  1400. "missing_slot_details": missing_profile_details,
  1401. }
  1402. title, message = await self._build_message_from_template(db, "print_missing_spool_assignment", variables)
  1403. await self._send_to_providers(
  1404. providers,
  1405. title,
  1406. message,
  1407. db,
  1408. "print_missing_spool_assignment",
  1409. printer_id,
  1410. printer_name,
  1411. force_immediate=True,
  1412. variables=variables,
  1413. )
  1414. async def on_billing_charge_failed(
  1415. self,
  1416. printer_id: int,
  1417. printer_name: str,
  1418. filename: str,
  1419. archive_id: int | None,
  1420. error: str,
  1421. db: AsyncSession,
  1422. ) -> None:
  1423. """Notify providers that a terminal print could not be charged."""
  1424. providers = await self._get_providers_for_event(db, "on_billing_charge_failed", printer_id)
  1425. if not providers:
  1426. return
  1427. variables = {
  1428. "printer": printer_name,
  1429. "filename": self._clean_filename(filename),
  1430. "archive_id": str(archive_id) if archive_id is not None else "Unknown",
  1431. "error": error,
  1432. }
  1433. title, message = await self._build_message_from_template(db, "billing_charge_failed", variables)
  1434. await self._send_to_providers(
  1435. providers,
  1436. title,
  1437. message,
  1438. db,
  1439. "billing_charge_failed",
  1440. printer_id,
  1441. printer_name,
  1442. force_immediate=True,
  1443. variables=variables,
  1444. )
  1445. async def on_printer_offline(self, printer_id: int, printer_name: str, db: AsyncSession):
  1446. """Handle printer offline event."""
  1447. providers = await self._get_providers_for_event(db, "on_printer_offline", printer_id)
  1448. if not providers:
  1449. return
  1450. variables = {"printer": printer_name}
  1451. title, message = await self._build_message_from_template(db, "printer_offline", variables)
  1452. await self._send_to_providers(
  1453. providers, title, message, db, "printer_offline", printer_id, printer_name, variables=variables
  1454. )
  1455. async def on_printer_error(
  1456. self,
  1457. printer_id: int,
  1458. printer_name: str,
  1459. error_type: str,
  1460. db: AsyncSession,
  1461. error_detail: str | None = None,
  1462. image_data: bytes | None = None,
  1463. ):
  1464. """Handle printer error event (AMS issues, etc.)."""
  1465. providers = await self._get_providers_for_event(db, "on_printer_error", printer_id)
  1466. if not providers:
  1467. return
  1468. variables = {
  1469. "printer": printer_name,
  1470. "error_type": error_type,
  1471. "error_detail": error_detail or "No details available",
  1472. }
  1473. title, message = await self._build_message_from_template(db, "printer_error", variables)
  1474. await self._send_to_providers(
  1475. providers,
  1476. title,
  1477. message,
  1478. db,
  1479. "printer_error",
  1480. printer_id,
  1481. printer_name,
  1482. image_data=image_data,
  1483. variables=variables,
  1484. )
  1485. async def on_ai_failure_detection(
  1486. self,
  1487. printer_id: int,
  1488. printer_name: str,
  1489. task_name: str,
  1490. confidence: float,
  1491. action: str,
  1492. db: AsyncSession,
  1493. image_data: bytes | None = None,
  1494. ):
  1495. """Handle AI failure-detection event (Obico spaghetti / print-failure ML).
  1496. Split out of on_printer_error (#1794) so a user can subscribe to AI
  1497. alerts without also being paged for every HMS hardware code.
  1498. """
  1499. providers = await self._get_providers_for_event(db, "on_ai_failure_detection", printer_id)
  1500. if not providers:
  1501. return
  1502. variables = {
  1503. "printer": printer_name,
  1504. "task_name": task_name or "current job",
  1505. "confidence": f"{confidence:.2f}",
  1506. "action": action,
  1507. }
  1508. title, message = await self._build_message_from_template(db, "ai_failure_detection", variables)
  1509. await self._send_to_providers(
  1510. providers,
  1511. title,
  1512. message,
  1513. db,
  1514. "ai_failure_detection",
  1515. printer_id,
  1516. printer_name,
  1517. image_data=image_data,
  1518. variables=variables,
  1519. )
  1520. async def on_plate_not_empty(
  1521. self,
  1522. printer_id: int,
  1523. printer_name: str,
  1524. db: AsyncSession,
  1525. difference_percent: float | None = None,
  1526. ):
  1527. """Handle plate not empty event - objects detected on build plate before print."""
  1528. providers = await self._get_providers_for_event(db, "on_plate_not_empty", printer_id)
  1529. if not providers:
  1530. return
  1531. variables = {
  1532. "printer": printer_name,
  1533. "difference_percent": f"{difference_percent:.1f}" if difference_percent else "N/A",
  1534. }
  1535. title, message = await self._build_message_from_template(db, "plate_not_empty", variables)
  1536. await self._send_to_providers(
  1537. providers,
  1538. title,
  1539. message,
  1540. db,
  1541. "plate_not_empty",
  1542. printer_id,
  1543. printer_name,
  1544. force_immediate=True,
  1545. variables=variables,
  1546. )
  1547. async def on_plate_clear_required(
  1548. self,
  1549. printer_id: int,
  1550. printer_name: str,
  1551. db: AsyncSession,
  1552. ):
  1553. """Handle plate-clear-required event — a print ended and the queue is gated (#2525).
  1554. Distinct from ``on_plate_not_empty``, which is the camera check *before* a
  1555. print starts. This one fires on the rising edge of the Bambuddy-side
  1556. awaiting-plate-clear flag, i.e. whenever a print reaches a terminal state
  1557. and the next queued job can't dispatch until someone confirms the bed is
  1558. free. Off by default on every provider: it lands at the same moment as the
  1559. print-complete notification, so opting in is a deliberate choice.
  1560. """
  1561. providers = await self._get_providers_for_event(db, "on_plate_clear_required", printer_id)
  1562. if not providers:
  1563. return
  1564. variables = {"printer": printer_name}
  1565. title, message = await self._build_message_from_template(db, "plate_clear_required", variables)
  1566. await self._send_to_providers(
  1567. providers,
  1568. title,
  1569. message,
  1570. db,
  1571. "plate_clear_required",
  1572. printer_id,
  1573. printer_name,
  1574. variables=variables,
  1575. )
  1576. async def on_filament_low(
  1577. self,
  1578. printer_id: int,
  1579. printer_name: str,
  1580. slot: int,
  1581. remaining_percent: int,
  1582. db: AsyncSession,
  1583. color: str | None = None,
  1584. ):
  1585. """Handle low filament event."""
  1586. providers = await self._get_providers_for_event(db, "on_filament_low", printer_id)
  1587. if not providers:
  1588. return
  1589. variables = {
  1590. "printer": printer_name,
  1591. "slot": str(slot),
  1592. "remaining_percent": str(remaining_percent),
  1593. "color": color or "",
  1594. }
  1595. title, message = await self._build_message_from_template(db, "filament_low", variables)
  1596. await self._send_to_providers(
  1597. providers, title, message, db, "filament_low", printer_id, printer_name, variables=variables
  1598. )
  1599. async def on_maintenance_due(
  1600. self,
  1601. printer_id: int,
  1602. printer_name: str,
  1603. maintenance_items: list[dict],
  1604. db: AsyncSession,
  1605. ):
  1606. """Handle maintenance due event - sends notification when maintenance is due or warning."""
  1607. if not maintenance_items:
  1608. return
  1609. providers = await self._get_providers_for_event(db, "on_maintenance_due", printer_id)
  1610. if not providers:
  1611. logger.info("No notification providers configured for maintenance_due event on printer %s", printer_id)
  1612. return
  1613. # Format maintenance items list
  1614. items_list = []
  1615. for item in maintenance_items:
  1616. status = "OVERDUE" if item.get("is_due") else "Soon"
  1617. items_list.append(f"- {item['name']} ({status})")
  1618. items_str = "\n".join(items_list)
  1619. variables = {
  1620. "printer": printer_name,
  1621. "items": items_str,
  1622. }
  1623. logger.info("Found %s providers for maintenance_due: %s", len(providers), [p.name for p in providers])
  1624. title, message = await self._build_message_from_template(db, "maintenance_due", variables)
  1625. await self._send_to_providers(
  1626. providers, title, message, db, "maintenance_due", printer_id, printer_name, variables=variables
  1627. )
  1628. async def on_ams_humidity_high(
  1629. self,
  1630. printer_id: int,
  1631. printer_name: str,
  1632. ams_label: str,
  1633. humidity: float,
  1634. threshold: float,
  1635. db: AsyncSession,
  1636. ):
  1637. """Handle AMS high humidity alarm event. Always sends immediately (bypasses digest)."""
  1638. providers = await self._get_providers_for_event(db, "on_ams_humidity_high", printer_id)
  1639. if not providers:
  1640. return
  1641. variables = {
  1642. "printer": printer_name,
  1643. "ams_label": ams_label,
  1644. "humidity": f"{humidity:.0f}",
  1645. "threshold": f"{threshold:.0f}",
  1646. }
  1647. title, message = await self._build_message_from_template(db, "ams_humidity_high", variables)
  1648. # Alarms always send immediately, bypassing digest mode
  1649. await self._send_to_providers(
  1650. providers,
  1651. title,
  1652. message,
  1653. db,
  1654. "ams_humidity_high",
  1655. printer_id,
  1656. printer_name,
  1657. force_immediate=True,
  1658. variables=variables,
  1659. )
  1660. async def on_ams_temperature_high(
  1661. self,
  1662. printer_id: int,
  1663. printer_name: str,
  1664. ams_label: str,
  1665. temperature: float,
  1666. threshold: float,
  1667. db: AsyncSession,
  1668. ):
  1669. """Handle AMS high temperature alarm event. Always sends immediately (bypasses digest)."""
  1670. providers = await self._get_providers_for_event(db, "on_ams_temperature_high", printer_id)
  1671. if not providers:
  1672. return
  1673. variables = {
  1674. "printer": printer_name,
  1675. "ams_label": ams_label,
  1676. "temperature": f"{temperature:.1f}",
  1677. "threshold": f"{threshold:.1f}",
  1678. }
  1679. title, message = await self._build_message_from_template(db, "ams_temperature_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_temperature_high",
  1687. printer_id,
  1688. printer_name,
  1689. force_immediate=True,
  1690. variables=variables,
  1691. )
  1692. async def on_ams_drying_suspended(
  1693. self,
  1694. printer_id: int,
  1695. printer_name: str,
  1696. ams_label: str,
  1697. humidity: float,
  1698. threshold: float,
  1699. cycles: int,
  1700. db: AsyncSession,
  1701. ):
  1702. """Handle automatic drying giving up on one AMS unit (#2770).
  1703. Sent immediately rather than folded into a digest: it reports that
  1704. Bambuddy has STOPPED doing something, and a report of inaction that
  1705. arrives with tomorrow's summary has already cost the user a day.
  1706. """
  1707. providers = await self._get_providers_for_event(db, "on_ams_drying_suspended", printer_id)
  1708. if not providers:
  1709. return
  1710. variables = {
  1711. "printer": printer_name,
  1712. "ams_label": ams_label,
  1713. "humidity": f"{humidity:.0f}",
  1714. "threshold": f"{threshold:.0f}",
  1715. "cycles": str(cycles),
  1716. }
  1717. title, message = await self._build_message_from_template(db, "ams_drying_suspended", variables)
  1718. await self._send_to_providers(
  1719. providers,
  1720. title,
  1721. message,
  1722. db,
  1723. "ams_drying_suspended",
  1724. printer_id,
  1725. printer_name,
  1726. force_immediate=True,
  1727. variables=variables,
  1728. )
  1729. async def on_ams_ht_humidity_high(
  1730. self,
  1731. printer_id: int,
  1732. printer_name: str,
  1733. ams_label: str,
  1734. humidity: float,
  1735. threshold: float,
  1736. db: AsyncSession,
  1737. ):
  1738. """Handle AMS-HT high humidity alarm event. Always sends immediately (bypasses digest)."""
  1739. providers = await self._get_providers_for_event(db, "on_ams_ht_humidity_high", 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. }
  1748. # Use the same template as regular AMS (can create separate templates later if needed)
  1749. title, message = await self._build_message_from_template(db, "ams_humidity_high", variables)
  1750. # Alarms always send immediately, bypassing digest mode
  1751. await self._send_to_providers(
  1752. providers,
  1753. title,
  1754. message,
  1755. db,
  1756. "ams_ht_humidity_high",
  1757. printer_id,
  1758. printer_name,
  1759. force_immediate=True,
  1760. variables=variables,
  1761. )
  1762. async def on_ams_ht_temperature_high(
  1763. self,
  1764. printer_id: int,
  1765. printer_name: str,
  1766. ams_label: str,
  1767. temperature: float,
  1768. threshold: float,
  1769. db: AsyncSession,
  1770. ):
  1771. """Handle AMS-HT high temperature alarm event. Always sends immediately (bypasses digest)."""
  1772. providers = await self._get_providers_for_event(db, "on_ams_ht_temperature_high", printer_id)
  1773. if not providers:
  1774. return
  1775. variables = {
  1776. "printer": printer_name,
  1777. "ams_label": ams_label,
  1778. "temperature": f"{temperature:.1f}",
  1779. "threshold": f"{threshold:.1f}",
  1780. }
  1781. # Use the same template as regular AMS (can create separate templates later if needed)
  1782. title, message = await self._build_message_from_template(db, "ams_temperature_high", variables)
  1783. # Alarms always send immediately, bypassing digest mode
  1784. await self._send_to_providers(
  1785. providers,
  1786. title,
  1787. message,
  1788. db,
  1789. "ams_ht_temperature_high",
  1790. printer_id,
  1791. printer_name,
  1792. force_immediate=True,
  1793. variables=variables,
  1794. )
  1795. async def on_bed_cooled(
  1796. self,
  1797. printer_id: int,
  1798. printer_name: str,
  1799. bed_temp: float,
  1800. threshold: float,
  1801. filename: str,
  1802. db: AsyncSession,
  1803. ):
  1804. """Handle bed cooled event - bed temperature dropped below threshold after print."""
  1805. providers = await self._get_providers_for_event(db, "on_bed_cooled", printer_id)
  1806. if not providers:
  1807. return
  1808. variables = {
  1809. "printer": printer_name,
  1810. "bed_temp": f"{bed_temp:.0f}",
  1811. "threshold": f"{threshold:.0f}",
  1812. "filename": self._clean_filename(filename) if filename else "Unknown",
  1813. }
  1814. title, message = await self._build_message_from_template(db, "bed_cooled", variables)
  1815. await self._send_to_providers(
  1816. providers, title, message, db, "bed_cooled", printer_id, printer_name, variables=variables
  1817. )
  1818. async def on_ha_sensor_alert(
  1819. self,
  1820. printer_id: int,
  1821. printer_name: str,
  1822. sensor_name: str,
  1823. state: str,
  1824. db: AsyncSession,
  1825. ):
  1826. """A Home Assistant sensor bound to a printer entered its alert state (#1148).
  1827. Sent immediately rather than folded into a digest: the case this exists
  1828. for is an enclosure door left open, which is only worth telling someone
  1829. about while they can still act on it.
  1830. """
  1831. providers = await self._get_providers_for_event(db, "on_ha_sensor_alert", printer_id)
  1832. if not providers:
  1833. return
  1834. variables = {
  1835. "printer": printer_name,
  1836. "sensor": sensor_name,
  1837. "state": state,
  1838. }
  1839. title, message = await self._build_message_from_template(db, "ha_sensor_alert", variables)
  1840. await self._send_to_providers(
  1841. providers,
  1842. title,
  1843. message,
  1844. db,
  1845. "ha_sensor_alert",
  1846. printer_id,
  1847. printer_name,
  1848. force_immediate=True,
  1849. variables=variables,
  1850. )
  1851. async def on_location_ha_sensor_alert(
  1852. self,
  1853. location_name: str,
  1854. sensor_name: str,
  1855. state: str,
  1856. db: AsyncSession,
  1857. ):
  1858. """A Home Assistant sensor bound to a storage location entered its alert state (#2824).
  1859. Sent immediately rather than folded into a digest, for the same reason
  1860. as on_ha_sensor_alert above: this is the "drybox went stale" case, only
  1861. worth acting on while the humidity/temperature is still climbing.
  1862. """
  1863. # Own column, not on_ha_sensor_alert (#2824): that one can be scoped to
  1864. # a single printer via provider.printer_id, and a location alert has no
  1865. # printer to scope by, so sharing it would leak drybox alerts to a
  1866. # provider narrowed to one printer's sensors.
  1867. providers = await self._get_providers_for_event(db, "on_location_ha_sensor_alert", None)
  1868. if not providers:
  1869. return
  1870. variables = {
  1871. "location": location_name,
  1872. "sensor": sensor_name,
  1873. "state": state,
  1874. }
  1875. title, message = await self._build_message_from_template(db, "location_ha_sensor_alert", variables)
  1876. await self._send_to_providers(
  1877. providers,
  1878. title,
  1879. message,
  1880. db,
  1881. "location_ha_sensor_alert",
  1882. force_immediate=True,
  1883. variables=variables,
  1884. )
  1885. async def on_first_layer_complete(
  1886. self,
  1887. printer_id: int,
  1888. printer_name: str,
  1889. filename: str,
  1890. total_layers: int,
  1891. db: AsyncSession,
  1892. image_data: bytes | None = None,
  1893. ):
  1894. """Handle first layer complete event."""
  1895. providers = await self._get_providers_for_event(db, "on_first_layer_complete", printer_id)
  1896. if not providers:
  1897. return
  1898. variables = {
  1899. "printer": printer_name,
  1900. "filename": self._clean_filename(filename),
  1901. "total_layers": str(total_layers),
  1902. }
  1903. title, message = await self._build_message_from_template(db, "first_layer_complete", variables)
  1904. await self._send_to_providers(
  1905. providers,
  1906. title,
  1907. message,
  1908. db,
  1909. "first_layer_complete",
  1910. printer_id,
  1911. printer_name,
  1912. image_data=image_data,
  1913. variables=variables,
  1914. )
  1915. def clear_template_cache(self):
  1916. """Clear the template cache. Call this when templates are updated."""
  1917. self._template_cache.clear()
  1918. async def send_user_print_email(
  1919. self,
  1920. event_type: str,
  1921. created_by_id: int | None,
  1922. printer_name: str,
  1923. filename: str,
  1924. db: AsyncSession,
  1925. ) -> None:
  1926. """Send a print event email notification to the user who submitted the job.
  1927. Args:
  1928. event_type: 'user_print_start', 'user_print_complete', 'user_print_failed', or 'user_print_stopped'
  1929. created_by_id: User ID who submitted the print job (from archive)
  1930. printer_name: Name of the printer
  1931. filename: Raw filename or subtask name
  1932. db: Database session
  1933. """
  1934. if created_by_id is None:
  1935. logger.debug("[EMAIL] Skipping user print email (%s): no created_by_id", event_type)
  1936. return
  1937. try:
  1938. # Check if advanced auth is enabled - required for user email notifications
  1939. from backend.app.models.settings import Settings
  1940. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  1941. setting = result.scalar_one_or_none()
  1942. if not setting or setting.value.lower() != "true":
  1943. logger.debug("[EMAIL] Skipping user print email (%s): advanced_auth not enabled", event_type)
  1944. return
  1945. # Check if user notifications are enabled (admin-controlled toggle)
  1946. notif_enabled_result = await db.execute(
  1947. select(Settings).where(Settings.key == "user_notifications_enabled")
  1948. )
  1949. notif_enabled_setting = notif_enabled_result.scalar_one_or_none()
  1950. if notif_enabled_setting and notif_enabled_setting.value.lower() == "false":
  1951. logger.debug("[EMAIL] Skipping user print email (%s): user_notifications_enabled is false", event_type)
  1952. return
  1953. # Check SMTP settings are configured - required for sending emails
  1954. from backend.app.services.email_service import get_smtp_settings, send_user_print_notification
  1955. smtp_settings = await get_smtp_settings(db)
  1956. if not smtp_settings:
  1957. logger.debug("[EMAIL] Skipping user print email (%s): SMTP settings not configured", event_type)
  1958. return
  1959. # Load user preferences
  1960. from backend.app.models.user import User
  1961. from backend.app.models.user_email_pref import UserEmailPreference
  1962. user_result = await db.execute(select(User).where(User.id == created_by_id))
  1963. user = user_result.scalar_one_or_none()
  1964. if user is None or not user.email:
  1965. logger.debug(
  1966. "[EMAIL] Skipping user print email (%s): user %s not found or has no email address",
  1967. event_type,
  1968. created_by_id,
  1969. )
  1970. return
  1971. # Load user's notification preferences
  1972. pref_result = await db.execute(
  1973. select(UserEmailPreference).where(UserEmailPreference.user_id == created_by_id)
  1974. )
  1975. pref = pref_result.scalar_one_or_none()
  1976. # Determine if this event type should be sent
  1977. should_send = False
  1978. if event_type == "user_print_start":
  1979. should_send = pref is None or pref.notify_print_start
  1980. elif event_type == "user_print_complete":
  1981. should_send = pref is None or pref.notify_print_complete
  1982. elif event_type == "user_print_failed":
  1983. should_send = pref is None or pref.notify_print_failed
  1984. elif event_type == "user_print_stopped":
  1985. should_send = pref is None or pref.notify_print_stopped
  1986. if not should_send:
  1987. logger.debug(
  1988. "[EMAIL] Skipping user print email (%s): user %s has notifications disabled for this event",
  1989. event_type,
  1990. created_by_id,
  1991. )
  1992. return
  1993. logger.info(
  1994. "[EMAIL] Sending user print email: event=%s, user=%s (%s), printer=%s, file=%s",
  1995. event_type,
  1996. user.username,
  1997. user.email,
  1998. printer_name,
  1999. filename,
  2000. )
  2001. # Build variables
  2002. variables = {
  2003. "printer": printer_name,
  2004. "filename": self._clean_filename(filename),
  2005. }
  2006. # Send the email
  2007. await send_user_print_notification(
  2008. db=db,
  2009. event_type=event_type,
  2010. user_email=user.email,
  2011. username=user.username,
  2012. variables=variables,
  2013. )
  2014. logger.info("[EMAIL] User print email sent: event=%s → %s", event_type, user.email)
  2015. except Exception as e:
  2016. logger.warning("Failed to send user print email notification: %s", e, exc_info=True)
  2017. # ==================== Queue Notifications ====================
  2018. async def on_queue_job_added(
  2019. self,
  2020. job_name: str,
  2021. target: str,
  2022. db: AsyncSession,
  2023. printer_id: int | None = None,
  2024. printer_name: str | None = None,
  2025. ):
  2026. """Handle queue job added event."""
  2027. providers = await self._get_providers_for_event(db, "on_queue_job_added", printer_id)
  2028. if not providers:
  2029. return
  2030. variables = {
  2031. "job_name": job_name,
  2032. "target": target, # e.g., "Printer1" or "Any X1C"
  2033. "printer": printer_name or target,
  2034. }
  2035. title, message = await self._build_message_from_template(db, "queue_job_added", variables)
  2036. await self._send_to_providers(
  2037. providers, title, message, db, "queue_job_added", printer_id, printer_name, variables=variables
  2038. )
  2039. async def on_queue_job_assigned(
  2040. self,
  2041. job_name: str,
  2042. printer_id: int,
  2043. printer_name: str,
  2044. target_model: str,
  2045. db: AsyncSession,
  2046. ):
  2047. """Handle model-based job assigned to printer event."""
  2048. providers = await self._get_providers_for_event(db, "on_queue_job_assigned", printer_id)
  2049. if not providers:
  2050. return
  2051. variables = {
  2052. "job_name": job_name,
  2053. "printer": printer_name,
  2054. "target_model": target_model,
  2055. }
  2056. title, message = await self._build_message_from_template(db, "queue_job_assigned", variables)
  2057. await self._send_to_providers(
  2058. providers, title, message, db, "queue_job_assigned", printer_id, printer_name, variables=variables
  2059. )
  2060. async def on_queue_job_started(
  2061. self,
  2062. job_name: str,
  2063. printer_id: int,
  2064. printer_name: str,
  2065. db: AsyncSession,
  2066. estimated_time: int | None = None,
  2067. ):
  2068. """Handle queue job started printing event."""
  2069. providers = await self._get_providers_for_event(db, "on_queue_job_started", printer_id)
  2070. if not providers:
  2071. return
  2072. eta_str = await self._format_eta(estimated_time, db)
  2073. variables = {
  2074. "job_name": job_name,
  2075. "printer": printer_name,
  2076. "estimated_time": self._format_duration(estimated_time),
  2077. "eta": eta_str,
  2078. }
  2079. title, message = await self._build_message_from_template(db, "queue_job_started", variables)
  2080. await self._send_to_providers(
  2081. providers, title, message, db, "queue_job_started", printer_id, printer_name, variables=variables
  2082. )
  2083. async def on_queue_job_waiting(
  2084. self,
  2085. job_name: str,
  2086. target_model: str,
  2087. waiting_reason: str,
  2088. db: AsyncSession,
  2089. ):
  2090. """Handle job waiting for filament event."""
  2091. providers = await self._get_providers_for_event(db, "on_queue_job_waiting", None)
  2092. if not providers:
  2093. return
  2094. variables = {
  2095. "job_name": job_name,
  2096. "target_model": target_model,
  2097. "waiting_reason": waiting_reason,
  2098. }
  2099. title, message = await self._build_message_from_template(db, "queue_job_waiting", variables)
  2100. await self._send_to_providers(providers, title, message, db, "queue_job_waiting", variables=variables)
  2101. async def on_queue_job_skipped(
  2102. self,
  2103. job_name: str,
  2104. printer_id: int,
  2105. printer_name: str,
  2106. reason: str,
  2107. db: AsyncSession,
  2108. ):
  2109. """Handle job skipped event (e.g., previous print failed)."""
  2110. providers = await self._get_providers_for_event(db, "on_queue_job_skipped", printer_id)
  2111. if not providers:
  2112. return
  2113. variables = {
  2114. "job_name": job_name,
  2115. "printer": printer_name,
  2116. "reason": reason,
  2117. }
  2118. title, message = await self._build_message_from_template(db, "queue_job_skipped", variables)
  2119. await self._send_to_providers(
  2120. providers, title, message, db, "queue_job_skipped", printer_id, printer_name, variables=variables
  2121. )
  2122. async def on_queue_job_failed(
  2123. self,
  2124. job_name: str,
  2125. printer_id: int | None,
  2126. printer_name: str | None,
  2127. reason: str,
  2128. db: AsyncSession,
  2129. ):
  2130. """Handle job failed to start event (upload error, etc.)."""
  2131. providers = await self._get_providers_for_event(db, "on_queue_job_failed", printer_id)
  2132. if not providers:
  2133. return
  2134. variables = {
  2135. "job_name": job_name,
  2136. "printer": printer_name or "Unknown",
  2137. "reason": reason,
  2138. }
  2139. title, message = await self._build_message_from_template(db, "queue_job_failed", variables)
  2140. await self._send_to_providers(
  2141. providers, title, message, db, "queue_job_failed", printer_id, printer_name, variables=variables
  2142. )
  2143. async def on_queue_completed(
  2144. self,
  2145. completed_count: int,
  2146. db: AsyncSession,
  2147. ):
  2148. """Handle all queue jobs completed event."""
  2149. providers = await self._get_providers_for_event(db, "on_queue_completed", None)
  2150. if not providers:
  2151. return
  2152. variables = {
  2153. "completed_count": str(completed_count),
  2154. }
  2155. title, message = await self._build_message_from_template(db, "queue_completed", variables)
  2156. await self._send_to_providers(providers, title, message, db, "queue_completed", variables=variables)
  2157. # ==================== Inventory Stock Alerts ====================
  2158. async def on_stock_reorder_alert(
  2159. self,
  2160. material: str,
  2161. brand: str | None,
  2162. stock_g: float,
  2163. rate_g_day: float,
  2164. days_left: int,
  2165. db: AsyncSession,
  2166. ):
  2167. """Fire when an inventory SKU reaches its reorder point."""
  2168. providers = await self._get_providers_for_event(db, "on_stock_reorder_alert", None)
  2169. if not providers:
  2170. return
  2171. variables = {
  2172. "material": material,
  2173. "brand": brand or "",
  2174. "stock_g": f"{stock_g:.0f}",
  2175. "rate_g_day": f"{rate_g_day:.1f}",
  2176. "days_left": str(days_left),
  2177. }
  2178. title, message = await self._build_message_from_template(db, "stock_reorder_alert", variables)
  2179. await self._send_to_providers(providers, title, message, db, "stock_reorder_alert", variables=variables)
  2180. async def on_stock_break_alert(
  2181. self,
  2182. material: str,
  2183. brand: str | None,
  2184. stock_g: float,
  2185. rate_g_day: float,
  2186. days_left: int,
  2187. lead_time_days: int,
  2188. db: AsyncSession,
  2189. ):
  2190. """Fire when a stock break is detected (stock runs out before lead time)."""
  2191. providers = await self._get_providers_for_event(db, "on_stock_break_alert", None)
  2192. if not providers:
  2193. return
  2194. variables = {
  2195. "material": material,
  2196. "brand": brand or "",
  2197. "stock_g": f"{stock_g:.0f}",
  2198. "rate_g_day": f"{rate_g_day:.1f}",
  2199. "days_left": str(days_left),
  2200. "lead_time_days": str(lead_time_days),
  2201. }
  2202. title, message = await self._build_message_from_template(db, "stock_break_alert", variables)
  2203. await self._send_to_providers(providers, title, message, db, "stock_break_alert", variables=variables)
  2204. async def _queue_for_digest(
  2205. self,
  2206. provider: NotificationProvider,
  2207. event_type: str,
  2208. title: str,
  2209. message: str,
  2210. db: AsyncSession,
  2211. printer_id: int | None = None,
  2212. printer_name: str | None = None,
  2213. ):
  2214. """Queue a notification for later delivery in the daily digest."""
  2215. try:
  2216. queue_entry = NotificationDigestQueue(
  2217. provider_id=provider.id,
  2218. event_type=event_type,
  2219. title=title,
  2220. message=message,
  2221. printer_id=printer_id,
  2222. printer_name=printer_name,
  2223. )
  2224. db.add(queue_entry)
  2225. await db.commit()
  2226. logger.info("Queued notification for digest: %s for provider %s", event_type, provider.name)
  2227. except Exception as e:
  2228. logger.warning("Failed to queue notification for digest: %s", e)
  2229. async def send_digest(self, provider_id: int):
  2230. """Send all queued notifications as a single digest for a provider."""
  2231. from backend.app.core.database import async_session
  2232. async with async_session() as db:
  2233. # Get the provider
  2234. result = await db.execute(select(NotificationProvider).where(NotificationProvider.id == provider_id))
  2235. provider = result.scalar_one_or_none()
  2236. if not provider or not provider.enabled:
  2237. return
  2238. # Get all queued notifications for this provider
  2239. result = await db.execute(
  2240. select(NotificationDigestQueue)
  2241. .where(NotificationDigestQueue.provider_id == provider_id)
  2242. .order_by(NotificationDigestQueue.created_at)
  2243. )
  2244. queue_entries = list(result.scalars().all())
  2245. if not queue_entries:
  2246. logger.debug("No queued notifications for provider %s", provider.name)
  2247. return
  2248. # Build digest message
  2249. title = f"Daily Digest - {len(queue_entries)} Events"
  2250. # Group by event type
  2251. events_by_type: dict[str, list] = {}
  2252. for entry in queue_entries:
  2253. if entry.event_type not in events_by_type:
  2254. events_by_type[entry.event_type] = []
  2255. events_by_type[entry.event_type].append(entry)
  2256. # Format the digest body
  2257. body_parts = []
  2258. for event_type, entries in events_by_type.items():
  2259. event_label = event_type.replace("_", " ").title()
  2260. body_parts.append(f"== {event_label} ({len(entries)}) ==")
  2261. for entry in entries:
  2262. time_str = entry.created_at.strftime("%H:%M")
  2263. printer_info = f"[{entry.printer_name}] " if entry.printer_name else ""
  2264. body_parts.append(f" {time_str} {printer_info}{entry.title}")
  2265. body_parts.append("")
  2266. body = "\n".join(body_parts)
  2267. # Send the digest
  2268. success, error = await self._send_to_provider(provider, title, body, db)
  2269. # Log the digest
  2270. await self._log_notification(
  2271. db=db,
  2272. provider_id=provider.id,
  2273. event_type="daily_digest",
  2274. title=title,
  2275. message=body,
  2276. success=success,
  2277. error_message=error if not success else None,
  2278. )
  2279. # Clear the queue
  2280. for entry in queue_entries:
  2281. await db.delete(entry)
  2282. await db.commit()
  2283. if success:
  2284. logger.info("Sent daily digest with %s events to %s", len(queue_entries), provider.name)
  2285. else:
  2286. logger.warning("Failed to send daily digest to %s: %s", provider.name, error)
  2287. async def check_and_send_digests(self):
  2288. """Check all providers and send digests if it's their scheduled time."""
  2289. from backend.app.core.database import async_session
  2290. current_time = datetime.now().strftime("%H:%M")
  2291. # Avoid duplicate checks within the same minute
  2292. if current_time == self._last_digest_check:
  2293. return
  2294. self._last_digest_check = current_time
  2295. async with async_session() as db:
  2296. # Find all providers with digest enabled at this time
  2297. result = await db.execute(
  2298. select(NotificationProvider).where(
  2299. NotificationProvider.enabled.is_(True),
  2300. NotificationProvider.daily_digest_enabled.is_(True),
  2301. NotificationProvider.daily_digest_time == current_time,
  2302. )
  2303. )
  2304. providers = result.scalars().all()
  2305. for provider in providers:
  2306. try:
  2307. await self.send_digest(provider.id)
  2308. except Exception as e:
  2309. logger.error("Error sending digest for provider %s: %s", provider.id, e)
  2310. def start_digest_scheduler(self):
  2311. """Start the background scheduler for daily digest notifications."""
  2312. if self._digest_scheduler_task is None:
  2313. self._digest_scheduler_task = asyncio.create_task(self._digest_scheduler_loop())
  2314. logger.info("Notification digest scheduler started")
  2315. def stop_digest_scheduler(self):
  2316. """Stop the background scheduler for daily digests."""
  2317. if self._digest_scheduler_task:
  2318. self._digest_scheduler_task.cancel()
  2319. self._digest_scheduler_task = None
  2320. logger.info("Notification digest scheduler stopped")
  2321. async def _digest_scheduler_loop(self):
  2322. """Background loop that checks for scheduled digests every minute."""
  2323. while True:
  2324. try:
  2325. await self.check_and_send_digests()
  2326. except Exception as e:
  2327. logger.error("Error in digest scheduler: %s", e)
  2328. # Wait until the next minute
  2329. await asyncio.sleep(60)
  2330. # Global instance
  2331. notification_service = NotificationService()