Autopep run.

This commit is contained in:
Matthew Stratford 2021-04-08 21:15:15 +01:00
parent fbf6052491
commit 2c27899d94
5 changed files with 59 additions and 42 deletions

View file

@ -1,5 +1,5 @@
import json
from multiprocessing import Queue # , current_process
from multiprocessing import Queue, current_process
from helpers.logging_manager import LoggingManager
from helpers.myradio_api import MyRadioAPI
from setproctitle import setproctitle
@ -7,7 +7,8 @@ from os import _exit
# The API handler is needed from the main flask thread to process API requests.
# Flask is not able to handle these during page loads, requests.get() hangs.
# TODO: This is single threadded, but it probably doesn't need to be multi.
class APIHandler:
logger: LoggingManager
api: MyRadioAPI
@ -18,7 +19,7 @@ class APIHandler:
process_title = "APIHandler"
setproctitle(process_title)
# current_process().name = process_title
current_process().name = process_title
self.server_from_q = server_from_q
self.server_to_q = server_to_q
@ -39,7 +40,8 @@ class APIHandler:
)
elif request == "LIST_PLAYLIST_MUSIC":
self.server_to_q.put(
request + ":" + json.dumps(self.api.get_playlist_music())
request + ":" +
json.dumps(self.api.get_playlist_music())
)
elif request == "LIST_PLAYLIST_AUX":
self.server_to_q.put(
@ -49,7 +51,7 @@ class APIHandler:
else:
# Commands with params
command = request[: request.index(":")]
params = request[request.index(":") + 1 :]
params = request[request.index(":") + 1:]
if command == "GET_PLAYLIST_AUX":
self.server_to_q.put(
@ -72,7 +74,8 @@ class APIHandler:
+ ":"
+ json.dumps(
self.api.get_track_search(
str(params["title"]), str(params["artist"])
str(params["title"]), str(
params["artist"])
)
)
)
@ -89,6 +92,7 @@ class APIHandler:
except SystemExit:
self.logger.log.info("Received SystemExit")
except Exception as e:
self.logger.log.exception("Received unexpected exception: {}".format(e))
self.logger.log.exception(
"Received unexpected exception: {}".format(e))
del self.logger
_exit(0)

View file

@ -19,22 +19,17 @@
# It is key that whenever the parent server tells us to do something
# that we respond with something, FAIL or OKAY. The server doesn't like to be kept waiting.
from helpers.types import PlayerState, RepeatMode
# Stop the Pygame Hello message.
import os
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
from queue import Empty
import multiprocessing
import setproctitle
import copy
import json
import time
from typing import Any, Callable, Dict, List, Optional
from plan import PlanItem
# Stop the Pygame Hello message.
import os
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
from pygame import mixer
from mutagen.mp3 import MP3
@ -42,6 +37,9 @@ from helpers.myradio_api import MyRadioAPI
from helpers.os_environment import isMacOS
from helpers.state_manager import StateManager
from helpers.logging_manager import LoggingManager
from helpers.types import PlayerState, RepeatMode
from plan import PlanItem
# TODO ENUM
VALID_MESSAGE_SOURCES = ["WEBSOCKET", "UI", "CONTROLLER", "TEST", "ALL"]
@ -302,12 +300,14 @@ class Player:
break
if loaded_item == None:
self.logger.log.error("Failed to find weight: {}".format(weight))
self.logger.log.error(
"Failed to find weight: {}".format(weight))
return False
reload = False
if loaded_item.filename == "" or loaded_item.filename == None:
self.logger.log.info("Filename is not specified, loading from API.")
self.logger.log.info(
"Filename is not specified, loading from API.")
reload = True
elif not os.path.exists(loaded_item.filename):
self.logger.log.warn(
@ -330,7 +330,8 @@ class Player:
# TODO: Update the show plan filenames
try:
self.logger.log.info("Loading file: " + str(loaded_item.filename))
self.logger.log.info("Loading file: " +
str(loaded_item.filename))
mixer.music.load(loaded_item.filename)
except:
# We couldn't load that file.
@ -345,10 +346,12 @@ class Player:
self.state.update("length", song.info.length)
else:
self.state.update(
"length", mixer.Sound(loaded_item.filename).get_length() / 1000
"length", mixer.Sound(
loaded_item.filename).get_length() / 1000
)
except:
self.logger.log.exception("Failed to update the length of item.")
self.logger.log.exception(
"Failed to update the length of item.")
return False
if self.state.state["play_on_load"]:
@ -475,7 +478,8 @@ class Player:
self.state.update(
"remaining",
max(0, (self.state.state["length"] - self.state.state["pos_true"])),
max(0, (self.state.state["length"] -
self.state.state["pos_true"])),
)
def _ping_times(self):
@ -515,7 +519,8 @@ class Player:
def _send_status(self):
# TODO This is hacky
self._retMsg(str(self.status), okay_str=True, custom_prefix="ALL:STATUS:")
self._retMsg(str(self.status), okay_str=True,
custom_prefix="ALL:STATUS:")
def __init__(
self, channel: int, in_q: multiprocessing.Queue, out_q: multiprocessing.Queue
@ -546,7 +551,8 @@ class Player:
loaded_state = copy.copy(self.state.state)
if loaded_state["output"]:
self.logger.log.info("Setting output to: " + str(loaded_state["output"]))
self.logger.log.info("Setting output to: " +
str(loaded_state["output"]))
self.output(loaded_state["output"])
else:
self.logger.log.info("Using default output device.")
@ -554,7 +560,8 @@ class Player:
loaded_item = loaded_state["loaded_item"]
if loaded_item:
self.logger.log.info("Loading filename: " + str(loaded_item.filename))
self.logger.log.info("Loading filename: " +
str(loaded_item.filename))
self.load(loaded_item.weight)
if loaded_state["pos_true"] != 0:
@ -581,7 +588,8 @@ class Player:
self.last_msg_source = ""
self.last_msg = ""
self.logger.log.warn(
"Message from unknown sender source: {}".format(source)
"Message from unknown sender source: {}".format(
source)
)
continue
@ -643,11 +651,13 @@ class Player:
"UNLOAD": lambda: self._retMsg(self.unload()),
"ADD": lambda: self._retMsg(
self.add_to_plan(
json.loads(":".join(self.last_msg.split(":")[1:]))
json.loads(
":".join(self.last_msg.split(":")[1:]))
)
),
"REMOVE": lambda: self._retMsg(
self.remove_from_plan(int(self.last_msg.split(":")[1]))
self.remove_from_plan(
int(self.last_msg.split(":")[1]))
),
"CLEAR": lambda: self._retMsg(self.clear_channel_plan()),
}
@ -677,7 +687,8 @@ class Player:
except SystemExit:
self.logger.log.info("Received SystemExit")
except Exception as e:
self.logger.log.exception("Received unexpected exception: {}".format(e))
self.logger.log.exception(
"Received unexpected exception: {}".format(e))
self.logger.log.info("Quiting player " + str(channel))
self.quit()

View file

@ -42,6 +42,7 @@ class PlayerHandler:
except SystemExit:
self.logger.log.info("Received SystemExit")
except Exception as e:
self.logger.log.exception("Received unexpected exception: {}".format(e))
self.logger.log.exception(
"Received unexpected exception: {}".format(e))
del self.logger
_exit(0)

View file

@ -130,7 +130,8 @@ def ui_status():
for i in range(state.state["num_channels"]):
channel_states.append(status(i))
data = {"channels": channel_states, "ui_page": "status", "ui_title": "Status"}
data = {"channels": channel_states,
"ui_page": "status", "ui_title": "Status"}
return render_template("status.html", data=data)
@ -294,10 +295,7 @@ def clear_channel_plan(channel: int):
@app.route("/player/<int:channel>/status")
def channel_json(channel: int):
try:
return jsonify(status(channel))
except:
return status(channel)
return jsonify(status(channel))
@app.route("/plan/list")
@ -311,7 +309,7 @@ def list_showplans():
try:
response = api_from_q.get_nowait()
if response.startswith("LIST_PLANS:"):
response = response[response.index(":") + 1 :]
response = response[response.index(":") + 1:]
return response
except queue.Empty:
@ -330,7 +328,8 @@ def search_library(type: str):
api_from_q.get() # Just waste any previous status responses.
params = json.dumps(
{"title": request.args.get("title"), "artist": request.args.get("artist")}
{"title": request.args.get(
"title"), "artist": request.args.get("artist")}
)
api_to_q.put("SEARCH_TRACK:{}".format(params))
@ -388,7 +387,7 @@ def get_playlist(type: str, library_id: str):
try:
response = api_from_q.get_nowait()
if response.startswith(command):
response = response[len(command) + 1 :]
response = response[len(command) + 1:]
if response == "null":
abort(401)
return response
@ -420,7 +419,7 @@ def status(channel: int):
if response.startswith("UI:STATUS:"):
response = response.split(":", 2)[2]
# TODO: Handle OKAY / FAIL
response = response[response.index(":") + 1 :]
response = response[response.index(":") + 1:]
try:
response = json.loads(response)
except Exception as e:

View file

@ -85,7 +85,8 @@ class WebsocketServer:
)
except websockets.exceptions.ConnectionClosedError as e:
self.logger.log.error("Client Disconncted {}, {}".format(websocket, e))
self.logger.log.error(
"Client Disconncted {}, {}".format(websocket, e))
# TODO: Proper Logging
except Exception as e:
@ -109,7 +110,7 @@ class WebsocketServer:
# Handle the general case
# Message format:
## SOURCE:COMMAND:EXTRADATA
# SOURCE:COMMAND:EXTRADATA
message = "WEBSOCKET:" + command
@ -147,7 +148,8 @@ class WebsocketServer:
item = data["item"]
item["weight"] = int(data["new_weight"])
# Now send the special case.
self.channel_to_q[new_channel].put("ADD:" + json.dumps(item))
self.channel_to_q[new_channel].put(
"ADD:" + json.dumps(item))
except ValueError as e:
self.logger.log.exception(