|
| 1 | +"""Mobile push notification helpers.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import urllib.parse |
| 6 | +import urllib.request |
| 7 | +from collections.abc import Sequence |
| 8 | +from email.header import Header |
| 9 | +from typing import Any |
| 10 | + |
| 11 | + |
| 12 | +PUSH_PROVIDER_NTFY = "ntfy" |
| 13 | +PUSH_PROVIDER_PUSHOVER = "pushover" |
| 14 | +DEFAULT_NTFY_API_BASE_URL = "https://ntfy.sh" |
| 15 | +DEFAULT_PUSHOVER_API_BASE_URL = "https://api.pushover.net" |
| 16 | + |
| 17 | + |
| 18 | +def parse_push_recipients(raw_value: str | Sequence[str] | None) -> tuple[str, ...]: |
| 19 | + if raw_value is None: |
| 20 | + return () |
| 21 | + if isinstance(raw_value, str): |
| 22 | + values = raw_value.replace(";", ",").replace("\n", ",").split(",") |
| 23 | + else: |
| 24 | + values = raw_value |
| 25 | + recipients = [] |
| 26 | + seen = set() |
| 27 | + for value in values: |
| 28 | + recipient = str(value or "").strip() |
| 29 | + if not recipient or recipient in seen: |
| 30 | + continue |
| 31 | + recipients.append(recipient) |
| 32 | + seen.add(recipient) |
| 33 | + return tuple(recipients) |
| 34 | + |
| 35 | + |
| 36 | +def send_strategy_plugin_push( |
| 37 | + *, |
| 38 | + provider: str, |
| 39 | + title: str, |
| 40 | + body: str, |
| 41 | + recipients: Sequence[str], |
| 42 | + app_token: str | None = None, |
| 43 | + access_token: str | None = None, |
| 44 | + api_base_url: str | None = None, |
| 45 | + device: str | None = None, |
| 46 | + priority: str | int | None = None, |
| 47 | + tags: str | None = None, |
| 48 | + timeout: float = 10.0, |
| 49 | + opener: Any = None, |
| 50 | + printer=print, |
| 51 | +) -> bool: |
| 52 | + normalized_provider = str(provider or "").strip().lower() |
| 53 | + if normalized_provider == PUSH_PROVIDER_PUSHOVER: |
| 54 | + return send_pushover_push( |
| 55 | + title=title, |
| 56 | + body=body, |
| 57 | + recipients=recipients, |
| 58 | + app_token=app_token, |
| 59 | + api_base_url=api_base_url or DEFAULT_PUSHOVER_API_BASE_URL, |
| 60 | + device=device, |
| 61 | + priority=priority, |
| 62 | + timeout=timeout, |
| 63 | + opener=opener, |
| 64 | + printer=printer, |
| 65 | + ) |
| 66 | + if normalized_provider == PUSH_PROVIDER_NTFY: |
| 67 | + return send_ntfy_push( |
| 68 | + title=title, |
| 69 | + body=body, |
| 70 | + recipients=recipients, |
| 71 | + access_token=access_token, |
| 72 | + api_base_url=api_base_url or DEFAULT_NTFY_API_BASE_URL, |
| 73 | + priority=priority, |
| 74 | + tags=tags, |
| 75 | + timeout=timeout, |
| 76 | + opener=opener, |
| 77 | + printer=printer, |
| 78 | + ) |
| 79 | + printer(f"Push send failed: unsupported provider {provider!r}", flush=True) |
| 80 | + return False |
| 81 | + |
| 82 | + |
| 83 | +def send_pushover_push( |
| 84 | + *, |
| 85 | + title: str, |
| 86 | + body: str, |
| 87 | + recipients: Sequence[str], |
| 88 | + app_token: str | None, |
| 89 | + api_base_url: str = DEFAULT_PUSHOVER_API_BASE_URL, |
| 90 | + device: str | None = None, |
| 91 | + priority: str | int | None = None, |
| 92 | + timeout: float = 10.0, |
| 93 | + opener: Any = None, |
| 94 | + printer=print, |
| 95 | +) -> bool: |
| 96 | + resolved_recipients = parse_push_recipients(recipients) |
| 97 | + token = str(app_token or "").strip() |
| 98 | + message = str(body or "").strip() |
| 99 | + if not resolved_recipients or not token or not message: |
| 100 | + return False |
| 101 | + |
| 102 | + request_opener = opener or urllib.request.urlopen |
| 103 | + endpoint = _pushover_messages_endpoint(api_base_url) |
| 104 | + all_sent = True |
| 105 | + for recipient in resolved_recipients: |
| 106 | + payload = { |
| 107 | + "token": token, |
| 108 | + "user": recipient, |
| 109 | + "message": message, |
| 110 | + } |
| 111 | + text_title = str(title or "").strip() |
| 112 | + if text_title: |
| 113 | + payload["title"] = text_title |
| 114 | + text_device = str(device or "").strip() |
| 115 | + if text_device: |
| 116 | + payload["device"] = text_device |
| 117 | + text_priority = str(priority or "").strip() |
| 118 | + if text_priority: |
| 119 | + payload["priority"] = text_priority |
| 120 | + data = urllib.parse.urlencode(payload).encode("utf-8") |
| 121 | + request = urllib.request.Request( |
| 122 | + endpoint, |
| 123 | + data=data, |
| 124 | + headers={"Content-Type": "application/x-www-form-urlencoded"}, |
| 125 | + method="POST", |
| 126 | + ) |
| 127 | + if not _request_succeeded(request_opener, request, timeout, printer, recipient): |
| 128 | + all_sent = False |
| 129 | + return all_sent |
| 130 | + |
| 131 | + |
| 132 | +def send_ntfy_push( |
| 133 | + *, |
| 134 | + title: str, |
| 135 | + body: str, |
| 136 | + recipients: Sequence[str], |
| 137 | + access_token: str | None = None, |
| 138 | + api_base_url: str = DEFAULT_NTFY_API_BASE_URL, |
| 139 | + priority: str | int | None = None, |
| 140 | + tags: str | None = None, |
| 141 | + timeout: float = 10.0, |
| 142 | + opener: Any = None, |
| 143 | + printer=print, |
| 144 | +) -> bool: |
| 145 | + resolved_recipients = parse_push_recipients(recipients) |
| 146 | + message = str(body or "").strip() |
| 147 | + if not resolved_recipients or not message: |
| 148 | + return False |
| 149 | + |
| 150 | + request_opener = opener or urllib.request.urlopen |
| 151 | + token = str(access_token or "").strip() |
| 152 | + all_sent = True |
| 153 | + for recipient in resolved_recipients: |
| 154 | + headers = { |
| 155 | + "Content-Type": "text/plain; charset=utf-8", |
| 156 | + } |
| 157 | + text_title = str(title or "").strip() |
| 158 | + if text_title: |
| 159 | + headers["Title"] = _encode_http_header(text_title) |
| 160 | + text_priority = str(priority or "").strip() |
| 161 | + if text_priority: |
| 162 | + headers["Priority"] = text_priority |
| 163 | + text_tags = str(tags or "").strip() |
| 164 | + if text_tags: |
| 165 | + headers["Tags"] = _encode_http_header(text_tags) |
| 166 | + if token: |
| 167 | + headers["Authorization"] = f"Bearer {token}" |
| 168 | + request = urllib.request.Request( |
| 169 | + _ntfy_topic_endpoint(api_base_url, recipient), |
| 170 | + data=message.encode("utf-8"), |
| 171 | + headers=headers, |
| 172 | + method="POST", |
| 173 | + ) |
| 174 | + if not _request_succeeded(request_opener, request, timeout, printer, recipient): |
| 175 | + all_sent = False |
| 176 | + return all_sent |
| 177 | + |
| 178 | + |
| 179 | +def _request_succeeded( |
| 180 | + request_opener: Any, |
| 181 | + request: urllib.request.Request, |
| 182 | + timeout: float, |
| 183 | + printer, |
| 184 | + recipient: str, |
| 185 | +) -> bool: |
| 186 | + try: |
| 187 | + with request_opener(request, timeout=timeout) as response: |
| 188 | + status = getattr(response, "status", None) |
| 189 | + if status is None: |
| 190 | + status = response.getcode() |
| 191 | + status = int(status) |
| 192 | + except Exception as exc: |
| 193 | + printer(f"Push send failed for {recipient}: {exc}", flush=True) |
| 194 | + return False |
| 195 | + if status < 200 or status >= 300: |
| 196 | + printer(f"Push send failed for {recipient}: HTTP {status}", flush=True) |
| 197 | + return False |
| 198 | + return True |
| 199 | + |
| 200 | + |
| 201 | +def _pushover_messages_endpoint(api_base_url: str) -> str: |
| 202 | + base_url = str(api_base_url or DEFAULT_PUSHOVER_API_BASE_URL).rstrip("/") |
| 203 | + if base_url.endswith("/1/messages.json"): |
| 204 | + return base_url |
| 205 | + return f"{base_url}/1/messages.json" |
| 206 | + |
| 207 | + |
| 208 | +def _ntfy_topic_endpoint(api_base_url: str, recipient: str) -> str: |
| 209 | + target = str(recipient or "").strip() |
| 210 | + if target.startswith(("https://", "http://")): |
| 211 | + return target |
| 212 | + base_url = str(api_base_url or DEFAULT_NTFY_API_BASE_URL).rstrip("/") |
| 213 | + path = "/".join( |
| 214 | + urllib.parse.quote(part.strip(), safe="") |
| 215 | + for part in target.strip("/").split("/") |
| 216 | + if part.strip() |
| 217 | + ) |
| 218 | + return f"{base_url}/{path}" |
| 219 | + |
| 220 | + |
| 221 | +def _encode_http_header(value: str) -> str: |
| 222 | + text = str(value or "") |
| 223 | + try: |
| 224 | + text.encode("latin-1") |
| 225 | + except UnicodeEncodeError: |
| 226 | + return Header(text, "utf-8").encode() |
| 227 | + return text |
0 commit comments