Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Der-Henning
GitHub Repository: Der-Henning/tgtg
Path: blob/main/tgtg_scanner/notifiers/ntfy.py
1218 views
1
import logging
2
3
from requests.auth import HTTPBasicAuth
4
5
from tgtg_scanner.errors import MaskConfigurationError, NtfyConfigurationError
6
from tgtg_scanner.models import Config, Favorites, Item, Reservations
7
from tgtg_scanner.models.reservations import Reservation
8
from tgtg_scanner.notifiers.webhook import WebHook
9
10
log = logging.getLogger("tgtg")
11
12
13
class Ntfy(WebHook):
14
"""Notifier for Ntfy."""
15
16
def __init__(self, config: Config, reservations: Reservations, favorites: Favorites):
17
super(WebHook, self).__init__(config, reservations, favorites)
18
self.enabled = config.ntfy.enabled
19
self.server = config.ntfy.server
20
self.topic = config.ntfy.topic
21
self.title = config.ntfy.title
22
self.message = config.ntfy.message
23
self.body = config.ntfy.body
24
self.priority = config.ntfy.priority
25
self.tags = config.ntfy.tags
26
self.click = config.ntfy.click
27
self.username = config.ntfy.username
28
self.password = config.ntfy.password
29
self.token = config.ntfy.token
30
self.timeout = config.ntfy.timeout
31
self.cron = config.ntfy.cron
32
self.headers = dict()
33
self.auth = None
34
self.method = "POST"
35
self.type = None
36
37
if self.enabled:
38
if not self.server or not self.topic:
39
raise NtfyConfigurationError()
40
self.url = f"{self.server}/{self.topic}"
41
log.debug("Ntfy url: %s", self.url)
42
if self.username is not None and self.password is not None:
43
self.auth = HTTPBasicAuth(self.username, self.password)
44
log.debug("Using basic auth with user '%s' for Ntfy", self.username)
45
elif self.token is not None:
46
self.headers = {
47
"Authorization": "Bearer " + self.token,
48
}
49
log.debug("Using access token for Ntfy")
50
else:
51
log.warning("Username and Password or Access Token missing for Ntfy authentication, defaulting to no auth")
52
try:
53
Item.check_mask(self.title)
54
Item.check_mask(self.message)
55
Item.check_mask(self.tags)
56
Item.check_mask(self.click)
57
except MaskConfigurationError as exc:
58
raise NtfyConfigurationError(exc.message) from exc
59
60
def _send(self, item: Item | Reservation) -> None:
61
"""Sends item information via configured Ntfy endpoint."""
62
if isinstance(item, Item):
63
title = item.unmask(self.title).encode("utf-8")
64
message = item.unmask(self.message).encode("utf-8")
65
tags = item.unmask(self.tags).encode("utf-8")
66
click = item.unmask(self.click).encode("utf-8")
67
self.headers |= {
68
"X-Title": title,
69
"X-Message": message,
70
"X-Priority": self.priority,
71
"X-Tags": tags,
72
"X-Click": click,
73
}
74
super()._send(item)
75
76
def __repr__(self) -> str:
77
return f"Ntfy: {self.server}/{self.topic}"
78
79