- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRLStatsAPIServer.py
More file actions
Latest commit
611 lines (521 loc) · 23.5 KB
/
Copy pathRLStatsAPIServer.py
File metadata and controls
611 lines (521 loc) · 23.5 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#!/usr/bin/env python3
"""
Rocket League PsyNet API Client with HTTP Stats Server
"""
importasyncio
importos
importre
importargparse
importjson
importrequests
importuuid
importwebbrowser
importbase64
importtkinterastk
fromtkinterimportsimpledialog, messagebox
fromhttp.serverimportBaseHTTPRequestHandler, HTTPServer
fromurllib.parseimporturlparse
importthreading
importtime
importssl
importlogging
fromtypingimportOptional, Dict, Any
frompathlibimportPath
fromrlapiimportPsyNet, Platform, PsyNetError
fromrlapi.authimportauth_player
fromrlapi.clientimportRocketLeagueClient
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger=logging.getLogger(__name__)
# Configuration constants
CONFIG= {
'envfile': '.epicenv', # Where to store your personal Epic Launcher API creds
'epic_api_url': 'https://account-public-service-prod.ak.epicgames.com/account/api',
'epic_dev_api_url': 'https://api.epicgames.dev',
'client_id': '34a02cf8f4414e29b15921876da36f9a', # Epic Launcher ID
'client_secret': 'daafbccc737745039dffe53d94fc76cf', # Epic Launcher secret (this is a publicly known secret)
'dev_client_id': 'xyza7891p5D7s9R6Gm6moTHWGloerp7B', # Epic Dev ID
'dev_client_secret': 'Knh18du4NVlFs+3uQ+ZPpDCVto0WYf4yXP8+OcwVt1o', # Epic Dev secret (this is a publicly known secret)
'deployment_id': 'da32ae9c12ae40e8a112c52e1f17f3ba',
'proxy': {}, # {'http': '127.0.0.1:8888', 'https': '127.0.0.1:8888'}
'verify_ssl': True,
'server_port': 9280,
'player_name': '', # You can leave this blank, it doesn't actually get verified
'version': '260506.26700.517210'# Placeholder - we'll dynamically figure out the version from RL's log file, or from a GitHub repo
}
classEpicAuthManager:
"""Handles Epic Games authentication flow"""
def__init__(self, envfile: str, proxy: Dict=None, verify: bool=True):
self.envfile=Path(envfile)
self.proxy=proxyor {}
self.verify=verify
self.headers= {
'Accept': '*/*',
'Accept-Encoding': 'deflate, gzip',
'User-Agent': 'UELauncher/16.12.1-36115220+++Portal+Release-Live Windows/10.0.22631.1.768.64bit',
}
def_make_basic_auth(self, client_id: str, client_secret: str) ->str:
"""Create Basic Auth header value with base64-encoded credentials"""
credentials=f"{client_id}:{client_secret}"
encoded=base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
returnf'basic {encoded}'
def_generate_correlation_id(self) ->str:
returnf'UE4-5dea7166457d308530e85a9b3333ff78-C9AD1AA540580FDB3CCEA5B0A22B3218-{uuid.uuid4().hex.upper()}'
def_api_request(self, method: str, path: str, data: str='',
auth: str='', base_url: str=None) ->requests.Response:
"""Make authenticated API request to Epic services"""
url= (base_urlorCONFIG['epic_api_url']) +path
headers=self.headers.copy()
headers['X-Epic-Correlation-ID'] =self._generate_correlation_id()
ifauth:
headers['Authorization'] =auth
ifdata:
headers['Content-Type'] ='application/x-www-form-urlencoded'
kwargs= {'headers': headers, 'proxies': self.proxy, 'verify': self.verify}
ifdata:
kwargs['data'] =data
ifmethod.lower() =='post':
returnrequests.post(url, **kwargs)
returnrequests.get(url, **kwargs)
defload_credentials(self) ->Dict[str, str]:
"""Load or initialize credentials from env file"""
ifself.envfile.exists():
try:
returnjson.loads(self.envfile.read_text().strip())
exceptjson.JSONDecodeError:
logger.warning(f"Invalid JSON in {self.envfile}, starting fresh")
return {}
defsave_credentials(self, creds: Dict[str, str]):
"""Save credentials to env file"""
self.envfile.write_text(json.dumps(creds, indent=2))
defget_authorization_code(self) ->str:
"""Open browser for user to login and retrieve auth code"""
redirect_url= (
f'https://www.epicgames.com/id/login?'
f'redirectUrl=https%3A//www.epicgames.com/id/api/redirect'
f'%3FclientId%3D{CONFIG["client_id"]}'
f'%26responseType%3Dcode%26prompt%3Dlogin%26'
)
webbrowser.open(redirect_url, new=0, autoraise=True)
# Create hidden Tk window for dialog
root=tk.Tk()
root.withdraw()
root.attributes('-topmost', True)
code=simpledialog.askstring(
"Authorization Code",
"Please login in your browser, then paste the authorization code:",
parent=root
)
root.destroy()
return (codeor'').strip()
asyncdefauthenticate(self) ->tuple[str, str, str]:
"""
Complete authentication flow.
Returns: (access_token, refresh_token, account_id)
"""
creds=self.load_credentials()
# Get auth code if needed
ifnotcreds.get('refreshToken') andnotcreds.get('authCode'):
logger.warning("No credentials found. Please authorize...")
messagebox.showwarning(
'Authorization Required',
f'Opening browser to login. Please copy the authorization code.'
)
code=self.get_authorization_code()
iflen(code) !=32:
raiseValueError("Invalid authorization code (must be 32 characters)")
creds['authCode'] =code
self.save_credentials(creds)
# Use Epic Games client credentials for the initial requests
client_auth=self._make_basic_auth(
CONFIG['client_id'],
CONFIG['client_secret']
)
# Exchange auth code for refresh token if needed
refresh_token=creds.get('refreshToken')
ifnotrefresh_tokenandcreds.get('authCode'):
logger.info("Exchanging auth code for refresh token...")
resp=self._api_request(
'post', '/oauth/token',
auth=client_auth,
data=f'grant_type=authorization_code&code={creds["authCode"]}'
)
resp.raise_for_status()
refresh_token=resp.json()['refresh_token']
# Get eg1 access token
logger.info("Obtaining eg1 access token...")
resp=self._api_request(
'post', '/oauth/token',
auth=client_auth,
data=f'grant_type=refresh_token&refresh_token={refresh_token}&token_type=eg1'
)
resp.raise_for_status()
token_data=resp.json()
if'errorMessage'intoken_data:
raiseRuntimeError(f"{token_data['errorCode']}: {token_data['errorMessage']}")
access_token=token_data['access_token']
refresh_token=token_data['refresh_token']
account_id=token_data['account_id']
# Update and save credentials
creds.update({
'authCode': '',
'refreshToken': refresh_token,
'accountId': account_id
})
self.save_credentials(creds)
# Get launcher exchange code
logger.info("Getting launcher exchange code...")
resp=self._api_request(
'get', '/oauth/exchange',
auth=f'bearer {access_token}'
)
resp.raise_for_status()
exchange_data=resp.json()
if'errorMessage'inexchange_data:
raiseRuntimeError(f"{exchange_data['errorCode']}: {exchange_data['errorMessage']}")
# Get dev API access token
logger.info("Obtaining dev API access token...")
dev_basic_auth=self._make_basic_auth(
CONFIG['dev_client_id'],
CONFIG['dev_client_secret']
)
resp=self._api_request(
'post', '/epic/oauth/v1/token',
data=(f'grant_type=exchange_code&deployment_id={CONFIG["deployment_id"]}'
f'&exchange_code={exchange_data["code"]}'),
auth=dev_basic_auth,
base_url=CONFIG['epic_dev_api_url']
)
resp.raise_for_status()
dev_tokens=resp.json()
if'errorMessage'indev_tokens:
raiseRuntimeError(f"{dev_tokens['errorCode']}: {dev_tokens['errorMessage']}")
# Save dev tokens
creds.update({
'accessTokenDev': dev_tokens['access_token'],
'refreshTokenDev': dev_tokens['refresh_token'],
'accessTokenDevExpiry': dev_tokens['expires_at']
})
self.save_credentials(creds)
returndev_tokens['access_token'], refresh_token, account_id
classRocketLeagueStatsServer:
"""Main application class managing RL client and HTTP server"""
def__init__(self, envfile: str, port: int=9280):
self.envfile=envfile
self.port=port
self.client: Optional[RocketLeagueClient] =None
self.rpc=None
self.loop: Optional[asyncio.AbstractEventLoop] =None
self._reauth_lock=asyncio.Lock() # Prevent concurrent reauth attempts
self._last_reauth_attempt=0# Timestamp for rate limiting
self._reauth_cooldown=30# Seconds between reauth attempts
self.auth_manager=EpicAuthManager(
envfile,
proxy=CONFIG['proxy'],
verify=CONFIG['verify_ssl']
)
asyncdefinitialize_client(self) ->bool:
"""Initialize the Rocket League websocket client"""
access_token, _, account_id=awaitself.auth_manager.authenticate()
# Try to get the latest version from GitHub
version=self._get_latest_version()
# Get build ID from version string (wide-string -> CRC-32/BZIP2 -> convert to signed int)
build_id=self._crc32_bzip2_utf16le(version)
build_id=build_idifbuild_id< (1<<31) elsebuild_id- (1<<32)
psy_net=PsyNet()
try:
self.rpc=awaitauth_player(
psy_net,
access_token,
account_id,
CONFIG['player_name'],
str(build_id),
CONFIG['version']
)
exceptPsyNetErrorase:
print(f"Exception: {e}")
returnFalse
logger.info(f"Local Player ID: {self.rpc.local_player_id}")
# Convert to RocketLeagueClient
self.client=RocketLeagueClient(
ws_conn=self.rpc.ws_conn,
local_player_id=self.rpc.local_player_id,
psy_token=self.rpc.psy_token,
session_id=self.rpc.session_id,
request_id=self.rpc.request_id,
logger=self.rpc.logger,
)
# Copy internal state
forattrin ['_lock', '_pending_reqs', '_pong_event', '_event_queue',
'_connected', '_ping_task', '_read_task']:
setattr(self.client, attr, getattr(self.rpc, attr))
returnTrue
asyncdef_reauthenticate_async(self) ->bool:
"""
Re-run the full authentication flow and update client references.
Must be called from within the event loop.
Returns True on success, False on failure.
"""
asyncwithself._reauth_lock:
# Rate limit reauth attempts
now=time.time()
ifnow-self._last_reauth_attempt<self._reauth_cooldown:
logger.warning(f"Reauth attempt rate-limited (cooldown: {self._reauth_cooldown}s)")
returnFalse
self._last_reauth_attempt=now
try:
logger.info("Starting reauthentication flow...")
# Re-authenticate with Epic and get new dev access token
access_token, _, account_id=awaitself.auth_manager.authenticate()
# Try to get the latest version from GitHub
version=self._get_latest_version()
# Get build ID from version string (wide-string -> CRC-32/BZIP2 -> convert to signed int)
build_id=self._crc32_bzip2_utf16le(version)
build_id=build_idifbuild_id< (1<<31) elsebuild_id- (1<<32)
psy_net=PsyNet()
new_rpc=awaitauth_player(
psy_net,
access_token,
account_id,
CONFIG['player_name'],
str(build_id),
CONFIG['version']
)
# Create new client instance
new_client=RocketLeagueClient(
ws_conn=new_rpc.ws_conn,
local_player_id=new_rpc.local_player_id,
psy_token=new_rpc.psy_token,
session_id=new_rpc.session_id,
request_id=new_rpc.request_id,
logger=new_rpc.logger,
)
# Copy internal state
forattrin ['_lock', '_pending_reqs', '_pong_event', '_event_queue',
'_connected', '_ping_task', '_read_task']:
setattr(new_client, attr, getattr(new_rpc, attr))
# Gracefully close old client if it exists
ifself.client:
try:
awaitself.client.close()
exceptExceptionase:
logger.warning(f"Error closing old client: {e}")
# Atomically swap references
self.rpc=new_rpc
self.client=new_client
logger.info("Reauthentication successful")
returnTrue
exceptExceptionase:
logger.exception(f"Reauthentication failed: {e}")
returnFalse
defreauthenticate(self) ->bool:
"""
Synchronous wrapper to trigger reauthentication from HTTP handler.
Returns True on success, False on failure.
"""
ifnotself.loopornotself.loop.is_running():
logger.error("Cannot reauthenticate: event loop not running")
returnFalse
# Run async reauth in the event loop and wait for result
future=asyncio.run_coroutine_threadsafe(
self._reauthenticate_async(),
self.loop
)
returnfuture.result(timeout=60) # 60s timeout for reauth flow
def_crc32_bzip2_utf16le(self, s: str) ->int:
crc=0xFFFFFFFF
table= [(i<<24) &0xFFFFFFFFforiinrange(256)]
foriinrange(256):
for_inrange(8):
table[i] = (table[i] <<1) ^0x04C11DB7iftable[i] &0x80000000elsetable[i] <<1
table[i] &=0xFFFFFFFF
forbyteins.encode('utf-16-le'):
crc= ((crc<<8) &0xFFFFFFFF) ^table[((crc>>24) ^byte) &0xFF]
returncrc^0xFFFFFFFF
def_get_latest_version(self) ->str:
"""Get the latest game version - first try reading from the RL log file, next try from a GitHub repository, or lastly fallback to the statically defined version"""
try:
withopen(os.getenv('USERPROFILE') +'\\Documents\\My Games\\Rocket League\\TAGame\\Logs\\Launch.log', 'rb') asf:
content=f.read().decode('latin-1')
match=re.findall(r'GPsyonixBuildID [0-9.]+', content)[0]
version=match.split(' ')[1]
returnversion
exceptExceptionase:
print(e)
pass
try:
resp=requests.get('https://raw.githubusercontent.com/smallest-cock/RLSDK/refs/heads/main/RLSDK/GameDefines.cpp')
version=resp.content.decode().split('Psyonix Build ID: ')[1].split('\n')[0].strip()
returnversion
except:
pass
returnCONFIG['version']
def_run_async_coroutine(self, coro):
"""Safely run an async coroutine from sync context"""
ifnotself.loopornotself.loop.is_running():
raiseRuntimeError("Event loop not running")
returnasyncio.run_coroutine_threadsafe(coro, self.loop).result()
defget_player_stats(self, player_id: str, timeout: float=10.0) ->Dict[str, Any]:
"""
Get player stats with optional automatic retry after reauth.
"""
ifnotself.client:
return {'error': 'Client not initialized'}
try:
result=self._run_async_coroutine(
self.client.get_player_skill(player_id, timeout=timeout)
)
returnresult
exceptExceptionase:
logger.error(f"Error fetching stats: {e}")
return {'error': str(e)}
defstart_http_server(self):
"""Start the HTTP server in a separate thread"""
server=HTTPServer(('', self.port), StatsRequestHandler)
server.app=self# ← Attach app reference here
logger.info(f"Starting HTTP server on port {self.port}")
defserve():
try:
server.serve_forever()
exceptKeyboardInterrupt:
pass
finally:
server.server_close()
thread=threading.Thread(target=serve, daemon=True)
thread.start()
returnserver
asyncdefrun(self):
"""Main entry point"""
initialized=awaitself.initialize_client()
ifinitializedisFalse:
return
self.loop=asyncio.get_running_loop()
# Start HTTP server
self.start_http_server()
# Keep alive
try:
whileTrue:
awaitasyncio.sleep(60)
# Optional: add health checks or token refresh logic here
exceptasyncio.CancelledError:
logger.info("Shutting down...")
ifself.client:
awaitself.client.close()
classStatsRequestHandler(BaseHTTPRequestHandler):
"""HTTP request handler for stats queries"""
deflog_message(self, format, *args):
logger.info(f"{self.address_string()} - {format%args}")
@property
defapp(self) ->RocketLeagueStatsServer:
"""Access the parent app instance via the server reference"""
returnself.server.app
defdo_POST(self):
# Parse path to ignore query strings
parsed_path=urlparse(self.path).path
ifparsed_path!='/stats':
self._send_error(404, "Not found. Use POST /stats")
return
# Read and parse JSON body
content_length=int(self.headers.get('Content-Length', 0))
ifcontent_length==0:
self._send_error(400, "Missing request body. Send JSON with 'id' field.")
return
try:
raw_body=self.rfile.read(content_length)
data=json.loads(raw_body.decode('utf-8'))
exceptjson.JSONDecodeErrorase:
self._send_error(400, f"Invalid JSON in request body: {str(e)}")
return
exceptExceptionase:
self._send_error(400, f"Failed to read request body: {str(e)}")
return
# Extract player ID
player_id=data.get('id')
ifnotplayer_id:
self._send_error(400, "Missing required 'id' field in JSON body")
return
# Fetch stats
stats=self.app.get_player_stats(str(player_id))
# Check for errors that warrant reauthentication
error_msg=stats.get('error', '') ifisinstance(stats, dict) else''
should_reauth=any(keywordinerror_msg.lower() forkeywordin [
'duplicatelogin', 'normal closure', 'perconmaintenance', 'no close frame'
])
try:
ifshould_reauth:
logger.warning(f"PsyNet API error detected: '{error_msg}'. Attempting reauthentication...")
ifself.app.reauthenticate():
logger.info("Reauth succeeded, retrying request...")
# Retry the request once after successful reauth
stats=self.app.get_player_stats(str(player_id))
else:
logger.error("Reauthentication failed, returning original error")
# Optionally add a hint to the error response
ifisinstance(stats, dict):
stats['reauth_hint'] ='Session may have expired. Try again in a moment.'
response_body=json.dumps(stats, indent=2).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', len(response_body))
self.send_header('Connection', 'close')
self.end_headers()
self.wfile.write(response_body)
self.wfile.flush()
exceptExceptionase:
logger.exception("Error handling /stats request")
self._send_error(500, f"Failed to fetch player stats: {str(e)}")
defdo_GET(self):
"""Keep a simple health check endpoint for monitoring"""
parsed_path=urlparse(self.path).path
ifparsed_path=='/health':
status= {
'server': 'ok',
'client_connected': bool(self.app.clientandself.app.client._connected),
'player_id': self.app.rpc.local_player_idifself.app.rpcelseNone
}
response_body=json.dumps(status).encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', len(response_body))
self.send_header('Connection', 'close')
self.end_headers()
self.wfile.write(response_body)
else:
self._send_error(404, "Not found. Use POST /stats with JSON body containing 'id'.")
def_send_error(self, code: int, message: str):
"""Helper to send consistent JSON error responses"""
response_body=json.dumps({'error': message}).encode()
self.send_response(code)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', len(response_body))
self.send_header('Connection', 'close')
self.end_headers()
self.wfile.write(response_body)
self.wfile.flush()
defmain():
parser=argparse.ArgumentParser(description='Rocket League Stats Server')
parser.add_argument('-f', '--envfile', type=str, default=CONFIG['envfile'],
help='Credential environment file')
parser.add_argument('-p', '--port', type=int, default=CONFIG['server_port'],
help='HTTP server port')
args=parser.parse_args()
# Suppress tkinter console on Windows
"""
if os.name == 'nt':
import ctypes
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
"""
app=RocketLeagueStatsServer(args.envfile, args.port)
try:
asyncio.run(app.run())
exceptKeyboardInterrupt:
logger.info("Interrupted by user")
exceptExceptionase:
logger.exception(f"Fatal error: {e}")
ifos.name=='nt':
messagebox.showerror("Error", str(e))
if__name__=='__main__':
main()