discord-rich-presence-plex/discordRichPresencePlex.py

313 lines
11 KiB
Python
Raw Normal View History

2018-02-14 18:54:15 +00:00
import asyncio
2018-04-24 19:12:36 +00:00
import hashlib
2018-02-14 18:54:15 +00:00
import json
import os
import plexapi.myplex
import struct
import subprocess
import sys
import tempfile
import threading
import time
2018-03-11 16:01:58 +00:00
class plexConfig:
2018-04-24 19:12:36 +00:00
extraLogging = True
def __init__(self, serverName = "", username = "", password = "", token = "", listenForUser = ""):
self.serverName = serverName
self.username = username
self.password = password
self.token = token
self.listenForUser = (username if listenForUser == "" else listenForUser).lower()
plexConfigs = [
# plexConfig(serverName = "", username = "", password = "", token = "", listenForUser = "")
]
2018-02-14 18:54:15 +00:00
class discordRichPresence:
2018-04-24 19:12:36 +00:00
def __init__(self, clientID, child):
2018-02-14 18:54:15 +00:00
self.IPCPipe = ((os.environ.get("XDG_RUNTIME_DIR", None) or os.environ.get("TMPDIR", None) or os.environ.get("TMP", None) or os.environ.get("TEMP", None) or "/tmp") + "/discord-ipc-0") if isLinux else "\\\\?\\pipe\\discord-ipc-0"
self.clientID = clientID
self.pipeReader = None
self.pipeWriter = None
self.process = None
self.running = False
2018-02-14 20:17:33 +00:00
self.resetNext = False
2018-04-24 19:12:36 +00:00
self.child = child
2018-02-14 18:54:15 +00:00
async def read(self):
2018-02-14 20:17:33 +00:00
try:
data = await self.pipeReader.read(1024)
2018-04-24 19:12:36 +00:00
self.child.log("[READ] " + str(json.loads(data[8:].decode("utf-8"))))
2018-02-14 20:17:33 +00:00
except Exception as e:
2018-04-24 19:12:36 +00:00
self.child.log("Error: " + str(e))
2018-02-14 20:17:33 +00:00
self.resetNext = True
2018-02-14 18:54:15 +00:00
def write(self, op, payload):
payload = json.dumps(payload)
2018-04-24 19:12:36 +00:00
self.child.log("[WRITE] " + str(payload))
2018-02-14 18:54:15 +00:00
data = self.pipeWriter.write(struct.pack("<ii", op, len(payload)) + payload.encode("utf-8"))
async def handshake(self):
if (isLinux):
self.pipeReader, self.pipeWriter = await asyncio.open_unix_connection(self.IPCPipe, loop = self.loop)
else:
self.pipeReader = asyncio.StreamReader(loop = self.loop)
self.pipeWriter, _ = await self.loop.create_pipe_connection(lambda: asyncio.StreamReaderProtocol(self.pipeReader, loop = self.loop), self.IPCPipe)
self.write(0, {"v": 1, "client_id": self.clientID})
await self.read()
self.running = True
def start(self):
2018-04-24 19:12:36 +00:00
self.child.log("Opening Discord IPC Pipe")
2018-02-14 18:54:15 +00:00
emptyProcessFilePath = tempfile.gettempdir() + "\\discordRichPresencePlex-emptyProcess.py"
if (not os.path.exists(emptyProcessFilePath)):
with open(emptyProcessFilePath, "w") as emptyProcessFile:
2018-04-24 19:12:36 +00:00
emptyProcessFile.write("import timetry:\twhile (True):\t\ttime.sleep(60)except:\tpass")
2018-03-14 19:39:40 +00:00
self.process = subprocess.Popen(["python3" if isLinux else "pythonw", emptyProcessFilePath])
2018-02-14 18:54:15 +00:00
self.loop = asyncio.get_event_loop() if isLinux else asyncio.ProactorEventLoop()
self.loop.run_until_complete(self.handshake())
def stop(self):
2018-04-24 19:12:36 +00:00
self.child.log("Closing Discord IPC Pipe")
2018-02-14 18:54:15 +00:00
self.process.kill()
self.pipeWriter.close()
self.loop.close()
self.running = False
def send(self, activity):
payload = {
"cmd": "SET_ACTIVITY",
"args": {
"activity": activity,
"pid": self.process.pid
},
"nonce": "{0:.20f}".format(time.time())
}
sent = self.write(1, payload)
self.loop.run_until_complete(self.read())
class discordRichPresencePlex(discordRichPresence):
productName = "Plex Media Server"
lastState = None
lastSessionKey = None
lastRatingKey = None
stopTimer = None
2018-03-14 19:39:40 +00:00
stopTimerInterval = 5
stopTimer2 = None
stopTimer2Interval = 35
2018-04-24 19:12:36 +00:00
checkConnectionTimer = None
checkConnectionTimerInterval = 60
2018-02-14 18:54:15 +00:00
2018-04-24 19:12:36 +00:00
def __init__(self, plexConfig):
self.plexConfig = plexConfig
self.instanceID = hashlib.md5(str(id(self)).encode("UTF-8")).hexdigest()[:5]
super().__init__("413407336082833418", self)
2018-02-14 18:54:15 +00:00
def run(self):
2018-04-24 19:12:36 +00:00
try:
if (self.plexConfig.token):
self.plexAccount = plexapi.myplex.MyPlexAccount(self.plexConfig.username, token = self.plexConfig.token)
else:
self.plexAccount = plexapi.myplex.MyPlexAccount(self.plexConfig.username, self.plexConfig.password)
self.log("Logged in as Plex User \"" + self.plexAccount.username + "\"")
self.plexServer = None
for resource in self.plexAccount.resources():
if (resource.product == self.productName and resource.name == self.plexConfig.serverName):
self.plexServer = resource.connect()
self.plexServer.startAlertListener(self.onPlexServerAlert)
self.log("Connected to " + self.productName + " \"" + self.plexConfig.serverName + "\"")
self.log("Listening for PlaySessionStateNotification alerts from user \"" + self.plexConfig.listenForUser + "\"")
if (self.checkConnectionTimer):
self.checkConnectionTimer.cancel()
self.checkConnectionTimer = threading.Timer(self.checkConnectionTimerInterval, self.checkConnection)
self.checkConnectionTimer.start()
break
if (not self.plexServer):
self.log(self.productName + " \"" + self.plexConfig.serverName + "\" not found")
except Exception as e:
self.log("Failed to connect to Plex: " + str(e))
self.log("Reconnecting in 5 seconds")
time.sleep(5)
self.run()
def checkConnection(self):
try:
self.plexAccount.users()
self.checkConnectionTimer = threading.Timer(self.checkConnectionTimerInterval, self.checkConnection)
self.checkConnectionTimer.start()
except:
if (self.stopTimer):
self.stopTimer.cancel()
if (self.stopTimer2):
self.stopTimer2.cancel()
if (self.running):
self.stop()
self.log("Connection to Plex lost, reconnecting")
self.run()
def log(self, text, colour = "", extra = False):
prefix = "[" + self.plexConfig.serverName + "/" + self.instanceID + "] "
lock.acquire()
if (extra):
if (plexConfig.extraLogging):
print(prefix + colourText(str(text), colour))
2018-02-14 18:54:15 +00:00
else:
2018-04-24 19:12:36 +00:00
print(prefix + colourText(str(text), colour))
lock.release()
2018-02-14 18:54:15 +00:00
def onPlexServerAlert(self, data):
try:
if (data["type"] == "playing" and "PlaySessionStateNotification" in data):
sessionData = data["PlaySessionStateNotification"][0]
state = sessionData["state"]
sessionKey = int(sessionData["sessionKey"])
ratingKey = int(sessionData["ratingKey"])
viewOffset = int(sessionData["viewOffset"])
2018-04-24 19:12:36 +00:00
self.log("Received Update: " + colourText(sessionData, "yellow").replace("'", "\""), extra = True)
2018-02-14 18:54:15 +00:00
if (self.lastSessionKey == sessionKey and self.lastRatingKey == ratingKey):
2018-03-14 19:39:40 +00:00
if (self.stopTimer2):
self.stopTimer2.cancel()
self.stopTimer2 = None
2018-02-14 18:54:15 +00:00
if (self.lastState == state):
2018-04-24 19:12:36 +00:00
self.log("Nothing changed, ignoring", "yellow", extra = True)
2018-03-14 19:39:40 +00:00
self.stopTimer2 = threading.Timer(self.stopTimer2Interval, self.stopOnNoUpdate)
self.stopTimer2.start()
2018-02-14 18:54:15 +00:00
return
elif (state == "stopped"):
self.lastState, self.lastSessionKey, self.lastRatingKey = None, None, None
2018-03-14 19:39:40 +00:00
self.stopTimer = threading.Timer(self.stopTimerInterval, self.stop)
2018-02-14 18:54:15 +00:00
self.stopTimer.start()
2018-04-24 19:12:36 +00:00
self.log("Started stopTimer", "yellow", True)
2018-02-14 18:54:15 +00:00
return
elif (state == "stopped"):
2018-04-24 19:12:36 +00:00
self.log("\"stopped\" state update from unknown session key, ignoring", "yellow", True)
2018-02-14 18:54:15 +00:00
return
2018-04-24 19:12:36 +00:00
self.log("Checking Sessions for Session Key " + colourText(sessionKey, "yellow"), extra = True)
2018-03-14 19:39:40 +00:00
plexServerSessions = self.plexServer.sessions()
if (len(plexServerSessions) < 1):
2018-04-24 19:12:36 +00:00
self.log("Empty session list, ignoring", "red", True)
2018-03-14 19:39:40 +00:00
return
2018-03-14 20:08:42 +00:00
for session in plexServerSessions:
2018-04-24 19:12:36 +00:00
self.log(str(session) + ", Session Key: " + colourText(session.sessionKey, "yellow") + ", Users: " + colourText(session.usernames, "yellow").replace("'", "\""), extra = True)
2018-03-14 20:08:42 +00:00
sessionFound = False
if (session.sessionKey == sessionKey):
sessionFound = True
2018-04-24 19:12:36 +00:00
self.log("Session found", "green", True)
if (session.usernames[0].lower() == self.plexConfig.listenForUser):
self.log("Username \"" + session.usernames[0].lower() + "\" matches \"" + self.plexConfig.listenForUser + "\", continuing", "green", True)
2018-03-14 20:08:42 +00:00
break
else:
2018-04-24 19:12:36 +00:00
self.log("Username \"" + session.usernames[0].lower() + "\" doesn't match \"" + self.plexConfig.listenForUser + "\", ignoring", "red", True)
2018-03-14 20:08:42 +00:00
return
if (not sessionFound):
2018-04-24 19:12:36 +00:00
self.log("No matching session found", "red", True)
2018-03-14 20:08:42 +00:00
return
2018-04-24 19:12:36 +00:00
if (self.stopTimer):
self.stopTimer.cancel()
self.stopTimer = None
2018-03-14 19:39:40 +00:00
if (self.stopTimer2):
self.stopTimer2.cancel()
self.stopTimer2 = threading.Timer(self.stopTimer2Interval, self.stopOnNoUpdate)
self.stopTimer2.start()
2018-02-14 18:54:15 +00:00
self.lastState, self.lastSessionKey, self.lastRatingKey = state, sessionKey, ratingKey
metadata = self.plexServer.fetchItem(ratingKey)
mediaType = metadata.type
if (mediaType == "movie"):
title = metadata.title + " (" + str(metadata.year) + ")"
if (state != "playing"):
extra = str(time.strftime("%H:%M:%S", time.gmtime(viewOffset / 1000))) + "/" + str(time.strftime("%H:%M:%S", time.gmtime(metadata.duration / 1000)))
else:
extra = str(time.strftime("%Hh%Mm", time.gmtime(metadata.duration / 1000)))
extra = extra + " · " + ", ".join([genre.tag for genre in metadata.genres[:3]])
2018-02-15 18:43:45 +00:00
largeText = "Watching a Movie"
2018-02-14 18:54:15 +00:00
elif (mediaType == "episode"):
title = metadata.grandparentTitle
2018-02-14 19:08:28 +00:00
extra = "S" + str(metadata.parentIndex) + " · E" + str(metadata.index) + " - " + metadata.title
2018-02-15 18:43:45 +00:00
largeText = "Watching a TV Show"
2018-02-14 18:54:15 +00:00
elif (mediaType == "track"):
title = metadata.title
2018-03-11 16:01:58 +00:00
artist = metadata.originalTitle
if (not artist):
artist = metadata.grandparentTitle
extra = artist + " · " + metadata.parentTitle
2018-02-15 18:43:45 +00:00
largeText = "Listening to Music"
2018-02-14 18:54:15 +00:00
else:
2018-04-24 19:12:36 +00:00
self.log("Unsupported media type \"" + mediaType + "\", ignoring", "red", True)
2018-02-14 18:54:15 +00:00
return
activity = {
"details": title,
"state": extra,
"assets": {
2018-02-15 18:43:45 +00:00
"large_text": largeText,
2018-02-14 19:23:03 +00:00
"large_image": "logo",
2018-02-14 18:54:15 +00:00
"small_text": state.capitalize(),
"small_image": state
},
}
if (state == "playing"):
2018-03-11 16:01:58 +00:00
currentTimestamp = int(time.time())
activity["timestamps"] = {"start": currentTimestamp - (viewOffset / 1000)} # "end": currentTimestamp + ((metadata.duration - viewOffset) / 1000)
2018-02-14 20:17:33 +00:00
if (self.resetNext):
self.resetNext = False
self.stop()
2018-02-14 18:54:15 +00:00
if (not self.running):
self.start()
self.send(activity)
except Exception as e:
2018-04-24 19:12:36 +00:00
self.log("Error: " + str(e))
2018-02-14 20:17:33 +00:00
if (self.process):
self.process.kill()
2018-02-14 18:54:15 +00:00
2018-03-14 19:39:40 +00:00
def stopOnNoUpdate(self):
2018-04-24 19:12:36 +00:00
self.log("No updates from session key " + str(self.lastSessionKey) + ", stopping", "red", True)
2018-03-14 19:39:40 +00:00
self.lastState, self.lastSessionKey, self.lastRatingKey = None, None, None
self.stop()
2018-03-11 19:57:52 +00:00
isLinux = sys.platform in ["linux", "darwin"]
2018-04-24 19:12:36 +00:00
lock = threading.Semaphore(value = 1)
os.system("clear" if isLinux else "cls")
if (len(plexConfigs) == 0):
print("Error: plexConfigs list is empty")
sys.exit()
2018-03-11 19:57:52 +00:00
colours = {
"red": "91",
"green": "92",
"yellow": "93",
"blue": "94",
"magenta": "96",
"cyan": "97"
}
def colourText(text, colour = ""):
prefix = ""
suffix = ""
colour = colour.lower()
if (colour in colours):
prefix = "\033[" + colours[colour] + "m"
suffix = "\033[0m"
return prefix + str(text) + suffix
2018-04-24 19:12:36 +00:00
discordRichPresencePlexInstances = []
for config in plexConfigs:
discordRichPresencePlexInstances.append(discordRichPresencePlex(config))
2018-02-14 18:54:15 +00:00
try:
2018-04-24 19:12:36 +00:00
for discordRichPresencePlexInstance in discordRichPresencePlexInstances:
discordRichPresencePlexInstance.run()
2018-02-14 18:54:15 +00:00
while True:
2018-04-24 19:12:36 +00:00
time.sleep(3600)
2018-02-14 18:54:15 +00:00
except KeyboardInterrupt:
2018-04-24 19:12:36 +00:00
for discordRichPresencePlexInstance in discordRichPresencePlexInstances:
if (discordRichPresencePlexInstance.running):
discordRichPresencePlexInstance.stop()
if (discordRichPresencePlexInstance.checkConnectionTimer):
discordRichPresencePlexInstance.checkConnectionTimer.cancel()
2018-02-14 18:54:15 +00:00
except Exception as e:
print("Error: " + str(e))