notification_service.py 127 KB

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