|
| 1 | +import subprocess |
| 2 | +import re |
| 3 | +from typing import List, Dict, Optional |
| 4 | + |
| 5 | + |
| 6 | +class DiscordAudioController: |
| 7 | + """Controller for managing Discord audio streams through PulseAudio""" |
| 8 | + |
| 9 | + def __init__(self): |
| 10 | + self.discord_patterns = [ |
| 11 | + r"WEBRTC VoiceEngine", |
| 12 | + r"Discord", |
| 13 | + r"discord", |
| 14 | + r"playStream", |
| 15 | + r"recStream" |
| 16 | + ] |
| 17 | + |
| 18 | + def _run_command(self, command: List[str]) -> Optional[str]: |
| 19 | + """Execute a command and return the result""" |
| 20 | + try: |
| 21 | + result = subprocess.run(command, capture_output=True, text=True, check=True) |
| 22 | + return result.stdout |
| 23 | + except subprocess.CalledProcessError as e: |
| 24 | + print(f"Command failed: {' '.join(command)} - {e}") |
| 25 | + return None |
| 26 | + |
| 27 | + def _get_sink_inputs(self) -> List[Dict[str, str]]: |
| 28 | + """Get all PulseAudio sink-inputs (playback streams)""" |
| 29 | + output = self._run_command(["pactl", "list", "sink-inputs"]) |
| 30 | + if not output: |
| 31 | + return [] |
| 32 | + |
| 33 | + sinks = [] |
| 34 | + current_sink = {} |
| 35 | + |
| 36 | + for line in output.split('\n'): |
| 37 | + line = line.strip() |
| 38 | + |
| 39 | + if line.startswith("Sink Input #"): |
| 40 | + if current_sink: |
| 41 | + sinks.append(current_sink) |
| 42 | + sink_id = re.search(r'#(\d+)', line) |
| 43 | + current_sink = { |
| 44 | + "id": sink_id.group(1) if sink_id else "", |
| 45 | + "type": "sink-input" |
| 46 | + } |
| 47 | + |
| 48 | + elif "application.name" in line: |
| 49 | + match = re.search(r'application\.name = "([^"]*)"', line) |
| 50 | + if match: |
| 51 | + current_sink["app_name"] = match.group(1) |
| 52 | + |
| 53 | + elif line.startswith("Mute:"): |
| 54 | + current_sink["muted"] = "yes" in line.lower() |
| 55 | + |
| 56 | + elif line.startswith("Volume:"): |
| 57 | + volume_match = re.search(r'(\d+)%', line) |
| 58 | + if volume_match: |
| 59 | + current_sink["volume"] = int(volume_match.group(1)) |
| 60 | + |
| 61 | + if current_sink: |
| 62 | + sinks.append(current_sink) |
| 63 | + |
| 64 | + return sinks |
| 65 | + |
| 66 | + def _get_source_outputs(self) -> List[Dict[str, str]]: |
| 67 | + """Get all PulseAudio source-outputs (recording streams)""" |
| 68 | + output = self._run_command(["pactl", "list", "source-outputs"]) |
| 69 | + if not output: |
| 70 | + return [] |
| 71 | + |
| 72 | + sources = [] |
| 73 | + current_source = {} |
| 74 | + |
| 75 | + for line in output.split('\n'): |
| 76 | + line = line.strip() |
| 77 | + |
| 78 | + if line.startswith("Source Output #"): |
| 79 | + if current_source: |
| 80 | + sources.append(current_source) |
| 81 | + source_id = re.search(r'#(\d+)', line) |
| 82 | + current_source = { |
| 83 | + "id": source_id.group(1) if source_id else "", |
| 84 | + "type": "source-output" |
| 85 | + } |
| 86 | + |
| 87 | + elif "application.name" in line: |
| 88 | + match = re.search(r'application\.name = "([^"]*)"', line) |
| 89 | + if match: |
| 90 | + current_source["app_name"] = match.group(1) |
| 91 | + |
| 92 | + elif line.startswith("Mute:"): |
| 93 | + current_source["muted"] = "yes" in line.lower() |
| 94 | + |
| 95 | + if current_source: |
| 96 | + sources.append(current_source) |
| 97 | + |
| 98 | + return sources |
| 99 | + |
| 100 | + def _find_discord_streams(self) -> List[Dict[str, str]]: |
| 101 | + """Find all Discord-related streams (both playback and recording)""" |
| 102 | + all_streams = self._get_sink_inputs() + self._get_source_outputs() |
| 103 | + discord_streams = [] |
| 104 | + |
| 105 | + for stream in all_streams: |
| 106 | + app_name = stream.get("app_name", "").lower() |
| 107 | + |
| 108 | + # Check against Discord patterns |
| 109 | + for pattern in self.discord_patterns: |
| 110 | + if pattern.lower() in app_name: |
| 111 | + discord_streams.append(stream) |
| 112 | + break |
| 113 | + |
| 114 | + return discord_streams |
| 115 | + |
| 116 | + def get_status(self) -> Dict: |
| 117 | + """Get current status of Discord streams""" |
| 118 | + discord_streams = self._find_discord_streams() |
| 119 | + |
| 120 | + if not discord_streams: |
| 121 | + return { |
| 122 | + "success": True, |
| 123 | + "found": False, |
| 124 | + "message": "No Discord streams found", |
| 125 | + "streams": [] |
| 126 | + } |
| 127 | + |
| 128 | + streams_info = [] |
| 129 | + for stream in discord_streams: |
| 130 | + stream_info = { |
| 131 | + "id": stream.get("id"), |
| 132 | + "type": "playback" if stream.get("type") == "sink-input" else "recording", |
| 133 | + "app_name": stream.get("app_name", "Unknown"), |
| 134 | + "muted": stream.get("muted", False), |
| 135 | + "volume": stream.get("volume", None) |
| 136 | + } |
| 137 | + streams_info.append(stream_info) |
| 138 | + |
| 139 | + return { |
| 140 | + "success": True, |
| 141 | + "found": True, |
| 142 | + "message": f"Found {len(discord_streams)} Discord streams", |
| 143 | + "streams": streams_info |
| 144 | + } |
| 145 | + |
| 146 | + def toggle_mute(self) -> Dict: |
| 147 | + """Toggle mute state for all Discord streams""" |
| 148 | + discord_streams = self._find_discord_streams() |
| 149 | + |
| 150 | + if not discord_streams: |
| 151 | + return { |
| 152 | + "success": False, |
| 153 | + "message": "No Discord streams found", |
| 154 | + "streams_affected": 0 |
| 155 | + } |
| 156 | + |
| 157 | + # Determine target state based on first stream |
| 158 | + first_stream = discord_streams[0] |
| 159 | + is_currently_muted = first_stream.get("muted", False) |
| 160 | + target_state = "0" if is_currently_muted else "1" # 0 = unmute, 1 = mute |
| 161 | + action = "unmuted" if is_currently_muted else "muted" |
| 162 | + |
| 163 | + results = [] |
| 164 | + success_count = 0 |
| 165 | + |
| 166 | + for stream in discord_streams: |
| 167 | + stream_id = stream.get("id") |
| 168 | + stream_type = stream.get("type") |
| 169 | + app_name = stream.get("app_name", "Unknown") |
| 170 | + |
| 171 | + if not stream_id or not stream_type: |
| 172 | + continue |
| 173 | + |
| 174 | + # Choose correct command based on stream type |
| 175 | + if stream_type == "sink-input": |
| 176 | + cmd = ["pactl", "set-sink-input-mute", stream_id, target_state] |
| 177 | + stream_desc = "playback" |
| 178 | + elif stream_type == "source-output": |
| 179 | + cmd = ["pactl", "set-source-output-mute", stream_id, target_state] |
| 180 | + stream_desc = "recording" |
| 181 | + else: |
| 182 | + continue |
| 183 | + |
| 184 | + result = self._run_command(cmd) |
| 185 | + stream_result = { |
| 186 | + "id": stream_id, |
| 187 | + "type": stream_desc, |
| 188 | + "app_name": app_name, |
| 189 | + "success": result is not None, |
| 190 | + "action": action |
| 191 | + } |
| 192 | + |
| 193 | + if result is not None: |
| 194 | + success_count += 1 |
| 195 | + |
| 196 | + results.append(stream_result) |
| 197 | + |
| 198 | + return { |
| 199 | + "success": success_count > 0, |
| 200 | + "message": f"Successfully {action} {success_count}/{len(discord_streams)} streams", |
| 201 | + "action": action, |
| 202 | + "streams_affected": success_count, |
| 203 | + "total_streams": len(discord_streams), |
| 204 | + "results": results |
| 205 | + } |
| 206 | + |
| 207 | + def set_mute(self, mute: bool) -> Dict: |
| 208 | + """Set mute state for all Discord streams""" |
| 209 | + discord_streams = self._find_discord_streams() |
| 210 | + |
| 211 | + if not discord_streams: |
| 212 | + return { |
| 213 | + "success": False, |
| 214 | + "message": "No Discord streams found", |
| 215 | + "streams_affected": 0 |
| 216 | + } |
| 217 | + |
| 218 | + target_state = "1" if mute else "0" # 1 = mute, 0 = unmute |
| 219 | + action = "muted" if mute else "unmuted" |
| 220 | + |
| 221 | + results = [] |
| 222 | + success_count = 0 |
| 223 | + |
| 224 | + for stream in discord_streams: |
| 225 | + stream_id = stream.get("id") |
| 226 | + stream_type = stream.get("type") |
| 227 | + app_name = stream.get("app_name", "Unknown") |
| 228 | + |
| 229 | + if not stream_id or not stream_type: |
| 230 | + continue |
| 231 | + |
| 232 | + if stream_type == "sink-input": |
| 233 | + cmd = ["pactl", "set-sink-input-mute", stream_id, target_state] |
| 234 | + stream_desc = "playback" |
| 235 | + elif stream_type == "source-output": |
| 236 | + cmd = ["pactl", "set-source-output-mute", stream_id, target_state] |
| 237 | + stream_desc = "recording" |
| 238 | + else: |
| 239 | + continue |
| 240 | + |
| 241 | + result = self._run_command(cmd) |
| 242 | + stream_result = { |
| 243 | + "id": stream_id, |
| 244 | + "type": stream_desc, |
| 245 | + "app_name": app_name, |
| 246 | + "success": result is not None, |
| 247 | + "action": action |
| 248 | + } |
| 249 | + |
| 250 | + if result is not None: |
| 251 | + success_count += 1 |
| 252 | + |
| 253 | + results.append(stream_result) |
| 254 | + |
| 255 | + return { |
| 256 | + "success": success_count > 0, |
| 257 | + "message": f"Successfully {action} {success_count}/{len(discord_streams)} streams", |
| 258 | + "action": action, |
| 259 | + "streams_affected": success_count, |
| 260 | + "total_streams": len(discord_streams), |
| 261 | + "results": results |
| 262 | + } |
0 commit comments