-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbackend.py
More file actions
277 lines (243 loc) · 11 KB
/
backend.py
File metadata and controls
277 lines (243 loc) · 11 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import json
from streamcontroller_plugin_tools import BackendBase
from loguru import logger as log
from discordrpc import AsyncDiscord, commands
class Backend(BackendBase):
def __init__(self):
super().__init__()
self.client_id: str = None
self.client_secret: str = None
self.access_token: str = None
self.refresh_token: str = None
self.discord_client: AsyncDiscord = None
self._is_authed: bool = False
self._current_voice_channel: str = None
self._is_reconnecting: bool = False
self._voice_channel_users: dict = {} # {user_id: {username, nick, volume, muted}}
self._current_user_id: str = None # Current user's ID (for filtering)
def discord_callback(self, code, event):
if code == 0:
return
try:
event = json.loads(event)
except Exception as ex:
log.error(f"failed to parse discord event: {ex}")
return
resp_code = (
event.get("data").get("code", 0) if event.get("data") is not None else 0
)
if resp_code in [4006, 4009]:
if not self.refresh_token:
self.setup_client()
return
try:
token_resp = self.discord_client.refresh(self.refresh_token)
except Exception as ex:
log.error(f"failed to refresh token {ex}")
self._update_tokens("", "")
self.setup_client()
return
access_token = token_resp.get("access_token")
refresh_token = token_resp.get("refresh_token")
self._update_tokens(access_token, refresh_token)
self.discord_client.authenticate(self.access_token)
return
match event.get("cmd"):
case commands.AUTHORIZE:
auth_code = event.get("data").get("code")
token_resp = self.discord_client.get_access_token(auth_code)
self.access_token = token_resp.get("access_token")
self.refresh_token = token_resp.get("refresh_token")
self.discord_client.authenticate(self.access_token)
self.frontend.save_access_token(self.access_token)
self.frontend.save_refresh_token(self.refresh_token)
case commands.AUTHENTICATE:
self.frontend.on_auth_callback(True)
self._is_authed = True
# Capture current user ID for filtering in UserVolume
data = event.get("data", {})
user = data.get("user", {})
self._register_callbacks()
self._current_user_id = user.get("id")
self._get_current_voice_channel()
case commands.DISPATCH:
evt = event.get("evt")
self.frontend.trigger_event(evt, event.get("data"))
case commands.GET_SELECTED_VOICE_CHANNEL:
self._current_voice_channel = (
event.get("data").get("channel_id") if event.get("data") else None
)
self.frontend.trigger_event(commands.VOICE_CHANNEL_SELECT, event.get("data"))
case commands.GET_CHANNEL:
self.frontend.trigger_event(commands.GET_CHANNEL, event.get("data"))
def _update_tokens(self, access_token: str = "", refresh_token: str = ""):
self.access_token = access_token
self.refresh_token = refresh_token
self.frontend.save_access_token(access_token)
self.frontend.save_refresh_token(refresh_token)
def setup_client(self):
if self._is_reconnecting:
log.debug("Already reconnecting, skipping duplicate attempt")
return
try:
self._is_reconnecting = True
self.discord_client = AsyncDiscord(self.client_id, self.client_secret)
self.discord_client.connect(self.discord_callback)
if not self.access_token:
self.discord_client.authorize()
else:
self.discord_client.authenticate(self.access_token)
except Exception as ex:
self.frontend.on_auth_callback(False, str(ex))
log.error("failed to setup discord client: {0}", ex)
if self.discord_client:
self.discord_client.disconnect()
self.discord_client = None
finally:
self._is_reconnecting = False
def update_client_credentials(
self,
client_id: str,
client_secret: str,
access_token: str = "",
refresh_token: str = "",
):
if None in (client_id, client_secret) or "" in (client_id, client_secret):
self.frontend.on_auth_callback(
False, "actions.base.credentials.missing_client_info"
)
return
self.client_id = client_id
self.client_secret = client_secret
self.access_token = access_token
self.refresh_token = refresh_token
self.setup_client()
def is_authed(self) -> bool:
return self._is_authed
def _register_callbacks(self):
self.discord_client.subscribe(commands.VOICE_SETTINGS_UPDATE)
self.discord_client.subscribe(commands.VOICE_CHANNEL_SELECT)
self.discord_client.subscribe(commands.GET_CHANNEL)
def _ensure_connected(self) -> bool:
"""Ensure client is connected, trigger reconnection if needed."""
if self.discord_client is None or not self.discord_client.is_connected():
if not self._is_reconnecting:
self.setup_client()
return False
return True
def set_mute(self, muted: bool):
if not self._ensure_connected():
log.warning("Discord client not connected, cannot set mute")
return
self.discord_client.set_voice_settings({"mute": muted})
def set_deafen(self, muted: bool):
if not self._ensure_connected():
log.warning("Discord client not connected, cannot set deafen")
return
self.discord_client.set_voice_settings({"deaf": muted})
def change_voice_channel(self, channel_id: str = None) -> bool:
if not self._ensure_connected():
log.warning("Discord client not connected, cannot change voice channel")
return False
self.discord_client.select_voice_channel(channel_id, True)
return True
def change_text_channel(self, channel_id: str) -> bool:
if not self._ensure_connected():
log.warning("Discord client not connected, cannot change text channel")
return False
self.discord_client.select_text_channel(channel_id)
return True
def set_push_to_talk(self, ptt: str) -> bool:
if not self._ensure_connected():
log.warning("Discord client not connected, cannot set push to talk")
return False
self.discord_client.set_voice_settings({"mode": {"type": ptt}})
return True
@property
def current_voice_channel(self):
return self._current_voice_channel
@property
def current_user_id(self):
return self._current_user_id
def _get_current_voice_channel(self):
if not self._ensure_connected():
log.warning(
"Discord client not connected, cannot get current voice channel"
)
return
self.discord_client.get_selected_voice_channel()
def request_current_voice_channel(self):
"""Public method to request current voice channel state (dispatches to callbacks)."""
self._get_current_voice_channel()
# User volume control methods
def set_user_volume(self, user_id: str, volume: int) -> bool:
"""Set volume for a specific user (0-200, 100 = normal)."""
if not self._ensure_connected():
log.warning("Discord client not connected, cannot set user volume")
return False
self.discord_client.set_user_voice_settings(user_id, volume=volume)
if user_id in self._voice_channel_users:
self._voice_channel_users[user_id]["volume"] = volume
return True
def set_user_mute(self, user_id: str, muted: bool) -> bool:
"""Mute/unmute a specific user locally."""
if not self._ensure_connected():
log.warning("Discord client not connected, cannot set user mute")
return False
self.discord_client.set_user_voice_settings(user_id, mute=muted)
if user_id in self._voice_channel_users:
self._voice_channel_users[user_id]["muted"] = muted
return True
def update_voice_channel_user(self, user_id: str, username: str, nick: str = None,
volume: int = 100, muted: bool = False):
"""Track a user in the current voice channel."""
self._voice_channel_users[user_id] = {
"username": username,
"nick": nick,
"volume": volume,
"muted": muted
}
def remove_voice_channel_user(self, user_id: str):
"""Remove a user from tracking when they leave."""
self._voice_channel_users.pop(user_id, None)
def clear_voice_channel_users(self):
"""Clear all tracked users (when leaving voice channel)."""
self._voice_channel_users.clear()
def get_voice_channel_users(self) -> dict:
"""Get a copy of the current voice channel users."""
return self._voice_channel_users.copy()
def get_channel(self, channel_id: str) -> bool:
"""Fetch channel information including voice states."""
if not self._ensure_connected():
log.warning("Discord client not connected, cannot get channel")
return False
self.discord_client.get_channel(channel_id)
return True
def subscribe_voice_states(self, channel_id: str) -> bool:
"""Subscribe to voice state events for a specific channel."""
if not self._ensure_connected():
log.warning("Discord client not connected, cannot subscribe to voice states")
return False
args = {"channel_id": channel_id}
self.discord_client.subscribe(commands.VOICE_STATE_CREATE, args)
self.discord_client.subscribe(commands.VOICE_STATE_DELETE, args)
self.discord_client.subscribe(commands.VOICE_STATE_UPDATE, args)
return True
def unsubscribe_voice_states(self, channel_id: str) -> bool:
"""Unsubscribe from voice state events for a specific channel."""
if not self._ensure_connected():
return False
args = {"channel_id": channel_id}
self.discord_client.unsubscribe(commands.VOICE_STATE_CREATE, args)
self.discord_client.unsubscribe(commands.VOICE_STATE_DELETE, args)
self.discord_client.unsubscribe(commands.VOICE_STATE_UPDATE, args)
return True
def close(self):
if self.discord_client:
try:
self.discord_client.disconnect()
except Exception as ex:
log.error(f"Error disconnecting Discord client: {ex}")
self.discord_client = None
self._is_authed = False
backend = Backend()