discord-rich-presence-plex/services/DiscordRpcService.py

94 lines
3.1 KiB
Python
Raw Normal View History

2022-05-14 09:43:02 +00:00
# pyright: reportOptionalMemberAccess=none
2022-05-10 20:23:12 +00:00
from store.constants import discordClientID, isUnix, processID
2022-05-14 09:43:02 +00:00
from typing import Any, Optional
from utils.logging import logger
2022-05-10 20:23:12 +00:00
import asyncio
import json
2022-05-14 09:43:02 +00:00
import models.discord
2022-05-10 20:23:12 +00:00
import os
import struct
import time
class DiscordRpcService:
2023-10-01 13:41:42 +00:00
ipcPipe = (((os.path.isdir("/run/app") and "/run/app") or 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 isUnix else r"\\?\pipe\discord-ipc-0"
2022-05-10 20:23:12 +00:00
2022-05-14 09:43:02 +00:00
def __init__(self) -> None:
self.loop: Optional[asyncio.AbstractEventLoop] = None
self.pipeReader: Optional[asyncio.StreamReader] = None
self.pipeWriter: Optional[Any] = None
2022-05-10 20:23:12 +00:00
self.connected = False
2022-05-14 09:43:02 +00:00
def connect(self) -> None:
2022-05-10 21:57:06 +00:00
if self.connected:
logger.debug("Attempt to connect Discord IPC Pipe while already connected")
return
2022-05-10 20:23:12 +00:00
logger.info("Connecting Discord IPC Pipe")
2022-05-14 09:43:02 +00:00
self.loop = asyncio.new_event_loop()
2022-05-10 20:23:12 +00:00
self.loop.run_until_complete(self.handshake())
2022-05-14 09:43:02 +00:00
async def handshake(self) -> None:
2022-05-10 20:23:12 +00:00
try:
if isUnix:
2022-05-14 09:43:02 +00:00
self.pipeReader, self.pipeWriter = await asyncio.open_unix_connection(self.ipcPipe) # type: ignore
2022-05-10 20:23:12 +00:00
else:
2022-05-11 00:16:02 +00:00
self.pipeReader = asyncio.StreamReader()
2022-05-14 09:43:02 +00:00
self.pipeWriter, _ = await self.loop.create_pipe_connection(lambda: asyncio.StreamReaderProtocol(self.pipeReader), self.ipcPipe) # type: ignore
self.write(0, { "v": 1, "client_id": discordClientID })
2022-05-10 20:23:12 +00:00
if await self.read():
self.connected = True
except:
logger.exception("An unexpected error occured during a RPC handshake operation")
2022-05-14 09:43:02 +00:00
async def read(self) -> Optional[Any]:
2022-05-10 20:23:12 +00:00
try:
dataBytes = await self.pipeReader.read(1024)
data = json.loads(dataBytes[8:].decode("utf-8"))
logger.debug("[READ] %s", data)
return data
except:
logger.exception("An unexpected error occured during a RPC read operation")
2022-05-10 21:57:06 +00:00
self.connected = False
2022-05-10 20:23:12 +00:00
2022-05-14 09:43:02 +00:00
def write(self, op: int, payload: Any) -> None:
2022-05-10 20:23:12 +00:00
try:
logger.debug("[WRITE] %s", payload)
payload = json.dumps(payload)
self.pipeWriter.write(struct.pack("<ii", op, len(payload)) + payload.encode("utf-8"))
except:
logger.exception("An unexpected error occured during a RPC write operation")
2022-05-10 21:57:06 +00:00
self.connected = False
2022-05-10 20:23:12 +00:00
2022-05-14 09:43:02 +00:00
def disconnect(self) -> None:
2022-05-10 21:57:06 +00:00
if not self.connected:
logger.debug("Attempt to disconnect Discord IPC Pipe while not connected")
return
2022-05-10 20:23:12 +00:00
logger.info("Disconnecting Discord IPC Pipe")
2022-05-10 21:57:06 +00:00
try:
self.pipeWriter.close()
except:
logger.exception("An unexpected error occured while closing an IPC pipe writer")
try:
self.loop.run_until_complete(self.pipeReader.read())
except:
logger.exception("An unexpected error occured while closing an IPC pipe reader")
2022-05-10 20:23:12 +00:00
try:
self.loop.close()
except:
logger.exception("An unexpected error occured while closing an asyncio event loop")
self.connected = False
2022-05-14 09:43:02 +00:00
def setActivity(self, activity: models.discord.Activity) -> None:
2022-05-10 20:23:12 +00:00
logger.info("Activity update: %s", activity)
payload = {
"cmd": "SET_ACTIVITY",
"args": {
"pid": processID,
"activity": activity,
},
2022-05-10 21:57:06 +00:00
"nonce": "{0:.2f}".format(time.time()),
2022-05-10 20:23:12 +00:00
}
self.write(1, payload)
self.loop.run_until_complete(self.read())