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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
|
# Copyright 2014-2022 Vincent Texier <vit@free.fr>
#
# DuniterPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DuniterPy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
from ipaddress import ip_address
from typing import Any, Dict, Optional, Tuple, Type, TypeVar
from duniterpy import constants as const
from ..documents import MalformedDocumentError
class ConnectionHandler:
"""Helper class used by other API classes to ease passing address connection information."""
def __init__(
self,
http_scheme: str,
ws_scheme: str,
address: str,
port: int,
path: str,
proxy: Optional[str] = None,
) -> None:
"""
Init instance of connection handler
:param http_scheme: Http scheme
:param ws_scheme: Web socket scheme
:param address: Domain name, IPv6, or IPv4 address
:param port: Port number
:param port: Url path
:param proxy: Proxy (optional, default=None)
"""
self.http_scheme = http_scheme
self.ws_scheme = ws_scheme
self.address = address
self.port = port
self.path = path
self.proxy = proxy
def __str__(self) -> str:
return f"connection info: {self.address}:{self.port}"
# required to type hint cls in classmethod
EndpointType = TypeVar("EndpointType", bound="Endpoint")
class Endpoint:
@classmethod
def from_inline(cls: Type[EndpointType], inline: str) -> EndpointType:
raise NotImplementedError("from_inline(..) is not implemented")
def inline(self) -> str:
raise NotImplementedError("inline() is not implemented")
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
raise NotImplementedError("conn_handler is not implemented")
def __str__(self) -> str:
raise NotImplementedError("__str__ is not implemented")
def __eq__(self, other: Any) -> bool:
return NotImplemented
# required to type hint cls in classmethod
UnknownEndpointType = TypeVar("UnknownEndpointType", bound="UnknownEndpoint")
class UnknownEndpoint(Endpoint):
API = None
def __init__(self, api: str, properties: list) -> None:
self.api = api
self.properties = properties
@classmethod
def from_inline(cls: Type[UnknownEndpointType], inline: str) -> UnknownEndpointType:
"""
Return UnknownEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
try:
api = inline.split()[0]
properties = inline.split()[1:]
return cls(api, properties)
except IndexError:
raise MalformedDocumentError(inline) from IndexError
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
doc = self.api
for p in self.properties:
doc += f" {p}"
return doc
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler
:param proxy: Proxy address
:return:
"""
return ConnectionHandler("", "", "", 0, "")
def __str__(self) -> str:
properties = " ".join([f"{p}" for p in self.properties])
return f"{self.api} {properties}"
def __eq__(self, other: Any) -> bool:
if not isinstance(other, UnknownEndpoint):
return NotImplemented
return self.api == other.api and self.properties == other.properties
def __hash__(self) -> int:
return hash((self.api, self.properties))
# required to type hint cls in classmethod
BMAEndpointType = TypeVar("BMAEndpointType", bound="BMAEndpoint")
class BMAEndpoint(Endpoint):
API = "BASIC_MERKLED_API"
re_inline = re.compile(
f"^{API}(?: (?P<host>{const.HOST_REGEX}))?(?: (?P<ipv4>{const.IPV4_REGEX}))?(?: (?P<ipv6>{const.IPV6_REGEX}))?(?: (?P<port>{const.PORT_REGEX}))$"
)
def __init__(self, host: str, ipv4: str, ipv6: str, port: int) -> None:
"""
Init BMAEndpoint instance
:param host: Hostname
:param ipv4: IP as IPv4 format
:param ipv6: IP as IPv6 format
:param port: Port number
"""
self.host = host
self.ipv4 = ipv4
self.ipv6 = ipv6
self.port = port
@classmethod
def from_inline(cls: Type[BMAEndpointType], inline: str) -> BMAEndpointType:
"""
Return BMAEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = BMAEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(BMAEndpoint.API)
host, ipv4 = fix_host_ipv4_mix_up(m["host"], m["ipv4"])
ipv6 = m["ipv6"]
port = int(m["port"])
return cls(host, ipv4, ipv6, port)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [
str(info) for info in (self.host, self.ipv4, self.ipv6, self.port) if info
]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
if self.host:
conn_handler = ConnectionHandler(
"http", "ws", self.host, self.port, "", proxy
)
elif self.ipv6:
conn_handler = ConnectionHandler(
"http", "ws", f"[{self.ipv6}]", self.port, "", proxy
)
else:
conn_handler = ConnectionHandler(
"http", "ws", self.ipv4, self.port, "", proxy
)
return conn_handler
def __str__(self) -> str:
return self.inline()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, BMAEndpoint):
return NotImplemented
return (
self.host == other.host
and self.ipv4 == other.ipv4
and self.ipv6 == other.ipv6
and self.port == other.port
)
def __hash__(self) -> int:
return hash((self.host, self.ipv4, self.ipv6, self.port))
# required to type hint cls in classmethod
SecuredBMAEndpointType = TypeVar("SecuredBMAEndpointType", bound="SecuredBMAEndpoint")
class SecuredBMAEndpoint(BMAEndpoint):
API = "BMAS"
re_inline = re.compile(
f"^{API}(?: (?P<host>{const.HOST_REGEX}))?(?: (?P<ipv4>{const.IPV4_REGEX}))?(?: (?P<ipv6>{const.IPV6_REGEX}))? (?P<port>{const.PORT_REGEX})(?: (?P<path>{const.PATH_REGEX}))?$"
)
def __init__(self, host: str, ipv4: str, ipv6: str, port: int, path: str) -> None:
"""
Init SecuredBMAEndpoint instance
:param host: Hostname
:param ipv4: IP as IPv4 format
:param ipv6: IP as IPv6 format
:param port: Port number
:param path: Url path
"""
super().__init__(host, ipv4, ipv6, port)
self.path = path
@classmethod
def from_inline(
cls: Type[SecuredBMAEndpointType], inline: str
) -> SecuredBMAEndpointType:
"""
Return SecuredBMAEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = SecuredBMAEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(SecuredBMAEndpoint.API)
host, ipv4 = fix_host_ipv4_mix_up(m["host"], m["ipv4"])
ipv6 = m["ipv6"]
port = int(m["port"])
path = m["path"]
if not path:
path = ""
return cls(host, ipv4, ipv6, port, path)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [
str(info)
for info in (self.host, self.ipv4, self.ipv6, self.port, self.path)
if info
]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
if self.host:
conn_handler = ConnectionHandler(
"https", "wss", self.host, self.port, self.path, proxy
)
elif self.ipv6:
conn_handler = ConnectionHandler(
"https", "wss", f"[{self.ipv6}]", self.port, self.path, proxy
)
else:
conn_handler = ConnectionHandler(
"https", "wss", self.ipv4, self.port, self.path, proxy
)
return conn_handler
# required to type hint cls in classmethod
WS2PEndpointType = TypeVar("WS2PEndpointType", bound="WS2PEndpoint")
class WS2PEndpoint(Endpoint):
API = "WS2P"
re_inline = re.compile(
f"^{API} (?P<ws2pid>{const.WS2PID_REGEX}) (?P<host>(?:{const.HOST_REGEX})|(?:{const.IPV4_REGEX})|(?:{const.IPV6_REGEX})) (?P<port>{const.PORT_REGEX})?(?: (?P<path>{const.PATH_REGEX}))?$"
)
def __init__(self, ws2pid: str, host: str, port: int, path: str) -> None:
self.ws2pid = ws2pid
self.host = host
self.port = port
self.path = path
@classmethod
def from_inline(cls: Type[WS2PEndpointType], inline: str) -> WS2PEndpointType:
"""
Return WS2PEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = WS2PEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(WS2PEndpoint.API)
ws2pid = m["ws2pid"]
host = m["host"]
port = int(m["port"])
path = m["path"]
if not path:
path = ""
return cls(ws2pid, host, port, path)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [
str(info) for info in (self.ws2pid, self.host, self.port, self.path) if info
]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
http_scheme = "http"
websocket_scheme = "ws"
if self.port == 443:
http_scheme += "s"
websocket_scheme += "s"
return ConnectionHandler(
http_scheme, websocket_scheme, self.host, self.port, self.path, proxy
)
def __str__(self) -> str:
return self.inline()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, WS2PEndpoint):
return NotImplemented
return (
self.host == other.host
and self.ws2pid == other.ws2pid
and self.port == other.port
and self.path == other.path
)
def __hash__(self) -> int:
return hash((self.ws2pid, self.host, self.port, self.path))
# required to type hint cls in classmethod
ESCoreEndpointType = TypeVar("ESCoreEndpointType", bound="ESCoreEndpoint")
class ESCoreEndpoint(Endpoint):
API = "ES_CORE_API"
re_inline = re.compile(
f"^{API} (?P<host>(?:{const.HOST_REGEX})|(?:{const.IPV4_REGEX})) (?P<port>{const.PORT_REGEX})$"
)
def __init__(self, host: str, port: int) -> None:
self.host = host
self.port = port
@classmethod
def from_inline(cls: Type[ESCoreEndpointType], inline: str) -> ESCoreEndpointType:
"""
Return ESCoreEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESCoreEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(ESCoreEndpoint.API)
host = m["host"]
port = int(m["port"])
return cls(host, port)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [str(info) for info in (self.host, self.port) if info]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
return ConnectionHandler("https", "wss", self.host, self.port, "", proxy)
def __str__(self) -> str:
return self.inline()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, ESCoreEndpoint):
return NotImplemented
return self.host == other.host and self.port == other.port
def __hash__(self) -> int:
return hash((self.host, self.port))
# required to type hint cls in classmethod
ESUserEndpointType = TypeVar("ESUserEndpointType", bound="ESUserEndpoint")
class ESUserEndpoint(Endpoint):
API = "ES_USER_API"
re_inline = re.compile(
f"^{API} (?P<host>(?:{const.HOST_REGEX})|(?:{const.IPV4_REGEX})) (?P<port>{const.PORT_REGEX})$"
)
def __init__(self, host: str, port: int) -> None:
self.host = host
self.port = port
@classmethod
def from_inline(cls: Type[ESUserEndpointType], inline: str) -> ESUserEndpointType:
"""
Return ESUserEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESUserEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(ESUserEndpoint.API)
host = m["host"]
port = int(m["port"])
return cls(host, port)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [str(info) for info in (self.host, self.port) if info]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
return ConnectionHandler("https", "wss", self.host, self.port, "", proxy)
def __str__(self) -> str:
return self.inline()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, ESUserEndpoint):
return NotImplemented
return self.host == other.host and self.port == other.port
def __hash__(self) -> int:
return hash((self.host, self.port))
# required to type hint cls in classmethod
ESSubscribtionEndpointType = TypeVar(
"ESSubscribtionEndpointType", bound="ESSubscribtionEndpoint"
)
class ESSubscribtionEndpoint(Endpoint):
API = "ES_SUBSCRIPTION_API"
re_inline = re.compile(
f"^{API} (?P<host>(?:{const.HOST_REGEX})|(?:{const.IPV4_REGEX})) (?P<port>{const.PORT_REGEX})$"
)
def __init__(self, host: str, port: int) -> None:
self.host = host
self.port = port
@classmethod
def from_inline(
cls: Type[ESSubscribtionEndpointType], inline: str
) -> ESSubscribtionEndpointType:
"""
Return ESSubscribtionEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESSubscribtionEndpoint.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(ESSubscribtionEndpoint.API)
host = m["host"]
port = int(m["port"])
return cls(host, port)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [str(info) for info in (self.host, self.port) if info]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
return ConnectionHandler("https", "wss", self.host, self.port, "", proxy)
def __str__(self) -> str:
return self.inline()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, ESSubscribtionEndpoint):
return NotImplemented
return self.host == other.host and self.port == other.port
def __hash__(self) -> int:
return hash((ESSubscribtionEndpoint.API, self.host, self.port))
# required to type hint cls in classmethod
GVAEndpointType = TypeVar("GVAEndpointType", bound="GVAEndpoint")
class GVAEndpoint(Endpoint):
API = "GVA"
endpoint_format = f"^GVA(?: (?P<flags>{const.ENDPOINT_FLAGS_REGEX}))?(?: (?P<host>{const.HOST_REGEX}))?(?: (?P<ipv4>{const.IPV4_REGEX}))?(?: (?P<ipv6>{const.IPV6_REGEX}))? (?P<port>{const.PORT_REGEX})(?: (?P<path>{const.PATH_REGEX}))?$"
re_inline = re.compile(endpoint_format)
def __init__(
self,
flags: str,
host: str,
ipv4: str,
ipv6: str,
port: int,
path: str,
) -> None:
"""
Init GVAEndpoint instance
:param flags: Flags of endpoint
:param host: Hostname
:param ipv4: IP as IPv4 format
:param ipv6: IP as IPv6 format
:param port: Port number
:param path: Url path
"""
self.flags = flags
self.host = host
self.ipv4 = ipv4
self.ipv6 = ipv6
self.port = port
self.path = path
@classmethod
def from_inline(cls: Type[GVAEndpointType], inline: str) -> GVAEndpointType:
"""
Return GVAEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = cls.re_inline.match(inline)
if m is None:
raise MalformedDocumentError(cls.API)
flags = m["flags"]
host, ipv4 = fix_host_ipv4_mix_up(m["host"], m["ipv4"])
ipv6 = m["ipv6"]
port = int(m["port"])
path = m["path"]
if not flags:
flags = ""
if not path:
path = ""
return cls(flags, host, ipv4, ipv6, port, path)
def inline(self) -> str:
"""
Return endpoint string
:return:
"""
inlined = [
str(info)
for info in (
self.flags,
self.host,
self.ipv4,
self.ipv6,
self.port,
self.path,
)
if info
]
return f'{self.API} {" ".join(inlined)}'
def conn_handler(self, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param proxy: Proxy url
:return:
"""
scheme_http = "https" if "S" in self.flags else "http"
scheme_ws = "wss" if "S" in self.flags else "ws"
if self.host:
conn_handler = ConnectionHandler(
scheme_http, scheme_ws, self.host, self.port, self.path, proxy
)
elif self.ipv6:
conn_handler = ConnectionHandler(
scheme_http,
scheme_ws,
f"[{self.ipv6}]",
self.port,
self.path,
proxy,
)
else:
conn_handler = ConnectionHandler(
scheme_http, scheme_ws, self.ipv4, self.port, self.path, proxy
)
return conn_handler
def __str__(self) -> str:
return self.inline()
def __eq__(self, other: Any) -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return (
self.flags == other.flags
and self.host == other.host
and self.ipv4 == other.ipv4
and self.ipv6 == other.ipv6
and self.port == other.port
and self.path == other.path
)
def __hash__(self) -> int:
return hash((self.flags, self.host, self.ipv4, self.ipv6, self.port, self.path))
MANAGED_API = {
BMAEndpoint.API: BMAEndpoint,
SecuredBMAEndpoint.API: SecuredBMAEndpoint,
WS2PEndpoint.API: WS2PEndpoint,
ESCoreEndpoint.API: ESCoreEndpoint,
ESUserEndpoint.API: ESUserEndpoint,
ESSubscribtionEndpoint.API: ESSubscribtionEndpoint,
GVAEndpoint.API: GVAEndpoint,
} # type: Dict[str, Any]
def endpoint(value: Any) -> Any:
"""
Convert an endpoint string to the corresponding Endpoint instance type
:param value: Endpoint string or subclass
:return:
"""
result = UnknownEndpoint.from_inline(value)
# if Endpoint instance...
if issubclass(type(value), Endpoint):
result = value
# if str...
elif isinstance(value, str):
# find Endpoint instance
for api, cls in MANAGED_API.items():
if value.startswith(f"{api} "):
result = cls.from_inline(value)
else:
raise TypeError(f"Cannot convert {value} to endpoint")
return result
def fix_host_ipv4_mix_up(host: str, ipv4: str) -> Tuple[str, str]:
mixed_up = False
try:
mixed_up = ip_address(host).version == 4 and not ipv4
except ValueError:
pass
return ("", host) if mixed_up else (host, ipv4)
|