-
Notifications
You must be signed in to change notification settings - Fork 2
/
sc4mpserver.py
2861 lines (2099 loc) · 74.4 KB
/
sc4mpserver.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 getpass
import hashlib
import inspect
import io
import json
import os
import random
import shutil
import socket
import string
import struct
import sys
import threading as th
import time
import traceback
from argparse import ArgumentParser, Namespace
from collections import deque
from datetime import datetime, timedelta
from pathlib import Path
from typing import Iterable
SC4MP_VERSION = "0.4.4"
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 = None
SC4MP_LOG_PATH = "sc4mpserver-" + datetime.now().strftime("%Y%m%d%H%M%S") + ".log"
SC4MP_README_PATH = "readme.html"
SC4MP_RESOURCES_PATH = "res"
SC4MP_TITLE = "SC4MP Server v" + SC4MP_VERSION + (" (x86)" if 8 * struct.calcsize('P') == 32 else "")
SC4MP_ICON = os.path.join(SC4MP_RESOURCES_PATH, "icon.ico")
SC4MP_HOST = None
SC4MP_PORT = None
SC4MP_BUFFER_SIZE = 4096
SC4MP_DELAY = .1
SC4MP_CONFIG_DEFAULTS = [
("NETWORK", [
("host", "0.0.0.0"),
("port", 7240),
("discoverable", True),
]),
("INFO", [
("server_id", ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for i in range(32))),
("server_name", getpass.getuser() + " on " + socket.gethostname()),
("server_description", "Join and build your city.\n\nRules:\n- Feed the llamas\n- Balance your budget\n- Do uncle Vinny some favors"),
("server_url", SC4MP_URL),
]),
("SECURITY", [
("private", False),
("password_enabled", False),
("password", "maxis2003"),
("max_ip_users", 3),
]),
("RULES", [
("claim_duration", 30),
#("abandoned_reset_delay", None) #TODO for resetting old abandoned saves
#("claim_delay", 60), #TODO
("max_region_claims", 1),
#("max_total_claims", None), #TODO
("godmode_filter", True),
("user_plugins", False),
]),
("PERFORMANCE", [
("request_limit", 60),
("max_request_threads", 200),
("connection_timeout", 600),
("filetable_update_interval", 60)
]),
("BACKUPS", [
("server_backup_interval", 6),
("backup_server_on_startup", True),
("max_server_backup_days", 30),
#("max_server_backups", 720),
("max_savegame_backups", 100),
])
]
SC4MP_SERVER_ID = None
SC4MP_SERVER_NAME = None
SC4MP_SERVER_DESCRIPTION = None
sc4mp_server_path = "_SC4MP"
sc4mp_server_running = False
sc4mp_request_threads = 0
# Methods
def main():
"""The main method."""
try:
# Parse arguments
args = parse_args()
# Output
sys.stdout = Logger()
set_thread_name("Main", enumerate=False)
# Title
report(SC4MP_TITLE)
# -s / --server-path argument
global sc4mp_server_path
if args.server_path:
sc4mp_server_path = args.server_path
# -r / --restore argument
if args.restore:
restore(args.restore)
# -p / --prep argument
global sc4mp_nostart
if args.prep is True:
sc4mp_nostart = True
else:
sc4mp_nostart = False
# -v / --verbose argument
if args.verbose:
# TODO: use this flag to set logger level to debug once the logger PR is merged
pass
# Server
global sc4mp_server
sc4mp_server = Server()
if not sc4mp_nostart:
sc4mp_server.run()
except Exception as e:
fatal_error(e)
def parse_args() -> Namespace:
"""Parse command line arguments"""
parser = ArgumentParser(prog="SC4MP Server",
description="SimCity 4 Multiplayer Server")
parser.add_argument("-s", "--server-path", help="specify server directory relative path")
parser.add_argument("-r", "--restore", help="restore the server to the specified backup")
parser.add_argument("-v", "--verbose",
help="increase stdout/log verbosity",
action="store_true")
parser.add_argument("-p", "--prep",
help="prep the server, but do not start",
action="store_true")
parser.add_argument("--version", action="version",
version=f"{parser.prog} {SC4MP_VERSION}")
return parser.parse_args()
def prep():
return #TODO move server init stuff here
def cleanup():
return #TODO
def get_sc4mp_path(filename):
"""TODO Gives the path of a given file in the SC4MP "resources" subdirectory
Arguments:
filename (str)
Returns:
TODO type: the path to the given file
"""
return os.path.join(SC4MP_RESOURCES_PATH, filename)
def md5(filename):
"""TODO Creates the hashcode for a given file.
Arguments:
filename (str)
Returns:
TODO type: hashcode
"""
hash_md5 = hashlib.md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
'''def string_md5(text):
"""TODO"""
return hashlib.md5(text.encode()).hexdigest()'''
def file_md5(file):
"""TODO"""
hash_md5 = hashlib.md5()
for chunk in iter(lambda: file.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def create_empty_json(filename):
"""TODO"""
with open(filename, 'w') as file:
data = {}
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 is None:
return {}
else:
return data
except FileNotFoundError:
return {}
def set_savegame_data(entry, savegame):
"""TODO entry values"""
# No overwrite
entry.setdefault("filename", os.path.basename(os.path.normpath(savegame.filename)))
entry.setdefault("owner", None)
entry.setdefault("modified", None)
entry.setdefault("locked", False)
entry.setdefault("reset_filename", None)
entry.setdefault("date_subfile_hashes", [])
# Append
date_subfile_hash = file_md5(savegame.decompress_subfile("2990c1e5"))
date_subfile_hashes = entry["date_subfile_hashes"]
if date_subfile_hash not in date_subfile_hashes:
date_subfile_hashes.append(date_subfile_hash)
# Overwrite
entry["hashcode"] = md5(savegame.filename)
entry["size"] = savegame.SC4ReadRegionalCity["citySizeX"]
entry["gamemode"] = savegame.SC4ReadRegionalCity["modeFlag"]
entry["difficulty"] = savegame.SC4ReadRegionalCity["starCount"]
entry["mayor_rating"] = savegame.SC4ReadRegionalCity["mayorRating"]
entry["residential_population"] = savegame.SC4ReadRegionalCity["residentialPopulation"]
entry["commercial_population"] = savegame.SC4ReadRegionalCity["commercialPopulation"]
entry["industrial_population"] = savegame.SC4ReadRegionalCity["industrialPopulation"]
entry["population"] = entry["residential_population"] + entry["commercial_population"] + entry["industrial_population"]
entry["population_density"] = round(entry["population"] / (entry["size"] * entry["size"]))
entry["residential_population_density"] = round(entry["residential_population"] / (entry["size"] * entry["size"]))
def update_json(filename, data):
"""TODO"""
with open(filename, 'w') as file:
file.seek(0)
json.dump(data, file, indent=4)
file.truncate()
def package_plugins_and_regions():
"""TODO"""
report("Packaging plugins and regions...")
report("- packaging plugins...")
package("plugins")
report("- packaging regions...")
package("regions")
# Regions manager
global sc4mp_regions_manager
sc4mp_regions_manager = RegionsManager()
sc4mp_regions_manager.start()
def package(package_type):
"""TODO"""
directory = None
if package_type == "plugins":
directory = "Plugins"
elif package_type == "regions":
directory = "Regions"
target = os.path.join(sc4mp_server_path, directory)
destination = os.path.join(sc4mp_server_path, "_Temp", "outbound", directory)
if os.path.exists(destination):
os.remove(destination)
shutil.make_archive(destination, "zip", target)
def export(export_type):
"""TODO"""
# Select directory name from input
directory = None
if export_type == "plugins":
directory = "Plugins"
elif export_type == "regions":
directory = "Regions"
# Set target and destination directories
target = os.path.join(sc4mp_server_path, directory)
destination = os.path.join(sc4mp_server_path, "_Temp", "outbound", directory)
# Erase file table if exists
if destination in sc4mp_filetables_manager.filetables.keys():
sc4mp_filetables_manager.erase(destination)
#TODO delete old abandoned savegames
# Replace missing savegame files with the reset savegame file
try:
if export_type == "regions":
for region in os.listdir(target):
if os.path.isdir(os.path.join(target, region)):
data_filename = os.path.join(target, region, "_Database", "region.json")
data = load_json(data_filename)
for coords in data.keys():
entry = data.get(coords, None)
if entry is not None:
filename = entry.get("filename", None)
reset_filename = entry.get("reset_filename", None)
if filename is not None and reset_filename is not None:
filename = os.path.join(target, region, filename)
if (not os.path.exists(filename)) and os.path.exists(reset_filename):
shutil.copy(reset_filename, filename)
except Exception as e:
show_error(e)
# Delete destination directory if it exists
if os.path.exists(destination):
shutil.rmtree(destination)
# Create the parent directories if they do not yet exist
#if (not os.path.exists(destination)):
# os.makedirs(destination)
# Copy recursively
shutil.copytree(target, destination, ignore=shutil.ignore_patterns('_Backups')) #, '_Database'))
# Generate filetable
sc4mp_filetables_manager.generate(destination)
def purge_directory(directory):
"""TODO
Arguments:
TODO
Returns:
TODO
"""
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except PermissionError as e:
raise ServerException('Failed to delete "' + file_path + '" because the file is being used by another process.') #\n\n' + str(e)
def send_filestream(c, rootpath):
"""TODO"""
# Loop through all files in path and append them to a list
#fullpaths = []
#for path, directories, files in os.walk(rootpath):
# for file in files:
# fullpaths.append(os.path.join(path, file))
# Get fullpaths to files in rootpath
#fullpaths = rootpath.rglob("*")
# Get file table
while sc4mp_server_running:
try:
filetable = sc4mp_filetables_manager.filetables[rootpath]
break
except KeyError:
print("[WARNING] Waiting for file table to generate...")
time.sleep(SC4MP_DELAY * 10)
#filetable = [(md5(fullpath), os.path.getsize(fullpath), os.path.relpath(fullpath, rootpath)) for fullpath in fullpaths]
# Send the file table to the client
send_json(c, filetable)
# Receive the modified filetable from the client and verify it
ft = [tuple(item) for item in recv_json(c)]
for item in ft:
if not item in filetable:
c.close()
filetable = ft
# Loop through the filetable and send the respective data
for checksum, size, relpath in filetable:
with open(os.path.join(rootpath, relpath), "rb") as file:
size_read = 0
while True:
size_remaining = size - size_read
buffer_size = SC4MP_BUFFER_SIZE if size_remaining > SC4MP_BUFFER_SIZE else size_remaining
data = file.read(buffer_size)
if not data:
break
size_read += len(data)
c.send(data)
def send_json(s, data):
"""TODO"""
s.sendall(json.dumps(data).encode())
def recv_json(s):
"""TODO"""
data = ""
while sc4mp_server_running:
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 send_tree(c, rootpath):
"""TODO"""
# Loop through all files in path and append them to a list
fullpaths = []
for path, directories, files in os.walk(rootpath):
for file in files:
fullpaths.append(os.path.join(path, file))
# Send file count
c.send(str(len(fullpaths)).encode())
# Separator
c.recv(SC4MP_BUFFER_SIZE)
# Send size
size = 0
for fullpath in fullpaths:
size += os.path.getsize(fullpath)
c.send(str(size).encode())
# Loop through the file list and send each one to the client
for fullpath in fullpaths:
# Separator
c.recv(SC4MP_BUFFER_SIZE)
# Get relative path to file
relpath = os.path.relpath(fullpath, rootpath)
# Send hashcode
c.send(md5(fullpath).encode())
# Separator
c.recv(SC4MP_BUFFER_SIZE)
# Send filesize
c.send(str(os.path.getsize(fullpath)).encode())
# Separator
c.recv(SC4MP_BUFFER_SIZE)
# Send relative path
c.send(relpath.encode())
# Send the file if not cached
if c.recv(SC4MP_BUFFER_SIZE).decode() != "y":
with open(fullpath, "rb") as file:
while True:
bytes_read = file.read(SC4MP_BUFFER_SIZE)
if not bytes_read:
break
c.sendall(bytes_read)
def send_or_cached(c, filename):
"""TODO"""
c.send(md5(filename).encode())
if c.recv(SC4MP_BUFFER_SIZE).decode() == "n":
send_file(c, filename)
else:
c.close()
def send_file(c, filename):
"""TODO"""
report("Sending file " + filename + "...")
filesize = os.path.getsize(filename)
c.send(str(filesize).encode())
with open(filename, "rb") as f:
while True:
bytes_read = f.read(SC4MP_BUFFER_SIZE)
if not bytes_read:
break
c.sendall(bytes_read)
def receive_file(c, filename, filesize):
"""TODO"""
#if (filesize is None):
#
# filesize = int(c.recv(SC4MP_BUFFER_SIZE).decode())
#
# c.send(SC4MP_SEPARATOR)
report("Receiving " + str(filesize) + " bytes...")
report("writing to " + filename)
if os.path.exists(filename):
os.remove(filename)
filesize_read = 0
with open(filename, "wb") as f:
while filesize_read < filesize:
filesize_remaining = filesize - filesize_read
buffersize = SC4MP_BUFFER_SIZE if filesize_remaining > SC4MP_BUFFER_SIZE else filesize_remaining
bytes_read = c.recv(buffersize)
if not bytes_read:
break
f.write(bytes_read)
filesize_read += len(bytes_read)
#print('Downloading "' + filename + '" (' + str(filesize_read) + " / " + str(filesize) + " bytes)...", int(filesize_read), int(filesize)) #os.path.basename(os.path.normpath(filename))
def xor(conditionA, conditionB):
return (conditionA or conditionB) and (not (conditionA and conditionB))
def report(message, obj=None, msg_type="INFO", ): #TODO do this in the logger to make sure output prints correctly
"""TODO"""
'''color = '\033[94m '
output = datetime.now().strftime("[%H:%M:%S] [SC4MP")
obj = None
for item in inspect.stack():
if (obj != None):
break
try:
obj = item[0].f_locals["self"]
except:
pass
if (obj != None):
output += "/" + obj.__class__.__name__
color = '\033[0m '
output+= "] [" + msg_type + "] " + message
if (msg_type=="WARNING"):
color = '\033[93m '
elif (msg_type == "ERROR" or msg_type == "FATAL"):
color = '\033[91m '
print(color + output)'''
print("[" + msg_type + "] " + message)
def update_config_constants(config):
"""TODO"""
global SC4MP_HOST
global SC4MP_PORT
global SC4MP_SERVER_ID
global SC4MP_SERVER_NAME
global SC4MP_SERVER_DESCRIPTION
SC4MP_HOST = config['NETWORK']['host']
SC4MP_PORT = config['NETWORK']['port']
SC4MP_SERVER_ID = config['INFO']['server_id']
SC4MP_SERVER_NAME = config['INFO']['server_name']
SC4MP_SERVER_DESCRIPTION = config['INFO']['server_description']
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 restore(filename):
"""TODO"""
possible_paths = [
os.path.join(sc4mp_server_path, "_Backups", filename),
os.path.join(sc4mp_server_path, "_Backups", filename + ".json"),
os.path.join(sc4mp_server_path, filename),
os.path.join(sc4mp_server_path, filename + ".json"),
filename,
filename + ".json",
]
for path in possible_paths:
if not os.path.exists(path):
continue
else:
if path[-5:] != ".json":
raise ServerException("Backup file must be a \".json\" file.")
print("Restoring backup at \"" + path + "\"")
data = load_json(path)
directory, filename = os.path.split(os.path.abspath(path))
files_entry = data["files"]
for original_filename, file_entry in files_entry.items():
hashcode = file_entry["hashcode"]
size = file_entry["size"]
data_filename = os.path.join(directory, "data", hashcode + "_" + str(size))
restore_filename = os.path.join(directory, "restores", filename[:-5], original_filename)
print("Copying \"" + data_filename + "\" to \"" + restore_filename + "\"")
restore_directory = os.path.split(restore_filename)[0]
if not os.path.exists(restore_directory):
os.makedirs(restore_directory)
shutil.copy(data_filename, restore_filename)
print("- done.")
return
raise ServerException("File not found.")
def show_error(e, no_ui=False):
"""TODO"""
message = None
if isinstance(e, str):
message = e
else:
message = str(e)
print("[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 fatal_error(e):
"""TODO"""
message = None
if isinstance(e, str):
message = e
else:
message = str(e)
print("[FATAL] " + message + "\n\n" + traceback.format_exc())
'''if (sc4mp_ui != None):
if (sc4mp_ui == True):
tk.Tk().withdraw()
messagebox.showerror(SC4MP_TITLE, message)'''
global sc4mp_server_running
sc4mp_server_running = False
#sys.exit()
def set_thread_name(name, enumerate=True):
if enumerate:
thread_names = [thread.name for thread in th.enumerate()]
count = 1
while (sc4mp_server_running):
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:
"""TODO"""
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(e, no_ui=True)
except Exception as e:
show_error(e, no_ui=True)
except Exception as e:
show_error(e, no_ui=True)
# Update config file
self.update()
def __getitem__(self, key):
"""TODO"""
return self.data.__getitem__(key)
def __setitem__(self, key, value):
"""TODO"""
return self.data.__setitem__(key, value)
def update(self):
"""TODO"""
parser = configparser.RawConfigParser()
for section_name, section in self.data.items():
parser.add_section(section_name)
for item_name, item_value in section.items():
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 DBPF:
"""TODO include credits to original php file"""
def __init__(self, filename, offset=0):
"""TODO"""
report('Parsing "' + filename + '"...', self)
self.filename = filename
self.offset = offset
self.NONSENSE_BYTE_OFFSET = 9
# Try opening the file to read bytes
try:
self.file = open(self.filename, 'rb')
except Exception as e:
raise e #TODO
# Advance to offset
start = self.offset
if self.offset > 0:
self.file.seek(self.offset)
# Verify that the file is a DBPF
test = self.file.read(4)
if test != b"DBPF":
return #TODO raise exception
# Read the header
self.majorVersion = self.read_UL4()
self.minorVersion = self.read_UL4()
self.reserved = self.file.read(12)
self.dateCreated = self.read_UL4()
self.dateModified = self.read_UL4()
self.indexMajorVersion = self.read_UL4()
self.indexCount = self.read_UL4()
self.indexOffset = self.read_UL4()
self.indexSize = self.read_UL4()
self.holesCount = self.read_UL4()
self.holesOffset = self.read_UL4()
self.holesSize = self.read_UL4()
self.indexMinorVersion = self.read_UL4() - 1
self.reserved2 = self.file.read(32)
self.header_end = self.file.tell()
# Seek to index table
self.file.seek(offset + self.indexOffset)
# Read index table
self.indexData = []
for index in range(0, self.indexCount):
self.indexData.append({})
self.indexData[index]['typeID'] = self.read_ID()
self.indexData[index]['groupID'] = self.read_ID()
self.indexData[index]['instanceID'] = self.read_ID()
if ((self.indexMajorVersion == "7") and (self.indexMinorVersion == "1")):
self.indexData[index]['instanceID2'] = self.read_ID()
self.indexData[index]['offset'] = self.read_UL4()
self.indexData[index]['filesize'] = self.read_UL4()
self.indexData[index]['compressed'] = False #TODO
self.indexData[index]['truesize'] = 0 #TODO
def decompress(self, length):
#report('Decompressing ' + str(length) + ' bytes...', self)
buf = ""
answer = bytes()
answerlen = 0
numplain = ""
numcopy = ""
offset = ""
while length > 0:
try:
cc = self.read_UL1(self.file)
except Exception as e:
show_error(e)
break
length -= 1
#print("Control char is " + str(cc) + ", length remaining is " + str(length) + ".\n")
if cc >= 252: #0xFC
numplain = cc & 3 #0x03
if numplain > length:
numplain = length
numcopy = 0
offset = 0
elif cc >= 224: #0xE0
numplain = (cc - 223) << 2 #223 = 0xdf
numcopy = 0
offset = 0
elif cc >= 192: #0xC0
length -= 3
byte1 = self.read_UL1(self.file)
byte2 = self.read_UL1(self.file)
byte3 = self.read_UL1(self.file)
numplain = cc & 3 #0x03
numcopy = ((cc & 12) << 6) + 5 + byte3 #12 = 0x0c
offset = ((cc & 16) << 12) + (byte1 << 8) + byte2 #16 = 0x10
elif cc >= 128: #0x80
length -= 2
byte1 = self.read_UL1(self.file)
byte2 = self.read_UL1(self.file)
numplain = (byte1 & 192) >> 6 #192 = 0xc0
numcopy = (cc & 63) + 4 #63 = 0x3f
offset = ((byte1 & 63) << 8) + byte2 #63 = 0x3f
else:
length -= 1
byte1 = self.read_UL1(self.file)
numplain = cc & 3 #3 = 0x03
numcopy = ((cc & 28) >> 2) + 3 #28 = 0x1c
offset = ((cc & 96) << 3) + byte1 #96 = 0x60
length -= numplain
# This section basically copies the parts of the string to the end of the buffer:
if numplain > 0:
buf = self.file.read(numplain)
answer = answer + buf
fromoffset = len(answer) - (offset + 1) # 0 == last char
for index in range(numcopy):
#print(str(answer))
#print(str(cc))
#print(str(offset))
#print(str(fromoffset))
#TODO remove try and except block. decompression algorithm breaks with a control char of 206. the offset becomes larger than the length of the answer, causing a negative fromindex and an indexing error. for now it does not seem to affect city coordinates
try:
answer = answer + (answer[fromoffset + index]).to_bytes(1, 'little') #substr(fromoffset + index, 1)
except Exception as e:
#show_error(e) #TODO
return io.BytesIO(answer)
answerlen += numplain
answerlen += numcopy
return io.BytesIO(answer)
def read_UL1(self, file=None):
"""TODO"""
if file is None:
file = self.file
return struct.unpack('<B', file.read(1))[0]
def read_UL2(self, file=None):
"""TODO"""
if file is None:
file = self.file
return struct.unpack('<H', file.read(2))[0]
def read_UL4(self, file=None):
"""TODO"""
if file is None:
file = self.file
return struct.unpack('<L', file.read(4))[0]
def read_ID(self, file=None):
"""TODO"""
if file is None:
file = self.file
return file.read(4)[::-1].hex()
def get_indexData_entry_by_type_ID(self, type_id):
"""TODO"""
for entry in self.indexData:
if entry['typeID'] == type_id:
return entry
def goto_subfile(self, type_id):
"""TODO"""
entry = self.get_indexData_entry_by_type_ID(type_id)
self.file.seek(entry['offset'])
#print(entry['offset'] + 9)
def get_subfile_size(self, type_id):
"""TODO"""
entry = self.get_indexData_entry_by_type_ID(type_id)
return entry['filesize']
#def get_subfile_header(self, type_id):
# """TODO"""
# self.goto_subfile(type_id)
# return (self.read_UL4(), self.read_ID(), ) #TODO how to read these values?
def decompress_subfile(self, type_id):
"""TODO"""
#report('Decompressing "' + type_id + '"...', self)
self.goto_subfile(type_id)
self.file.read(self.NONSENSE_BYTE_OFFSET)
return self.decompress(self.get_subfile_size(type_id))
def get_SC4ReadRegionalCity(self):
"""TODO"""
report('Parsing region view subfile of "' + self.filename + '"...', self)