notification_service.py 130 KB

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