Skip to content

Commit f9b7788

Browse files
authored
Merge pull request #1 from yazconnect/main
Config Management & Professional Logging & Subscription Management System
2 parents c84ed2b + a5e1d03 commit f9b7788

7 files changed

Lines changed: 1791 additions & 32 deletions

File tree

examples/config_manager.py

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
#!/usr/bin/env python3
2+
"""
3+
V2Root Configuration Manager Example
4+
5+
This example demonstrates how to:
6+
1. Save and load V2Ray configurations
7+
2. Test multiple configurations
8+
3. Select the best performing configuration
9+
4. Apply and start a configuration
10+
"""
11+
12+
import os
13+
import sys
14+
import time
15+
from colorama import init, Fore, Style
16+
17+
# Add the parent directory to sys.path to import v2root
18+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19+
from v2root import V2ROOT
20+
21+
init(autoreset=True)
22+
23+
def main():
24+
# Initialize V2ROOT with custom ports
25+
v2root = V2ROOT(http_port=2300, socks_port=2301)
26+
27+
print(f"{Fore.CYAN}V2Root Configuration Manager Example{Style.RESET_ALL}")
28+
print(f"{Fore.CYAN}===================================={Style.RESET_ALL}")
29+
30+
while True:
31+
print("\nOptions:")
32+
print("1. Save a new configuration")
33+
print("2. List saved configurations")
34+
print("3. Load and test a configuration")
35+
print("4. Batch test multiple configurations")
36+
print("5. Reset network proxy")
37+
print("6. Exit")
38+
39+
choice = input("\nEnter your choice (1-6): ")
40+
41+
if choice == '1':
42+
# Save a new configuration
43+
config_str = input("Enter the V2Ray configuration string: ")
44+
name = input("Enter a name for this configuration (or press Enter for auto-name): ")
45+
name = name if name.strip() else None
46+
47+
try:
48+
file_path = v2root.save_config(config_str, name)
49+
print(f"{Fore.GREEN}Configuration saved to {file_path}{Style.RESET_ALL}")
50+
except Exception as e:
51+
print(f"{Fore.RED}Error: {str(e)}{Style.RESET_ALL}")
52+
53+
elif choice == '2':
54+
# List saved configurations
55+
configs = v2root.list_saved_configs()
56+
57+
elif choice == '3':
58+
# Load and test a configuration
59+
configs = v2root.list_saved_configs()
60+
if not configs:
61+
continue
62+
63+
index = input("Enter the number of the configuration to load: ")
64+
try:
65+
index = int(index) - 1
66+
if 0 <= index < len(configs):
67+
config = v2root.load_saved_config(configs[index])
68+
69+
print(f"{Fore.CYAN}Testing configuration...{Style.RESET_ALL}")
70+
try:
71+
latency = v2root.test_connection(config)
72+
print(f"{Fore.GREEN}Test successful! Latency: {latency}ms{Style.RESET_ALL}")
73+
74+
start = input("Do you want to start V2Ray with this configuration? (y/n): ")
75+
if start.lower() == 'y':
76+
v2root.set_config_string(config)
77+
v2root.start()
78+
except Exception as e:
79+
print(f"{Fore.RED}Test failed: {str(e)}{Style.RESET_ALL}")
80+
else:
81+
print(f"{Fore.RED}Invalid selection{Style.RESET_ALL}")
82+
except ValueError:
83+
print(f"{Fore.RED}Please enter a valid number{Style.RESET_ALL}")
84+
85+
elif choice == '4':
86+
# Batch test multiple configurations
87+
configs = v2root.list_saved_configs()
88+
if not configs:
89+
continue
90+
91+
config_list = []
92+
for config_name in configs:
93+
try:
94+
config = v2root.load_saved_config(config_name)
95+
config_list.append(config)
96+
except Exception as e:
97+
print(f"{Fore.RED}Error loading {config_name}: {str(e)}{Style.RESET_ALL}")
98+
99+
if not config_list:
100+
print(f"{Fore.RED}No valid configurations to test{Style.RESET_ALL}")
101+
continue
102+
103+
print(f"{Fore.CYAN}Testing {len(config_list)} configurations...{Style.RESET_ALL}")
104+
timeout = input("Enter timeout in seconds (default: 10): ")
105+
timeout = int(timeout) if timeout.strip() and timeout.isdigit() else 10
106+
107+
parallel = input("Test in parallel? (slower machines should use 'n') (y/n): ")
108+
parallel = parallel.lower() == 'y'
109+
110+
start_time = time.time()
111+
results = v2root.batch_test(config_list, timeout, parallel)
112+
elapsed = time.time() - start_time
113+
114+
print(f"{Fore.CYAN}Testing completed in {elapsed:.2f} seconds{Style.RESET_ALL}")
115+
116+
if results:
117+
print(f"{Fore.GREEN}Top 3 configurations by latency:{Style.RESET_ALL}")
118+
for i, (config, latency) in enumerate(results[:3], 1):
119+
print(f"{i}. Latency: {latency}ms - Config: {config[:50]}...")
120+
121+
use_best = input("Do you want to use the best configuration? (y/n): ")
122+
if use_best.lower() == 'y':
123+
best_config = results[0][0]
124+
v2root.set_config_string(best_config)
125+
v2root.start()
126+
else:
127+
print(f"{Fore.RED}No working configurations found{Style.RESET_ALL}")
128+
129+
elif choice == '5':
130+
# Reset network proxy
131+
try:
132+
v2root.reset_network_proxy()
133+
except Exception as e:
134+
print(f"{Fore.RED}Error: {str(e)}{Style.RESET_ALL}")
135+
136+
elif choice == '6':
137+
# Exit
138+
try:
139+
v2root.reset_network_proxy()
140+
except:
141+
pass
142+
print(f"{Fore.CYAN}Exiting...{Style.RESET_ALL}")
143+
break
144+
145+
else:
146+
print(f"{Fore.RED}Invalid choice. Please enter a number between 1 and 6.{Style.RESET_ALL}")
147+
148+
if __name__ == "__main__":
149+
try:
150+
main()
151+
except KeyboardInterrupt:
152+
print(f"{Fore.CYAN}\nExiting...{Style.RESET_ALL}")
153+
try:
154+
v2root = V2ROOT()
155+
v2root.reset_network_proxy()
156+
except:
157+
pass
158+
sys.exit(0)

examples/logging_demo.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#!/usr/bin/env python3
2+
"""
3+
V2Root Logging System Example
4+
5+
This example demonstrates how to:
6+
1. Configure the logging system
7+
2. Use different log levels
8+
3. Get log files and enable/disable file logging
9+
4. Create module-specific loggers
10+
"""
11+
12+
import os
13+
import sys
14+
import time
15+
16+
# Add the parent directory to sys.path to import v2root
17+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
18+
from v2root import configure_logger, get_logger, debug, info, warning, error, critical
19+
from v2root import V2ROOT
20+
21+
def demonstrate_log_levels():
22+
"""Demonstrate different log levels."""
23+
print("\n=== Log Levels ===")
24+
debug("This is a DEBUG message - detailed information for debugging")
25+
info("This is an INFO message - confirmation that things are working")
26+
warning("This is a WARNING message - something unexpected happened")
27+
error("This is an ERROR message - something failed but program continues")
28+
critical("This is a CRITICAL message - serious error, program may be unable to continue")
29+
30+
# Create a module-specific logger
31+
module_logger = get_logger("demo")
32+
module_logger.info("This message comes from the 'demo' logger")
33+
34+
def demonstrate_logger_configuration():
35+
"""Demonstrate how to configure the logger."""
36+
print("\n=== Logger Configuration ===")
37+
38+
# Change log level
39+
print("Changing log level to DEBUG...")
40+
configure_logger(log_level=10) # DEBUG = 10
41+
debug("This DEBUG message should now be visible")
42+
43+
# Change log level back to INFO
44+
print("Changing log level back to INFO...")
45+
configure_logger(log_level=20) # INFO = 20
46+
debug("This DEBUG message should NOT be visible")
47+
info("This INFO message should be visible")
48+
49+
# Disable file logging
50+
print("Disabling file logging...")
51+
configure_logger(log_to_file=False)
52+
info("This message will only go to console, not to file")
53+
54+
# Re-enable file logging with custom directory
55+
print("Enabling file logging with custom directory...")
56+
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
57+
configure_logger(log_to_file=True, log_dir=log_dir)
58+
info(f"This message will go to console and file in {log_dir}")
59+
60+
# Configure maximum file size and backup count
61+
print("Configuring log rotation...")
62+
configure_logger(max_file_size=1024*1024, backup_count=5) # 1MB, 5 backups
63+
info("Log files will now rotate at 1MB with 5 backup files")
64+
65+
def demonstrate_v2root_integration():
66+
"""Demonstrate how logging is integrated with V2ROOT."""
67+
print("\n=== V2ROOT Integration ===")
68+
69+
try:
70+
# Set DEBUG level to see initialization logs
71+
configure_logger(log_level=10)
72+
73+
# Initialize V2ROOT with custom ports
74+
v2root = V2ROOT(http_port=2300, socks_port=2301)
75+
76+
# Test a method that will be logged
77+
try:
78+
# This will likely fail but shows how errors are logged
79+
v2root.ping_server("example.com", 80)
80+
except Exception as e:
81+
print(f"Expected error: {str(e)}")
82+
83+
except Exception as e:
84+
print(f"Error initializing V2ROOT: {str(e)}")
85+
86+
def main():
87+
"""Main function demonstrating the logging system."""
88+
print("V2Root Logging System Example")
89+
print("=============================")
90+
91+
# Start with default logging configuration
92+
info("Starting logging demonstration")
93+
94+
# Show log levels
95+
demonstrate_log_levels()
96+
97+
# Show configuration options
98+
demonstrate_logger_configuration()
99+
100+
# Show V2ROOT integration
101+
demonstrate_v2root_integration()
102+
103+
print("\nLogging demonstration completed")
104+
info("Logging demonstration completed")
105+
106+
if __name__ == "__main__":
107+
main()

0 commit comments

Comments
 (0)