-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathManager.py
More file actions
2243 lines (1848 loc) · 90 KB
/
Manager.py
File metadata and controls
2243 lines (1848 loc) · 90 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
# Manager.py - Unified BlackBoT Configuration & Multi-Instance Manager
import os
import sys
import json
import yaml
import shutil
import signal
import time
import subprocess
from pathlib import Path
from typing import Dict, List
from dataclasses import dataclass, asdict
from datetime import datetime
import re
import platform
# Colors for terminal output
class Colors:
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
WARNING = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def print_header(text: str):
print(f"\n{Colors.HEADER}{Colors.BOLD}{'='*70}{Colors.END}")
print(f"{Colors.HEADER}{Colors.BOLD}{text.center(70)}{Colors.END}")
print(f"{Colors.HEADER}{Colors.BOLD}{'='*70}{Colors.END}\n")
def print_success(text: str):
print(f"{Colors.GREEN}✅ {text}{Colors.END}")
def print_warning(text: str):
print(f"{Colors.WARNING}⚠️ {text}{Colors.END}")
def print_error(text: str):
print(f"{Colors.RED}❌ {text}{Colors.END}")
def print_info(text: str):
print(f"{Colors.BLUE}💡 {text}{Colors.END}")
def print_question(text: str):
return input(f"{Colors.CYAN}❓ {text}{Colors.END}")
@dataclass
class BotInstanceConfig:
"""Complete configuration for a BlackBoT instance"""
# Core Identity
name: str
nickname: str
username: str
realname: str
# Network Configuration
servers: List[str]
port: int = 6667
ssl_enabled: bool = False
# Stats / Web UI (FastAPI)
stats_api_port: int = 8000
stats_api_host: str = "0.0.0.0"
ssl_cert_file: str = ""
ssl_key_file: str = ""
# Channels
channels: List[str] = None
# Authentication - Universal System
auth_method: str = "none" # Options: 'none', 'nickserv', 'q', 'x'
# NickServ Authentication (Libera.Chat, OFTC, etc.)
nickserv_enabled: bool = False
nickserv_password: str = ""
# QuakeNet Q Authentication
quakenet_auth_enabled: bool = False
quakenet_username: str = ""
quakenet_password: str = ""
# Undernet X Authentication
undernet_auth_enabled: bool = False
undernet_username: str = ""
undernet_password: str = ""
# User modes (set after connection)
user_modes: str = "" # Example: '+x' for IP hiding, '+ix' for invisible+hide
# Database & Logging
database: str = ""
log_level: str = "INFO"
log_dir: str = "logs"
# Network & Performance
dcc_port: int = 51999
message_delay: float = 1.5
command_char: str = "!"
# Environment & Instance
environment: str = "local"
enabled: bool = True
auto_start: bool = False
# File paths (auto-generated)
config_file: str = ""
log_file: str = ""
pid_file: str = ""
def __post_init__(self):
if self.channels is None:
self.channels = [f"#{self.name}"]
if not self.database:
self.database = f"instances/{self.name}/{self.name}.db"
if not self.config_file:
self.config_file = f"instances/{self.name}/.env"
if not self.log_file:
self.log_file = f"instances/{self.name}/logs/{self.name}.log"
if not self.pid_file:
self.pid_file = f"instances/{self.name}/{self.name}.pid"
def _kill_process(pid, force=False):
system = platform.system().lower()
if system == "windows":
if force:
subprocess.run(["taskkill", "/PID", str(pid), "/F"], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
else:
subprocess.run(["taskkill", "/PID", str(pid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
if force:
os.killpg(os.getpgid(pid), signal.SIGKILL)
else:
os.killpg(os.getpgid(pid), signal.SIGTERM)
class UnifiedBlackBotManager:
"""Unified manager for all BlackBoT configuration and instance management"""
def __init__(self):
self.base_dir = Path(__file__).parent.resolve()
self.instances_dir = self.base_dir / "instances"
self.config_dir = self.base_dir / "config"
self.registry_file = self.base_dir / "instances.json"
self.instances: Dict[str, BotInstanceConfig] = {}
# Ensure directories exist
self.instances_dir.mkdir(exist_ok=True)
self.config_dir.mkdir(exist_ok=True)
# Load existing instances
self.load_instances()
self._auto_migrate_instances()
print_info(f"🤖 Unified BlackBoT Manager initialized")
print_info(f"📁 Base directory: {self.base_dir}")
def _detect_advanced_config(self) -> bool:
"""Detect if advanced config system is available"""
required_files = ["config_manager.py", "blackbot_config_integration.py"]
return all((self.base_dir / f).exists() for f in required_files)
def load_instances(self):
"""Load instance configurations from registry"""
if self.registry_file.exists():
try:
with open(self.registry_file, 'r', encoding='utf-8') as f:
data = json.load(f)
self.instances = {}
for name, config_data in data.get('instances', {}).items():
self.instances[name] = BotInstanceConfig(**config_data)
if self.instances:
print_success(f"Loaded {len(self.instances)} instance configurations")
except Exception as e:
print_error(f"Failed to load instances registry: {e}")
self.instances = {}
def save_instances(self):
"""Save instance configurations to registry"""
try:
registry_data = {
'version': '2.0',
'created': datetime.now().isoformat(),
'unified_manager': True,
'instances': {name: asdict(config) for name, config in self.instances.items()}
}
with open(self.registry_file, 'w', encoding='utf-8') as f:
json.dump(registry_data, f, indent=2)
except Exception as e:
print_error(f"Failed to save instances registry: {e}")
def create_instance_interactive(self) -> bool:
"""Interactive instance creation with full configuration"""
print_header("🆕 Create New BlackBoT Instance")
try:
# Instance name
while True:
name = print_question("Instance name (alphanumeric, unique): ").strip()
if name and self._validate_instance_name(name) and name not in self.instances:
break
if name in self.instances:
print_error(f"Instance '{name}' already exists")
else:
print_error("Invalid instance name. Use alphanumeric characters and underscores only")
print_info(f"Creating instance: {name}")
print()
# Core Identity
print(f"{Colors.BOLD}🤖 Bot Identity{Colors.END}")
nickname = print_question(f"Bot nickname [{name}_bot]: ").strip()
if not nickname:
nickname = f"{name}_bot"
username = print_question(f"IRC username/ident [{name}]: ").strip()
if not username:
username = name
realname = print_question(f"Real name [BlackBoT Instance: {name}]: ").strip()
if not realname:
realname = f"BlackBoT Instance: {name}"
print()
# Network Configuration
print(f"{Colors.BOLD}🌐 Network Configuration{Colors.END}")
# Show popular networks
self._show_popular_networks()
servers_input = print_question("IRC servers (comma-separated) [irc.libera.chat:6667]: ").strip()
if not servers_input:
servers_input = "irc.libera.chat:6667"
# Parse servers and normalize format
servers = []
for server in servers_input.split(','):
server = server.strip()
if ':' not in server:
server = f"{server}:6667"
servers.append(server)
# Port and SSL
port = 6667
ssl_enabled = print_question("Enable SSL connection? [y/N]: ").lower().startswith('y')
ssl_cert_file = ""
ssl_key_file = ""
if ssl_enabled:
port = 6697
print_success("SSL enabled - will use secure connection (default port 6697)")
use_client_cert = print_question(
"Use client TLS certificate (mutual TLS)? [y/N]: "
).lower().startswith('y')
if use_client_cert:
default_cert = f"instances/{name}/client_cert.pem"
default_key = f"instances/{name}/client_key.pem"
cert_input = print_question(
f"Path to certificate file (.pem) [{default_cert}]: "
).strip()
key_input = print_question(
f"Path to private key file (.pem) [{default_key}]: "
).strip()
ssl_cert_file = cert_input or default_cert
ssl_key_file = key_input or default_key
print_success(f"TLS client certificate configured: {ssl_cert_file}")
else:
print_info("No client certificate configured (server-side TLS only)")
print()
# Channels
print(f"{Colors.BOLD}📺 Channel Configuration{Colors.END}")
channels_input = print_question(f"Channels (comma-separated) [#{name}]: ").strip()
if not channels_input:
channels_input = f"#{name}"
channels = [c.strip() for c in channels_input.split(',')]
# Ensure channels start with #
channels = [c if c.startswith('#') else f"#{c}" for c in channels]
print()
# Authentication
print(f"{Colors.BOLD}🔐 Authentication{Colors.END}")
# Detectare automată rețea din servers
network_type = self._detect_network_type(servers)
print_info(f"Detected network: {network_type}")
# Inițializare variabile
auth_method = "none"
nickserv_enabled = False
nickserv_password = ""
quakenet_auth_enabled = False
quakenet_username = ""
quakenet_password = ""
undernet_auth_enabled = False
undernet_username = ""
undernet_password = ""
# Oferă opțiuni de autentificare bazate pe rețea
if network_type == "quakenet":
print()
print(f"{Colors.CYAN}QuakeNet uses Q for authentication{Colors.END}")
print()
use_auth = print_question("Enable QuakeNet Q authentication? [y/N]: ").lower().startswith('y')
if use_auth:
# Credentials
quakenet_username = print_question("Q username: ").strip()
if quakenet_username:
import getpass
quakenet_password = getpass.getpass(f"{Colors.CYAN}▶ Q password: {Colors.END}")
if quakenet_password:
quakenet_auth_enabled = True
auth_method = 'q'
print_success(f"QuakeNet Q authentication configured")
print_info(f"Username: {quakenet_username}")
else:
print_warning("No password provided - authentication disabled")
else:
print_warning("No username provided - authentication disabled")
else:
print_info("No authentication configured")
elif network_type == "undernet":
print()
print(f"{Colors.CYAN}Undernet uses X for authentication{Colors.END}")
print()
use_auth = print_question("Enable Undernet X authentication? [y/N]: ").lower().startswith('y')
if use_auth:
# Credentials
undernet_username = print_question("X username: ").strip()
if undernet_username:
import getpass
undernet_password = getpass.getpass(f"{Colors.CYAN}▶ X password: {Colors.END}")
if undernet_password:
undernet_auth_enabled = True
auth_method = 'x'
print_success(f"Undernet X authentication configured")
print_info(f"Username: {undernet_username}")
else:
print_warning("No password provided - authentication disabled")
else:
print_warning("No username provided - authentication disabled")
else:
print_info("No authentication configured")
elif network_type in ["libera", "freenode", "oftc"]:
print()
print(f"{Colors.CYAN}{network_type.capitalize()} uses NickServ for authentication{Colors.END}")
print()
nickserv_enabled = print_question("Enable NickServ authentication? [y/N]: ").lower().startswith('y')
if nickserv_enabled:
import getpass
nickserv_password = getpass.getpass(f"{Colors.CYAN}▶ NickServ password: {Colors.END}")
if nickserv_password:
auth_method = "nickserv"
print_success("NickServ authentication configured")
else:
print_warning("No password provided - authentication disabled")
nickserv_enabled = False
else:
print_info("No authentication configured")
else:
# Rețea necunoscută - oferă toate opțiunile
print()
print(f"{Colors.CYAN}Authentication options:{Colors.END}")
print(" 1. None - No authentication")
print(" 2. NickServ - For Libera.Chat, OFTC, etc.")
print(" 3. QuakeNet Q - For QuakeNet")
print(" 4. Undernet X - For Undernet")
print()
auth_choice = print_question("Choose authentication [1-4, default=1]: ").strip()
if auth_choice == "2":
# NickServ
import getpass
nickserv_password = getpass.getpass(f"{Colors.CYAN}▶ NickServ password: {Colors.END}")
if nickserv_password:
nickserv_enabled = True
auth_method = "nickserv"
print_success("NickServ authentication configured")
elif auth_choice == "3":
# QuakeNet Q
quakenet_username = print_question("Q username: ").strip()
if quakenet_username:
import getpass
quakenet_password = getpass.getpass(f"{Colors.CYAN}▶ Q password: {Colors.END}")
if quakenet_password:
quakenet_auth_enabled = True
auth_method = 'q'
print_success("QuakeNet Q authentication configured")
elif auth_choice == "4":
# Undernet X
undernet_username = print_question("X username: ").strip()
if undernet_username:
import getpass
undernet_password = getpass.getpass(f"{Colors.CYAN}▶ X password: {Colors.END}")
if undernet_password:
undernet_auth_enabled = True
auth_method = 'x'
print_success("Undernet X authentication configured")
else:
print_info("No authentication configured")
print()
# User Modes Configuration
print(f"{Colors.BOLD}🎭 User Modes{Colors.END}")
# Auto-suggest modes bazat pe rețea
suggested_modes = ""
if network_type == "undernet":
suggested_modes = "+x"
print_info("Undernet recommendation: +x (hide your IP address)")
elif network_type == "quakenet":
suggested_modes = "+x"
print_info("QuakeNet recommendation: +x (hide your IP address)")
elif network_type in ["libera", "oftc"]:
suggested_modes = ""
print_info("No special modes recommended for this network")
else:
suggested_modes = ""
print_info("Common modes: +x (hide IP), +i (invisible), +B (bot)")
print()
print("User modes are IRC modes set on your nickname after connecting")
print("Common modes:")
print(" • +x - Hide your IP/hostname (recommended for Undernet/QuakeNet)")
print(" • +i - Invisible (don't show in global WHO)")
print(" • +B - Mark as bot")
print(" • +ix - Combination (invisible + hide IP)")
print()
if suggested_modes:
user_modes_input = print_question(f"User modes [{suggested_modes}]: ").strip()
user_modes = user_modes_input if user_modes_input else suggested_modes
else:
user_modes_input = print_question("User modes [leave empty for none]: ").strip()
user_modes = user_modes_input
if user_modes:
print_success(f"User modes configured: {user_modes}")
else:
print_info("No user modes will be set")
print()
# Advanced Configuration
print(f"{Colors.BOLD}⚙️ Advanced Configuration{Colors.END}")
# Environment
env_options = ['local', 'dev', 'prod', 'test']
print("Environment types:")
for i, env in enumerate(env_options, 1):
desc = {
'local': 'Local development (default)',
'dev': 'Development environment',
'prod': 'Production environment',
'test': 'Testing environment'
}[env]
print(f" {i}. {env} - {desc}")
env_choice = print_question("Choose environment [1-4, default=1]: ").strip()
try:
env_idx = int(env_choice) - 1 if env_choice else 0
environment = env_options[env_idx] if 0 <= env_idx < len(env_options) else 'local'
except:
environment = 'local'
# DCC Port (auto-assign unique)
dcc_port = self._get_next_available_port()
print_info(f"Assigned DCC port: {dcc_port}")
# ─────────────────────────────────────────────
# Stats API (FastAPI) Port auto-assign
# ─────────────────────────────────────────────
stats_api_port = self._get_next_available_stats_port(8000)
print_info(f"Assigned Stats API port: {stats_api_port}")
override = print_question(
f"Change Stats API port? [enter to keep {stats_api_port}]: "
).strip()
if override:
try:
stats_api_port = int(override)
except:
pass
# Other settings with defaults
message_delay = 1.5
advanced = print_question("Configure advanced settings (delays, logging)? [y/N]: ").lower().startswith('y')
if advanced:
try:
delay_input = print_question(f"Message delay in seconds [{message_delay}]: ").strip()
if delay_input:
message_delay = float(delay_input)
except:
pass
log_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR']
print("Log levels:")
for i, level in enumerate(log_levels, 1):
print(f" {i}. {level}")
log_choice = print_question("Choose log level [1-4, default=2]: ").strip()
try:
log_idx = int(log_choice) - 1 if log_choice else 1
log_level = log_levels[log_idx] if 0 <= log_idx < len(log_levels) else 'INFO'
except:
log_level = 'INFO'
else:
log_level = 'INFO'
# Auto-start
auto_start = print_question("Auto-start with 'start all'? [y/N]: ").lower().startswith('y')
print()
# Create instance configuration
config = BotInstanceConfig(
name=name,
nickname=nickname,
username=username,
realname=realname,
servers=servers,
port=port,
ssl_enabled=ssl_enabled,
channels=channels,
auth_method=auth_method,
nickserv_enabled=nickserv_enabled,
nickserv_password=nickserv_password,
quakenet_auth_enabled=quakenet_auth_enabled,
quakenet_username=quakenet_username,
quakenet_password=quakenet_password,
undernet_auth_enabled=undernet_auth_enabled,
undernet_username=undernet_username,
undernet_password=undernet_password,
user_modes=user_modes,
environment=environment,
dcc_port=dcc_port,
stats_api_port=stats_api_port,
stats_api_host="0.0.0.0",
message_delay=message_delay,
log_level=log_level,
auto_start=auto_start,
ssl_cert_file = ssl_cert_file,
ssl_key_file = ssl_key_file
)
# Create instance files
if self._create_instance_files(config):
self.instances[name] = config
self.save_instances()
print_success(f"Instance '{name}' created successfully!")
# Show summary
self._show_instance_summary(config)
# Ask to start now
start_now = print_question("Start instance now? [Y/n]: ").lower()
if start_now != 'n':
return self.start_instance(name)
return True
else:
print_error(f"Failed to create instance '{name}'")
return False
except KeyboardInterrupt:
print(f"\n{Colors.WARNING}Instance creation cancelled{Colors.END}")
return False
except Exception as e:
print_error(f"Error creating instance: {e}")
return False
def _show_popular_networks(self):
"""Show popular IRC networks for reference"""
print_info("Popular IRC networks:")
networks = [
("Libera Chat", "irc.libera.chat", "6667/6697 (SSL)"),
("OFTC", "irc.oftc.net", "6667/6697 (SSL)"),
("Undernet", "irc.undernet.org", "6667"),
("QuakeNet", "irc.quakenet.org", "6667"),
("Rizon", "irc.rizon.net", "6667/6697 (SSL)"),
]
for name, server, ports in networks:
print(f" • {Colors.CYAN}{name}{Colors.END}: {server} ({ports})")
print()
def _detect_network_type(self, servers: List[str]) -> str:
"""
Detectează tipul de rețea bazat pe numele serverului
Returns:
str: 'quakenet', 'libera', 'freenode', 'oftc', 'undernet', 'rizon', or 'other'
"""
# Normalizăm numele serverelor
servers_lower = ' '.join(servers).lower()
# Detectare bazată pe keywords
if 'quakenet' in servers_lower:
return 'quakenet'
elif 'undernet' in servers_lower:
return 'undernet'
elif 'libera' in servers_lower:
return 'libera'
elif 'freenode' in servers_lower:
return 'freenode'
elif 'oftc' in servers_lower:
return 'oftc'
elif 'rizon' in servers_lower:
return 'rizon'
elif 'efnet' in servers_lower:
return 'efnet'
else:
return 'other'
def _show_instance_summary(self, config: BotInstanceConfig):
"""Show instance configuration summary"""
print_info("📋 Instance Configuration Summary:")
print(f" 🤖 Name: {Colors.CYAN}{config.name}{Colors.END}")
print(f" 🏷️ Nickname: {Colors.CYAN}{config.nickname}{Colors.END}")
print(f" 🌐 Servers: {Colors.CYAN}{', '.join(config.servers)}{Colors.END}")
print(f" 📺 Channels: {Colors.CYAN}{', '.join(config.channels)}{Colors.END}")
print(f" 🌍 Environment: {Colors.CYAN}{config.environment}{Colors.END}")
print(f" 🔐 SSL: {Colors.CYAN}{'Enabled' if config.ssl_enabled else 'Disabled'}{Colors.END}")
print(f" 🔌 DCC Port: {Colors.CYAN}{config.dcc_port}{Colors.END}")
print(f" 💾 Database: {Colors.CYAN}{config.database}{Colors.END}")
print()
def _validate_instance_name(self, name: str) -> bool:
"""Validate instance name"""
return bool(re.match(r'^[a-zA-Z][a-zA-Z0-9_-]*$', name)) and len(name) <= 32
def _get_next_available_port(self, start_port: int = 52000) -> int:
"""Get next available DCC port"""
used_ports = {config.dcc_port for config in self.instances.values()}
port = start_port
while port in used_ports:
port += 1
return port
def _get_next_available_stats_port(self, start_port: int = 8000) -> int:
"""Get next available Stats API port (avoid conflicts between instances)."""
used = {getattr(cfg, "stats_api_port", 8000) for cfg in self.instances.values()}
port = start_port
while port in used:
port += 1
return port
def _ensure_stats_port_in_env(self, instance_dir: str, cfg) -> None:
env_path = os.path.join(instance_dir, ".env")
if not os.path.exists(env_path):
return
with open(env_path, "r", encoding="utf-8") as f:
content = f.read()
# dacă există deja, nu facem nimic
if "STATS_API_PORT=" in content:
return
# alocăm un port liber (în funcție de instanțele deja încărcate)
port = getattr(cfg, "stats_api_port", None) or self._get_next_available_stats_port(8000)
host = getattr(cfg, "stats_api_host", "0.0.0.0")
patch = (
"\n# ─────────────────────────────────────────────\n"
"# Stats / Web UI (FastAPI)\n"
"# ─────────────────────────────────────────────\n"
f"STATS_API_ENABLED=true\n"
f"STATS_API_HOST={host}\n"
f"STATS_API_PORT={port}\n"
)
with open(env_path, "a", encoding="utf-8") as f:
f.write(patch)
# opțional: update și în cfg în memorie
try:
cfg.stats_api_port = port
cfg.stats_api_host = host
except:
pass
def _create_instance_files(self, config: BotInstanceConfig) -> bool:
"""Create all files for an instance"""
try:
instance_dir = self.instances_dir / config.name
instance_dir.mkdir(exist_ok=True)
# Create subdirectories
(instance_dir / "logs").mkdir(exist_ok=True)
(instance_dir / "data").mkdir(exist_ok=True)
# Create .env file
env_content = self._generate_env_content(config)
env_path = self.base_dir / config.config_file
with open(env_path, 'w', encoding='utf-8') as f:
f.write(env_content)
os.chmod(env_path, 0o600) # Secure permissions
print_success(f"Created configuration files for '{config.name}'")
return True
except Exception as e:
print_error(f"Failed to create instance files: {e}")
return False
def _auto_migrate_instances(self):
"""
Auto-migrate all instances at Manager startup (one-time check)
Adds Q/X auth settings to old .env files
"""
if not self.instances:
return
# Check if any instances need migration
needs_migration = []
for name, config in self.instances.items():
env_file = self.base_dir / "instances" / name / ".env"
if env_file.exists():
with open(env_file, 'r', encoding='utf-8') as f:
content = f.read()
if 'BLACKBOT_QUAKENET_AUTH_ENABLED' not in content:
needs_migration.append(name)
if not needs_migration:
return # All instances are up-to-date
# Show migration prompt
print()
print_info(f"🔄 Found {len(needs_migration)} instance(s) that need authentication settings update:")
for name in needs_migration[:5]: # Show first 5
print(f" • {name}")
if len(needs_migration) > 5:
print(f" ... and {len(needs_migration) - 5} more")
print()
print_info("These instances will be automatically updated with new Q/X auth settings")
print_info("(Settings will be disabled by default, no impact on current behavior)")
print()
# Auto-migrate (with option to skip)
response = input(f"{Colors.CYAN}▶ Auto-migrate now? [Y/n]: {Colors.END}").strip().lower()
if response == 'n':
print_warning("⚠️ Migration skipped - will be prompted again at next Manager start")
print_info(" Or instances will be migrated automatically when started")
return
print()
migrated_count = 0
for name in needs_migration:
config = self.instances[name]
try:
if self._migrate_instance_env(config):
migrated_count += 1
except Exception as e:
print_warning(f"⚠️ Failed to migrate {name}: {e}")
print()
if migrated_count > 0:
print_success(f"✅ Successfully migrated {migrated_count} instance(s)")
print_info(" Backups saved as .env.pre-migration")
print()
def _migrate_instance_env(self, config: BotInstanceConfig) -> bool:
"""
Migrează fișierul .env al unei instanțe cu setările noi de autentificare
Adaugă automat setările Q/X dacă lipsesc
Returns:
bool: True dacă a făcut modificări, False dacă era deja up-to-date
"""
env_file = self.base_dir / "instances" / config.name / ".env"
if not env_file.exists():
return False
# Citește conținut existent
with open(env_file, 'r', encoding='utf-8') as f:
content = f.read()
needs_migration = (
('BLACKBOT_QUAKENET_AUTH_ENABLED' not in content) or
('BLACKBOT_UNDERNET_AUTH_ENABLED' not in content) or
('BLACKBOT_USER_MODES' not in content)
)
print_info(f"🔄 Migrating {config.name} .env with new auth settings...")
# Găsește unde să inserăm (după NickServ settings)
lines = content.split('\n')
insert_index = None
# Caută după BLACKBOT_NICKSERV_PASSWORD sau BLACKBOT_NICKSERV_BOTNICK
for i, line in enumerate(lines):
if 'BLACKBOT_NICKSERV_PASSWORD' in line:
insert_index = i + 1
break
elif 'BLACKBOT_NICKSERV_BOTNICK' in line:
# Check if next line is not another NICKSERV setting
if i + 1 < len(lines) and 'BLACKBOT_NICKSERV_PASSWORD' not in lines[i + 1]:
insert_index = i + 1
break
if insert_index is None:
# Fallback: după BLACKBOT_NICKSERV_ENABLED
for i, line in enumerate(lines):
if 'BLACKBOT_NICKSERV_ENABLED' in line:
insert_index = i + 1
break
if insert_index is None:
print_warning(f"⚠️ Could not find insertion point in {config.name} .env")
return False
# Construiește DOAR ce lipsește
new_auth_section_lines = []
# QuakeNet Q (dacă lipsește)
if 'BLACKBOT_QUAKENET_AUTH_ENABLED' not in content:
new_auth_section_lines.extend([
"",
"# QuakeNet Q Authentication",
"BLACKBOT_QUAKENET_AUTH_ENABLED=false",
"BLACKBOT_QUAKENET_USERNAME=",
"BLACKBOT_QUAKENET_PASSWORD=",
])
# Undernet X (dacă lipsește)
if 'BLACKBOT_UNDERNET_AUTH_ENABLED' not in content:
new_auth_section_lines.extend([
"",
"# Undernet X Authentication",
"BLACKBOT_UNDERNET_AUTH_ENABLED=false",
"BLACKBOT_UNDERNET_USERNAME=",
"BLACKBOT_UNDERNET_PASSWORD=",
])
# User Modes (dacă lipsește)
if 'BLACKBOT_USER_MODES' not in content:
new_auth_section_lines.extend([
"",
"# User Modes (set after connection)",
"BLACKBOT_USER_MODES=",
])
if new_auth_section_lines:
new_auth_section_lines.append("")
new_auth_section = '\n'.join(new_auth_section_lines)
# Inserează
lines.insert(insert_index, new_auth_section)
# Scrie înapoi
new_content = '\n'.join(lines)
# Backup
backup_file = env_file.with_suffix('.env.pre-migration')
if not backup_file.exists(): # Nu suprascrie backup-uri existente
with open(backup_file, 'w', encoding='utf-8') as f:
f.write(content)
with open(env_file, 'w', encoding='utf-8') as f:
f.write(new_content)
print_success(f"✅ Migrated {config.name} .env")
print_info(f" Backup saved: {backup_file.name}")
return True
def _generate_env_content(self, config: BotInstanceConfig) -> str:
"""Generate .env file content with all supported variables"""
servers_str = ','.join(config.servers)
channels_str = ','.join(config.channels)
env_content = f"""# BlackBoT Instance Configuration: {config.name}
# Generated by Unified BlackBoT Manager on {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
# This file contains environment variables for this specific instance
# ═══════════════════════════════════════════════════════════════════
# Environment & Instance Identity
# ═══════════════════════════════════════════════════════════════════
BLACKBOT_ENV={config.environment}
BLACKBOT_INSTANCE_NAME={config.name}
# ═══════════════════════════════════════════════════════════════════
# Bot Identity (IRC Persona)
# ═══════════════════════════════════════════════════════════════════
BLACKBOT_NICKNAME={config.nickname}
BLACKBOT_USERNAME={config.username}
BLACKBOT_REALNAME="{config.realname}"
BLACKBOT_AWAY="No Away"
BLACKBOT_ALTNICK={config.nickname}_
# ═══════════════════════════════════════════════════════════════════
# Network & Server Configuration
# ═══════════════════════════════════════════════════════════════════
BLACKBOT_SERVERS={servers_str}
BLACKBOT_PORT={config.port}
BLACKBOT_SSL_USE={str(config.ssl_enabled).lower()}
# TLS client certificate (optional)
BLACKBOT_SSL_CERT_FILE={config.ssl_cert_file}
BLACKBOT_SSL_KEY_FILE={config.ssl_key_file}
# Source IP configuration (leave empty for auto-detection)
BLACKBOT_SOURCE_IP=
BLACKBOT_SOURCE_PORT=3337
# ═══════════════════════════════════════════════════════════════════
# Channel Configuration
# ═══════════════════════════════════════════════════════════════════
BLACKBOT_CHANNELS={channels_str}
# ═══════════════════════════════════════════════════════════════════
# Authentication & Security
# ═══════════════════════════════════════════════════════════════════
# NickServ Authentication (Libera.Chat, OFTC, etc.)
BLACKBOT_NICKSERV_ENABLED={str(config.nickserv_enabled).lower()}
BLACKBOT_NICKSERV_NICK=NickServ
BLACKBOT_NICKSERV_BOTNICK={config.nickname}
"""
# ✅ ÎNTOTDEAUNA scrie parola (goală sau completată)
if config.nickserv_enabled and config.nickserv_password:
env_content += f"BLACKBOT_NICKSERV_PASSWORD={config.nickserv_password}\n"
else:
env_content += "BLACKBOT_NICKSERV_PASSWORD=\n"
env_content += f"""
# QuakeNet Q Authentication
BLACKBOT_QUAKENET_AUTH_ENABLED={str(config.quakenet_auth_enabled).lower()}
"""
# ✅ ÎNTOTDEAUNA scrie username și password (goale sau completate)
if config.quakenet_auth_enabled and config.quakenet_username:
env_content += f"BLACKBOT_QUAKENET_USERNAME={config.quakenet_username}\n"
else:
env_content += "BLACKBOT_QUAKENET_USERNAME=\n"
if config.quakenet_auth_enabled and config.quakenet_password:
env_content += f"BLACKBOT_QUAKENET_PASSWORD={config.quakenet_password}\n"
else:
env_content += "BLACKBOT_QUAKENET_PASSWORD=\n"
env_content += f"""
# Undernet X Authentication
BLACKBOT_UNDERNET_AUTH_ENABLED={str(config.undernet_auth_enabled).lower()}
"""