Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Der-Henning
GitHub Repository: Der-Henning/tgtg
Path: blob/main/tgtg_scanner/notifiers/webhook.py
725 views
1
import json
2
import logging
3
from typing import Union
4
5
import requests
6
from requests.auth import HTTPBasicAuth
7
8
from tgtg_scanner.errors import MaskConfigurationError, WebHookConfigurationError
9
from tgtg_scanner.models import Config, Favorites, Item, Reservations
10
from tgtg_scanner.models.reservations import Reservation
11
from tgtg_scanner.notifiers.base import Notifier
12
13
log = logging.getLogger("tgtg")
14
15
16
class WebHook(Notifier):
17
"""Notifier for custom Webhooks"""
18
19
def __init__(self, config: Config, reservations: Reservations, favorites: Favorites):
20
super().__init__(config, reservations, favorites)
21
self.enabled: bool = config.webhook.enabled
22
self.method: str = config.webhook.method
23
self.url: Union[str, None] = config.webhook.url
24
self.body: Union[str, None] = config.webhook.body
25
self.type: Union[str, None] = config.webhook.type
26
self.headers: dict[str, Union[str, bytes]] = config.webhook.headers
27
self.auth = None
28
self.username: Union[str, None] = config.webhook.username
29
self.password: Union[str, None] = config.webhook.password
30
self.timeout: int = config.webhook.timeout
31
self.cron = config.webhook.cron
32
if self.enabled:
33
if self.method is None or self.url is None:
34
raise WebHookConfigurationError()
35
if self.username is not None and self.password is not None:
36
self.auth = HTTPBasicAuth(self.username, self.password)
37
log.debug("Using basic auth with user '%s' for webhook", self.username)
38
try:
39
Item.check_mask(self.body)
40
Item.check_mask(self.url)
41
except MaskConfigurationError as exc:
42
raise WebHookConfigurationError(exc.message) from exc
43
44
def _send(self, item: Union[Item, Reservation]) -> None:
45
"""Sends item information via configured Webhook endpoint"""
46
if isinstance(item, Item):
47
if self.url is None:
48
raise WebHookConfigurationError()
49
url = item.unmask(self.url)
50
log.debug("%s url: %s", self.name, url)
51
body: Union[bytes, None] = None
52
headers = self.headers or dict()
53
if self.type:
54
headers["Content-Type"] = self.type
55
if self.body:
56
if self.type is not None and "json" in self.type:
57
body = json.dumps(json.loads(item.unmask(self.body).replace("\n", "\\n"))).encode("utf-8")
58
else:
59
body = item.unmask(self.body).encode("utf-8")
60
log.debug("%s body: %s", self.name, body)
61
# body = item.unmask(self.body)
62
# if isinstance(body, bytes):
63
# pass
64
# elif self.type and "json" in self.type:
65
# body = json.dumps(json.loads(body.replace("\n", "\\n")))
66
# log.debug("%s body: %s", self.name, body)
67
# else:
68
# body = body.encode("utf-8")
69
# log.debug("%s body: %s", self.name, body)
70
log.debug("%s headers: %s", self.name, headers)
71
res = requests.request(
72
method=self.method,
73
url=url,
74
timeout=self.timeout,
75
data=body,
76
headers=headers,
77
auth=self.auth,
78
)
79
if not res.ok:
80
log.error("%s Request failed with status code %s", self.name, res.status_code)
81
log.debug("%s Response content: %s", self.name, res.text)
82
83
def __repr__(self) -> str:
84
return f"WebHook: {self.url}"
85
86