2019-12-08 22:43:49 +01:00
|
|
|
import requests
|
|
|
|
|
|
|
|
from bemani.client.common import random_hex_string
|
|
|
|
from bemani.protocol import EAmuseProtocol, Node
|
|
|
|
|
|
|
|
|
|
|
|
class ClientProtocol:
|
2022-10-15 20:56:30 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
address: str,
|
|
|
|
port: int,
|
|
|
|
encryption: bool,
|
|
|
|
compression: bool,
|
|
|
|
verbose: bool,
|
|
|
|
) -> None:
|
2019-12-08 22:43:49 +01:00
|
|
|
self.__address = address
|
|
|
|
self.__port = port
|
|
|
|
self.__encryption = encryption
|
|
|
|
self.__compression = compression
|
|
|
|
self.__verbose = verbose
|
|
|
|
|
2022-10-15 20:56:30 +02:00
|
|
|
def exchange(
|
|
|
|
self,
|
|
|
|
uri: str,
|
|
|
|
tree: Node,
|
|
|
|
text_encoding: str = "shift-jis",
|
|
|
|
packet_encoding: str = "binary",
|
|
|
|
) -> Node:
|
2019-12-08 22:43:49 +01:00
|
|
|
headers = {}
|
|
|
|
|
|
|
|
if self.__verbose:
|
2022-10-15 20:56:30 +02:00
|
|
|
print("Outgoing request:")
|
2019-12-08 22:43:49 +01:00
|
|
|
print(tree)
|
|
|
|
|
|
|
|
# Handle encoding
|
|
|
|
if packet_encoding == "xml":
|
|
|
|
_packet_encoding = EAmuseProtocol.XML
|
|
|
|
elif packet_encoding == "binary":
|
|
|
|
_packet_encoding = EAmuseProtocol.BINARY
|
|
|
|
else:
|
2020-01-07 22:29:07 +01:00
|
|
|
raise Exception(f"Unknown packet encoding {packet_encoding}")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
# Handle encryption
|
|
|
|
if self.__encryption:
|
2022-10-15 20:56:30 +02:00
|
|
|
encryption = f"1-{random_hex_string(8)}-{random_hex_string(4)}"
|
|
|
|
headers["X-Eamuse-Info"] = encryption
|
2019-12-08 22:43:49 +01:00
|
|
|
else:
|
|
|
|
encryption = None
|
|
|
|
|
|
|
|
# Handle compression
|
|
|
|
if self.__compression:
|
2022-10-15 20:56:30 +02:00
|
|
|
compression = "lz77"
|
2019-12-08 22:43:49 +01:00
|
|
|
else:
|
|
|
|
compression = None
|
2022-10-15 20:56:30 +02:00
|
|
|
headers["X-Compress"] = compression
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
# Convert it
|
|
|
|
proto = EAmuseProtocol()
|
|
|
|
req = proto.encode(
|
|
|
|
compression,
|
|
|
|
encryption,
|
|
|
|
tree,
|
|
|
|
text_encoding=text_encoding,
|
|
|
|
packet_encoding=_packet_encoding,
|
|
|
|
)
|
|
|
|
|
|
|
|
# Send the request, get the response
|
|
|
|
r = requests.post(
|
2022-10-15 20:56:30 +02:00
|
|
|
f"http://{self.__address}:{self.__port}/{uri}",
|
2019-12-08 22:43:49 +01:00
|
|
|
headers=headers,
|
|
|
|
data=req,
|
|
|
|
)
|
|
|
|
|
|
|
|
# Get the compression and encryption
|
2022-10-15 20:56:30 +02:00
|
|
|
encryption = headers.get("X-Eamuse-Info")
|
|
|
|
compression = headers.get("X-Compress")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
# Decode it
|
|
|
|
packet = proto.decode(
|
|
|
|
compression,
|
|
|
|
encryption,
|
|
|
|
r.content,
|
|
|
|
)
|
|
|
|
if self.__verbose:
|
2022-10-15 20:56:30 +02:00
|
|
|
print("Incoming response:")
|
2019-12-08 22:43:49 +01:00
|
|
|
print(packet)
|
|
|
|
return packet
|