-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpc.py
198 lines (158 loc) · 5.3 KB
/
rpc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
from abc import ABCMeta, abstractmethod
import json
import logging
import os
import socket
import sys
import struct
import uuid
OP_HANDSHAKE = 0
OP_FRAME = 1
OP_CLOSE = 2
OP_PING = 3
OP_PONG = 4
logger = logging.getLogger(__name__)
class DiscordIpcError(Exception):
pass
class DiscordIpcClient(metaclass=ABCMeta):
"""Work with an open Discord instance via its JSON IPC for its rich presence API.
In a blocking way.
Classmethod `for_platform`
will resolve to one of WinDiscordIpcClient or UnixDiscordIpcClient,
depending on the current platform.
Supports context handler protocol.
"""
def __init__(self, client_id):
self.client_id = client_id
self._connect()
self._do_handshake()
logger.info("connected via ID %s", client_id)
@classmethod
def for_platform(cls, client_id, platform=sys.platform):
if platform == 'win32':
return WinDiscordIpcClient(client_id)
else:
return UnixDiscordIpcClient(client_id)
@abstractmethod
def _connect(self):
pass
def _do_handshake(self):
ret_op, ret_data = self.send_recv({'v': 1, 'client_id': self.client_id}, op=OP_HANDSHAKE)
# {'cmd': 'DISPATCH', 'data': {'v': 1, 'config': {...}}, 'evt': 'READY', 'nonce': None}
if ret_op == OP_FRAME and ret_data['cmd'] == 'DISPATCH' and ret_data['evt'] == 'READY':
return
else:
if ret_op == OP_CLOSE:
self.close()
raise RuntimeError(ret_data)
@abstractmethod
def _write(self, date: bytes):
pass
@abstractmethod
def _recv(self, size: int) -> bytes:
pass
def _recv_header(self) -> (int, int):
header = self._recv_exactly(8)
return struct.unpack("<II", header)
def _recv_exactly(self, size) -> bytes:
buf = b""
size_remaining = size
while size_remaining:
chunk = self._recv(size_remaining)
buf += chunk
size_remaining -= len(chunk)
return buf
def close(self):
logger.warning("closing connection")
try:
self.send({}, op=OP_CLOSE)
finally:
self._close()
@abstractmethod
def _close(self):
pass
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
def send_recv(self, data, op=OP_FRAME):
self.send(data, op)
return self.recv()
def send(self, data, op=OP_FRAME):
logger.debug("sending %s", data)
data_str = json.dumps(data, separators=(',', ':'))
data_bytes = data_str.encode('utf-8')
header = struct.pack("<II", op, len(data_bytes))
self._write(header)
self._write(data_bytes)
def recv(self) -> (int, "JSON"):
"""Receives a packet from discord.
Returns op code and payload.
"""
op, length = self._recv_header()
payload = self._recv_exactly(length)
data = json.loads(payload.decode('utf-8'))
logger.debug("received %s", data)
return op, data
def set_activity(self, act):
# act
data = {
'cmd': 'SET_ACTIVITY',
'args': {'pid': os.getpid(),
'activity': act},
'nonce': str(uuid.uuid4())
}
self.send(data)
class WinDiscordIpcClient(DiscordIpcClient):
_pipe_pattern = R'\\?\pipe\discord-ipc-{}'
def _connect(self):
for i in range(10):
path = self._pipe_pattern.format(i)
try:
self._f = open(path, "w+b")
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
self.path = path
def _write(self, data: bytes):
self._f.write(data)
self._f.flush()
def _recv(self, size: int) -> bytes:
return self._f.read(size)
def _close(self):
self._f.close()
class UnixDiscordIpcClient(DiscordIpcClient):
def _connect(self):
self._sock = socket.socket(socket.AF_UNIX)
pipe_pattern = self._get_pipe_pattern()
for i in range(10):
path = pipe_pattern.format(i)
if not os.path.exists(path):
continue
try:
self._sock.connect(path)
except OSError as e:
logger.error("failed to open {!r}: {}".format(path, e))
else:
break
else:
return DiscordIpcError("Failed to connect to Discord pipe")
@staticmethod
def _get_pipe_pattern():
env_keys = ('XDG_RUNTIME_DIR', 'TMPDIR', 'TMP', 'TEMP')
for env_key in env_keys:
dir_path = os.environ.get(env_key)
if dir_path:
break
else:
dir_path = '/tmp'
return os.path.join(dir_path, 'discord-ipc-{}')
def _write(self, data: bytes):
self._sock.sendall(data)
def _recv(self, size: int) -> bytes:
return self._sock.recv(size)
def _close(self):
self._sock.close()