forked from MarechJ/hll_rcon_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
465 lines (396 loc) · 12.6 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
import inspect
import logging
from functools import wraps
import os
from subprocess import run, PIPE
from dataclasses import asdict
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from rcon.config import get_config
from rcon.utils import MapsHistory
from rcon.recorded_commands import RecordedRcon
from rcon.commands import CommandFailedError
from rcon.steam_utils import get_steam_profile
from rcon.settings import SERVER_INFO
from rcon.player_history import (
get_players_by_appearance,
add_player_to_blacklist,
remove_player_from_blacklist,
get_player_profile,
get_player_profile_by_id,
add_flag_to_player,
remove_flag,
)
from rcon.discord import send_to_discord_audit
from rcon.game_logs import ChatLoop
from rcon.user_config import AutoBroadcasts, InvalidConfigurationError, StandardMessages
from rcon.cache_utils import RedisCached, get_redis_pool
from rcon.user_config import DiscordHookConfig
from rcon.watchlist import PlayerWatch
from .auth import login_required, api_response
from .utils import _get_data
from .multi_servers import forward_request, forward_command
logger = logging.getLogger("rconweb")
@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
@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"])
return api_response(
result=DiscordHookConfig.get_all_hook_types(),
command="get_hooks",
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):
@csrf_exempt
@login_required
@wraps(func)
def wrapper(request):
logger = logging.getLogger("rconweb")
arguments = {}
data = {}
failure = False
others = None
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)
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:
failure = True
res = None
if data.get("forward"):
try:
others = forward_request(request)
except:
logger.exception("Unexpected error while forwarding request")
# logger.debug("%s %s -> %s", func.__name__, arguments, res)
return JsonResponse(
dict(
result=res,
command=func.__name__,
arguments=data,
failed=failure,
forward_results=others,
)
)
return wrapper
ctl = RecordedRcon(SERVER_INFO)
@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",
)
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),
]
logger.info("Initializing endpoint")
# 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)))
# Warm the cache as fetching steam profile 1 by 1 takes a while
if not os.getenv("DJANGO_DEBUG", None):
try:
logger.info("Warming up the cache this may take minutes")
ctl.get_players()
logger.info("Cache warm up done")
except:
logger.exception("Failed to warm the cache")