Skip to content

Commit

Permalink
Format code with yapf
Browse files Browse the repository at this point in the history
This commit fixes the style issues introduced in 1dd7816 according to the output
from yapf.

Details: https://deepsource.io/gh/kokarare1212/librespot-python/transform/6f1ff38a-0e76-4ac9-9757-4a6558507d5d/
  • Loading branch information
deepsource-autofix[bot] authored Sep 13, 2021
1 parent 1dd7816 commit 6bb8764
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 20 deletions.
11 changes: 8 additions & 3 deletions librespot/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1097,10 +1097,13 @@ class Builder(AbsBuilder):
def blob(self, username: str, blob: bytes) -> Session.Builder:
if self.device_id is None:
raise TypeError("You must specify the device ID first.")
self.login_credentials = self.decrypt_blob(self.device_id, username, blob)
self.login_credentials = self.decrypt_blob(self.device_id,
username, blob)
return self

def decrypt_blob(self, device_id: str, username: str, encrypted_blob: bytes) -> Authentication.LoginCredentials:
def decrypt_blob(
self, device_id: str, username: str,
encrypted_blob: bytes) -> Authentication.LoginCredentials:
encrypted_blob = base64.b64decode(encrypted_blob)
sha1 = SHA1.new()
sha1.update(device_id.encode())
Expand All @@ -1119,7 +1122,9 @@ def decrypt_blob(self, device_id: str, username: str, encrypted_blob: bytes) ->
type_int = self.read_blob_int(blob)
type_ = Authentication.AuthenticationType.Name(type_int)
if type_ is None:
raise IOError(TypeError("Unknown AuthenticationType: {}".format(type_int)))
raise IOError(
TypeError(
"Unknown AuthenticationType: {}".format(type_int)))
le = self.read_blob_int(blob)
auth_data = blob.read(le)
return Authentication.LoginCredentials(
Expand Down
56 changes: 39 additions & 17 deletions librespot/zeroconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,26 +62,32 @@ def __init__(self, inner: Inner, listen_port):
if listen_port == -1:
listen_port = random.randint(self.__min_port + 1, self.__max_port)
self.__runner = ZeroconfServer.HttpRunner(self, listen_port)
threading.Thread(target=self.__runner.run, name="zeroconf-http-server").start()
threading.Thread(target=self.__runner.run,
name="zeroconf-http-server").start()
self.__zeroconf = zeroconf.Zeroconf()
self.__service_info = zeroconf.ServiceInfo(
ZeroconfServer.service,
inner.device_name + "." + ZeroconfServer.service,
listen_port, 0, 0, {
listen_port,
0,
0,
{
"CPath": "/",
"VERSION": "1.0",
"STACK": "SP",
},
inner.device_name,
)
self.__zeroconf.register_service(self.__service_info)
threading.Thread(target=self.__zeroconf.start, name="zeroconf-multicast-dns-server").start()
threading.Thread(target=self.__zeroconf.start,
name="zeroconf-multicast-dns-server").start()

def close(self) -> None:
self.__zeroconf.close()
self.__runner.close()

def handle_add_user(self, __socket: socket.socket, params: dict[str, str], http_version: str) -> None:
def handle_add_user(self, __socket: socket.socket, params: dict[str, str],
http_version: str) -> None:
username = params.get("userName")
if not username:
logging.error("Missing userName!")
Expand All @@ -95,13 +101,16 @@ def handle_add_user(self, __socket: socket.socket, params: dict[str, str], http_
logging.error("Missing clientKey!")
with self.__connection_lock:
if username == self.__connecting_username:
logging.info("{} is already trying to connect.".format(username))
logging.info(
"{} is already trying to connect.".format(username))
__socket.send(http_version.encode())
__socket.send(b" 403 Forbidden")
__socket.send(self.__eol)
__socket.send(self.__eol)
return
shared_key = util.int_to_bytes(self.__keys.compute_shared_key(base64.b64decode(client_key_str.encode())))
shared_key = util.int_to_bytes(
self.__keys.compute_shared_key(
base64.b64decode(client_key_str.encode())))
blob_bytes = base64.b64decode(blob_str)
iv = blob_bytes[:16]
encrypted = blob_bytes[16:len(blob_bytes) - 20]
Expand Down Expand Up @@ -129,7 +138,8 @@ def handle_add_user(self, __socket: socket.socket, params: dict[str, str], http_
decrypted = aes.decrypt(encrypted)
with self.__connection_lock:
self.__connecting_username = username
logging.info("Accepted new user from {}. [deviceId: {}]".format(params.get("deviceName"), self.__inner.device_id))
logging.info("Accepted new user from {}. [deviceId: {}]".format(
params.get("deviceName"), self.__inner.device_id))
response = json.dumps(self.__default_successful_add_user)
__socket.send(http_version.encode())
__socket.send(b" 200 OK")
Expand All @@ -149,14 +159,18 @@ def handle_add_user(self, __socket: socket.socket, params: dict[str, str], http_
with self.__connection_lock:
self.__connecting_username = None

def handle_get_info(self, __socket: socket.socket, http_version: str) -> None:
def handle_get_info(self, __socket: socket.socket,
http_version: str) -> None:
info = copy.deepcopy(self.__default_get_info_fields)
info["device_id"] = self.__inner.device_id
info["remoteName"] = self.__inner.device_name
info["publicKey"] = base64.b64encode(self.__keys.public_key_bytes()).decode()
info["publicKey"] = base64.b64encode(
self.__keys.public_key_bytes()).decode()
info["deviceType"] = Connect.DeviceType.Name(self.__inner.device_type)
with self.__connection_lock:
info["activeUser"] = self.__connecting_username if self.__connecting_username is not None else self.__session.username() if self.has_valid_session() else ""
info[
"activeUser"] = self.__connecting_username if self.__connecting_username is not None else self.__session.username(
) if self.has_valid_session() else ""

def has_valid_session(self) -> bool:
valid = self.__session and self.__session.is_valid()
Expand Down Expand Up @@ -195,13 +209,15 @@ def run(self):
def anonymous():
self.__handle(__socket)
__socket.close()

self.__worker.submit(anonymous)

def __handle(self, __socket: socket.socket) -> None:
request = io.BytesIO(__socket.recv(1024 * 1024))
request_line = request.readline().split(b" ")
if len(request_line) != 3:
logging.warning("Unexpected request line: {}".format(request_line))
logging.warning(
"Unexpected request line: {}".format(request_line))
method = request_line[0].decode()
path = request_line[1].decode()
http_version = request_line[2].decode()
Expand All @@ -213,7 +229,9 @@ def __handle(self, __socket: socket.socket) -> None:
split = header.split(b":")
headers[split[0].decode()] = split[1].strip().decode()
if not self.__zeroconf_server.has_valid_session():
logging.debug("Handling request: {}, {}, {}, headers: {}".format(method, path, http_version, headers))
logging.debug(
"Handling request: {}, {}, {}, headers: {}".format(
method, path, http_version, headers))
params = {}
if method == "POST":
content_type = headers.get("Content-Type")
Expand All @@ -229,7 +247,8 @@ def __handle(self, __socket: socket.socket) -> None:
pairs = body.split("&")
for pair in pairs:
split = pair.split("=")
params[urllib.parse.unquote(split[0])] = urllib.parse.unquote(split[1])
params[urllib.parse.unquote(
split[0])] = urllib.parse.unquote(split[1])
else:
params = self.__zeroconf_server.parse_path(path)
action = params.get("action")
Expand All @@ -238,22 +257,25 @@ def __handle(self, __socket: socket.socket) -> None:
return
self.handle_request(__socket, http_version, action, params)

def handle_request(self, __socket: socket.socket, http_version: str, action: str, params: dict[str, str]) -> None:
def handle_request(self, __socket: socket.socket, http_version: str,
action: str, params: dict[str, str]) -> None:
if action == "addUser":
if params is None:
raise RuntimeError


class Inner:
conf: typing.Final[Session.Configuration]
device_name: typing.Final[str]
device_id: typing.Final[str]
device_type: typing.Final[Connect.DeviceType]
preferred_locale: typing.Final[str]

def __init__(self, device_type: Connect.DeviceType, device_name: str, device_id: str, preferred_locale: str, conf: Session.Configuration):
def __init__(self, device_type: Connect.DeviceType, device_name: str,
device_id: str, preferred_locale: str,
conf: Session.Configuration):
self.conf = conf
self.device_name = device_name
self.device_id = util.random_hex_string(40).lower() if device_id else device_id
self.device_id = util.random_hex_string(
40).lower() if device_id else device_id
self.device_type = device_type
self.preferred_locale = preferred_locale

0 comments on commit 6bb8764

Please sign in to comment.