-
Notifications
You must be signed in to change notification settings - Fork 5
/
sc4mpclient.py
5404 lines (4016 loc) · 149 KB
/
sc4mpclient.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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import configparser
import hashlib
import inspect
import io
import json
import math
import os
import platform
import random
import re
import shutil
import socket
import string
import struct
import subprocess
import sys
import threading as th
import time
import tkinter as tk
import traceback
import webbrowser
from datetime import datetime, timedelta
from pathlib import Path
from tkinter import Menu, filedialog, messagebox, ttk
from typing import Optional
SC4MP_VERSION = "0.4.3"
SC4MP_SERVERS = [("servers.sc4mp.org", port) for port in range(7240, 7250)]
SC4MP_URL = "www.sc4mp.org"
SC4MP_CONTRIBUTORS_URL = "https://github.com/kegsmr/sc4mp-client/contributors/"
SC4MP_ISSUES_URL = "https://github.com/kegsmr/sc4mp-client/issues/"
SC4MP_RELEASES_URL = "https://github.com/kegsmr/sc4mp-client/releases/"
SC4MP_AUTHOR_NAME = "SimCity 4 Multiplayer Project"
SC4MP_WEBSITE_NAME = "www.sc4mp.org"
SC4MP_LICENSE_NAME = "MIT-0"
SC4MP_CONFIG_PATH = "config.ini"
SC4MP_LOG_PATH = "sc4mpclient.log"
SC4MP_README_PATH = "readme.html"
SC4MP_RESOURCES_PATH = "resources"
SC4MP_TITLE = f"SC4MP Launcher v{SC4MP_VERSION}" + (" (x86)" if 8 * struct.calcsize('P') == 32 else "")
SC4MP_ICON: Path() = Path(SC4MP_RESOURCES_PATH) / "icon.png"
SC4MP_HOST = SC4MP_SERVERS[0][0]
SC4MP_PORT = SC4MP_SERVERS[0][1]
SC4MP_BUFFER_SIZE = 4096
SC4MP_DELAY = .1
SC4MP_SERVERLIST_ENABLED = True
SC4MP_LAUNCHERMAP_ENABLED = False
SC4MP_CONFIG_DEFAULTS = [
("GENERAL", [
#("nickname", os.getlogin()), #TODO unused
#(first_run, True) #TODO
#("use_custom_user_id", False), #TODO
#("custom_user_id", ""), #TODO
("default_host", SC4MP_HOST),
("default_port", SC4MP_PORT),
#("use_overlay", 1), #TODO
("custom_plugins", False),
("custom_plugins_path", Path("~/Documents/SimCity 4/Plugins").expanduser()),
("stat_mayors_online_cutoff", 60),
("ignore_token_errors", False),
("allow_game_monitor_exit", False)
]),
("STORAGE", [
("storage_path", Path("~/Documents/SimCity 4/_SC4MP").expanduser()),
("cache_size", 8000)
]),
("SC4", [
("game_path", ""),
("fullscreen", False),
("resw", 1280),
("resh", 800),
("cpu_count", 1),
("cpu_priority", "high"),
("additional_properties", "")
]),
("DEBUG", [
("random_server_stats", False),
])
]
SC4MP_LAUNCHPATH = None
SC4MP_LAUNCHRESW = None
SC4MP_LAUNCHRESH = None
SC4MP_CUSTOMPATH = None
sc4mp_args = sys.argv
sc4mp_ui = None
sc4mp_current_server = None
# Methods
def main():
"""The main method.
Arguments:
None
Returns:
None
"""
try:
# Exit if already running
try:
count = process_count("sc4mpclient.exe")
if count is not None and count > 1:
return
except:
pass
# Output
sys.stdout = Logger()
set_thread_name("Main", enumerate=False)
# Title
print(SC4MP_TITLE)
# "-no-ui" argument
global sc4mp_ui
sc4mp_ui = not "-no-ui" in sc4mp_args
# "--host" argument
global sc4mp_host
sc4mp_host = None
if "--host" in sc4mp_args:
try:
sc4mp_host = get_arg_value("--host", sc4mp_args)
except:
raise ClientException("Invalid arguments.")
# "--port" argument
global sc4mp_port
sc4mp_port = None
if "--port" in sc4mp_args:
try:
sc4mp_port = int(get_arg_value("--port", sc4mp_args))
except:
raise ClientException("Invalid arguments.")
# "--password" argument
global sc4mp_password
sc4mp_password = None
if "--password" in sc4mp_args:
try:
sc4mp_password = get_arg_value("--password", sc4mp_args)
except:
raise ClientException("Invalid arguments.")
# Prep
prep()
# Client
if sc4mp_ui:
sc4mp_ui = UI()
if sc4mp_host != None and sc4mp_port != None:
server = Server(sc4mp_host, sc4mp_port)
server.password = sc4mp_password
ServerLoaderUI(server)
sc4mp_ui.mainloop()
else:
sc4mp_ui = None
if sc4mp_host == None or sc4mp_port == None:
print("[PROMPT] Connect to server:")
if sc4mp_host == None:
sc4mp_host = input("[PROMPT] - Enter server address... ")
if sc4mp_port == None:
sc4mp_port = int(input("[PROMPT] - Enter server port... "))
server = Server(sc4mp_host, sc4mp_port)
server.fetch()
if sc4mp_password == None and server.password_enabled:
sc4mp_password = input("[PROMPT] - Enter server password... ")
server.password = sc4mp_password
ServerLoader(None, server).run()
# Cleanup
cleanup()
except Exception as e:
# Fatal error
fatal_error()
def prep():
"""Prepares the client to launch."""
load_config()
create_subdirectories()
load_database()
def cleanup():
"""TODO"""
sc4mp_servers_database.end = True
def load_config():
"""Loads settings from the configuration file."""
global sc4mp_config
print("Loading config...")
sc4mp_config = Config(SC4MP_CONFIG_PATH, SC4MP_CONFIG_DEFAULTS)
def update_config_constants(config):
"""For backwards compatibility. Updates the global config constants that are sometimes used internally."""
global SC4MP_LAUNCHPATH
global SC4MP_LAUNCHRESW
global SC4MP_LAUNCHRESH
global SC4MP_CUSTOMPATH
SC4MP_LAUNCHPATH = config['STORAGE']['storage_path']
SC4MP_LAUNCHRESW = config['SC4']['resw']
SC4MP_LAUNCHRESH = config['SC4']['resh']
SC4MP_CUSTOMPATH = config['SC4']['game_path']
def create_subdirectories() -> None:
"""Creates the required subdirectories in the launch directory if they do not yet exist."""
print("Creating subdirectories...")
directories = [
Path("_Cache"),
Path("_Database"),
Path("_Salvage"),
Path("_Temp"),
Path("_Temp") / "ServerList",
Path("Plugins"),
Path("Plugins") / "server",
Path("Plugins") / "client",
Path("Regions")
] #"SC4MPBackups", os.path.join("_Cache","Plugins"), os.path.join("_Cache","Regions")]
# Update old directory names
#if (os.path.exists(os.path.join(SC4MP_LAUNCHPATH, "_Profiles"))):
# os.rename(os.path.join(SC4MP_LAUNCHPATH, "_Database"), os.path.join(SC4MP_LAUNCHPATH, "_Database"))
# Create new directories
launchdir = Path(SC4MP_LAUNCHPATH)
launchdir.mkdir(exist_ok=True, parents=True)
for directory in directories:
new_directory = launchdir / directory
try:
new_directory.mkdir(exist_ok=True, parents=True)
except Exception as e:
raise ClientException("Failed to create SC4MP subdirectories.\n\n" + str(e))
def load_database():
"""TODO"""
print("Loading database...")
global sc4mp_servers_database
sc4mp_servers_database = DatabaseManager(Path(SC4MP_LAUNCHPATH) / "_Database" / "servers.json")
sc4mp_servers_database.start()
def get_sc4_path() -> Optional[Path]:
"""Returns the path to the SimCity 4 executable if found."""
sc4_dirs = Path("SimCity 4 Deluxe") / "Apps" / "SimCity 4.exe"
steam_dirs = Path("Steam") / "steamapps" / "common"
config_path = Path(sc4mp_config['SC4']['game_path'])
home_drive = Path(Path.home().drive)
possible_paths: list[Path] = [
config_path,
config_path / "SimCity 4.exe",
config_path / "Apps" / "SimCity 4.exe",
home_drive / "Program Files" / steam_dirs / sc4_dirs,
home_drive / "Program Files" / "Origin Games" / sc4_dirs,
home_drive / "Program Files" / "Maxis" / sc4_dirs,
home_drive / "Program Files (x86)" / steam_dirs / sc4_dirs,
home_drive / "Program Files (x86)" / "Origin Games" / sc4_dirs,
home_drive / "Program Files (x86)" / "Maxis" / sc4_dirs,
]
for possible_path in possible_paths:
if possible_path.is_file():
return possible_path
return None
def start_sc4():
"""Attempts to find the install path of SimCity 4 and launches the game with custom launch parameters if found."""
global sc4mp_allow_game_monitor_exit_if_error, sc4mp_game_exit_ovveride
sc4mp_allow_game_monitor_exit_if_error = False
sc4mp_game_exit_ovveride = False
print("Starting SimCity 4...")
path = get_sc4_path()
if not path:
show_error("Path to SimCity 4 not found. Specify the correct path in settings.")
return
arguments = [str(path),
f'-UserDir:"{SC4MP_LAUNCHPATH}{os.sep}"', # add trailing slash here because SC4 expects it
'-intro:off',
'-CustomResolution:enabled',
f'-r{sc4mp_config["SC4"]["resw"]}x{sc4mp_config["SC4"]["resh"]}x32',
f'-CPUCount:{sc4mp_config["SC4"]["cpu_count"]}',
f'-CPUPriority:{sc4mp_config["SC4"]["cpu_priority"]}'
]
if sc4mp_config["SC4"]["fullscreen"] == True:
arguments.append('-f')
else:
arguments.append('-w')
arguments.extend(sc4mp_config["SC4"]["additional_properties"].strip().split(' ')) # assumes that properties do not have spaces
command = ' '.join(arguments)
print(f"'{command}'")
try:
if platform.system() == "Windows":
subprocess.run(command) # `subprocess.run(arguments)` won't work on Windows for some unknowable reason
else:
subprocess.run(arguments) # on Linux, the first String passed as argument must be a file that exists
except PermissionError as e:
show_error(f"Permission denied. Try running the SC4MP Launcher as administrator.\n\n{e}")
# For compatability with the steam version of SC4
sc4mp_allow_game_monitor_exit_if_error = True
time.sleep(3)
while True:
if sc4mp_game_exit_ovveride:
print("Exiting without checking whether SC4 is still running...")
return
try:
while process_exists("simcity 4.exe"):
time.sleep(1)
print("SimCity 4 closed.")
break
except Exception as e:
show_error(f"An error occured while checking if SC4 had exited yet.", no_ui=True)
time.sleep(10)
def process_exists(process_name): #TODO add MacOS compatability / deprecate in favor of `process_count`?
"""TODO"""
if platform.system() == "Windows":
call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
output = subprocess.check_output(call, shell=True).decode()
last_line = output.strip().split('\r\n')[-1]
return last_line.lower().startswith(process_name.lower())
else:
return None
def process_count(process_name): #TODO add MacOS compatability
if platform.system() == "Windows":
return int(subprocess.check_output(f"tasklist | find /I /C \"{process_name}\"", shell=True))
else:
return None
def get_sc4mp_path(filename: str) -> Path:
"""Returns the path to a given file in the SC4MP "resources" subdirectory"""
return Path(SC4MP_RESOURCES_PATH) / filename
def md5(filename: Path) -> str:
"""Returns an md5 hashcode generated from a given file."""
hash_md5 = hashlib.md5()
with filename.open("rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def random_string(length):
"""Returns a random string of ascii letters of the specified length."""
return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for i in range(length))
def purge_directory(directory: Path) -> None:
"""Deletes all files and subdirectories of a directory"""
for path in directory.iterdir():
try:
if path.is_file():
path.unlink()
elif path.is_dir():
shutil.rmtree(path)
except PermissionError as e:
raise ClientException(f'Failed to delete "{path}" because the file is being used by another process.') #\n\n' + str(e)
def directory_size(directory: Path) -> int:
"""Returns the size of a directory recursively."""
size = 0
with os.scandir(directory) as items:
for item in items:
if item.is_file():
size += item.stat().st_size
elif item.is_dir():
size += directory_size(item.path)
return size
def event_generate(ui, event, when):
"""Deprecated."""
if ui != None:
ui.event_generate(event, when=when)
'''def create_empty_json(filename):
"""Deprecated."""
with open(filename, 'w') as file:
data = dict()
file.seek(0)
json.dump(data, file, indent=4)
file.truncate()'''
def load_json(filename):
"""Returns data from a json file as a dictionary."""
try:
with open(filename, 'r') as file:
data = json.load(file)
if data == None:
return dict()
else:
return data
except FileNotFoundError:
return dict()
def update_json(filename, data):
"""Writes data as a dictionary to a json file."""
with open(filename, 'w') as file:
file.seek(0)
json.dump(data, file, indent=4)
file.truncate()
def show_error(e, no_ui=False):
"""Shows an error message in the console and optionally in the UI."""
message = None
if isinstance(e, str):
message = e
else:
message = str(e)
print(f"[ERROR] {message}\n\n{traceback.format_exc()}")
if not no_ui:
if sc4mp_ui != None:
if sc4mp_ui == True:
tk.Tk().withdraw()
messagebox.showerror(SC4MP_TITLE, message)
def startfile(filename):
syst = platform.system()
if syst == "Windows":
os.startfile(filename)
else:
opener = "open" if syst == "Darwin" else "xdg-open" # Linux
subprocess.call([opener, filename])
def fatal_error():
"""Shows a fatal error message in the console and the UI. Exits the program."""
message = f"A fatal error occurred.\n\n{traceback.format_exc()}"
print(f"[FATAL] {message}")
if sc4mp_ui != None:
if sc4mp_ui == True:
tk.Tk().withdraw()
messagebox.showerror(SC4MP_TITLE, message)
startfile(SC4MP_LOG_PATH)
cleanup()
sys.exit()
def show_warning(e):
"""Shows a warning in the console and the UI."""
message = None
if isinstance(e, str):
message = e
else:
message = str(e)
print(f"[WARNING] {message}")
if sc4mp_ui != None:
if sc4mp_ui == True:
tk.Tk().withdraw()
messagebox.showwarning(SC4MP_TITLE, message)
def center_window(window):
"""Centers a tkinter window."""
win = window
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry(f'{width}x{height}+{x}+{y}')
win.deiconify()
def prep_server(path: Path) -> None:
"""Runs the server executable in prep mode. Takes the server path as an argument."""
subprocess.Popen(f"sc4mpserver.exe -prep --server-path {path}")
def start_server(path: Path) -> None:
"""Runs the server executable. Takes the server path as an argument."""
subprocess.Popen(f"sc4mpserver.exe --server-path {path}", creationflags=subprocess.CREATE_NEW_CONSOLE)
#th.Thread(target=lambda: subprocess.Popen("sc4mpserver.exe --server-path " + str(path))).start()
def update_config_value(section, item, value):
"""Updates a value in the config, attempting to convert it to the proper data type."""
try:
t = type(sc4mp_config[section][item])
sc4mp_config[section][item] = t(value)
except:
show_error(f'Invalid config value for "{item}" in section "{section}"', no_ui=True)
def get_fullpaths_recursively(dir: Path) -> list[Path]:
"""Returns full paths of all files in a directory recursively."""
return [path for path in dir.rglob("*") if path.is_file()]
def get_relpaths_recursively(dir: Path) -> list[Path]:
"""Returns relative paths of all files in a directory recursively."""
return [path.relative_to(dir) for path in dir.rglob("*") if path.is_file()]
def get_arg_value(arg, args):
"""Returns the following token in commandline arguments."""
return args[args.index(arg) + 1]
def request_header(s, server):
"""A "handshake" between the client and server which establishes that a request can be made."""
s.recv(SC4MP_BUFFER_SIZE)
s.send(SC4MP_VERSION.encode())
if server.password_enabled:
s.recv(SC4MP_BUFFER_SIZE)
s.send(server.password.encode())
s.recv(SC4MP_BUFFER_SIZE)
s.send(server.user_id.encode())
def format_version(version: tuple[int, int, int]) -> str:
"""Converts a version number from a tuple to a string."""
major, minor, patch = version
return f'{major}.{minor}.{patch}'
def unformat_version(version: str) -> tuple[int, int, int]:
"""Converts a version number from a string to a tuple."""
return tuple([int(v) for v in version.split('.')])
def set_server_data(entry, server):
"""Updates the json entry for a given server with the appropriate values."""
entry["host"] = server.host
entry["port"] = server.port
entry["server_name"] = server.server_name
entry["server_description"] = server.server_description
entry["server_url"] = server.server_url
entry["server_version"] = server.server_version
entry["password_enabled"] = server.password_enabled
entry["user_plugins"] = server.user_plugins_enabled
entry.setdefault("first_contact", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
entry["last_contact"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_sc4_cfg_path() -> Path: #TODO can this find the cfg for the origin version?
"""TODO"""
return Path(SC4MP_LAUNCHPATH) / "SimCity 4.cfg"
def region_open(region):
"""TODO"""
cfg_path = get_sc4_cfg_path()
return b"\x00" + region.encode() + b"\x00" in DBPF(cfg_path).decompress_subfile("a9dd6e06").read() #TODO maybe the surrounding zeroes are just from that decompression error?
def refresh_region_open():
"""TODO"""
return region_open("Refresh...")
def report(message, object):
"""TODO"""
print(message)
def prep_region_config(path):
try:
config = configparser.RawConfigParser()
config.read(path)
config.set("Regional Settings", "Name", "[SC4MP] " + config.get("Regional Settings", "Name"))
with open(path, 'wt') as config_file:
config.write(config_file)
except:
raise ClientException(f"Failed to prep region config at {path}.")
def format_filesize(size):
if size >= 10 ** 11:
return ">99GB"
elif size >= 10 ** 10:
return str(int(size / (10 ** 9))) + "GB"
elif size >= 10 ** 9:
return str(float(int(size / (10 ** 8)) / 10)) + "GB"
elif size >= 10 ** 8:
return str(int(size / (10 ** 6))) + "MB"
elif size >= 10 ** 7:
return str(int(size / (10 ** 6))) + "MB"
elif size >= 10 ** 6:
return str(float(int(size / (10 ** 5)) / 10)) + "MB"
elif size >= 10 ** 5:
return str(int(size / (10 ** 3))) + "KB"
elif size >= 10 ** 4:
return str(int(size / (10 ** 3))) + "KB"
elif size >= 10 ** 3:
return str(float(int(size / (10 ** 2)) / 10)) + "KB"
else:
return str(int(size)) + "B"
def get_bitmap_dimensions(filename):
"""TODO"""
with open(filename, "rb") as file:
data = bytearray(file.read())
width = struct.unpack_from('<i', data, 18)
height = struct.unpack_from('<i', data, 22)
return width[0], height[0]
def arp():
if platform.system() == "Windows":
call = 'arp', '-a'
output = subprocess.check_output(call, shell=True).decode()
return [line for line in re.findall('([-.0-9]+)\s+([-0-9a-f]{17})\s+(\w+)', output)]
else: #TODO make this work on other platforms besides Windows
return []
def send_json(s, data):
"""TODO"""
s.sendall(json.dumps(data).encode())
def recv_json(s):
"""TODO"""
data = ""
while True:
new_data = s.recv(SC4MP_BUFFER_SIZE).decode()
if len(new_data) > 0:
data += new_data
try:
return json.loads(data)
except json.decoder.JSONDecodeError:
pass
time.sleep(SC4MP_DELAY)
def set_thread_name(name, enumerate=True):
if enumerate:
thread_names = [thread.name for thread in th.enumerate()]
count = 1
while (True):
thread_name = f"{name}-{count}"
if not thread_name in thread_names:
th.current_thread().name = thread_name
return thread_name
count += 1
else:
th.current_thread().name = name
return name
# Objects
class Config:
"""Encapsules a dictionary that represents config values set by the user."""
def __init__(self, path, defaults):
"""TODO"""
# Parameters
self.PATH = path
self.DEFAULTS = defaults
# Create dictionary with default config settings
self.data = {}
for section_name, section_items in self.DEFAULTS:
self.data.setdefault(section_name, {})
for item_name, item_value in section_items:
self.data[section_name].setdefault(item_name, item_value)
# Try to read settings from the config file and update the dictionary accordingly
parser = configparser.RawConfigParser()
try:
parser.read(self.PATH)
for section_name, section in self.data.items():
try:
for item_name in section:
try:
from_file = parser.get(section_name, item_name)
if from_file in ("true", "True", "TRUE"):
self.data[section_name][item_name] = True
elif from_file in ("false", "False", "FALSE"):
self.data[section_name][item_name] = False
elif from_file in ("none", "None", "NONE"):
self.data[section_name][item_name] = None
else:
t = type(self.data[section_name][item_name])
self.data[section_name][item_name] = t(from_file)
except (configparser.NoSectionError, configparser.NoOptionError):
print(f"[WARNING] Option \"{item_name}\" missing from section \"{section_name}\" of the config file at \"{self.PATH}\". Using default value.")
except Exception as e:
show_error("An error occured while reading a config item.", no_ui=True)
except Exception as e:
show_error("An error occured while reading a config section.", no_ui=True)
except Exception as e:
show_error("An error occured while reading the config.", no_ui=True)
# Update config file
self.update()
def __getitem__(self, key):
return self.data.__getitem__(key)
def __setitem__(self, key, value):
return self.data.__setitem__(key, value)
def update(self):
"""Writes config values set by the user to the config file."""
parser = configparser.RawConfigParser()
for section_name in self.data.keys():
parser.add_section(section_name)
section = self.data[section_name]
for item_name in section.keys():
item_value = section[item_name]
parser.set(section_name, item_name, item_value)
with open(self.PATH, 'wt') as file:
parser.write(file)
try:
update_config_constants(self)
except:
pass
class Server:
"""An interface for interaction with a server."""
def __init__(self, host, port):
self.host = host
self.port = port
self.fetched = False
#self.stats = False
self.password = None
self.user_id = None
self.categories = ["All"]
if (host, port) in SC4MP_SERVERS:
self.categories.append("Official")
def fetch(self):
"""Retreives basic information from a server and saves them as instance variables. Updates the json entry for the server if possible."""
# Mark server as fetched
self.fetched = True
# Request server info
server_info = self.request("info")
if server_info is not None:
try:
server_info = json.loads(server_info)
except:
raise ClientException("Unable to fetch server info.")
else:
raise ClientException("Unable to find server. Check the IP address and port, then try again.")
self.server_id = server_info["server_id"] #self.request("server_id")
self.server_name = server_info["server_name"] #self.request("server_name")
self.server_description = server_info["server_description"] #self.request("server_description")
self.server_url = server_info["server_url"] #self.request("server_url")
self.server_version = server_info["server_version"] #self.request("server_version")
self.password_enabled = server_info["password_enabled"] #self.request("password_enabled") == "y"
self.user_plugins_enabled = server_info["user_plugins_enabled"] #self.request("user_plugins_enabled") == "y"
self.private = server_info["private"] #self.request("private") == "y"
if self.password_enabled:
self.categories.append("Private")
else:
self.categories.append("Public")
#if (self.server_version != None):
# self.server_version = unformat_version(self.server_version)
if self.fetched == True:
try:
self.update_database()
except Exception as e:
show_error("An error occured while updating the server database.", no_ui = True)
def fetch_stats(self):
"""TODO"""
download = self.fetch_temp()
regions_path: Path = Path(SC4MP_LAUNCHPATH) / "_Temp" / "ServerList" / self.server_id / "Regions"
server_time = self.time()
mayors = []
mayors_online = []
claimed_area = 0
total_area = 0
for region in os.listdir(regions_path):
try:
region_path = regions_path / region
region_config_path = region_path / "config.bmp"
region_dimensions = get_bitmap_dimensions(region_config_path)
region_database_path = region_path / "_Database" / "region.json"
region_database = load_json(region_database_path)
for coords in region_database.keys():
city_entry = region_database[coords]
if city_entry != None:
owner = city_entry["owner"]
if owner != None:
claimed_area += city_entry["size"] ** 2
if owner not in mayors:
mayors.append(owner)
modified = city_entry["modified"]
if modified != None:
modified = datetime.strptime(modified, "%Y-%m-%d %H:%M:%S")
if modified > server_time - timedelta(minutes=sc4mp_config["GENERAL"]["stat_mayors_online_cutoff"]) and owner not in mayors_online:
mayors_online.append(owner)
total_area += region_dimensions[0] * region_dimensions[1]
except Exception as e:
show_error(f"An error occurred while calculating region statistics for \"{region}\".", no_ui=True)
self.stat_mayors = len(mayors) #(random.randint(0,1000))
self.stat_mayors_online = len(mayors_online) #int(self.stat_mayors * (float(random.randint(0, 100)) / 100))
try:
self.stat_claimed = (float(claimed_area) / float(total_area)) #(float(random.randint(0, 100)) / 100)
except ZeroDivisionError:
self.stat_claimed = 1
self.stat_download = download #(random.randint(0, 10 ** 11))
ping = self.ping()
if ping != None:
self.stat_ping = ping
if (sc4mp_config["DEBUG"]["random_server_stats"]):
self.stat_mayors = random.randint(0,1000)
self.stat_mayors_online = int(self.stat_mayors * (float(random.randint(0, 100)) / 100))
self.stat_claimed = float(random.randint(0, 100)) / 100
self.stat_download = random.randint(0, 10 ** 11)
sc4mp_servers_database[self.server_id]["stat_mayors"] = self.stat_mayors
sc4mp_servers_database[self.server_id]["stat_mayors_online"] = self.stat_mayors_online
sc4mp_servers_database[self.server_id]["stat_claimed"] = self.stat_claimed
sc4mp_servers_database[self.server_id]["stat_download"] = self.stat_download
sc4mp_servers_database[self.server_id]["stat_ping"] = self.stat_ping
def fetch_temp(self):
"""TODO"""
REQUESTS = ["plugins", "regions"]
DIRECTORIES = ["Plugins", "Regions"]
total_size = 0
for request, directory in zip(REQUESTS, DIRECTORIES):
# Set destination
destination = Path(SC4MP_LAUNCHPATH) / "_Temp" / "ServerList" / self.server_id / directory
# Create the socket
s = socket.socket()
s.settimeout(30)
s.connect((self.host, self.port))
# Request the type of data
if not self.private:
s.send(request.encode())
else:
s.send(f"{request} {SC4MP_VERSION} {self.server.user_id} {self.server.password}".encode())
# Receive file table
file_table = recv_json(s)
# Get total download size
size = sum([entry[1] for entry in file_table])
# Prune file table as necessary
ft = []
for entry in file_table:
filename = Path(entry[2]).name
if filename in ["region.json", "config.bmp"]:
ft.append(entry)
file_table = ft
# Send pruned file table
send_json(s, file_table)
# Receive files
for entry in file_table:
# Get necessary values from entry
filesize = entry[1]
relpath = Path(entry[2])
# Set the destination
d = Path(destination) / relpath
# Create the destination directory if necessary
d.parent.mkdir(parents=True, exist_ok=True)
# Delete the destination file if it exists
d.unlink(missing_ok=True)
# Receive the file. Write to both the destination and cache
filesize_read = 0
with d.open("wb") as dest:
while filesize_read < filesize:
filesize_remaining = filesize - filesize_read
buffersize = SC4MP_BUFFER_SIZE if filesize_remaining > SC4MP_BUFFER_SIZE else filesize_remaining
bytes_read = s.recv(buffersize)
if not bytes_read:
break
dest.write(bytes_read)
filesize_read += len(bytes_read)
total_size += size