discord-rich-presence-plex/main.py

64 lines
2.3 KiB
Python
Raw Normal View History

from services import PlexAlertListener
from services.cache import loadCache
from services.config import config, loadConfig, saveConfig
from store.constants import isUnix, logFilePath, name, plexClientID, version
from utils.logging import formatter, logger
2022-05-10 20:23:12 +00:00
import logging
import os
import requests
import sys
import time
import urllib.parse
2022-05-10 20:23:12 +00:00
2022-05-22 17:03:17 +00:00
plexAlertListeners: list[PlexAlertListener] = []
2022-05-22 17:03:17 +00:00
try:
loadConfig()
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 = {
"X-Plex-Product": name,
"X-Plex-Client-Identifier": plexClientID,
}).json()
2022-05-22 17:03:17 +00:00
logger.info("Open the below URL in your web browser and sign in:")
logger.info("https://app.plex.tv/auth#?clientID=%s&code=%s&context%%5Bdevice%%5D%%5Bproduct%%5D=%s", plexClientID, response["code"], urllib.parse.quote(name))
2022-05-11 02:19:49 +00:00
time.sleep(5)
2022-05-22 17:03:17 +00:00
logger.info("Checking whether authentication is successful...")
for _ in range(120):
authCheckResponse = requests.get(f"https://plex.tv/api/v2/pins/{response['id']}.json?code={response['code']}", headers = {
"X-Plex-Client-Identifier": plexClientID,
}).json()
if authCheckResponse["authToken"]:
logger.info("Authentication successful.")
serverName = input("Enter the name of the Plex Media Server you wish to connect to: ")
config["users"].append({ "token": authCheckResponse["authToken"], "servers": [{ "name": serverName }] })
saveConfig()
break
time.sleep(5)
else:
logger.info("Authentication failed.")
exit()
2022-05-14 09:43:02 +00:00
plexAlertListeners = [PlexAlertListener(user["token"], server) for user in config["users"] for server in user["servers"]]
2022-05-22 17:03:17 +00:00
if sys.stdin:
while True:
userInput = input()
if userInput in ["exit", "quit"]:
raise KeyboardInterrupt
2022-05-22 17:03:17 +00:00
else:
while True:
time.sleep(3600)
2022-05-10 20:23:12 +00:00
except KeyboardInterrupt:
for plexAlertListener in plexAlertListeners:
plexAlertListener.disconnect()
except:
logger.exception("An unexpected error occured")