forked from MarechJ/hll_rcon_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
661 lines (568 loc) · 18.4 KB
/
views.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
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import inspect
import logging
import os
import traceback
from functools import wraps
from subprocess import PIPE, run
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rcon.broadcast import get_votes_status
from rcon.cache_utils import RedisCached, get_redis_pool
from rcon.commands import CommandFailedError
from rcon.config import get_config
from rcon.discord import send_to_discord_audit
from rcon.gtx import GTXFtp
from rcon.player_history import (add_player_to_blacklist,
remove_player_from_blacklist)
from rcon.recorded_commands import RecordedRcon
from rcon.settings import SERVER_INFO
from rcon.user_config import (AutoBroadcasts, AutoVoteKickConfig, CameraConfig,
DiscordHookConfig, InvalidConfigurationError,
StandardMessages)
from rcon.utils import LONG_HUMAN_MAP_NAMES, MapsHistory, map_name
from rcon.watchlist import PlayerWatch
from rcon.workers import temporary_broadcast, temporary_welcome
from .auth import api_response, login_required
from .multi_servers import forward_command, forward_request
from .utils import _get_data
logger = logging.getLogger("rconweb")
ctl = RecordedRcon(SERVER_INFO)
def set_temp_msg(request, func, name):
data = _get_data(request)
failed = False
error = None
try:
func(ctl, data["msg"], data["seconds"])
except Exception as e:
failed = True
error = repr(e)
return api_response(failed=failed, error=error, result=None, command=name)
@csrf_exempt
@login_required
def set_name(request):
data = _get_data(request)
failed = False
error = None
try:
gtx = GTXFtp.from_config()
gtx.change_server_name(data["name"])
except Exception as e:
failed = True
error = repr(e)
return api_response(failed=failed, error=error, result=None, command="set_server_name")
@csrf_exempt
@login_required
def set_temp_broadcast(request):
return set_temp_msg(request, temporary_broadcast, "set_temp_broadcast")
@csrf_exempt
@login_required
def set_temp_welcome(request):
return set_temp_msg(request, temporary_welcome, "set_temp_welcome")
@csrf_exempt
def get_version(request):
res = run(["git", "describe", "--tags"], stdout=PIPE, stderr=PIPE)
return api_response(res.stdout.decode(), failed=False, command="get_version")
@csrf_exempt
def public_info(request):
status = ctl.get_status()
try:
current_map = MapsHistory()[0]
except IndexError:
logger.error("Can't get current map time, map_recorder is probably offline")
current_map = {"name": status["map"], "start": None, "end": None}
current_map = dict(
just_name=map_name(current_map["name"]),
human_name=LONG_HUMAN_MAP_NAMES.get(current_map["name"], current_map["name"]),
**current_map,
)
vote_status = get_votes_status(none_on_fail=True)
next_map = ctl.get_next_map()
return api_response(
result=dict(
current_map=current_map,
**status,
vote_status=vote_status,
next_map=next_map,
public_stats_port=os.getenv('PUBLIC_STATS_PORT', "Not defined"),
public_stats_port_https=os.getenv('PUBLIC_STATS_PORT_HTTPS', "Not defined")
),
failed=False,
command="public_info",
)
@csrf_exempt
@login_required
def get_hooks(request):
return api_response(
result=DiscordHookConfig.get_all_hook_types(as_dict=True),
command="get_hooks",
failed=False,
)
@csrf_exempt
@login_required
def set_hooks(request):
data = _get_data(request)
hook_config = DiscordHookConfig(for_type=data["name"])
hook_config.set_hooks(data["hooks"])
audit("set_hooks", request, data)
return api_response(
result=DiscordHookConfig.get_all_hook_types(),
command="get_hooks",
failed=False,
)
@csrf_exempt
@login_required
def get_camera_config(request):
config = CameraConfig()
return api_response(
result={
"broadcast": config.is_broadcast(),
"welcome": config.is_welcome(),
},
command="get_camera_config",
failed=False,
)
@csrf_exempt
@login_required
def get_votekick_autotoggle_config(request):
config = AutoVoteKickConfig()
return api_response(
result={
"min_ingame_mods": config.get_min_ingame_mods(),
"min_online_mods": config.get_min_online_mods(),
"is_enabled": config.is_enabled(),
"condition_type": config.get_condition_type(),
},
command="get_votekick_autotoggle_config",
failed=False,
)
@csrf_exempt
@login_required
def set_votekick_autotoggle_config(request):
config = AutoVoteKickConfig()
data = _get_data(request)
funcs = {
"min_ingame_mods": config.set_min_ingame_mods,
"min_online_mods": config.set_min_online_mods,
"is_enabled": config.set_is_enabled,
"condition_type": config.set_condition_type,
}
for k, v in data.items():
try:
funcs[k](v)
except KeyError:
return api_response(
error="{} invalid key".format(k),
command="set_votekick_autotoggle_config",
)
audit("set_votekick_autotoggle_config", request, {k: v})
return api_response(
command="set_votekick_autotoggle_config",
failed=False,
)
@csrf_exempt
@login_required
def set_camera_config(request):
config = CameraConfig()
data = _get_data(request)
funcs = {
"broadcast": config.set_broadcast,
"welcome": config.set_welcome,
}
for k, v in data.items():
if not isinstance(v, bool):
return api_response(
error="Values must be boolean", command="set_camera_config"
)
try:
funcs[k](v)
except KeyError:
return api_response(
error="{} invalid key".format(k), command="set_camera_config"
)
audit("set_camera_config", request, {k: v})
return api_response(
result={
"broadcast": config.is_broadcast(),
"welcome": config.is_welcome(),
},
command="set_camera_config",
failed=False,
)
def _do_watch(request, add: bool):
data = _get_data(request)
error = None
failed = True
result = None
try:
watcher = PlayerWatch(data["steam_id_64"])
if add:
params = dict(
reason=data["reason"],
comment=data.get("comment"),
player_name=data.get("player_name"),
)
result = watcher.watch(**params)
audit("do_watch_player", request, params)
else:
result = watcher.unwatch()
audit("do_unwatch_player", request, dict(steam_id_64=data["steam_id_64"]))
failed = False
except KeyError as e:
error = f"No {e.args} provided"
except CommandFailedError as e:
error = e.args[0]
return api_response(
result=result,
arguments=data,
error=error,
command="do_watch_player",
failed=failed,
)
@csrf_exempt
@login_required
def do_watch_player(request):
return _do_watch(request, add=True)
@csrf_exempt
@login_required
def do_unwatch_player(request):
return _do_watch(request, add=False)
@csrf_exempt
@login_required
def clear_cache(request):
res = RedisCached.clear_all_caches(get_redis_pool())
audit("clear_cache", request, {})
return JsonResponse(
{
"result": res,
"command": "clear_cache",
"arguments": None,
"failed": res is None,
}
)
@csrf_exempt
@login_required
def get_auto_broadcasts_config(request):
failed = False
config = None
try:
broadcasts = AutoBroadcasts()
config = {
"messages": ["{} {}".format(m[0], m[1]) for m in broadcasts.get_messages()],
"randomized": broadcasts.get_randomize(),
"enabled": broadcasts.get_enabled(),
}
except:
logger.exception("Error fetch broadcasts config")
failed = True
return JsonResponse(
{
"result": config,
"command": "get_auto_broadcasts_config",
"arguments": None,
"failed": failed,
}
)
@csrf_exempt
@login_required
def set_auto_broadcasts_config(request):
failed = False
res = None
data = _get_data(request)
broadcasts = AutoBroadcasts()
config_keys = {
"messages": broadcasts.set_messages,
"randomized": broadcasts.set_randomize,
"enabled": broadcasts.set_enabled,
}
try:
for k, v in data.items():
if k in config_keys:
config_keys[k](v)
audit(set_auto_broadcasts_config.__name__, request, {k: v})
except InvalidConfigurationError as e:
failed = True
res = str(e)
return JsonResponse(
{
"result": res,
"command": "set_auto_broadcasts_config",
"arguments": data,
"failed": failed,
}
)
@csrf_exempt
@login_required
def get_standard_messages(request):
failed = False
data = _get_data(request)
try:
msgs = StandardMessages()
res = msgs.get_messages(data["message_type"])
except CommandFailedError as e:
failed = True
res = repr(e)
except:
logger.exception("Error fetching standard messages config")
failed = True
res = "Error setting standard messages config"
return JsonResponse(
{
"result": res,
"command": "get_standard_messages",
"arguments": data,
"failed": failed,
}
)
@csrf_exempt
@login_required
def set_standard_messages(request):
failed = False
data = _get_data(request)
try:
msgs = StandardMessages()
res = msgs.set_messages(data["message_type"], data["messages"])
send_to_discord_audit("set_standard_messages", request.user.username)
except CommandFailedError as e:
failed = True
res = repr(e)
except:
logger.exception("Error setting standard messages config")
failed = True
res = "Error setting standard messages config"
return JsonResponse(
{
"result": res,
"command": "get_standard_messages",
"arguments": data,
"failed": failed,
}
)
@csrf_exempt
@login_required
def blacklist_player(request):
data = _get_data(request)
res = {}
try:
name = data["name"] if "name" in data else None
# Using the the perma ban by steamid actually sucks because the player won't see the reason for his ban
# Also it could seem interesting to use it, so that if the player is on the server at the time of the
# Blacklist he'd be banned immediately, however that's not the case, which is apparently a bug
# ctl.do_perma_ban(
# steam_id_64=data["steam_id_64"], reason=data["reason"], by=name
# )
add_player_to_blacklist(
data["steam_id_64"], data["reason"], name, request.user.username
)
audit("Blacklist", request, data)
failed = False
except:
logger.exception("Unable to blacklist player")
failed = True
return JsonResponse(
{
"result": res,
"command": "blacklist_player",
"arguments": data,
"failed": failed,
}
)
@csrf_exempt
@login_required
def unblacklist_player(request):
data = _get_data(request)
res = {}
try:
remove_player_from_blacklist(data["steam_id_64"])
audit("unblacklist", request, data)
if get_config()["BANS"]["unblacklist_does_unban"]:
ctl.do_unban(data["steam_id_64"]) # also remove bans
if get_config()["MULTI_SERVERS"]["broadcast_unbans"]:
forward_command(
"/api/do_unban",
json=data,
sessionid=request.COOKIES.get("sessionid"),
)
failed = False
except:
logger.exception("Unable to unblacklist player")
failed = True
return JsonResponse(
{
"result": res,
"command": "unblacklist_player",
"arguments": data,
"failed": failed,
}
)
@csrf_exempt
@login_required
def unban(request):
data = _get_data(request)
res = {}
results = None
try:
ctl.do_unban(data["steam_id_64"]) # also remove bans
audit("unban", request, data)
if get_config()["MULTI_SERVERS"]["broadcast_unbans"]:
results = forward_command(
"/api/do_unban", json=data, sessionid=request.COOKIES.get("sessionid")
)
if get_config()["BANS"]["unban_does_unblacklist"]:
try:
remove_player_from_blacklist(data["steam_id_64"])
except CommandFailedError:
logger.warning("Player %s was not on blacklist", data["steam_id_64"])
failed = False
except:
logger.exception("Unable to unban player")
failed = True
return JsonResponse(
{
"result": res,
"command": "unban_player",
"arguments": data,
"failed": failed,
"forward_results": results,
}
)
def audit(func_name, request, arguments):
dont_audit = ["get_"]
try:
if any(func_name.startswith(s) for s in dont_audit):
return
args = dict(**arguments)
try:
del args["by"]
except KeyError:
pass
arguments = " ".join([f"{k}: `{v}`" for k, v in args.items()])
send_to_discord_audit(
"`{}`: {}".format(func_name, arguments), request.user.username
)
except:
logger.exception("Can't send audit log")
# This is were all the RCON commands are turned into HTTP endpoints
def wrap_method(func, parameters, command_name):
@csrf_exempt
@login_required
@wraps(func)
def wrapper(request):
logger = logging.getLogger("rconweb")
arguments = {}
data = {}
failure = False
others = None
error = ""
data = _get_data(request)
for pname, param in parameters.items():
if pname == "by":
arguments[pname] = request.user.username
elif param.default != inspect._empty:
arguments[pname] = data.get(pname, param.default)
else:
try:
arguments[pname] = data[pname]
except KeyError:
# TODO raise 400
raise
try:
logger.debug("%s %s", func.__name__, arguments)
res = func(**arguments)
audit(func.__name__, request, arguments)
except CommandFailedError as e:
failure = True
error = e.args[0] if e.args else None
res = None
response = JsonResponse(
dict(
result=res,
command=func.__name__,
arguments=data,
failed=failure,
error=error,
forward_results=others,
)
)
if data.get("forward"):
if command_name == "do_temp_ban" and not get_config().get(
"MULTI_SERVERS", {}
).get("broadcast_temp_bans", True):
logger.debug("Not broadcasting temp ban due to settings")
return response
try:
others = forward_request(request)
except:
logger.exception("Unexpected error while forwarding request")
# logger.debug("%s %s -> %s", func.__name__, arguments, res)
return response
return wrapper
@login_required
@csrf_exempt
def get_connection_info(request):
return api_response(
{
"name": ctl.get_name(),
"port": os.getenv("RCONWEB_PORT"),
"link": os.getenv("RCONWEB_SERVER_URL"),
},
failed=False,
command="get_connection_info",
)
@csrf_exempt
@login_required
def run_raw_command(request):
data = _get_data(request)
command = data.get('command')
if not command:
res = "Parameter \"command\" must not be none"
else:
try:
res = ctl._request(command, can_fail=True, log_info=True)
except CommandFailedError:
res = "Command returned FAIL"
except:
logging.exception("Internal error when executing raw command")
res = "Internal error!\n\n" + traceback.format_exc()
return HttpResponse(res, content_type="text/plain")
PREFIXES_TO_EXPOSE = ["get_", "set_", "do_"]
commands = [
("blacklist_player", blacklist_player),
("unblacklist_player", unblacklist_player),
("get_auto_broadcasts_config", get_auto_broadcasts_config),
("set_auto_broadcasts_config", set_auto_broadcasts_config),
("clear_cache", clear_cache),
("get_standard_messages", get_standard_messages),
("set_standard_messages", set_standard_messages),
("get_version", get_version),
("get_connection_info", get_connection_info),
("unban", unban),
("get_hooks", get_hooks),
("set_hooks", set_hooks),
("do_unwatch_player", do_unwatch_player),
("do_watch_player", do_watch_player),
("public_info", public_info),
("set_camera_config", set_camera_config),
("get_camera_config", get_camera_config),
("set_votekick_autotoggle_config", set_votekick_autotoggle_config),
("get_votekick_autotoggle_config", get_votekick_autotoggle_config),
("set_name", set_name),
("run_raw_command", run_raw_command),
]
logger.info("Initializing endpoint")
try:
# Dynamically register all the methods from ServerCtl
for name, func in inspect.getmembers(ctl):
if not any(name.startswith(prefix) for prefix in PREFIXES_TO_EXPOSE):
continue
commands.append((name, wrap_method(func, inspect.signature(func).parameters, name)))
except:
logger.exception("Failed to initialized endpoints - Most likely bad configuration")
raise
# Warm the cache as fetching steam profile 1 by 1 takes a while
if not os.getenv("DJANGO_DEBUG", None):
try:
logger.warning("Warming up the cache this may take minutes")
ctl.get_players()
logger.warning("Cache warm up done")
except:
logger.exception("Failed to warm the cache")