Fixed issue while running in background

This commit is contained in:
Phin 2022-05-22 10:07:09 +05:30
parent 2952870e1f
commit 9f1113c07f
9 changed files with 44 additions and 27 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
config.json
cache.json
lint.bat
console.log

View file

@ -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,

27
main.py
View file

@ -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()

View file

@ -2,6 +2,7 @@ from typing import TypedDict
class Logging(TypedDict):
debug: bool
writeToFile: bool
class Posters(TypedDict):
enabled: bool

View file

@ -1,5 +1,3 @@
{
"reportMissingTypeStubs": "information",
"reportUnknownArgumentType": "none",
"reportUnknownMemberType": "none"
"reportMissingTypeStubs": "information"
}

View file

@ -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":

View file

@ -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:

View file

@ -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()

View file

@ -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