-
Notifications
You must be signed in to change notification settings - Fork 421
/
webhook_item.py
85 lines (67 loc) · 2.59 KB
/
webhook_item.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import re
import xml.etree.ElementTree as ET
from typing import List, Optional, Tuple, Type
from defusedxml.ElementTree import fromstring
NAMESPACE_RE = re.compile(r"^{.*}")
def _parse_event(events):
event = events[0]
# Strip out the namespace from the tag name
return NAMESPACE_RE.sub("", event.tag)
class WebhookItem(object):
def __init__(self):
self._id: Optional[str] = None
self.name: Optional[str] = None
self.url: Optional[str] = None
self._event: Optional[str] = None
self.owner_id: Optional[str] = None
def _set_values(self, id, name, url, event, owner_id):
if id is not None:
self._id = id
if name:
self.name = name
if url:
self.url = url
if event:
self.event = event
if owner_id:
self.owner_id = owner_id
@property
def id(self) -> Optional[str]:
return self._id
@property
def event(self) -> Optional[str]:
if self._event:
return self._event.replace("webhook-source-event-", "")
return None
@event.setter
def event(self, value: str) -> None:
self._event = "webhook-source-event-{}".format(value)
@classmethod
def from_response(cls: Type["WebhookItem"], resp: bytes, ns) -> List["WebhookItem"]:
all_webhooks_items = list()
parsed_response = fromstring(resp)
all_webhooks_xml = parsed_response.findall(".//t:webhook", namespaces=ns)
for webhook_xml in all_webhooks_xml:
values = cls._parse_element(webhook_xml, ns)
webhook_item = cls()
webhook_item._set_values(*values)
all_webhooks_items.append(webhook_item)
return all_webhooks_items
@staticmethod
def _parse_element(webhook_xml: ET.Element, ns) -> Tuple:
id = webhook_xml.get("id", None)
name = webhook_xml.get("name", None)
url = None
url_tag = webhook_xml.find(".//t:webhook-destination-http", namespaces=ns)
if url_tag is not None:
url = url_tag.get("url", None)
event = webhook_xml.findall(".//t:webhook-source/*", namespaces=ns)
if event is not None and len(event) > 0:
event = _parse_event(event)
owner_id = None
owner_tag = webhook_xml.find(".//t:owner", namespaces=ns)
if owner_tag is not None:
owner_id = owner_tag.get("id", None)
return id, name, url, event, owner_id
def __repr__(self) -> str:
return "<Webhook id={} name={} url={} event={}>".format(self.id, self.name, self.url, self.event)