-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheml_client.py
More file actions
245 lines (191 loc) · 7.46 KB
/
Copy patheml_client.py
File metadata and controls
245 lines (191 loc) · 7.46 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
"""
EML Caster RPC Client Library
Direct callable functions for Mel production tool integration.
Import this module and call functions directly.
Setup:
import eml_client
eml_client.configure("http://localhost:8080", "your-api-key")
Usage:
# Using simple numeric ID
eml_client.create_channel(42)
eml_client.set_stream_channel(42, channel=1)
eml_client.crew_ready(42)
eml_client.go_live(42)
# Using full match key from button ID
eml_client.create_channel("nocturne_Valiants_03272026_1030_PM")
# Get match info
match = eml_client.get_match(42)
print(match["team_a"], "vs", match["team_b"])
"""
import json
import os
from urllib.request import Request, urlopen # AGENTS-AUDIT: urllib call path should be httpx.
from urllib.error import HTTPError, URLError
from typing import Any # AGENTS-AUDIT: Any is imported without an inline reason and is unused.
# === MAINTAINABILITY / AGENTS AUDIT ANNOTATIONS ===
# AGENTS violation: imports Any but does not justify usage with `# reason:`.
# AGENTS violation: urllib usage instead of httpx.
# AGENTS violation: several parameters use `= None` with non-optional annotations (e.g. url: str = None).
# AGENTS violation: broad data shape typing (`dict`, `list[dict]`) instead of TypedDict / dataclass models.
# Code smell: module-level mutable global config dictionary introduces hidden shared state.
# Code smell: error mapping wraps exceptions without `raise ... from ...`, reducing traceback fidelity.
# Code smell: synchronous network I/O API design can block callers and makes async integration harder.
# AUDIT COUNTS: format gate failed for this file; ruff findings=1; pyright findings=4.
# AUDIT COUNTS: source scan found future_imports=0, print_calls=1, untyped_defs=1, dict_shapes=6.
# AUDIT SCOPE: every generic dict-shaped boundary in this file is part of the TypedDict/dataclass violation class.
# Module-level configuration
_config = {
"url": os.environ.get("EML_RPC_URL", "http://localhost:8080"),
"api_key": os.environ.get("EML_RPC_API_KEY", ""),
}
class EMLError(Exception):
"""Error from EML Caster API."""
pass
def configure(url: str = None, api_key: str = None): # AGENTS-AUDIT: non-optional str defaults to None and lacks -> None.
"""
Configure the client.
Args:
url: Base URL of EML Caster web server (e.g., "http://localhost:8080")
api_key: RPC API key from .env
"""
if url:
_config["url"] = url.rstrip("/")
if api_key:
_config["api_key"] = api_key
def _call(endpoint: str, method: str = "POST", data: dict = None) -> dict:
"""Internal: Make an RPC call."""
if not _config["api_key"]:
raise EMLError("API key not configured. Call configure() or set EML_RPC_API_KEY env var.")
full_url = f"{_config['url']}{endpoint}"
headers = {
"X-API-Key": _config["api_key"],
"Content-Type": "application/json",
}
body = json.dumps(data).encode("utf-8") if data else None
req = Request(full_url, data=body, headers=headers, method=method)
try:
with urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode("utf-8"))
except HTTPError as e:
error_body = e.read().decode("utf-8")
try:
error_json = json.loads(error_body)
raise EMLError(error_json.get("error", error_body))
except json.JSONDecodeError:
raise EMLError(f"HTTP {e.code}: {error_body}")
except URLError as e:
raise EMLError(f"Connection error: {e.reason}")
def get_match(match_id: int | str) -> dict:
"""
Get match details.
Args:
match_id: Simple numeric ID (42) or full match key (nocturne_Valiants_03272026_1030_PM)
Returns:
dict with match info:
- id: Simple numeric ID
- match_id: Full match key
- team_a, team_b: Team names
- match_date, match_time, match_timestamp
- stream_channel: Currently selected channel (1 or 2)
- has_channel: Whether private channel exists
- casters: List of caster info
- cam_op: Cam op info or None
"""
result = _call(f"/rpc/match?id={match_id}", method="GET")
if not result.get("success"):
raise EMLError(result.get("error", "Unknown error"))
return result["match"]
def get_matches() -> list[dict]:
"""
Get all active matches.
Returns:
List of match dicts (same format as get_match)
"""
result = _call("/api/matches", method="GET")
if not result.get("success"):
raise EMLError(result.get("error", "Unknown error"))
return result["matches"]
def set_stream_channel(match_id: int | str, channel: int) -> bool:
"""
Set the stream channel for a match.
Args:
match_id: Simple numeric ID or full match key
channel: Stream channel (1 or 2)
Returns:
True on success
"""
if channel not in (1, 2):
raise EMLError("Channel must be 1 or 2")
result = _call("/rpc/set_stream_channel", data={"id": match_id, "channel": channel})
if not result.get("success"):
raise EMLError(result.get("error", "Unknown error"))
return True
def create_channel(match_id: int | str) -> int:
"""
Create the private match channel.
Args:
match_id: Simple numeric ID or full match key
Returns:
Discord channel ID
Raises:
EMLError: If channel already exists or requirements not met
"""
result = _call("/rpc/create_channel", data={"id": match_id})
if not result.get("success"):
raise EMLError(result.get("error", "Unknown error"))
return result.get("channel_id")
def crew_ready(match_id: int | str) -> bool:
"""
Send "crew ready" message to teams.
Args:
match_id: Simple numeric ID or full match key
Returns:
True on success
Raises:
EMLError: If channel doesn't exist
"""
result = _call("/rpc/crew_ready", data={"id": match_id})
if not result.get("success"):
raise EMLError(result.get("error", "Unknown error"))
return True
def go_live(match_id: int | str) -> bool:
"""
Post live announcement.
Args:
match_id: Simple numeric ID or full match key
Returns:
True on success
Raises:
EMLError: If stream channel not selected or requirements not met
"""
result = _call("/rpc/go_live", data={"id": match_id})
if not result.get("success"):
raise EMLError(result.get("error", "Unknown error"))
return True
# Convenience: Full workflow
def broadcast_workflow(match_id: int | str, stream_channel: int = 1) -> dict:
"""
Run the full broadcast workflow: set channel -> create channel -> crew ready.
Args:
match_id: Simple numeric ID or full match key
stream_channel: Stream channel to use (1 or 2)
Returns:
dict with status of each step
"""
results = {"match_id": match_id}
try:
set_stream_channel(match_id, stream_channel)
results["set_channel"] = "success"
except EMLError as e:
results["set_channel"] = str(e)
try:
channel_id = create_channel(match_id)
results["create_channel"] = channel_id
except EMLError as e:
results["create_channel"] = str(e)
try:
crew_ready(match_id)
results["crew_ready"] = "success"
except EMLError as e:
results["crew_ready"] = str(e)
return results