notification_service.py 128 KB

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