From 86d59fa16a7b50089b3999afc3f69677cd772f51 Mon Sep 17 00:00:00 2001 From: Phin <59180111+phin05@users.noreply.github.com> Date: Wed, 11 May 2022 03:27:06 +0530 Subject: [PATCH] Cleanup and tweaks --- main.py | 2 +- services/ConfigService.py | 10 +-- services/DiscordRpcService.py | 32 ++++---- services/PlexAlertListener.py | 138 +++++++++++++++++----------------- utils/text.py | 4 +- 5 files changed, 95 insertions(+), 91 deletions(-) diff --git a/main.py b/main.py index d7cb3ba..7295026 100644 --- a/main.py +++ b/main.py @@ -15,7 +15,7 @@ if config["logging"]["debug"]: PlexAlertListener.useRemainingTime = config["display"]["useRemainingTime"] if len(config["users"]) == 0: - logger.info("No users in config. Initiating authorisation flow. ! TBD !") # TODO + logger.info("No users found in the config file. Initiating authorisation flow. ! TBD !") # TODO exit() plexAlertListeners: list[PlexAlertListener] = [] diff --git a/services/ConfigService.py b/services/ConfigService.py index fa8bd18..e2cb19f 100644 --- a/services/ConfigService.py +++ b/services/ConfigService.py @@ -1,8 +1,8 @@ -from datetime import datetime from models.config import Config from utils.logs import logger import json import os +import time class ConfigService: @@ -15,7 +15,7 @@ class ConfigService: with open(self.configFilePath, "r", encoding = "UTF-8") as configFile: self.config = json.load(configFile) except: - os.rename(configFilePath, configFilePath.replace(".json", f"-{datetime.now().timestamp():.0f}.json")) + os.rename(configFilePath, configFilePath.replace(".json", f"-{time.time():.0f}.json")) logger.exception("Failed to parse the application's config file. A new one will be created.") self.resetConfig() else: @@ -24,12 +24,12 @@ class ConfigService: def resetConfig(self) -> None: self.config = { "logging": { - "debug": True + "debug": True, }, "display": { - "useRemainingTime": False + "useRemainingTime": False, }, - "users": [] + "users": [], } self.saveConfig() diff --git a/services/DiscordRpcService.py b/services/DiscordRpcService.py index ee03863..78ee911 100644 --- a/services/DiscordRpcService.py +++ b/services/DiscordRpcService.py @@ -20,6 +20,9 @@ class DiscordRpcService: self.connected = False def connect(self): + if self.connected: + logger.debug("Attempt to connect Discord IPC Pipe while already connected") + return logger.info("Connecting Discord IPC Pipe") self.loop = asyncio.new_event_loop() if isUnix else asyncio.ProactorEventLoop() self.loop.run_until_complete(self.handshake()) @@ -45,7 +48,7 @@ class DiscordRpcService: return data except: logger.exception("An unexpected error occured during a RPC read operation") - self.disconnect() + self.connected = False def write(self, op, payload): try: @@ -54,22 +57,21 @@ class DiscordRpcService: self.pipeWriter.write(struct.pack(" 0: - stateText += f" · {', '.join(genre.tag for genre in metadata.genres[:3])}" + stateText = formatSeconds(item.duration / 1000) + mediaType = item.type + if mediaType == "movie": + title = f"{item.title} ({item.year})" + if len(item.genres) > 0: + stateText += f" · {', '.join(genre.tag for genre in item.genres[:3])}" largeText = "Watching a movie" - elif (mediaType == "episode"): - title = metadata.grandparentTitle - stateText += f" · S{metadata.parentIndex:02}E{metadata.index:02} - {metadata.title}" + # self.logger.debug("Poster: %s", item.thumbUrl) + elif mediaType == "episode": + title = item.grandparentTitle + stateText += f" · S{item.parentIndex:02}E{item.index:02} - {item.title}" largeText = "Watching a TV show" - elif (mediaType == "track"): - print(metadata) - title = metadata.title - artist = metadata.originalTitle - if (not artist): - artist = metadata.grandparentTitle - stateText = f"{artist} - {metadata.parentTitle}" + # self.logger.debug("Poster: %s", self.plexServer.url(item.grandparentThumb, True)) + elif mediaType == "track": + title = item.title + artist = item.originalTitle + if not artist: + artist = item.grandparentTitle + stateText = f"{artist} - {item.parentTitle}" largeText = "Listening to music" + # self.logger.debug("Album Art: %s", item.thumbUrl) else: self.logger.debug("Unsupported media type \"%s\", ignoring", mediaType) return @@ -202,18 +204,18 @@ class PlexAlertListener: "large_text": largeText, "large_image": "logo", "small_text": state.capitalize(), - "small_image": state + "small_image": state, }, } - if (state == "playing"): + if state == "playing": currentTimestamp = int(time.time()) - if (self.useRemainingTime): - activity["timestamps"] = {"end": round(currentTimestamp + ((metadata.duration - viewOffset) / 1000))} + if self.useRemainingTime: + activity["timestamps"] = {"end": round(currentTimestamp + ((item.duration - viewOffset) / 1000))} else: activity["timestamps"] = {"start": round(currentTimestamp - (viewOffset / 1000))} - if (not self.discordRpcService.connected): + if not self.discordRpcService.connected: self.discordRpcService.connect() - if (self.discordRpcService.connected): + if self.discordRpcService.connected: self.discordRpcService.sendActivity(activity) except: self.logger.exception("An unexpected error occured in the alert handler") diff --git a/utils/text.py b/utils/text.py index 72d78f7..320f725 100644 --- a/utils/text.py +++ b/utils/text.py @@ -1,8 +1,8 @@ def formatSeconds(seconds: int, joiner: str = "") -> str: seconds = round(seconds) timeValues = {"h": seconds // 3600, "m": seconds // 60 % 60, "s": seconds % 60} - if (not joiner): + if not joiner: return "".join(str(v) + k for k, v in timeValues.items() if v > 0) - if (timeValues["h"] == 0): + if timeValues["h"] == 0: del timeValues["h"] return joiner.join(str(v).rjust(2, "0") for v in timeValues.values())