-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
507 lines (434 loc) · 19.7 KB
/
server.py
File metadata and controls
507 lines (434 loc) · 19.7 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
import os
import json
from flask import Flask, jsonify, request, render_template, send_from_directory
from werkzeug.utils import secure_filename
import time
import threading
import logging
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
with open("server.json", "r") as f:
config = json.load(f)
# Global in-memory state for chat and moderation
CHAT_LOG = []
MUTED_USERS = {}
BANNED_USERS = {}
KICKED_USERS = []
ACTIVE_USERS = {} # New: In-memory dictionary to track active users
# A dictionary to hold mission data, loaded from files
MISSIONS = {}
# The shared, authoritative file system
file_system = {
"root": {
"home": {
"user": {
"documents": {
"mission1.txt": "Welcome, agent. Your first mission is to gain access to the 'Alpha' server. We believe the password is 'hunter2'. You can use the 'hack' command to submit a solution.",
},
"bin": {}
}
},
"etc": {}
}
}
# --- User Data Persistence ---
def get_user_data_path(username):
# Sanitize the username to prevent path traversal
safe_username = secure_filename(username)
base_dir = os.path.abspath("cloud_saves")
path = os.path.join(base_dir, f"{safe_username}.json")
norm_path = os.path.normpath(path)
# Ensure the normalized path is within the intended directory
if not norm_path.startswith(base_dir):
raise Exception("Invalid username/path traversal detected")
return norm_path
def save_user_data(username, data):
if not os.path.exists("cloud_saves"):
os.makedirs("cloud_saves")
path = get_user_data_path(username)
try:
with open(path, "w") as f:
json.dump(data, f)
return True
except Exception as e:
print(f"Error saving user data: {e}")
return False
# Function to load mission data from the missions directory
def load_missions():
missions_dir = "missions"
if not os.path.exists(missions_dir):
print("Server: 'missions' directory not found.")
return
for filename in os.listdir(missions_dir):
if filename.endswith(".json"):
filepath = os.path.join(missions_dir, filename)
try:
with open(filepath, "r") as f:
mission_data = json.load(f)
MISSIONS[mission_data["id"]] = mission_data
print(f"Server: Loaded mission '{mission_data['title']}' from '{filename}'")
except Exception as e:
print(f"Server: Failed to load mission from '{filename}': {e}")
# --- Server-Side Command Handling ---
SERVER_COMMANDS = {
"echo": "Echoes back the arguments provided",
"chat": "Sends a message to all connected players",
"hack": "Attempts to solve a mission or hack a system",
"ls": "Lists files in the current directory",
"cd": "Changes the current directory",
"cat": "Displays the content of a file",
"missions": "Lists all available missions and their status"
}
def get_current_directory_object(location):
"""Navigates the file system tree to the player's current location."""
current_dir = file_system
for part in location:
if isinstance(current_dir, dict) and part in current_dir:
current_dir = current_dir[part]
else:
return None # Should not happen with valid locations
return current_dir
def handle_server_command(command, args, username):
# Fetch player data to get their current location
player_path = get_user_data_path(username)
if not os.path.exists(player_path):
return {"status": "error", "message": "User data not found. Please relog."}
with open(player_path, "r") as f:
player_data = json.load(f)
player_location = player_data.get("location", ["root", "home", "user"])
if username in MUTED_USERS:
return {"status": "error", "message": "You are muted and cannot use the chat command."}
if username in BANNED_USERS:
return {"status": "error", "message": "You are banned."}
if command == "echo":
return {"status": "success", "message": " ".join(args)}
if command == "chat":
message = " ".join(args)
CHAT_LOG.append({"sender": username, "message": message, "timestamp": time.time()})
return {"status": "success", "message": "Message sent."}
if command == "hack":
if len(args) < 2:
return {"status": "error", "message": "Usage: hack <mission_id> <password>"}
mission_id = args[0]
password = args[1]
mission = MISSIONS.get(mission_id)
if not mission:
return {"status": "error", "message": "Mission not found."}
# Check if the mission has already been completed
if mission.get("completed", False):
return {"status": "success", "message": "Mission already completed."}
if password == mission["solution"]:
mission["completed"] = True
return {"status": "success", "message": f"SUCCESS! Mission '{mission['title']}' completed. {mission['reward']}"}
else:
return {"status": "error", "message": "Incorrect password. Access denied."}
if command == "ls":
current_dir = get_current_directory_object(player_location)
if not current_dir or not isinstance(current_dir, dict):
return {"status": "error", "message": "Error accessing directory."}
output = "Files and folders in this directory:\n"
output += "\n".join([f" - {item}" for item in current_dir.keys()])
return {"status": "success", "message": output}
if command == "cd":
if not args:
return {"status": "error", "message": "Usage: cd <directory>"}
target = args[0]
new_location = player_location[:]
if target == "..":
if len(new_location) > 1:
new_location.pop()
else:
return {"status": "error", "message": "You can't go back any further."}
else:
current_dir = get_current_directory_object(player_location)
if current_dir is not None and target in current_dir and isinstance(current_dir[target], dict):
new_location.append(target)
else:
return {"status": "error", "message": f"cd: no such file or directory: {target}"}
player_data["location"] = new_location
save_user_data(username, player_data)
location_str = "~" if new_location == ["root", "home", "user"] else "/".join(new_location)
return {"status": "success", "message": f"Directory changed. Current location: {location_str}"}
if command == "cat":
if not args:
return {"status": "error", "message": "Usage: cat <file>"}
file_name = args[0]
current_dir = get_current_directory_object(player_location)
if current_dir is not None and file_name in current_dir and isinstance(current_dir[file_name], str):
content = current_dir[file_name]
return {"status": "success", "message": content}
else:
return {"status": "error", "message": f"cat: {file_name}: No such file or directory"}
if command == "missions":
output = "--- Missions ---\n"
if not MISSIONS:
output += "No missions available.\n"
else:
for mission_id, mission_details in MISSIONS.items():
status = "COMPLETED" if mission_details.get("completed", False) else "IN PROGRESS"
output += f"ID: {mission_id}\n"
output += f"Title: {mission_details['title']}\n"
output += f"Status: {status}\n"
output += f"Description: {mission_details['description']}\n"
output += "---\n"
return {"status": "success", "message": output.strip()}
else:
return {"status": "error", "message": f"Command '{command}' not found on server."}
# --- API Endpoints ---
@app.route("/check_command", methods=["POST"])
def check_command():
data = request.get_json()
command = data.get("command")
args = data.get("args", [])
username = data.get("username")
if username:
ACTIVE_USERS[username] = time.time() # Update last activity
if command in SERVER_COMMANDS:
response = handle_server_command(command, args, username)
return jsonify(response)
return jsonify({"status": "error", "message": f"Command '{command}' not found on server."})
@app.route("/check_username", methods=["POST"])
def check_username():
data = request.get_json()
username = data.get("username")
if os.path.exists(get_user_data_path(username)):
return jsonify({"is_available": False})
else:
return jsonify({"is_available": True})
@app.route("/register_user", methods=["POST"])
def register_user():
data = request.get_json()
username = data.get("username")
if not username:
return jsonify({"status": "error", "message": "Username not provided."}), 400
if os.path.exists(get_user_data_path(username)):
print(f"Server: HEY GUYS SOME IDIOT JUST TRIED TO MAKE {username} BUT THEY ALREADY EXIST LMAOOO")
return jsonify({"status": "error", "message": "User already exists."}), 409
initial_data = {"username": username, "progress": "fresh_start", "location": ["root", "home", "user"]}
if save_user_data(username, initial_data):
print(f"Server: [NEW USER] created: {username}")
return jsonify({"status": "success", "message": "User created."})
else:
return jsonify({"status": "error", "message": "Failed to create user."}), 500
@app.route("/reconnect", methods=["POST"])
def log_reconnection():
data = request.get_json()
username = data.get("username")
if username:
print(f"Server: User {username} reconnected.")
ACTIVE_USERS[username] = time.time() # New: Update last activity on reconnect
return jsonify({"status": "success", "message": "Reconnection logged."})
return jsonify({"status": "error", "message": "Username not provided."}), 400
@app.route("/save", methods=["POST"])
def save_progress():
data = request.get_json()
username = data.get("username")
save_data = data.get("data")
if not username:
return jsonify({"status": "error", "message": "Username not provided."}), 400
print(f"Server: Saving client {username}'s game...")
if save_user_data(username, save_data):
print("Server: Done!")
return jsonify({"status": "success", "message": "Progress saved to server."})
else:
return jsonify({"status": "error", "message": "Failed to save progress on server."}), 500
@app.route("/disconnect", methods=["POST"])
def log_disconnect():
data = request.get_json()
username = data.get("username")
if not username:
return jsonify({"status": "error", "message": "Username not provided."}), 400
# New: Remove user from active list on explicit disconnect
if username in ACTIVE_USERS:
del ACTIVE_USERS[username]
print(f"Server: Client {username} disconnected. Reason: disconnect command used")
return jsonify({"status": "success", "message": "Disconnect logged."})
@app.route("/get_chat_messages", methods=["GET"])
def get_chat_messages():
return jsonify({"messages": CHAT_LOG})
@app.route("/get_new_chat_messages", methods=["GET"])
def get_new_chat_messages():
username = request.args.get("username")
if username:
ACTIVE_USERS[username] = time.time() # New: Update last activity
last_timestamp = float(request.args.get("last_timestamp", 0))
new_messages = [msg for msg in CHAT_LOG if msg["timestamp"] > last_timestamp]
return jsonify({"messages": new_messages})
@app.route("/check_kick", methods=["POST"])
def check_kick():
data = request.get_json()
username = data.get("username")
if username:
ACTIVE_USERS[username] = time.time() # New: Update last activity
if username in KICKED_USERS:
KICKED_USERS.remove(username)
return jsonify({"should_kick": True})
return jsonify({"should_kick": False})
@app.route("/get_commands", methods=["GET"])
def get_commands():
return jsonify({"commands": SERVER_COMMANDS})
@app.route("/get_user_state", methods=["POST"])
def get_user_state():
data = request.get_json()
username = data.get("username")
if username:
ACTIVE_USERS[username] = time.time() # New: Update last activity
player_path = get_user_data_path(username)
if not os.path.exists(player_path):
return jsonify({"status": "error", "message": "User data not found."})
with open(player_path, "r") as f:
player_data = json.load(f)
location = player_data.get("location", ["root", "home", "user"])
location_str = "~" if location == ["root", "home", "user"] else "/".join(location)
return jsonify({"status": "success", "location": location_str})
# New: Admin web routes
@app.route("/admin")
def admin_panel():
return render_template("admin.html")
@app.route("/admin/chat_log")
def get_admin_chat_log():
return jsonify(CHAT_LOG)
@app.route("/admin/users")
def get_admin_users():
users = [f.replace(".json", "") for f in os.listdir("cloud_saves") if f.endswith(".json")]
active_users_list = list(ACTIVE_USERS.keys()) # New: Get a list of active users
return jsonify({
"active_users": active_users_list,
"all_users": users,
"muted": list(MUTED_USERS.keys()),
"banned": list(BANNED_USERS.keys())
})
@app.route("/admin/mute_user", methods=["POST"])
def mute_user():
data = request.get_json()
username = data.get("username")
if username:
MUTED_USERS[username] = True
return jsonify({"status": "success", "message": f"{username} muted."})
return jsonify({"status": "error", "message": "Username not provided."})
@app.route("/admin/unmute_user", methods=["POST"])
def unmute_user():
data = request.get_json()
username = data.get("username")
if username in MUTED_USERS:
del MUTED_USERS[username]
return jsonify({"status": "success", "message": f"{username} unmuted."})
return jsonify({"status": "error", "message": "Username not found."})
# New: Admin web routes for ban and kick
@app.route("/admin/ban_user", methods=["POST"])
def ban_user():
data = request.get_json()
username = data.get("username")
if username:
BANNED_USERS[username] = True
return jsonify({"status": "success", "message": f"{username} banned."})
return jsonify({"status": "error", "message": "Username not provided."})
@app.route("/admin/unban_user", methods=["POST"])
def unban_user():
data = request.get_json()
username = data.get("username")
if username in BANNED_USERS:
del BANNED_USERS[username]
return jsonify({"status": "success", "message": f"{username} unbanned."})
return jsonify({"status": "error", "message": "Username not found."})
@app.route("/admin/kick_user", methods=["POST"])
def kick_user():
data = request.get_json()
username = data.get("username")
if username:
KICKED_USERS.append(username)
return jsonify({"status": "success", "message": f"{username} marked for kick."})
return jsonify({"status": "error", "message": "Username not provided."})
def get_admin_users():
users = [f.replace(".json", "") for f in os.listdir("cloud_saves") if f.endswith(".json")]
active_users_list = list(ACTIVE_USERS.keys())
return jsonify({
"active_users": active_users_list,
"all_users": users,
"muted": list(MUTED_USERS.keys()),
"banned": list(BANNED_USERS.keys())
})
# --- Server-Side Admin Commands ---
def handle_server_input():
while True:
command = input("SERVER> ").strip().split()
if not command:
continue
cmd = command[0].lower()
args = command[1:]
if cmd == "mute" and len(args) == 1:
username = args[0]
MUTED_USERS[username] = True
print(f"SERVER: User {username} has been muted.")
elif cmd == "unmute" and len(args) == 1:
username = args[0]
if username in MUTED_USERS:
del MUTED_USERS[username]
print(f"SERVER: User {username} has been unmuted.")
else:
print(f"SERVER: User {username} is not muted.")
elif cmd == "ban" and len(args) == 1:
username = args[0]
BANNED_USERS[username] = True
print(f"SERVER: User {username} has been banned.")
elif cmd == "unban" and len(args) == 1:
username = args[0]
if username in BANNED_USERS:
del BANNED_USERS[username]
print(f"SERVER: User {username} has been unbanned.")
else:
print(f"SERVER: User {username} is not unbanned.")
elif cmd == "kick" and len(args) == 1:
username = args[0]
if username not in KICKED_USERS:
KICKED_USERS.append(username)
print(f"SERVER: User {username} will be disconnected on their next poll.")
else:
print(f"SERVER: User {username} is already marked for disconnection.")
elif cmd == "list_muted":
print("SERVER: Muted users:", ", ".join(MUTED_USERS.keys()))
elif cmd == "list_banned":
print("SERVER: Banned users:", ", ".join(BANNED_USERS.keys()))
elif cmd == "help":
print("SERVER: Available commands:")
print(" mute <username> - Mutes a user from chatting.")
print(" unmute <username> - Unmutes a user.")
print(" ban <username> - Bans a user.")
print(" unban <username> - Unbans a user.")
print(" kick <username> - Force-disconnects a user.")
print(" list_muted - Lists all muted users.")
print(" list_banned - Lists all banned users.")
else:
print("SERVER: Unknown command. Type 'help' for a list of commands.")
# New: Function to clean up inactive users
def cleanup_inactive_users():
while True:
# Check every 60 seconds
time.sleep(60)
# Remove users who haven't pinged in the last 120 seconds
inactive_threshold = time.time() - 120
users_to_remove = []
for username, last_ping in ACTIVE_USERS.items():
if last_ping < inactive_threshold:
users_to_remove.append(username)
for username in users_to_remove:
del ACTIVE_USERS[username]
print(f"Server: {username} has been marked as inactive.")
if __name__ == "__main__":
print("Server: Starting up...")
if not os.path.exists("cloud_saves"):
os.makedirs("cloud_saves")
# Load missions at startup
load_missions()
# Disable Flask logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
# Start the admin input thread
admin_thread = threading.Thread(target=handle_server_input, daemon=True)
admin_thread.start()
# New: Start the user cleanup thread
cleanup_thread = threading.Thread(target=cleanup_inactive_users, daemon=True)
cleanup_thread.start()
# Note: The code for running with waitress is outside the 'if __name__ == "__main__":' block.
# This ensures it can be imported by the waitress-serve command.