From 9f1113c07fc6ae1caf0a8fdc7ea2831936413b58 Mon Sep 17 00:00:00 2001 From: Phin <59180111+phin05@users.noreply.github.com> Date: Sun, 22 May 2022 10:07:09 +0530 Subject: [PATCH] Fixed issue while running in background --- .gitignore | 1 + README.md | 6 ++++-- main.py | 27 ++++++++++++++++++--------- models/config.py | 1 + pyrightconfig.json | 4 +--- services/PlexAlertListener.py | 6 ++++-- services/config.py | 4 +++- store/constants.py | 3 ++- utils/logging.py | 19 ++++++++++--------- 9 files changed, 44 insertions(+), 27 deletions(-) diff --git a/.gitignore b/.gitignore index aaef6a5..ca4192d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ config.json cache.json lint.bat +console.log diff --git a/README.md b/README.md index fdd6584..6297290 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A Python script that displays your [Plex](https://www.plex.tv) status on [Discord](https://discord.com) using [Rich Presence](https://discord.com/developers/docs/rich-presence/how-to). -Current Version: 2.2.2 +Current Version: 2.2.3 ## Getting Started @@ -25,6 +25,7 @@ The script must be running on the same machine as your Discord client. * `logging` * `debug` (boolean, default: `true`) - Outputs additional debug-helpful information to the console if enabled. + * `writeToFile` (boolean, default: `false`) - Writes everything outputted to console to a `console.log` file if enabled. * `display` * `useRemainingTime` (boolean, default: `false`) - Displays your media's remaining time instead of elapsed time in your Rich Presence if enabled. * `posters` @@ -49,7 +50,8 @@ The script must be running on the same machine as your Discord client. ```json { "logging": { - "debug": true + "debug": true, + "writeToFile": false }, "display": { "useRemainingTime": false, diff --git a/main.py b/main.py index 4df0d1f..1017999 100644 --- a/main.py +++ b/main.py @@ -1,21 +1,27 @@ from services import PlexAlertListener from services.cache import loadCache from services.config import config, loadConfig, saveConfig -from store.constants import isUnix, name, plexClientID, version -from utils.logging import logger +from store.constants import isUnix, logFilePath, name, plexClientID, version +from utils.logging import formatter, logger import logging import os import requests +import sys import time import urllib.parse -os.system("clear" if isUnix else "cls") -logger.info("%s - v%s", name, version) loadConfig() -loadCache() - if config["logging"]["debug"]: logger.setLevel(logging.DEBUG) +if config["logging"]["writeToFile"]: + fileHandler = logging.FileHandler(logFilePath) + fileHandler.setFormatter(formatter) + logger.addHandler(fileHandler) + +os.system("clear" if isUnix else "cls") +logger.info("%s - v%s", name, version) +loadCache() + if len(config["users"]) == 0: logger.info("No users found in the config file. Initiating authentication flow.") response = requests.post("https://plex.tv/api/v2/pins.json?strong=true", headers = { @@ -45,9 +51,12 @@ plexAlertListeners: list[PlexAlertListener] = [] try: plexAlertListeners = [PlexAlertListener(user["token"], server) for user in config["users"] for server in user["servers"]] while True: - userInput = input() - if userInput in ["exit", "quit"]: - raise KeyboardInterrupt + if sys.stdin: + userInput = input() + if userInput in ["exit", "quit"]: + raise KeyboardInterrupt + else: + time.sleep(3600) except KeyboardInterrupt: for plexAlertListener in plexAlertListeners: plexAlertListener.disconnect() diff --git a/models/config.py b/models/config.py index ab9ae1e..78e9953 100644 --- a/models/config.py +++ b/models/config.py @@ -2,6 +2,7 @@ from typing import TypedDict class Logging(TypedDict): debug: bool + writeToFile: bool class Posters(TypedDict): enabled: bool diff --git a/pyrightconfig.json b/pyrightconfig.json index 2158766..9b758be 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -1,5 +1,3 @@ { - "reportMissingTypeStubs": "information", - "reportUnknownArgumentType": "none", - "reportUnknownMemberType": "none" + "reportMissingTypeStubs": "information" } diff --git a/services/PlexAlertListener.py b/services/PlexAlertListener.py index c6a350e..56526e6 100644 --- a/services/PlexAlertListener.py +++ b/services/PlexAlertListener.py @@ -1,4 +1,4 @@ -# pyright: reportTypedDictNotRequiredAccess=none +# pyright: reportTypedDictNotRequiredAccess=none,reportUnknownArgumentType=none,reportUnknownMemberType=none from .DiscordRpcService import DiscordRpcService from .cache import getKey, setKey @@ -175,7 +175,9 @@ class PlexAlertListener(threading.Thread): self.updateTimeoutTimer = threading.Timer(self.updateTimeoutTimerInterval, self.updateTimeout) self.updateTimeoutTimer.start() self.lastState, self.lastSessionKey, self.lastRatingKey = state, sessionKey, ratingKey - mediaType = item.type + mediaType: str = item.type + title: str + thumb: str if mediaType in ["movie", "episode"]: stateStrings: list[str] = [formatSeconds(item.duration / 1000)] if mediaType == "movie": diff --git a/services/config.py b/services/config.py index 1a441bb..ef766d5 100644 --- a/services/config.py +++ b/services/config.py @@ -9,6 +9,7 @@ import time config: models.config.Config = { "logging": { "debug": True, + "writeToFile": False, }, "display": { "useRemainingTime": False, @@ -25,10 +26,11 @@ def loadConfig() -> None: try: with open(configFilePath, "r", encoding = "UTF-8") as configFile: loadedConfig = json.load(configFile) - merge(loadedConfig, config) except: 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.") + else: + merge(loadedConfig, config) saveConfig() def saveConfig() -> None: diff --git a/store/constants.py b/store/constants.py index 699c328..92a3763 100644 --- a/store/constants.py +++ b/store/constants.py @@ -2,12 +2,13 @@ import os import sys name = "Discord Rich Presence for Plex" -version = "2.2.2" +version = "2.2.3" plexClientID = "discord-rich-presence-plex" discordClientID = "413407336082833418" configFilePath = "config.json" cacheFilePath = "cache.json" +logFilePath = "console.log" isUnix = sys.platform in ["linux", "darwin"] processID = os.getpid() diff --git a/utils/logging.py b/utils/logging.py index f576775..3bf5701 100644 --- a/utils/logging.py +++ b/utils/logging.py @@ -3,21 +3,22 @@ import logging logger = logging.getLogger("discord-rich-presence-plex") logger.setLevel(logging.INFO) -handler = logging.StreamHandler() -handler.setFormatter(logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s", datefmt = "%d-%m-%Y %I:%M:%S %p")) -logger.addHandler(handler) +formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s", datefmt = "%d-%m-%Y %I:%M:%S %p") +streamHandler = logging.StreamHandler() +streamHandler.setFormatter(formatter) +logger.addHandler(streamHandler) class LoggerWithPrefix: def __init__(self, prefix: str) -> None: self.prefix = prefix - self.info = self._wrapLoggerFunc(logger.info) - self.warning = self._wrapLoggerFunc(logger.warning) - self.error = self._wrapLoggerFunc(logger.error) - self.exception = self._wrapLoggerFunc(logger.exception) - self.debug = self._wrapLoggerFunc(logger.debug) + self.info = self.wrapLoggerFunc(logger.info) + self.warning = self.wrapLoggerFunc(logger.warning) + self.error = self.wrapLoggerFunc(logger.error) + self.exception = self.wrapLoggerFunc(logger.exception) + self.debug = self.wrapLoggerFunc(logger.debug) - def _wrapLoggerFunc(self, func: Callable[..., None]) -> Callable[..., None]: + def wrapLoggerFunc(self, func: Callable[..., None]) -> Callable[..., None]: def wrappedFunc(obj: Any, *args: Any, **kwargs: Any) -> None: func(self.prefix + str(obj), *args, **kwargs) return wrappedFunc