-
Notifications
You must be signed in to change notification settings - Fork 284
/
Copy path_psl_faup.py
209 lines (166 loc) · 6.87 KB
/
_psl_faup.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python
from __future__ import annotations
import ipaddress
import socket
import idna
from publicsuffixlist import PublicSuffixList # type: ignore
from urllib.parse import urlparse, urlunparse, ParseResult
class UrlNotDecoded(Exception):
pass
class PSLFaup:
"""
Fake Faup Python Library using PSL for Windows support
"""
def __init__(self) -> None:
self.decoded = False
self.psl = PublicSuffixList()
self._url: ParseResult | None = None
self._retval: dict[str, str | int | None | bytes] = {}
self.ip_as_host = ''
def _clear(self) -> None:
self.decoded = False
self._url = None
self._retval = {}
self.ip_as_host = ''
def decode(self, url: str) -> None:
"""
This function creates a dict of all the url fields.
:param url: The URL to normalize
"""
self._clear()
if isinstance(url, bytes) and b'//' not in url[:10]:
url = b'//' + url
elif '//' not in url[:10]:
url = '//' + url
self._url = urlparse(url)
if self._url is None:
raise UrlNotDecoded("Unable to parse URL")
self.ip_as_host = ''
if self._url.hostname is None:
raise UrlNotDecoded("Unable to parse URL")
hostname = _ensure_str(self._url.hostname)
try:
ipv4_bytes = socket.inet_aton(hostname)
ipv4 = ipaddress.IPv4Address(ipv4_bytes)
self.ip_as_host = ipv4.compressed
except (OSError, ValueError):
try:
addr, _, _ = hostname.partition('%')
ipv6 = ipaddress.IPv6Address(addr)
self.ip_as_host = ipv6.compressed
except ValueError:
pass
self.decoded = True
self._retval = {}
@property
def url(self) -> bytes | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if host := self.get_host():
netloc = host + ('' if self.get_port() is None else f':{self.get_port()}')
return _ensure_bytes(
urlunparse(
(self.get_scheme(), netloc, self.get_resource_path(),
'', self.get_query_string(), self.get_fragment(),)
)
)
return None
def get_scheme(self) -> str:
"""
Get the scheme of the url given in the decode function
:returns: The URL scheme
"""
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
return _ensure_str(self._url.scheme if self._url.scheme else '')
def get_credential(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if self._url.username and self._url.password:
return _ensure_str(self._url.username) + ':' + _ensure_str(self._url.password)
if self._url.username:
return _ensure_str(self._url.username)
return None
def get_subdomain(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if self.get_host() is not None and not self.ip_as_host:
domain = self.get_domain()
host = self.get_host()
if domain and host and domain in host:
return host.rsplit(domain, 1)[0].rstrip('.') or None
return None
def get_domain(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if self.get_host() is not None and not self.ip_as_host:
return self.psl.privatesuffix(self.get_host())
return None
def get_domain_without_tld(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if self.get_tld() is not None and not self.ip_as_host:
if domain := self.get_domain():
return domain.rsplit(self.get_tld(), 1)[0].rstrip('.')
return None
def get_host(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if self._url.hostname is None:
return None
elif self._url.hostname.isascii():
return _ensure_str(self._url.hostname)
else:
return _ensure_str(idna.encode(self._url.hostname, uts46=True))
def get_unicode_host(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if not self.ip_as_host:
if host := self.get_host():
return idna.decode(host, uts46=True)
return None
def get_tld(self) -> str | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
if self.get_host() is not None and not self.ip_as_host:
return self.psl.publicsuffix(self.get_host())
return None
def get_port(self) -> int | None:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
return self._url.port
def get_resource_path(self) -> str:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
return _ensure_str(self._url.path)
def get_query_string(self) -> str:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
return _ensure_str(self._url.query)
def get_fragment(self) -> str:
if not self.decoded or not self._url:
raise UrlNotDecoded("You must call faup.decode() first")
return _ensure_str(self._url.fragment)
def get(self) -> dict[str, str | int | None | bytes]:
self._retval["scheme"] = self.get_scheme()
self._retval["tld"] = self.get_tld()
self._retval["domain"] = self.get_domain()
self._retval["domain_without_tld"] = self.get_domain_without_tld()
self._retval["subdomain"] = self.get_subdomain()
self._retval["host"] = self.get_host()
self._retval["port"] = self.get_port()
self._retval["resource_path"] = self.get_resource_path()
self._retval["query_string"] = self.get_query_string()
self._retval["fragment"] = self.get_fragment()
self._retval["url"] = self.url
return self._retval
def _ensure_bytes(binary: str | bytes) -> bytes:
if isinstance(binary, bytes):
return binary
else:
return binary.encode('utf-8')
def _ensure_str(string: str | bytes) -> str:
if isinstance(string, str):
return string
else:
return string.decode('utf-8')