-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_main.py
More file actions
7558 lines (7167 loc) · 372 KB
/
Copy path_main.py
File metadata and controls
7558 lines (7167 loc) · 372 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
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
import sublime
import sublime_plugin
import threading
import time
import struct
import zlib
import random
import os
import re
import csv
import platform
import hashlib
import ctypes
import socket
from urllib.parse import quote
SERVERS = []
LISTSERVER_SEED = 4
LISTSERVER_ICONS = (
"\U0001f310",
"\U0001f4e1",
"\U0001f9ed",
"\U0001f4ab",
"\u2728",
"\U0001f680",
"\U0001f6f0\ufe0f",
"\U0001f5a5\ufe0f",
)
GSCRIPT_EDITOR_COLOR_SCHEME = "Packages/SublimeRC/SublimeRC-gscript-editor.sublime-color-scheme"
GOPTION_EDITOR_COLOR_SCHEME = "Packages/SublimeRC/SublimeRC-goption-editor.sublime-color-scheme"
def getSetting(key, default=""):
settings = sublime.load_settings("SublimeRC.sublime-settings")
return settings.get(key, default)
def sortKey(name):
name_lower = name.lower()
prefix = '0' if name_lower[:1].isalnum() else '1'
return prefix + name_lower
def getCleanServerName(server_name):
cleaned = re.sub(r'^[🪙⏳🕶️🚧🌍]\s*', '', server_name)
return sanitizePath(cleaned.strip())
def sanitizePath(path):
invalid_chars = r'[\\/:*?"<>|]'
parts = path.split('/')
sanitized_parts = [re.sub(invalid_chars, '_', part) for part in parts]
return '/'.join(sanitized_parts)
def sanitizeDisplayFilename(name):
return re.sub(r'[\\/:*?"<>|]+', '_', name).strip() or "Untitled"
def urlEncodeFilename(filename):
safe_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.'
return ''.join(char if char in safe_chars else '%{:02X}'.format(ord(char)) for char in filename)
def getScriptsFolder():
settings = sublime.load_settings("SublimeRC.sublime-settings")
default_folder = os.path.join(os.path.expanduser("~"), "SublimeRC") if platform.system() != "Windows" else "C:/SublimeRC"
folder = settings.get("scripts_folder", default_folder)
return os.path.normpath(folder)
def md5RevHex(data):
if not data:
return ""
digest = hashlib.md5(bytes(data or b"")).digest()
hexchars = "0123456789abcdef"
return ''.join(hexchars[b & 0x0f] + hexchars[(b >> 4) & 0x0f] for b in digest)
def getWindowsIDBytes():
if platform.system() != "Windows":
return b""
try:
import winreg
paths = (
r"Software\Microsoft\Windows\CurrentVersion",
r"Software\Microsoft\Windows NT\CurrentVersion",
)
for path in paths:
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) as key:
value, _ = winreg.QueryValueEx(key, "DigitalProductId")
if value:
return bytes(value)
except OSError:
pass
except:
pass
return b""
def getNetworkIDBytes():
if platform.system() != "Windows":
return b""
try:
class IP_ADDR_STRING(ctypes.Structure):
pass
IP_ADDR_STRING._fields_ = [
("Next", ctypes.POINTER(IP_ADDR_STRING)),
("IpAddress", ctypes.c_char * 16),
("IpMask", ctypes.c_char * 16),
("Context", ctypes.c_ulong),
]
class IP_ADAPTER_INFO(ctypes.Structure):
pass
IP_ADAPTER_INFO._fields_ = [
("Next", ctypes.POINTER(IP_ADAPTER_INFO)),
("ComboIndex", ctypes.c_ulong),
("AdapterName", ctypes.c_char * 260),
("Description", ctypes.c_char * 132),
("AddressLength", ctypes.c_uint),
("Address", ctypes.c_ubyte * 8),
("Index", ctypes.c_ulong),
("Type", ctypes.c_uint),
("DhcpEnabled", ctypes.c_uint),
("CurrentIpAddress", ctypes.POINTER(IP_ADDR_STRING)),
("IpAddressList", IP_ADDR_STRING),
("GatewayList", IP_ADDR_STRING),
("DhcpServer", IP_ADDR_STRING),
("HaveWins", ctypes.c_bool),
("PrimaryWinsServer", IP_ADDR_STRING),
("SecondaryWinsServer", IP_ADDR_STRING),
("LeaseObtained", ctypes.c_long),
("LeaseExpires", ctypes.c_long),
]
iphlpapi = ctypes.WinDLL("iphlpapi")
size = ctypes.c_ulong(0)
if iphlpapi.GetAdaptersInfo(None, ctypes.byref(size)) != 111 or size.value <= 0:
return b""
buf = ctypes.create_string_buffer(size.value)
if iphlpapi.GetAdaptersInfo(ctypes.cast(buf, ctypes.POINTER(IP_ADAPTER_INFO)), ctypes.byref(size)) != 0:
return b""
adapter = ctypes.cast(buf, ctypes.POINTER(IP_ADAPTER_INFO))
while adapter:
info = adapter.contents
if info.AddressLength >= 6:
ip = info.IpAddressList.IpAddress.decode("ascii", errors="ignore").strip("\x00")
if ip and ip not in ("0", "0.0.0.0", "127.0.0.1"):
return bytes(info.Address[:6])
adapter = info.Next
except:
pass
return b""
def getHarddiskIDBytes():
if platform.system() != "Windows":
return b""
try:
serial = ctypes.c_ulong(0)
ok = ctypes.windll.kernel32.GetVolumeInformationW(
ctypes.c_wchar_p("C:\\"),
None,
0,
ctypes.byref(serial),
None,
None,
None,
0
)
if ok:
return int(serial.value).to_bytes(4, "little", signed=False)
except:
pass
return b""
def generatePcid(account=None):
return gtokenize("\n".join([
"win",
md5RevHex(getWindowsIDBytes()),
md5RevHex(getNetworkIDBytes()),
md5RevHex(getHarddiskIDBytes()),
]))
class ListServerScrambler:
def __init__(self, seed):
self.mask = 0x4A80B38
self.seed = seed
self.MASK_ROTATION = 0x8088405
def decrypt(self, data):
result = bytearray(data)
rotations = 4
offset = 0
while offset < 4 * rotations and offset < len(data):
self.mask = (self.mask * self.MASK_ROTATION + self.seed) & 0xFFFFFFFF
index = offset
while index < len(data) and index < offset + 4:
byte_mask = (self.mask >> (8 * (index % 4))) & 0xFF
result[index] = data[index] ^ byte_mask
index += 1
offset += 4
return bytes(result)
def writeGByte(value): return (value & 0xFF) + 0x20
def decodeGByte(byte): return (byte & 0xFF) - 0x20
def writeGShort(value):
high = ((value >> 7) & 0xFF) + 32
low = (value & 0x7F) + 32
return bytes([high, low])
def decodeGShort(data, offset=0):
return ((data[offset] - 32) << 7) + (data[offset + 1] - 32)
def writeGInt3(value):
b0 = ((value >> 14) & 0x7F) + 32
b1 = ((value >> 7) & 0x7F) + 32
b2 = (value & 0x7F) + 32
return bytes([b0, b1, b2])
def decodeGInt3(data, offset=0):
return ((data[offset] - 32) << 14) + ((data[offset + 1] - 32) << 7) + (data[offset + 2] - 32)
def findTerminator(buf, start=0):
for i in range(start, len(buf)):
if buf[i] == 0x0A: return i
return -1
def getCredentials(cls):
if cls.connected_server and cls.connected_server.get('listserver_config'):
config = cls.connected_server['listserver_config']
return config['account'], config['password']
return getSetting('account'), getSetting('password')
def scrambleData(data, seed, compression_type):
mask = 0x4A80B38
MASK_ROTATION = 0x8088405
result = bytearray(data)
rotations = 12 if compression_type == 0x02 else 4
offset = 0
while offset < 4 * rotations and offset < len(data):
mask = (mask * MASK_ROTATION + seed) & 0xFFFFFFFF
index = offset
while index < len(data) and index < offset + 4:
byte_mask = (mask >> (8 * (index % 4))) & 0xFF
result[index] = data[index] ^ byte_mask
index += 1
offset += 4
return bytes(result)
def getListserverConfigs():
settings = sublime.load_settings("SublimeRC.sublime-settings")
configs = []
default_config = {
"name": getSetting("listserver_name", "Listserver"),
"host": getSetting("listserver_host", "127.0.0.1"),
"port": getSetting("listserver_port", 14922),
"account": getSetting("listserver_account", getSetting("account", "")),
"password": getSetting("listserver_password", getSetting("password", ""))
}
configs.append(default_config)
i = 1
while True:
host_key = "listserver_host{}".format(i)
port_key = "listserver_port{}".format(i)
name_key = "listserver_name{}".format(i)
account_key = "listserver_account{}".format(i)
password_key = "listserver_password{}".format(i)
host = settings.get(host_key)
if not host: break
config = {
"name": settings.get(name_key, "Listserver {}".format(i)),
"host": host,
"port": settings.get(port_key, 14922),
"account": settings.get(account_key, getSetting("account", "")),
"password": settings.get(password_key, getSetting("password", ""))
}
configs.append(config)
i += 1
return configs
def getListserverIcon(config):
key = "{}|{}|{}".format(
str(config.get("host", "")).lower(),
str(config.get("name", "")).lower(),
config.get("port", "")
)
index = (zlib.crc32(key.encode("utf-8")) + LISTSERVER_SEED) % len(LISTSERVER_ICONS)
return LISTSERVER_ICONS[index]
def getListserverLabel(config):
account = config.get("account") or "unknown"
return "{} {} ({})".format(getListserverIcon(config), config.get("name", "Listserver"), account)
def fetchServerList(listserver_config=None):
if listserver_config is None:
listserver_config = {
"host": getSetting("listserver_host", "127.0.0.1"),
"port": getSetting("listserver_port", 14922),
"account": getSetting("account", ""),
"password": getSetting("password", "")
}
sock = None
listserver_debug = bool(getSetting("listserver_debug", False))
def debug(message):
if listserver_debug:
print(message)
try:
listserver_host = listserver_config["host"]
listserver_port = listserver_config["port"]
listserver_account = listserver_config["account"]
listserver_password = listserver_config["password"]
debug("Connecting to {}:{}".format(listserver_host, listserver_port))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(15.0)
sock.connect((listserver_host, listserver_port))
debug("Connected, sending edition packet")
edition_payload = bytearray()
edition_payload.append(writeGByte(7))
edition_payload.append(writeGByte(4))
edition_payload.extend(b"G3D30123")
edition_payload.extend(b"rc2")
edition_payload.append(0x0a)
compressed_edition = zlib.compress(bytes(edition_payload))
edition_packet = struct.pack('>H', len(compressed_edition)) + compressed_edition
sock.send(edition_packet)
debug("Edition sent, waiting...")
time.sleep(0.2)
debug("Sending login packet")
login_payload = bytearray()
login_payload.append(writeGByte(1))
login_payload.append(writeGByte(len(listserver_account)))
login_payload.extend(listserver_account.encode('latin-1'))
login_payload.append(writeGByte(len(listserver_password)))
login_payload.extend(listserver_password.encode('latin-1'))
login_payload.append(0x0a)
if len(login_payload) > 40:
compressed_login = zlib.compress(bytes(login_payload))
compression_type = 0x04
else:
compressed_login = bytes(login_payload)
compression_type = 0x02
encrypted_login = scrambleData(compressed_login, LISTSERVER_SEED, compression_type)
login_packet = struct.pack('>H', len(encrypted_login) + 1) + bytes([compression_type]) + encrypted_login
sock.send(login_packet)
debug("Login sent (compression {}), waiting for response...".format(compression_type))
length_bytes = sock.recv(2)
if len(length_bytes) != 2:
debug("Failed to read packet length")
return []
packet_length = struct.unpack('>H', length_bytes)[0]
debug("Reading {} bytes".format(packet_length))
packet_data = bytearray()
while len(packet_data) < packet_length:
chunk = sock.recv(packet_length - len(packet_data))
if not chunk: break
packet_data.extend(chunk)
if len(packet_data) < packet_length:
debug("Incomplete packet: got {} of {}".format(len(packet_data), packet_length))
return []
debug("Received packet, decoding...")
format_type = packet_data[0]
debug("Format type: {}".format(format_type))
unscrambled = scrambleData(bytes(packet_data[1:]), LISTSERVER_SEED, format_type)
try: decompressed = zlib.decompress(unscrambled)
except Exception as e:
debug("Decompress failed: {}".format(str(e)))
decompressed = unscrambled
debug("Decompressed {} bytes".format(len(decompressed)))
servers = []
offset = 0
if offset >= len(decompressed): return []
packet_type = decodeGByte(decompressed[offset])
offset += 1
debug("Packet type: {}".format(packet_type))
if packet_type != 0:
if packet_type == 16:
msg = decompressed[offset:].decode('latin-1', errors='ignore').split('\n')[0]
debug("Server rejected: {}".format(msg))
elif packet_type == 4:
msg = decompressed[offset:].decode('latin-1', errors='ignore').strip()
debug("Server disconnected: {}".format(msg))
return []
if offset >= len(decompressed): return []
server_count = decodeGByte(decompressed[offset])
offset += 1
debug("Server count: {}".format(server_count))
for _ in range(server_count):
if offset >= len(decompressed): break
attr_count = decodeGByte(decompressed[offset])
offset += 1
attributes = []
for _ in range(attr_count):
if offset >= len(decompressed): break
attr_len = decodeGByte(decompressed[offset])
offset += 1
if offset + attr_len > len(decompressed): break
attr_value = decompressed[offset:offset + attr_len].decode('latin-1', errors='ignore')
attributes.append(attr_value)
offset += attr_len
if len(attributes) >= 8:
servers.append({"name": ("{} {}".format({"P": "🪙", "H": "⏳", "3": "🕶️", "U": "🚧"}[attributes[0][0]], attributes[0][2:]) if len(attributes[0]) > 2 and attributes[0][1] == ' ' and attributes[0][0] in "PH3U" else "🌍 " + attributes[0]), "ip": attributes[6], "port": int(attributes[7]), "type": "listserver", "language": attributes[1], "description": attributes[2], "players": int(attributes[5])})
return servers
except Exception as e:
debug("Listserver error ({}): {}".format(type(e).__name__, str(e)))
return []
finally:
if sock:
try: sock.close()
except: pass
def get1PlusTextNetString(s):
if len(s) > 223: return chr(255) + s[223:]
else: return chr(32 + len(s)) + s
def gtokenize(text):
text = text.replace('\r', '')
lines = text.split('\n')
result = []
for line in lines:
if not line:
result.append('')
continue
needs_quotes = False
if line[0] == '"':
needs_quotes = True
for char in line:
if ord(char) < 33 or ord(char) > 126 or char in ',/':
needs_quotes = True
break
if line.strip() == '': needs_quotes = True
if needs_quotes:
escaped = line.replace('\\', '\\\\').replace('"', '""')
result.append('"' + escaped + '"')
else: result.append(line)
return ','.join(result)
def gtokenizeReverse(content):
output = []
currently_inside_quotes = False
line_quoted = False
pos = 0
i = 0
while i < len(content):
if content[i] == '"':
if currently_inside_quotes:
if i + 1 < len(content) and content[i + 1] == '"':
i += 1
i += 1
continue
line_quoted = True
currently_inside_quotes = not currently_inside_quotes
if not currently_inside_quotes:
if content[i] == ',' or i + 1 == len(content):
line_start = pos + (1 if line_quoted else 0)
line_length = i - pos - (2 if line_quoted else 0) + (1 if i + 1 == len(content) and content[i] != ',' else 0)
line = content[line_start:line_start + line_length]
if line_quoted:
line = line.replace('""', '"')
line = line.replace('\\\\', '\\')
line = line.replace('\n', '')
line = line.replace('\r', '')
output.append(line)
pos = i + 1
line_quoted = False
i += 1
return '\n'.join(output)
class GRCProtocol:
def __init__(self):
self.encryption_key = None
self.iterator_out = 0x4A80B38
self.iterator_in = 0x4A80B38
def setEncryptionKey(self, key): self.encryption_key = key
def getIteratorLimit(self, compression_type): return 0x0C if compression_type == 0x02 else 0x04
def applyEncryption(self, direction, buf, compression_type):
if self.encryption_key is None or not buf: return buf
limit = self.getIteratorLimit(compression_type)
result = bytearray(buf)
for i in range(len(result)):
if i % 4 == 0:
if limit <= 0: break
limit -= 1
if direction == 0:
self.iterator_out = (self.iterator_out * 0x8088405 + self.encryption_key) & 0xFFFFFFFF
iterator_val = self.iterator_out
else:
self.iterator_in = (self.iterator_in * 0x8088405 + self.encryption_key) & 0xFFFFFFFF
iterator_val = self.iterator_in
result[i] ^= (iterator_val >> ((i % 4) * 8)) & 0xFF
return bytes(result)
def sendPacket(self, socket_conn, packet_type, data):
payload = bytearray()
payload.append(packet_type + 32)
payload.extend(data)
payload.append(0x0A)
if len(data) > 40:
compressed_payload = zlib.compress(payload)
compression_type = 0x04
else:
compressed_payload = payload
compression_type = 0x02
if self.encryption_key is not None:
encrypted_buffer = self.applyEncryption(0, compressed_payload, compression_type)
length = len(encrypted_buffer) + 1
final_packet = struct.pack('>H', length) + bytes([compression_type]) + encrypted_buffer
else:
length = len(compressed_payload)
final_packet = struct.pack('>H', length) + compressed_payload
socket_conn.send(final_packet)
return final_packet
def sendRawBlock(self, socket_conn, data):
raw_payload = bytes(data)
if len(raw_payload) > 40:
compressed_payload = zlib.compress(raw_payload)
compression_type = 0x04
else:
compressed_payload = raw_payload
compression_type = 0x02
if self.encryption_key is not None:
encrypted_buffer = self.applyEncryption(0, compressed_payload, compression_type)
length = len(encrypted_buffer) + 1
final_packet = struct.pack('>H', length) + bytes([compression_type]) + encrypted_buffer
else:
length = len(compressed_payload)
final_packet = struct.pack('>H', length) + compressed_payload
socket_conn.send(final_packet)
return final_packet
def decrypt(self, buf):
if self.encryption_key is None: return buf
if len(buf) < 1: return buf
compression_type = buf[0]
encrypted_data = buf[1:]
decrypted_data = self.applyEncryption(1, encrypted_data, compression_type)
if compression_type == 0x04:
try: return zlib.decompress(decrypted_data)
except: return decrypted_data
else: return decrypted_data
class NCProtocol:
def __init__(self):
self.iterator = 0x4A80B38
def sendPacket(self, socket_conn, packet_type, data):
payload = bytearray()
payload.append(packet_type + 32)
payload.extend(data)
payload.append(0x0A)
compressed_payload = zlib.compress(payload)
length_bytes = struct.pack('>H', len(compressed_payload))
socket_conn.send(length_bytes + compressed_payload)
return length_bytes + compressed_payload
def decrypt(self, buf):
try: return zlib.decompress(buf)
except: return buf
class GPlugin:
RIGHTS_NAMES = [
'Warp to XY', 'Warp to Player', 'Warp player', 'Update Level',
'Disconnect', 'View Attributes', 'Set Attributes', 'Set Own Attributes',
'Reset Attributes', 'Admin Message', 'Change Rights', 'Ban Players',
'Comments', '', 'Staff Accounts', 'Server Flags',
'Server Options', 'Folder Configuration', 'Folder Rights', 'NPC Control'
]
COLOR_NAMES = ['White', 'Yellow', 'Orange', 'Pink', 'Red', 'Darkred', 'Lightgreen', 'Green', 'Darkgreen', 'Lightblue', 'Blue', 'Darkblue', 'Brown', 'Cynober', 'Purple', 'Darkpurple', 'Lightgray', 'Gray', 'Black', 'Transparent']
servers = []
weapons = []
classes = []
npcs = []
players = []
external_players = {}
pm_servers = []
pm_server_players = {}
pm_server_update_timers = {}
recent_servers = []
next_external_id = 16000
weapon_scripts = {}
class_scripts = {}
npc_scripts = {}
npc_flags = {}
server_options = None
server_flags = None
folder_config = None
pending_weapon_request = None
pending_class_request = None
pending_npc_request = None
pending_npc_flags_request = None
pending_npc_props_request = None
pending_account_request = None
player_accounts = {}
pending_weapon_callback = None
pending_class_callback = None
pending_npc_callback = None
npc_sort_timer = None
class_sort_timer = None
connected_server = None
socket_connection = None
nc_socket = None
protocol = None
nc_protocol = None
output_panel = None
file_browser_log_view = None
toalls_log_view = None
compiler_log_view = None
nc_log_view = None
authenticated = False
nc_authenticated = False
switching_servers = False
has_set_nickname = False
has_received_welcome = False
shown_not_authenticated = False
npc_server_address = None
npcserver_player_id = None
debug_mode = False
ignore_world_time_debug = True
pending_player_rights_request = None
pending_player_attrs_request = None
pending_player_comments_request = None
pending_player_profile_request = None
account_list = []
account_list_callback = None
player_rights = {}
player_attributes = {}
player_comments = {}
player_profiles = {}
pending_player_ban_request = None
pending_player_ban_request_id = None
player_bans = {}
ban_types = []
isNewProtocol = False
current_listserver_config = None
folders = []
current_folder = None
folder_files = []
file_transfers = {}
pending_file_download = None
open_after_download = False
external_file_watchers = {}
external_file_watch_timer = None
file_upload_chunk_size = 49152
expecting_folder_list = False
pending_local_npcs_request = None
find_results = []
find_result_base = ""
find_result_links = {}
pending_server_options_request = False
pending_server_flags_request = False
pending_folder_config_request = False
pending_pm_server_request = None
private_messages = {}
private_message_order = []
private_message_open_index = 0
pm_chat_links = {}
irc_channels = {}
irc_bootstrapped = False
compiler_output_target = None
npc_defined_commands = set()
LISTSERVER_CLIENT = {
"EDITION_PACKET": 7,
"EDITION_TYPE": 4,
"LOGIN_PACKET": 1,
"ERROR_REJECTED": 16,
"ERROR_DISCONNECTED": 4
}
RC_TO_SERVER = {
"PLI_TOALL": 6,
"PLI_RAWDATA": 50,
"PLI_RC_SERVEROPTIONSGET": 51, "PLI_RC_SERVEROPTIONSSET": 52, "PLI_RC_FOLDERCONFIGGET": 53, "PLI_RC_FOLDERCONFIGSET": 54,
"PLI_RC_RESPAWNSET": 55, "PLI_RC_HORSELIFESET": 56, "PLI_RC_APINCREMENTSET": 57, "PLI_RC_BODYRESPAWNSET": 58,
"PLI_RC_PLAYERPROPSGET": 59, "PLI_RC_PLAYERPROPSSET": 2, "PLI_PRIVATEMESSAGE": 28, "PLI_RC_DISCONNECTPLAYER": 61, "PLI_RC_UPDATELEVELS": 62,
"PLI_RC_ADMINMESSAGE": 63, "PLI_RC_PRIVADMINMESSAGE": 64, "PLI_RC_LISTRCS": 65, "PLI_RC_DISCONNECTRC": 66,
"PLI_RC_APPLYREASON": 67, "PLI_RC_SERVERFLAGSGET": 68, "PLI_RC_SERVERFLAGSSET": 69, "PLI_RC_ACCOUNTADD": 70,
"PLI_RC_ACCOUNTDEL": 71, "PLI_RC_ACCOUNTLISTGET": 72, "PLI_RC_PLAYERPROPSGET2": 73, "PLI_RC_PLAYERPROPSGET3": 74,
"PLI_RC_PLAYERPROPSRESET": 75, "PLI_RC_PLAYERPROPSSET2": 76, "PLI_RC_ACCOUNTGET": 77, "PLI_RC_ACCOUNTSET": 78,
"PLI_RC_CHAT": 79, "PLI_RC_PROFILEGET": 80, "PLI_RC_PROFILESET": 81, "PLI_RC_WARPPLAYER": 82,
"PLI_RC_PLAYERRIGHTSGET": 83, "PLI_RC_PLAYERRIGHTSSET": 84, "PLI_RC_PLAYERCOMMENTSGET": 85, "PLI_RC_PLAYERCOMMENTSSET": 86,
"PLI_RC_PLAYERBANGET": 87, "PLI_RC_PLAYERBANSET": 88, "PLI_RC_FILEBROWSER_START": 89, "PLI_RC_FILEBROWSER_CD": 90,
"PLI_RC_FILEBROWSER_END": 91, "PLI_RC_FILEBROWSER_DOWN": 92, "PLI_RC_FILEBROWSER_UP": 93, "PLI_NPCSERVERQUERY": 94,
"PLI_RC_FILEBROWSER_MOVE": 96, "PLI_RC_FILEBROWSER_DELETE": 97, "PLI_RC_FILEBROWSER_RENAME": 98, "PLI_NC_LISTNPCS": 100,
"PLI_NC_NPCGET": 103, "PLI_NC_NPCDELETE": 104, "PLI_NC_NPCRESET": 105, "PLI_NC_NPCSCRIPTGET": 106,
"PLI_NC_NPCWARP": 107, "PLI_NC_NPCFLAGSGET": 108, "PLI_NC_NPCSCRIPTSET": 109, "PLI_NC_NPCFLAGSSET": 110,
"PLI_NC_NPCADD": 111, "PLI_NC_CLASSEDIT": 112, "PLI_NC_CLASSADD": 113, "PLI_NC_LOCALNPCSGET": 114,
"PLI_NC_WEAPONLISTGET": 115, "PLI_NC_WEAPONGET": 116, "PLI_NC_WEAPONADD": 117, "PLI_NC_WEAPONDELETE": 118,
"PLI_NC_CLASSDELETE": 119, "PLI_REQUESTUPDATEBOARD": 130, "PLI_NC_LEVELLISTGET": 150, "PLI_NC_LEVELLISTSET": 151,
"PLI_REQUESTTEXT": 152, "PLI_SENDTEXT": 154, "PLI_RC_LARGEFILESTART": 155, "PLI_RC_LARGEFILEEND": 156,
"PLI_UPDATEGANI": 157, "PLI_UPDATESCRIPT": 158, "PLI_UPDATEPACKAGEREQUESTFILE": 159, "PLI_RC_FOLDERDELETE": 160,
"PLI_UPDATECLASS": 161
}
NC_TO_SERVER = {
"PLI_NC_LOGIN": 3,
"PLI_NC_NPCGET": 103, "PLI_NC_NPCDELETE": 104, "PLI_NC_NPCRESET": 105, "PLI_NC_NPCSCRIPTGET": 106,
"PLI_NC_NPCWARP": 107, "PLI_NC_NPCFLAGSGET": 108, "PLI_NC_NPCSCRIPTSET": 109, "PLI_NC_NPCFLAGSSET": 110,
"PLI_NC_NPCADD": 111, "PLI_NC_CLASSEDIT": 112, "PLI_NC_CLASSADD": 113, "PLI_NC_LOCALNPCSGET": 114,
"PLI_NC_WEAPONLISTGET": 115, "PLI_NC_WEAPONGET": 116, "PLI_NC_WEAPONADD": 117, "PLI_NC_WEAPONDELETE": 118,
"PLI_NC_CLASSDELETE": 119, "PLI_NC_LEVELLISTGET": 150, "PLI_NC_LEVELLISTSET": 151
}
prop_map = {
'Account': (34, str),
'Hearts': (1, int),
'Full Hearts': (2, lambda x: int(float(x) * 2)),
'Level': (20, str),
'X': (5, float),
'Y': (6, float),
5: ('x', float),
6: ('y', float),
17: ('glove', int),
19: ('bombs', int),
4: (4, int),
'Sword Power': ('sword_power', str),
'Sword Image': ('sword_image', str),
'Shield Power': ('shield_power', str),
'Shield Image': ('shield_image', str),
'Head Image': ('head_image', str),
'Body Image': ('body_image', str),
'Health': (26, int),
'Max Health': (27, int),
'MP': (27, int),
'Max Magic': (28, int),
'Gralats': (30, int),
'Glove': (17, int),
'Bombs': (19, int),
'Male': ('status_male', lambda x: 4 if x.lower() == 'true' else 0),
'Weapons Enabled': ('status_weapons', lambda x: 16 if x.lower() == 'true' else 0),
'Spin Attack': ('status_spin', lambda x: 64 if x.lower() == 'true' else 0),
}
color_map = {
'Skin Color': 0,
'Coat Color': 1,
'Sleeves Color': 2,
'Shoes Color': 3,
'Belt Color': 4,
}
status_map = {
'Paused': 1,
'Hidden': 2,
'Male': 4,
'Dead': 8,
'Weapons allowed': 16,
'Hide sword': 32,
'Has spin attack': 64,
}
SERVER_TO_RC = {
"PLO_PLAYERPROPS": 8, "PLO_UNKNOWN11": 11, "PLO_TOALL": 13, "PLO_FILESENDFAILED": 30,
"PLO_NEWWORLDTIME": 42,
"PLO_RC_ADMINMESSAGE": 35, "PLO_RC_ACCOUNTADD": 50, "PLO_RC_ACCOUNTSTATUS": 51, "PLO_RC_ACCOUNTNAME": 52, "PLO_RC_ACCOUNTDEL": 53,
"PLO_RC_ACCOUNTPROPS": 54, "PLO_ADDPLAYER": 55, "PLO_DELPLAYER": 56, "PLO_RC_ACCOUNTPROPSGET": 57, "PLO_RC_ACCOUNTCHANGE": 58,
"PLO_RC_PLAYERPROPSCHANGE": 59, "PLO_UNKNOWN60": 60, "PLO_RC_SERVERFLAGSGET": 61, "PLO_RC_PLAYERRIGHTSGET": 62,
"PLO_RC_PLAYERCOMMENTSGET": 63, "PLO_RC_PLAYERBANGET": 64, "PLO_RC_FILEBROWSER_DIRLIST": 65, "PLO_RC_FILEBROWSER_DIR": 66,
"PLO_RC_FILEBROWSER_MESSAGE": 67, "PLO_LARGEFILESTART": 68, "PLO_LARGEFILEEND": 69, "PLO_RC_ACCOUNTLISTGET": 70,
"PLO_RC_PLAYERPROPS": 71, "PLO_RC_PLAYERPROPSGET": 72, "PLO_RC_ACCOUNTGET": 73, "PLO_RC_CHAT": 74, "PLO_PROFILE": 75,
"PLO_RC_SERVEROPTIONSGET": 76, "PLO_RC_FOLDERCONFIGGET": 77, "PLO_NC_CONTROL": 78, "PLO_NPCSERVERADDR": 79, "PLO_NC_LEVELLIST": 80,
"PLO_SERVERTEXT": 82, "PLO_EDITION_PACKET": 16, "PLO_RC_LOGIN": 25, "PLO_PRIVATEMESSAGE": 37, "PLO_BOARDPACKET": 101, "PLO_SVI_SERVERINFO": 47,
"PLO_LARGEFILESIZE": 84, "PLO_FILE": 102, "PLO_NC_NPCATTRIBUTES": 103,
"PLO_RC_MAXUPLOADFILESIZE": 103, "PLO_NC_NPCADD": 158,
"PLO_NC_NPCDELETE": 159, "PLO_NC_NPCSCRIPT": 160, "PLO_NC_NPCFLAGS": 161, "PLO_NC_CLASSGET": 162,
"PLO_NC_CLASSADD": 163, "PLO_NC_LEVELDUMP": 164, "PLO_NC_WEAPONLISTGET": 167, "PLO_NC_CLASSDELETE": 188, "PLO_STATUSLIST": 180,
"PLO_NC_WEAPONGET": 192, "PLO_CLEARWEAPONS": 194, "PLO_UNKNOWN190": 190
}
SERVER_TO_NC = {
"PLO_NC_NPCATTRIBUTES": 157, "PLO_NC_NPCADD": 158, "PLO_NC_NPCDELETE": 159, "PLO_NC_NPCSCRIPT": 160,
"PLO_NC_NPCFLAGS": 161, "PLO_NC_CLASSGET": 162, "PLO_NC_CLASSADD": 163, "PLO_NC_LEVELDUMP": 164,
"PLO_NC_WEAPONLISTGET": 167, "PLO_NC_CLASSDELETE": 188, "PLO_NC_WEAPONGET": 192
}
@classmethod
def log(cls, message, debug_only=False, show_panel=False):
if debug_only and not cls.debug_mode: return
if debug_only: message = "Debug: " + message
try:
if "Game files found (relative to" in message:
import re
match = re.search(r'relative to\s+(.+?),\s*max', message)
cls.find_result_base = match.group(1).strip() if match else ""
cls.find_results = []
cls.find_results.append(message)
cls.logFileBrowser(message)
return
parsed_find_result = cls.parseFindResultMessage(message)
if parsed_find_result:
filename, status, ftype, size, date = parsed_find_result
cls.find_results.append(message)
cls.showFindResultLine(filename, status, ftype, size, date)
return
if "Also found default files matching this" in message:
cls.logFileBrowser(message)
return
if cls.isFileBrowserChatMessage(message):
cls.logFileBrowser(message)
return
if cls.handleScriptCompilerMessage(message):
return
if cls.isScriptUpdateMessage(message):
cls.logCompiler(message)
return
cls.logPlain(message, show_panel)
except Exception as e:
print("RC log error:", str(e))
cls.logPlain(message, show_panel)
@classmethod
def isFileBrowserChatMessage(cls, message):
message_lower = message.lower()
return bool(re.search(r'\bprob:\s+file\s+.+\s+not found\b', message_lower))
@classmethod
def parseFindResultMessage(cls, message):
import re
match = re.match(r'^\[[^\]]+\]\s+', message)
message_content = message[match.end():] if match else message
match = re.match(r'^([^:]+):\s*(.*?),\s*(?:(.*?),\s*)?(\d+)\s*byte,\s*(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})', message_content)
if not match:
return None
filename, status, ftype, size, date = match.groups()
if "/" not in filename and "." not in filename:
return None
return filename, status, ftype or "", size, date
@classmethod
def handleScriptCompilerMessage(cls, message):
import re
target_match = re.match(r'^Script compiler output for\s+(.+):$', message)
if target_match:
cls.compiler_output_target = target_match.group(1).strip()
cls.logCompiler(message)
return True
error_match = re.search(r'\berror:\s+(.+?)\s+at line\s+(\d+):\s*(.*)$', message)
if error_match and cls.compiler_output_target:
error_text = error_match.group(1).strip()
line_number = int(error_match.group(2))
line_text = error_match.group(3).strip()
cls.logCompiler(message)
cls.markScriptCompilerError(cls.compiler_output_target, line_number, error_text, line_text)
return True
if cls.compiler_output_target and (
message.startswith("Will keep running the old NPC script")
or message.startswith("Script compiler")
or message.lower().startswith("warning:")
):
cls.logCompiler(message)
return True
return False
@classmethod
def isScriptUpdateMessage(cls, message):
return bool(
re.search(r'\bWeapon/GUI-script .+ added/updated by\b', message)
or re.search(r'\bThe script of NPC .+ has been updated by\b', message)
or re.search(r'\bScript .+ updated by\b', message)
)
@classmethod
def markScriptCompilerError(cls, target, line_number, error_text, line_text):
target_lower = target.lower()
annotation = "{}: {}".format(error_text, line_text) if line_text else error_text
flags = sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_SQUIGGLY_UNDERLINE
for window in sublime.windows():
for view in window.views():
names = [
view.settings().get("rc_weapon_name"),
view.settings().get("rc_class_name"),
view.settings().get("rc_npc_name")
]
display_name = view.settings().get("rc_display_name") or view.name()
if display_name:
names.append(display_name)
if not any(name and target_lower in str(name).lower() for name in names):
continue
point = view.text_point(max(line_number - 1, 0), 0)
line_region = view.line(point)
if line_region.empty():
line_region = sublime.Region(point, point)
try:
view.add_regions(
"sublimerc_compile_errors",
[line_region],
"invalid",
"dot",
flags,
annotations=[annotation],
annotation_color="#ff6b6b"
)
except TypeError:
view.add_regions("sublimerc_compile_errors", [line_region], "invalid", "dot", flags)
view.set_status("sublimerc_compile_error", "Line {}: {}".format(line_number, annotation))
window.focus_view(view)
return
@classmethod
def logPlain(cls, message, show_panel=False):
from datetime import datetime
timestamp_console = datetime.now().strftime("%I:%M:%S %p")
timestamp_terminal = datetime.now().strftime("%I:%M:%S %p")
alert_scope = None
if message.startswith('#ALERT'):
match = re.match(r'^#ALERT([A-Z]*)\s*(.*)', message)
if match:
alert_type = '#ALERT' + match.group(1)
alert_msg = match.group(2)
prefix_map = {'#ALERT': '⚠ ALERT ', '#ALERTF': '⚠ ALERT ', '#ALERTP': '🔔 PRIORITY ', '#ALERTFS': '💬 NOTICE ', '#ALERTPS': 'ℹ️ INFO '}
scope_map = {'#ALERT': 'alert.red', '#ALERTF': 'alert.red', '#ALERTP': 'alert.yellow', '#ALERTFS': 'alert.blue', '#ALERTPS': 'alert.green'}
prefix = prefix_map.get(alert_type, 'ALERT ')
alert_scope = scope_map.get(alert_type)
formatted = "[{}] {}{}".format(timestamp_terminal, prefix, alert_msg)
cls.sendAlert(alert_type, None, alert_msg, 'red')
else:
formatted = "[{}] {}".format(timestamp_terminal, message)
else:
formatted = "[{}] {}".format(timestamp_terminal, message)
view = cls.ensureChatView(focus=show_panel)
if view:
view.run_command("rc_chat_append", {"characters": formatted + "\n"})
formatted_console = "[{}] {}".format(timestamp_console, message)
print("RC: " + formatted_console)
@classmethod
def handleRcControlMessage(cls, message):
if message.startswith("#DEFINECMD "):
raw_name = message[len("#DEFINECMD "):].strip()
cmd_name = raw_name.split()[0] if raw_name else ""
if cmd_name and len(cmd_name) < 0x100:
cmd_key = cmd_name.lower()
if not re.fullmatch(r'[0-9a-fA-F]+', cmd_name) and not cmd_key.startswith(("global", "npc")):
cls.npc_defined_commands.add(cmd_key)
cls.log("Registered NPC command alias: /{}".format(cmd_name), debug_only=True)
return True
if message.startswith("#HIDENCMESSAGES"):
return True
if message.startswith("#SHOWNCMESSAGES"):
return True
if message.startswith("#ALERT"):
cls.log(message)
return True
return False
@classmethod
def logPrivateMessageReceived(cls, label, key):
from datetime import datetime
timestamp_console = datetime.now().strftime("%I:%M:%S %p")
timestamp_terminal = datetime.now().strftime("%I:%M:%S %p")
link_text = "from " + label
formatted = "[{}] PM received: {}".format(timestamp_terminal, link_text)
view = cls.ensureChatView()
if view:
view.run_command("rc_chat_append", {"characters": formatted + "\n"})
content = view.substr(sublime.Region(0, view.size()))
line_start = content.rfind(formatted)
if line_start >= 0:
start = line_start + formatted.find(link_text)
end = start + len(link_text)
view_id = view.id()
links = cls.pm_chat_links.setdefault(view_id, [])
links.append((start, end, key))
regions = [sublime.Region(a, b) for a, b, _ in links]
view.add_regions("sublimerc_pm_links", regions, "entity.name.function", "", sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE | sublime.DRAW_SOLID_UNDERLINE)
print("RC: [{}] PM received: {}".format(timestamp_console, link_text))
@classmethod
def showFindResultLine(cls, filename, status, ftype, size, date):
from datetime import datetime
timestamp = datetime.now().strftime("%I:%M:%S %p")
details = [status]
if ftype:
details.append(ftype)
details.extend([size + " byte", date])
formatted = "[{}] {}: {}".format(timestamp, filename, ", ".join(details))
icon = cls.getFileIcon(filename)
file_browser_formatted = "[{}] {} {}: {}".format(timestamp, icon, filename, ", ".join(details))
cls.appendFindResultLineToView(cls.ensureFileBrowserLogView(), file_browser_formatted, filename)
print("RC: " + formatted)
@classmethod
def getFileIcon(cls, filename):
ext = os.path.splitext(filename.lower())[1]
if ext in (".nw", ".graal", ".zelda"):
return "\U0001f5fa\ufe0f"
if ext in (".png", ".gif", ".jpg", ".jpeg", ".bmp", ".webp"):
return "\U0001f5bc\ufe0f"
if ext in (".gani",):
return "\U0001f3ad"
if ext in (".txt", ".log", ".md"):
return "\U0001f4dd"
if ext in (".gs2", ".gscript"):
return "\U0001f4dc"
if ext in (".wav", ".mp3", ".ogg", ".mid", ".midi"):
return "\U0001f3b5"
if ext in (".assetbundle", ".bundle"):
return "\U0001f4e6"
if ext in (".zip", ".rar", ".7z", ".gz"):
return "\U0001f5dc\ufe0f"
return "\U0001f4c4"
@classmethod
def appendFindResultLineToView(cls, view, formatted, filename):
if not view:
return
view.run_command("rc_chat_append", {"characters": formatted + "\n"})
content = view.substr(sublime.Region(0, view.size()))
line_start = content.rfind(formatted)
if line_start < 0:
return
start = line_start + formatted.find(filename)
end = start + len(filename)
base = cls.find_result_base or "levels/"
full_path = (base.rstrip("/") + "/" + filename.lstrip("/")) if base else filename
view_id = view.id()
links = cls.find_result_links.setdefault(view_id, [])