-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner_v2GUI.py
More file actions
3018 lines (2530 loc) · 102 KB
/
scanner_v2GUI.py
File metadata and controls
3018 lines (2530 loc) · 102 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 asyncio, random, socket, struct, json, aiohttp, os, sys, time, sqlite3, subprocess
from colorama import Fore, Style, init
import config.config as config
import threading
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
from ressources.instance_manager import get_instance_manager, StatsMessage
from datetime import datetime
# ======== LOG FUNCTIONS ========
def log_print(message: str, tag: str = None):
"""Print a message to the log text field"""
global logs_text
if not logs_text:
return
try:
# Check if widget still exists
if not logs_text.winfo_exists():
return
logs_text.insert("end", message + "\n", tag)
logs_text.see("end")
except Exception as e:
# Silently ignore GUI errors to prevent crashes
pass
try:
import tkinter as tk
from tkinter import ttk
except Exception:
tk = None
ttk = None
executor = ThreadPoolExecutor(max_workers=max(50, config.CONCURRENCY * 2))
http_session: aiohttp.ClientSession | None = None
last_title_update = 0
last_title_scan_count = 0
# Title update thresholds (can be overridden in config.py)
TITLE_MIN_SECONDS = getattr(config, 'TITLE_MIN_SECONDS', 0.5)
TITLE_SCAN_STEP = getattr(config, 'TITLE_SCAN_STEP', 10)
# GUI references
gui_root = None
scan_log_text = None
logs_text = None
stats_labels = {}
recent_box = None
# Thread-safe GUI message queue
gui_message_queue: Queue = Queue()
gui_queue_processing = False
# Scanner instance control
active_scanners = 1
scanner_instances = [] # List of running scanner tasks
stop_event = asyncio.Event()
# Multi-run control
target_runs = 0 # 0 = infinite (default), 2-10 = number of runs
current_run = 0 # Current run number
runs_completed = 0 # Completed runs counter
# Instance management
instance_mgr = get_instance_manager()
is_worker_mode = False # True if running as worker (no GUI)
worker_stats_lock = threading.Lock()
worker_local_stats = {
"scanned": 0,
"found": 0,
"with_players": 0,
"sent_count": 0
}
# Worker callback functions
def on_worker_stats_received(message):
"""Callback when worker stats are received by master"""
pass # Stats are aggregated in gui_update_stats via get_all_stats()
def on_worker_disconnect(worker_id):
"""Callback when a worker disconnects"""
gui_print(f"[MASTER] Worker {worker_id[:8]}... disconnected", "error")
def on_server_broadcast(server_key: str):
"""Callback when master broadcasts a newly sent server to workers"""
global sent_set
# Add to local sent_set to prevent duplicate sends
# Note: This is called from a thread, so we can't use async with
# The sent_set is thread-safe for this use case
sent_set.add(server_key)
gui_print(f"[SYNC] Received server update from master: {server_key}", "webhook")
init(autoreset=True)
# ========= FARBEN =========
SCAN = Fore.YELLOW
NOSRV = Fore.RED
EMPTY = Fore.GREEN
ONLINE = Fore.GREEN
WEBHOOK = Fore.CYAN
ERROR = Fore.MAGENTA
Pink = Fore.MAGENTA
RAINBOW = [Fore.RED, Fore.YELLOW, Fore.GREEN, Fore.CYAN, Fore.BLUE, Fore.MAGENTA]
PINK = [Fore.RED, Fore.LIGHTMAGENTA_EX, Fore.MAGENTA, Fore.LIGHTRED_EX]
PINK_GRAD = [Fore.LIGHTMAGENTA_EX, Fore.MAGENTA, Fore.RED]
# GUI Farben (Hex-Codes für Tkinter)
CYAN = "#00ffea"
RED = "#ff0055"
YELLOW = "#ffff00"
GREEN = "#00ff99"
NEON = "#ff4df2"
# ========= SENT PERSISTENCE =========
SENT_FILE = "ressources//sent_servers.txt"
sent_set: set = set()
sent_lock = asyncio.Lock()
def load_sent():
global sent_set
try:
with open(SENT_FILE, "r", encoding="utf-8") as f:
for line in f:
k = line.strip()
if k:
sent_set.add(k)
except FileNotFoundError:
open(SENT_FILE, "a", encoding="utf-8").close()
def _append_sent_file(key: str):
try:
with open(SENT_FILE, "a", encoding="utf-8") as f:
f.write(key + "\n")
except Exception:
pass
async def mark_sent(key: str) -> bool:
"""Mark key as sent. Returns True if newly marked, False if already present."""
global sent_set
# If in worker mode, check with master first
if is_worker_mode and instance_mgr.master_socket:
# Check if already sent with master
already_sent = await asyncio.get_running_loop().run_in_executor(
None, instance_mgr.check_server_sent, key
)
if already_sent:
# Update local set and return False
async with sent_lock:
sent_set.add(key)
return False
# Mark as sent with master
success = await asyncio.get_running_loop().run_in_executor(
None, instance_mgr.mark_server_sent, key
)
if not success:
# Another worker marked it first
async with sent_lock:
sent_set.add(key)
return False
# Master mode or single instance - check local set
async with sent_lock:
if key in sent_set:
return False
sent_set.add(key)
# Append to file
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, _append_sent_file, key)
return True
# load existing sent entries
load_sent()
# ========= DATABASE FUNCTIONS =========
DATABASE_FILE = "ressources//servers.db"
def init_db():
"""Initialize the database"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
# Use UNIQUE(ip, port) to allow multiple servers with same IP but different ports
cursor.execute('''
CREATE TABLE IF NOT EXISTS servers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT NOT NULL,
port INTEGER NOT NULL,
motd TEXT,
version TEXT,
players_online INTEGER,
players_max INTEGER,
host TEXT,
bild TEXT,
scanned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(ip, port)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_ip_port ON servers(ip, port)')
conn.commit()
conn.close()
except Exception as e:
gui_print(f"[DB] Error initializing database: {e}")
def get_servers_from_db(search_query=""):
"""Get servers from database with optional search
Supports:
- Text search: searches ip, motd, version, host
- Number search: searches for exact player count (e.g., "3" finds servers with exactly 3 players)
"""
try:
conn = sqlite3.connect(DATABASE_FILE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
if search_query:
# Check if search_query is a number (for player count search)
try:
player_count = int(search_query)
# Exact player count search
query = """
SELECT * FROM servers
WHERE players_online = ?
ORDER BY scanned_at DESC
"""
cursor.execute(query, (player_count,))
results = [dict(row) for row in cursor.fetchall()]
conn.close()
return results
except ValueError:
# Not a number, do text search
query = """
SELECT * FROM servers
WHERE ip LIKE ? OR motd LIKE ? OR version LIKE ? OR host LIKE ?
ORDER BY scanned_at DESC
"""
search_pattern = f"%{search_query}%"
cursor.execute(query, (search_pattern, search_pattern, search_pattern, search_pattern))
results = [dict(row) for row in cursor.fetchall()]
conn.close()
return results
else:
cursor.execute("SELECT * FROM servers ORDER BY scanned_at DESC LIMIT 1000000000000")
results = [dict(row) for row in cursor.fetchall()]
conn.close()
return results
except Exception as e:
gui_print(f"[DB] Error getting servers: {e}")
return []
def get_server_count():
"""Get total server count"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM servers")
count = cursor.fetchone()[0]
conn.close()
return count
except:
return 0
def update_server(ip, port, motd, version, players_online, players_max, host="", bild=""):
"""Update or insert a server"""
try:
conn = sqlite3.connect(DATABASE_FILE)
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO servers
(ip, port, motd, version, players_online, players_max, host, bild, scanned_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
''', (ip, port, motd, version, players_online, players_max, host, bild))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"[DB] Error updating server: {e}")
return False
# Initialize database
init_db()
# ========= YOURSERVERS HELPER FUNCTIONS =========
# Store reference to the servers treeview for refreshing
servers_tree = None
servers_search_var = None
server_count_label = None # Add reference to count label
def run_server_checker():
"""Run server_checker.py in a background thread"""
import subprocess
import threading
def run_checker():
try:
gui_print("[YourSERVERS] Starting server checker...", "scan")
result = subprocess.run(
[sys.executable, "server_checker.py"],
capture_output=True,
text=True,
timeout=3600 # 1 hour timeout
)
if result.returncode == 0:
gui_print("[YourSERVERS] Server checker completed successfully!", "online")
else:
gui_print(f"[YourSERVERS] Server checker error: {result.stderr}", "error")
# Refresh the server list after checking
try:
refresh_servers_list()
except Exception as e:
gui_print(f"[YourSERVERS] Error refreshing list: {e}", "error")
except subprocess.TimeoutExpired:
gui_print("[YourSERVERS] Server checker timed out!", "error")
except Exception as e:
gui_print(f"[YourSERVERS] Server checker error: {e}", "error")
# Run in background thread to not block GUI
try:
checker_thread = threading.Thread(target=run_checker, daemon=True)
checker_thread.start()
except Exception as e:
gui_print(f"[YourSERVERS] Failed to start checker thread: {e}", "error")
def refresh_servers_list():
"""Refresh the servers list in the YourSERVERS tab"""
global servers_tree, servers_search_var, server_count_label
if servers_tree is None:
return
try:
# Clear existing items
for item in servers_tree.get_children():
servers_tree.delete(item)
# Get search query (ignore placeholder text)
search_query = servers_search_var.get() if servers_search_var else ""
if search_query == "Search servers...":
search_query = ""
# Get servers from database
servers = get_servers_from_db(search_query)
# Add servers to treeview
for server in servers:
ip_port = f"{server['ip']}:{server['port']}"
motd = server.get('motd', '') or ''
# Truncate MOTD if too long
if len(motd) > 40:
motd = motd[:37] + "..."
version = server.get('version', '') or 'Unknown'
players = f"{server.get('players_online', 0)}/{server.get('players_max', 0)}"
scanned_at = server.get('scanned_at', '') or ''
servers_tree.insert('', 'end', values=(ip_port, motd, version, players, scanned_at))
# Update server count label
if server_count_label:
server_count_label.config(text=f"Servers: {len(servers)}")
gui_print(f"[YourSERVERS] Loaded {len(servers)} servers from database", "scan")
except Exception as e:
gui_print(f"[YourSERVERS] Error refreshing servers list: {e}", "error")
def ping_single_server(ip, port):
"""Ping a single server and return the result"""
try:
s = socket.socket()
s.settimeout(config.TIMEOUT)
s.connect((ip, port))
handshake = (
encode_varint(0) +
encode_varint(754) +
encode_varint(len(ip)) + ip.encode() +
struct.pack(">H", port) +
encode_varint(1)
)
s.sendall(encode_varint(len(handshake)) + handshake)
s.sendall(b"\x01\x00")
decode_varint(s)
decode_varint(s)
length = decode_varint(s)
if not length:
s.close()
return None
data = s.recv(length)
s.close()
return json.loads(data.decode())
except Exception:
return None
def open_server_detail(server_data):
"""Open a detailed popup window for a server"""
global gui_root
# Colors matching the main theme
BG = "#000000"
CARD = "#050505"
PINK = "#ff00aa"
PURPLE = "#8a2be2"
NEON = "#ff4df2"
CYAN = "#00ffea"
GREEN = "#00ff99"
RED = "#ff0055"
YELLOW = "#ffff00"
# Create popup window
popup = tk.Toplevel(gui_root)
ip = server_data.get('ip', '')
port = server_data.get('port', 25565)
popup.title(f"Server Details - {ip}:{port}")
popup.geometry("600x500")
popup.configure(bg=BG)
popup.resizable(False, False)
# Make it modal-like (stay on top)
popup.transient(gui_root)
popup.grab_set()
# Title bar
title_frame = tk.Frame(popup, bg=CARD, height=40)
title_frame.pack(fill="x")
title_frame.pack_propagate(False)
title_label = tk.Label(
title_frame,
text=f"🖥️ SERVER DETAILS",
bg=CARD,
fg=PINK,
font=("Consolas", 14, "bold")
)
title_label.pack(side="left", padx=15, pady=8)
# Close button
close_btn = tk.Label(
title_frame,
text=" ✕ ",
bg=CARD,
fg=PINK,
font=("Segoe UI", 12, "bold"),
cursor="hand2"
)
close_btn.pack(side="right", padx=10)
close_btn.bind("<Button-1>", lambda e: popup.destroy())
# Content frame
content = tk.Frame(popup, bg=BG)
content.pack(fill="both", expand=True, padx=20, pady=20)
log_print(f"[YourSERVERS] Opened details for {ip}:{port}", "scan")
# Server IP and Port (main info)
ip_port_label = tk.Label(
content,
text=f"{ip}:{port}",
bg=BG,
fg=CYAN,
font=("Consolas", 20, "bold")
)
ip_port_label.pack(pady=(0, 15))
# Status indicator frame
status_frame = tk.Frame(content, bg=CARD, highlightbackground=PURPLE, highlightthickness=2)
status_frame.pack(fill="x", pady=(0, 15))
status_label = tk.Label(
status_frame,
text="⚫ OFFLINE",
bg=CARD,
fg=RED,
font=("Consolas", 14, "bold")
)
status_label.pack(pady=15)
# Info grid
info_frame = tk.Frame(content, bg=CARD, highlightbackground=PURPLE, highlightthickness=2)
info_frame.pack(fill="both", expand=True)
# Helper function to create info row
def create_info_row(parent, label_text, value_text, row):
label = tk.Label(
parent,
text=label_text,
bg=CARD,
fg=PINK,
font=("Consolas", 10, "bold"),
anchor="w"
)
label.grid(row=row, column=0, sticky="w", padx=15, pady=10)
value = tk.Label(
parent,
text=value_text,
bg=CARD,
fg=CYAN,
font=("Consolas", 10),
anchor="w"
)
value.grid(row=row, column=1, sticky="w", padx=15, pady=10)
return value
# MOTD (row 0, needs to span both columns)
motd_label = tk.Label(
info_frame,
text="MOTD",
bg=CARD,
fg=PINK,
font=("Consolas", 10, "bold"),
anchor="w"
)
motd_label.grid(row=0, column=0, sticky="w", padx=15, pady=(15, 5))
motd_value = tk.Label(
info_frame,
text=server_data.get('motd', 'N/A') or 'N/A',
bg=CARD,
fg=CYAN,
font=("Consolas", 10),
anchor="w",
wraplength=500
)
motd_value.grid(row=0, column=1, sticky="w", padx=15, pady=(15, 5))
# Version
version_value = create_info_row(info_frame, "Version", server_data.get('version', 'Unknown') or 'Unknown', 1)
# Players
players_online = server_data.get('players_online', 0)
players_max = server_data.get('players_max', 0)
players_text = f"{players_online} / {players_max}"
players_value = create_info_row(info_frame, "Players", players_text, 2)
# Host
host_value = create_info_row(info_frame, "Host", server_data.get('host', 'N/A') or 'N/A', 3)
# Last Scanned
scanned_at = server_data.get('scanned_at', 'N/A') or 'N/A'
scanned_value = create_info_row(info_frame, "Last Scanned", scanned_at, 4)
# Server ID
server_id = server_data.get('id', 'N/A')
id_value = create_info_row(info_frame, "Server ID", str(server_id), 5)
# Button frame
btn_frame = tk.Frame(content, bg=BG)
btn_frame.pack(fill="x", pady=(15, 0))
# ReInitialize button
reinitalize_btn = tk.Button(
btn_frame,
text="🔄 ReInitialize",
command=lambda: reinitalize_server(),
bg=PURPLE,
fg="#ffffff",
font=("Consolas", 12, "bold"),
bd=0,
padx=20,
pady=10,
cursor="hand2",
activebackground=PINK,
activeforeground="#ffffff"
)
reinitalize_btn.pack(side="left", padx=(0, 10))
# Close button
close_btn_action = tk.Button(
btn_frame,
text="✕ Close",
command=popup.destroy,
bg=CARD,
fg=PINK,
font=("Consolas", 12, "bold"),
bd=2,
highlightbackground=PURPLE,
highlightthickness=2,
padx=20,
pady=10,
cursor="hand2",
activebackground=PURPLE,
activeforeground="#ffffff"
)
close_btn_action.pack(side="right")
# ReInitialize function
def reinitalize_server():
# Update button state
reinitalize_btn.config(text="⏳ Checking...", state="disabled")
status_label.config(text="⏳ CHECKING...", fg=YELLOW)
popup.update()
# Ping server
result = ping_single_server(ip, port)
if result:
# Server is online
status_label.config(text="🟢 ONLINE", fg=GREEN)
# Update values
motd = result.get("description", "")
if isinstance(motd, dict):
motd = motd.get("text", "") or str(motd)
motd_value.config(text=motd if motd else "N/A")
version = result.get("version", {}).get("name", "Unknown")
version_value.config(text=version)
players_online = result.get("players", {}).get("online", 0)
players_max = result.get("players", {}).get("max", 0)
players_text = f"{players_online} / {players_max}"
players_value.config(text=players_text)
# Update database with new info
update_server(ip, port, motd, version, players_online, players_max, server_data.get('host', ''), '')
gui_print(f"[YourSERVERS] Updated server {ip}:{port} - {players_online}/{players_max} players", "online")
else:
# Server is offline
status_label.config(text="🔴 OFFLINE", fg=RED)
players_value.config(text="0 / 0")
# Restore button
reinitalize_btn.config(text="🔄 ReInitialize", state="normal")
# Try to ping on open to get current status
def try_ping_on_open():
result = ping_single_server(ip, port)
if result:
status_label.config(text="🟢 ONLINE", fg=GREEN)
else:
status_label.config(text="🔴 OFFLINE", fg=RED)
# Run ping in background after window opens
popup.after(500, try_ping_on_open)
# ========= GUI OUTPUT FUNCTIONS =========
def gui_print(message: str, tag: str = None):
global scan_log_text
if not scan_log_text:
return
try:
# Check if widget still exists
if not scan_log_text.winfo_exists():
return
scan_log_text.insert("end", message + "\n", tag)
scan_log_text.see("end")
line_count = int(scan_log_text.index("end-1c").split(".")[0])
if line_count > 1200:
scan_log_text.delete("1.0", "300.0")
except Exception as e:
# Silently ignore GUI errors to prevent crashes
pass
def gui_clear():
"""Clear the scan log."""
global scan_log_text
if scan_log_text:
try:
scan_log_text.delete('1.0', tk.END)
except:
pass
def gui_update_stats():
"""Update stats in GUI."""
global stats_labels, recent_box, gui_root, active_scanners, target_runs, current_run, runs_completed
if not gui_root:
return
try:
# Check if root window still exists
if not gui_root.winfo_exists():
return
# Get aggregated stats from all workers if master
if instance_mgr.is_master:
all_stats = instance_mgr.get_all_stats()
total_scanned = scanned + all_stats["total_scanned"]
total_found = found + all_stats["total_found"]
total_with_players = with_players + all_stats["total_with_players"]
total_sent = sent_count + all_stats["total_sent"]
worker_count = all_stats["active_workers"]
else:
total_scanned = scanned
total_found = found
total_with_players = with_players
total_sent = sent_count
worker_count = 0
# Safely update labels
if "Scanned" in stats_labels and stats_labels["Scanned"].winfo_exists():
stats_labels["Scanned"].config(text=str(total_scanned))
if "Found" in stats_labels and stats_labels["Found"].winfo_exists():
stats_labels["Found"].config(text=str(total_found))
if "With Players" in stats_labels and stats_labels["With Players"].winfo_exists():
stats_labels["With Players"].config(text=str(total_with_players))
# Update rate per hour
rate = compute_rate_per_hour(60)
if "Server scanner per hour" in stats_labels and stats_labels["Server scanner per hour"].winfo_exists():
stats_labels["Server scanner per hour"].config(text=f"{rate:.0f}")
# Update webhooks sent
if "Webhooks Sent" in stats_labels and stats_labels["Webhooks Sent"].winfo_exists():
stats_labels["Webhooks Sent"].config(text=str(total_sent))
# Update active scanners/workers
if "Active Scanners" in stats_labels and stats_labels["Active Scanners"].winfo_exists():
if instance_mgr.is_master:
stats_labels["Active Scanners"].config(text=str(worker_count + 1)) # +1 for master
else:
stats_labels["Active Scanners"].config(text="1")
# Update run progress
if "Run Progress" in stats_labels and stats_labels["Run Progress"].winfo_exists():
if target_runs >= 2:
progress_text = f"{runs_completed}/{target_runs}"
if current_run > runs_completed and current_run <= target_runs:
progress_text = f"{current_run}/{target_runs} (running)"
stats_labels["Run Progress"].config(text=progress_text)
else:
stats_labels["Run Progress"].config(text="-")
if recent_box and recent_box.winfo_exists():
recent_box.delete(0, tk.END)
with recent_found_lock:
for ip in list(recent_found):
recent_box.insert(tk.END, ip)
except Exception as e:
# Silently ignore GUI errors
pass
try:
if gui_root and gui_root.winfo_exists():
gui_root.after(500, gui_update_stats)
except:
pass
def gui_update_advanced_stats():
"""Update advanced statistics and 10-second graph."""
global advanced_stats_labels, scan_graph_canvas, graph_bars, gui_root
global peak_scans_per_minute, peak_found_per_minute
if not gui_root:
return
# Check if root window still exists
try:
if not gui_root.winfo_exists():
return
except:
return
if not advanced_stats_labels:
try:
if gui_root.winfo_exists():
gui_root.after(1000, gui_update_advanced_stats)
except:
pass
return
try:
# Calculate current statistics
scans_per_min = compute_scans_per_minute(60)
found_per_min = compute_found_per_minute(60)
current_rate = compute_scans_per_minute(10) / 10 # Scans per second over last 10s
# Update peak values
with peak_stats_lock:
if scans_per_min > peak_scans_per_minute:
peak_scans_per_minute = scans_per_min
# Get aggregated advanced stats from workers if master
if instance_mgr.is_master:
all_stats = instance_mgr.get_all_stats()
total_scans_per_min = scans_per_min + all_stats.get("total_scans_per_minute", 0)
total_found_per_min = found_per_min + all_stats.get("total_found_per_minute", 0)
max_peak_scans = max(peak_scans_per_minute, all_stats.get("max_peak_scans_per_minute", 0))
else:
total_scans_per_min = scans_per_min
total_found_per_min = found_per_min
max_peak_scans = peak_scans_per_minute
# Safely update labels
if "scans_per_min" in advanced_stats_labels and advanced_stats_labels["scans_per_min"].winfo_exists():
advanced_stats_labels["scans_per_min"].config(text=f"{total_scans_per_min:.1f}")
if "found_per_min" in advanced_stats_labels and advanced_stats_labels["found_per_min"].winfo_exists():
advanced_stats_labels["found_per_min"].config(text=f"{total_found_per_min:.1f}")
if "current_rate" in advanced_stats_labels and advanced_stats_labels["current_rate"].winfo_exists():
advanced_stats_labels["current_rate"].config(text=f"{current_rate:.1f}/s")
if "peak_scans" in advanced_stats_labels and advanced_stats_labels["peak_scans"].winfo_exists():
advanced_stats_labels["peak_scans"].config(text=f"{max_peak_scans:.1f}")
# Update scan history for graph (every second)
now = time.time()
with scan_times_lock:
# Count scans in the last second
one_second_ago = now - 1
scans_last_second = sum(1 for ts in scan_times if ts >= one_second_ago)
with scan_history_lock:
scan_history.append((now, scans_last_second))
# Keep only last 10 seconds
while len(scan_history) > 10:
scan_history.popleft()
# Update graph every 10 seconds using reliable timestamp check
global last_graph_update
if now - last_graph_update >= 10 and scan_graph_canvas:
try:
# Clear old bars
scan_graph_canvas.delete("bar")
# Get data from scan_history
with scan_history_lock:
data = list(scan_history)
if not data:
return
# Calculate max for scaling
max_val = max((count for _, count in data), default=1)
if max_val < 1:
max_val = 1
# Draw bars
bar_width = 30
spacing = 35
start_x = 55
for i, (timestamp, count) in enumerate(data):
# Calculate bar height (scale to 200 pixels max)
bar_height = (count / max_val) * 200 if max_val > 0 else 0
if bar_height < 2 and count > 0:
bar_height = 2 # Minimum visible height
x = start_x + i * spacing
y_bottom = 230
y_top = y_bottom - bar_height
# Color based on height (gradient from cyan to pink)
if count / max_val > 0.7:
color = "#ff00aa" # Pink for high
elif count / max_val > 0.4:
color = "#8a2be2" # Purple for medium
else:
color = "#00ffea" # Cyan for low
# Draw bar
scan_graph_canvas.create_rectangle(
x - bar_width/2, y_top,
x + bar_width/2, y_bottom,
fill=color, outline="", tags="bar"
)
# Draw value on top if bar is tall enough
if bar_height > 15:
scan_graph_canvas.create_text(
x, y_top - 8,
text=str(count),
fill="#ffffff",
font=("Consolas", 8, "bold"),
tags="bar"
)
# Update max value label
scan_graph_canvas.delete("max_label")
scan_graph_canvas.create_text(
20, 20,
text=f"{int(max_val)}",
fill="#666666",
font=("Consolas", 8),
tags="max_label"
)
last_graph_update = now
except Exception as e:
pass
except Exception as e:
pass
# Schedule next update
try:
if gui_root and gui_root.winfo_exists():
gui_root.after(1000, gui_update_advanced_stats)
except:
pass
# ========= COUNTER =========
scanned = 0
found = 0
with_players = 0
sent_count = 0
counter_lock = threading.Lock() # Thread-safe counter updates
# timestamps of recent scans (for rate calculation)
scan_times: deque = deque(maxlen=1000)
scan_times_lock = threading.Lock()
# recent found servers (most-recent first)
recent_found: deque = deque(maxlen=20)
recent_found_lock = threading.Lock()
# ========= TITLE =========
def set_title():
global last_title_update
global last_title_scan_count
now = time.time()
# Only update if enough time has passed OR enough scans have occurred
time_ok = (now - last_title_update) >= TITLE_MIN_SECONDS
scans_ok = (scanned - last_title_scan_count) >= TITLE_SCAN_STEP
if not (time_ok or scans_ok):
return
last_title_update = now
last_title_scan_count = scanned
# Title is now handled by GUI window title
#========= RATE CALCULATION =========
def compute_rate_per_hour(window_seconds: int = 60) -> float:
"""Compute an extrapolated servers/hour rate over last `window_seconds` seconds."""
now = time.time()
cutoff = now - window_seconds
with scan_times_lock:
count = 0
for ts in reversed(scan_times):
if ts >= cutoff:
count += 1
else:
break
if window_seconds == 0:
return 0.0
return (count / window_seconds) * 3600.0
def compute_scans_per_minute(window_seconds: int = 60) -> float:
"""Compute scans per minute over last `window_seconds` seconds."""
now = time.time()
cutoff = now - window_seconds
with scan_times_lock:
count = 0
for ts in reversed(scan_times):
if ts >= cutoff:
count += 1
else:
break
if window_seconds == 0:
return 0.0
return (count / window_seconds) * 60.0
def compute_found_per_minute(window_seconds: int = 60) -> float:
"""Compute servers found per minute over last `window_seconds` seconds."""
# Track found timestamps
global found_times, found_times_lock
try:
found_times
except NameError:
found_times = deque(maxlen=10000)
found_times_lock = threading.Lock()
now = time.time()
cutoff = now - window_seconds
with found_times_lock:
count = 0
for ts in reversed(found_times):
if ts >= cutoff:
count += 1
else:
break
if window_seconds == 0: