-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew_main.py
More file actions
1706 lines (1485 loc) · 70 KB
/
Copy pathnew_main.py
File metadata and controls
1706 lines (1485 loc) · 70 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
# активировать VENV: venv\Scripts\activate либо .\venv\Scripts\Activate.ps1
# КОМПИЛИЦИЯ:
# 1. cd "F:\Doki\СВОЙ ЗАПРЕТ\CODE PY\zapret-discord-youtube" 2. pyinstaller --noconsole --name="ZapretCustom" main.py
# # Если будет ошибка выполнения скриптов: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
"""
Zapret-Custom GUI - PyQt6 + QFluentWidgets версия
Современный интерфейс в стиле Hiddify с системой логирования
Установка: pip install PyQt6 PyQt6-Fluent-Widgets psutil
"""
import sys
import os
import subprocess
import platform
import urllib.request
import urllib.error
import ssl
import json
import socket
import signal
import webbrowser
import threading
import winreg
from datetime import datetime
from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QThread, QSize, QObject
from PyQt6.QtGui import QIcon, QFont, QPalette, QColor, QPixmap
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel
from qfluentwidgets import (
NavigationInterface, NavigationItemPosition,
PushButton, PrimaryPushButton, TransparentToolButton,
FluentIcon as FIF, setTheme, Theme, InfoBar, InfoBarPosition,
ComboBox, CheckBox, TextEdit, ListWidget, ScrollArea,
MessageBox, Dialog, BodyLabel, SubtitleLabel, TitleLabel,
StrongBodyLabel, CaptionLabel, ProgressRing, StateToolTip, isDarkTheme
)
import psutil
class Logger(QObject):
"""Централизованная система логирования"""
log_updated = pyqtSignal(str)
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Logger, cls).__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
if self._initialized:
return
super().__init__()
self._initialized = True
self.logs = []
self.max_logs = 1000
def log(self, level, message):
"""Добавление записи в лог"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] [{level}] {message}"
self.logs.append(log_entry)
# Ограничение количества логов
if len(self.logs) > self.max_logs:
self.logs = self.logs[-self.max_logs:]
self.log_updated.emit(log_entry)
print(log_entry) # Также выводим в консоль
def info(self, message):
"""Информационное сообщение"""
self.log("INFO", message)
def success(self, message):
"""Успешное действие"""
self.log("SUCCESS", message)
def warning(self, message):
"""Предупреждение"""
self.log("WARNING", message)
def error(self, message):
"""Ошибка"""
self.log("ERROR", message)
def get_all_logs(self):
"""Получить все логи"""
return "\n".join(self.logs)
def clear_logs(self):
"""Очистить логи"""
self.logs.clear()
self.info("Логи очищены")
class TestConnectionThread(QThread):
"""Поток для тестирования соединения"""
finished = pyqtSignal(str)
def run(self):
logger = Logger()
logger.info("Начато тестирование соединения")
try:
result = "═══════════════════════════════════════════════\n"
result += " ТЕСТИРОВАНИЕ СОЕДИНЕНИЯ\n"
result += "═══════════════════════════════════════════════\n\n"
websites = [
('Discord (Домен)', 'https://discord.com'),
('YouTube', 'https://www.youtube.com'),
('Google', 'https://www.google.com'),
('Cloudflare', 'https://www.cloudflare.com'),
('Yahoo', 'https://www.yahoo.com'),
('Amazon', 'https://www.amazon.com')
]
result += "ПРОВЕРКА ДОСТУПНОСТИ САЙТОВ:\n"
result += "─────────────────────────────────────────────\n"
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
for name, url in websites:
try:
request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
response = urllib.request.urlopen(request, timeout=5, context=ssl_context)
result += f"✓ {name:20} | Доступен (Код: {response.status})\n"
logger.info(f"Сайт {name} доступен (код {response.status})")
except urllib.error.URLError as e:
result += f"✗ {name:20} | Недоступен ({str(e.reason)[:30]})\n"
logger.warning(f"Сайт {name} недоступен: {str(e.reason)[:30]}")
except Exception as e:
result += f"✗ {name:20} | Ошибка ({str(e)[:30]})\n"
logger.error(f"Ошибка проверки {name}: {str(e)[:30]}")
result += "\nПРОВЕРКА IP И DNS:\n"
result += "─────────────────────────────────────────────\n"
try:
request = urllib.request.Request('https://api.ipify.org', headers={'User-Agent': 'Mozilla/5.0'})
ip_response = urllib.request.urlopen(request, timeout=5, context=ssl_context)
external_ip = ip_response.read().decode('utf-8')
result += f"✓ Внешний IP: {external_ip}\n"
logger.info(f"Внешний IP: {external_ip}")
except Exception as e:
result += f"✗ Не удалось получить внешний IP: {str(e)[:40]}\n"
logger.error(f"Не удалось получить внешний IP: {str(e)[:40]}")
dns_servers = [
('Google DNS', '8.8.8.8'),
('Cloudflare DNS', '1.1.1.1'),
('Yandex DNS', '77.88.8.8')
]
result += "\nПРОВЕРКА DNS СЕРВЕРОВ:\n"
result += "─────────────────────────────────────────────\n"
for name, dns_ip in dns_servers:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
sock.connect((dns_ip, 53))
sock.close()
result += f"✓ {name:20} | {dns_ip} - Доступен\n"
logger.info(f"DNS {name} ({dns_ip}) доступен")
except Exception as e:
result += f"✗ {name:20} | {dns_ip} - Недоступен\n"
logger.warning(f"DNS {name} ({dns_ip}) недоступен")
result += "\nПРОВЕРКА DNS РЕЗОЛВИНГА:\n"
result += "─────────────────────────────────────────────\n"
test_domains = ['discord.com', 'google.com', 'cloudflare.com']
for domain in test_domains:
try:
ip = socket.gethostbyname(domain)
result += f"✓ {domain:20} → {ip}\n"
logger.info(f"DNS резолвинг {domain} → {ip}")
except Exception as e:
result += f"✗ {domain:20} → Не удалось разрешить\n"
logger.error(f"Не удалось разрешить {domain}")
result += "\n═══════════════════════════════════════════════\n"
result += " ТЕСТИРОВАНИЕ ЗАВЕРШЕНО\n"
result += "═══════════════════════════════════════════════\n"
logger.success("Тестирование соединения завершено успешно")
self.finished.emit(result)
except Exception as e:
logger.error(f"Критическая ошибка при тестировании: {str(e)}")
self.finished.emit(f"Критическая ошибка при тестировании:\n{str(e)}")
class HomeInterface(QWidget):
"""Главная страница с кнопкой подключения"""
def __init__(self, parent=None):
super().__init__(parent)
self.zapret_process = None
self.zapret_pid = None
self.selected_config = None
self.script_dir = os.path.dirname(os.path.abspath(__file__))
self.is_connected = False
self.logger = Logger()
self.setObjectName("homeInterface")
self.init_ui()
self.load_settings()
self.logger.info("Интерфейс HomeInterface инициализирован")
def init_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(40, 40, 40, 40)
layout.setSpacing(20)
title = TitleLabel("Zapret Custom", self)
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(title)
version_label = CaptionLabel("version 0.3", self)
version_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(version_label)
layout.addStretch(1)
center_widget = QWidget()
center_layout = QVBoxLayout(center_widget)
center_layout.setSpacing(30)
center_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.connection_icon = QLabel()
self.connection_icon.setFixedSize(180, 180)
self.connection_icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.update_icon_theme()
icon_path = os.path.join(self.script_dir, 'iconhome.png')
if os.path.exists(icon_path):
pixmap = QPixmap(icon_path)
self.connection_icon.setPixmap(pixmap.scaled(120, 120, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation))
else:
self.connection_icon.setText("⚡")
center_layout.addWidget(self.connection_icon, 0, Qt.AlignmentFlag.AlignCenter)
self.connect_button = PrimaryPushButton("Нажмите для подключения", self)
self.connect_button.setFixedSize(280, 50)
self.connect_button.clicked.connect(self.toggle_connection)
center_layout.addWidget(self.connect_button, 0, Qt.AlignmentFlag.AlignCenter)
self.status_label = StrongBodyLabel("Отключено", self)
self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.status_label.setStyleSheet("color: #f44336; font-size: 14px;")
center_layout.addWidget(self.status_label, 0, Qt.AlignmentFlag.AlignCenter)
self.config_label = BodyLabel("Конфигурация: Не выбрана", self)
self.config_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
center_layout.addWidget(self.config_label, 0, Qt.AlignmentFlag.AlignCenter)
layout.addWidget(center_widget)
layout.addStretch(2)
def update_icon_theme(self):
if self.is_connected:
if isDarkTheme():
self.connection_icon.setStyleSheet("""
QLabel {
background-color: #1a1a2e;
border-radius: 90px;
border: 2px solid #64B5F6;
}
""")
else:
self.connection_icon.setStyleSheet("""
QLabel {
background-color: #e3f2fd;
border-radius: 90px;
border: 2px solid #2196F3;
}
""")
else:
if isDarkTheme():
self.connection_icon.setStyleSheet("""
QLabel {
background-color: #2d2d2d;
border-radius: 90px;
border: 2px solid #444;
}
""")
else:
self.connection_icon.setStyleSheet("""
QLabel {
background-color: #f5f5f5;
border-radius: 90px;
border: 2px solid #ccc;
}
""")
def toggle_connection(self):
if self.is_connected:
self.stop_zapret()
else:
self.start_zapret()
def start_zapret(self):
if not self.selected_config:
self.logger.warning("Попытка запуска без выбранной конфигурации")
InfoBar.warning(
title="Ошибка",
content="Сначала выберите конфигурацию в Config Options!",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
return
if self.selected_config.startswith("version 1.8.3/"):
bat_path = os.path.join(self.script_dir, self.selected_config)
else:
bat_path = os.path.join(self.script_dir, self.selected_config)
if not os.path.exists(bat_path):
self.logger.error(f"Файл конфигурации не найден: {self.selected_config}")
InfoBar.error(
title="Ошибка",
content=f"Файл {self.selected_config} не найден!",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
return
try:
bat_dir = os.path.dirname(bat_path)
os.chdir(bat_dir)
if platform.system() == "Windows":
self.zapret_process = subprocess.Popen(
[bat_path],
shell=True,
creationflags=subprocess.CREATE_NEW_CONSOLE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
else:
self.zapret_process = subprocess.Popen(
['bash', bat_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
self.zapret_pid = self.zapret_process.pid
self.is_connected = True
self.animate_connection_start()
display_name = self.selected_config.replace("version 1.8.3/", "")
self.logger.success(f"Zapret запущен: {display_name} (PID: {self.zapret_pid})")
InfoBar.success(
title="Успех",
content=f"Zapret запущен: {display_name}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
except Exception as e:
self.logger.error(f"Ошибка запуска Zapret: {str(e)}")
InfoBar.error(
title="Ошибка",
content=f"Не удалось запустить: {str(e)}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
def stop_zapret(self):
if not self.zapret_process:
return
try:
if self.zapret_process.poll() is None:
if platform.system() == "Windows":
if self.zapret_pid:
subprocess.run(
['taskkill', '/PID', str(self.zapret_pid), '/F'],
capture_output=True,
timeout=5
)
self.zapret_process.terminate()
else:
os.kill(self.zapret_process.pid, signal.SIGTERM)
self.zapret_process = None
self.zapret_pid = None
self.is_connected = False
self.animate_connection_stop()
self.logger.success("Zapret остановлен")
InfoBar.success(
title="Успех",
content="Zapret остановлен!",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=2000,
parent=self
)
except Exception as e:
self.logger.error(f"Ошибка остановки Zapret: {str(e)}")
InfoBar.error(
title="Ошибка",
content=f"Не удалось остановить: {str(e)}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
def animate_connection_start(self):
self.update_icon_theme()
self.update_connection_ui()
def animate_connection_stop(self):
self.update_icon_theme()
self.update_connection_ui()
def update_connection_ui(self):
if self.is_connected:
self.connect_button.setText("Отключиться")
self.status_label.setText("Подключено")
self.status_label.setStyleSheet("color: #4CAF50; font-size: 14px;")
else:
self.connect_button.setText("Нажмите для подключения")
self.status_label.setText("Отключено")
self.status_label.setStyleSheet("color: #f44336; font-size: 14px;")
def set_config(self, config_name):
self.selected_config = config_name
display_name = config_name.replace("version 1.8.3/", "")
self.config_label.setText(f"Конфигурация: {display_name}")
self.config_label.setStyleSheet("color: #2196F3; font-size: 12px;")
self._save_selected_config()
self.logger.info(f"Выбрана конфигурация: {display_name}")
def _save_selected_config(self):
try:
settings_path = os.path.join(self.script_dir, 'settings.json')
settings = {}
if os.path.exists(settings_path):
with open(settings_path, 'r', encoding='utf-8') as f:
settings = json.load(f)
settings['selected_config'] = self.selected_config
with open(settings_path, 'w', encoding='utf-8') as f:
json.dump(settings, f, indent=4, ensure_ascii=False)
except Exception as e:
self.logger.error(f"Ошибка сохранения конфигурации: {e}")
def load_settings(self):
try:
settings_path = os.path.join(self.script_dir, 'settings.json')
if os.path.exists(settings_path):
with open(settings_path, 'r', encoding='utf-8') as f:
settings = json.load(f)
if 'selected_config' in settings:
self.selected_config = settings['selected_config']
display_name = self.selected_config.replace("version 1.8.3/", "")
self.config_label.setText(f"Конфигурация: {display_name}")
self.config_label.setStyleSheet("color: #2196F3; font-size: 12px;")
self.logger.info(f"Загружена конфигурация из настроек: {display_name}")
except Exception as e:
self.logger.error(f"Ошибка загрузки настроек: {e}")
class ConfigInterface(QWidget):
config_selected = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.script_dir = os.path.dirname(os.path.abspath(__file__))
self.bat_directory = self.script_dir
self.logger = Logger()
self.setObjectName("configInterface")
self.init_ui()
self.load_bat_files()
self.logger.info("Интерфейс ConfigInterface инициализирован")
def init_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(30, 30, 30, 30)
layout.setSpacing(15)
title = SubtitleLabel("Выбор конфигурации", self)
layout.addWidget(title)
dir_layout = QHBoxLayout()
self.dir_label = BodyLabel(f"Директория: {self.bat_directory}", self)
dir_layout.addWidget(self.dir_label)
dir_button = PushButton("Выбрать папку", self)
dir_button.clicked.connect(self.select_directory)
dir_layout.addWidget(dir_button)
layout.addLayout(dir_layout)
self.config_list = ListWidget(self)
self.update_list_theme()
self.config_list.itemClicked.connect(self.on_config_clicked)
layout.addWidget(self.config_list)
buttons_layout = QHBoxLayout()
self.select_button = PrimaryPushButton("Выбрать", self)
self.select_button.clicked.connect(self.select_config)
self.select_button.setEnabled(False)
buttons_layout.addWidget(self.select_button)
refresh_button = PushButton("Обновить", self)
refresh_button.clicked.connect(self.load_bat_files)
buttons_layout.addWidget(refresh_button)
layout.addLayout(buttons_layout)
def update_list_theme(self):
if isDarkTheme():
self.config_list.setStyleSheet("""
QListWidget {
background-color: #2d2d2d;
border: 1px solid #444;
border-radius: 5px;
color: white;
outline: none;
}
QListWidget::item {
background-color: #2d2d2d;
color: white;
padding: 8px;
border-bottom: 1px solid #444;
}
QListWidget::item:selected {
background-color: #2196F3;
color: white;
}
QListWidget::item:hover {
background-color: #3d3d3d;
}
""")
else:
self.config_list.setStyleSheet("""
QListWidget {
background-color: white;
border: 1px solid #ddd;
border-radius: 5px;
color: black;
outline: none;
}
QListWidget::item {
background-color: white;
color: black;
padding: 8px;
border-bottom: 1px solid #eee;
}
QListWidget::item:selected {
background-color: #2196F3;
color: white;
}
QListWidget::item:hover {
background-color: #f5f5f5;
}
""")
def select_directory(self):
from PyQt6.QtWidgets import QFileDialog
directory = QFileDialog.getExistingDirectory(
self,
"Выберите директорию с BAT файлами",
self.bat_directory
)
if directory:
self.bat_directory = directory
self.dir_label.setText(f"Директория: {directory}")
self.load_bat_files()
self.logger.info(f"Изменена директория конфигураций: {directory}")
def load_bat_files(self):
try:
self.config_list.clear()
bat_files = [
f for f in os.listdir(self.bat_directory)
if f.endswith('.bat') and f.lower() != 'service.bat'
and os.path.isfile(os.path.join(self.bat_directory, f))
]
version_dir = os.path.join(self.bat_directory, 'version 1.8.3')
version_bat_files = []
if os.path.exists(version_dir) and os.path.isdir(version_dir):
version_bat_files = [
f"version 1.8.3/{f}" for f in os.listdir(version_dir)
if f.endswith('.bat') and f.lower() != 'service.bat'
and os.path.isfile(os.path.join(version_dir, f))
]
all_files = bat_files + version_bat_files
if all_files:
for bat_file in sorted(all_files):
self.config_list.addItem(bat_file)
self.select_button.setEnabled(False)
self.logger.info(f"Загружено конфигураций: {len(all_files)}")
else:
self.config_list.addItem("Нет доступных BAT файлов")
self.select_button.setEnabled(False)
self.logger.warning("BAT файлы не найдены")
except Exception as e:
self.logger.error(f"Ошибка загрузки BAT файлов: {str(e)}")
InfoBar.error(
title="Ошибка",
content=f"Ошибка загрузки файлов: {str(e)}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
def on_config_clicked(self, item):
if item.text() != "Нет доступных BAT файлов":
self.select_button.setEnabled(True)
def select_config(self):
current_item = self.config_list.currentItem()
if current_item and current_item.text() != "Нет доступных BAT файлов":
config_name = current_item.text()
self.config_selected.emit(config_name)
display_name = config_name.replace("version 1.8.3/", "")
InfoBar.success(
title="Успех",
content=f"Выбрана конфигурация: {display_name}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=2000,
parent=self
)
class TestConnectionInterface(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.test_thread = None
self.logger = Logger()
self.setObjectName("testInterface")
self.init_ui()
self.logger.info("Интерфейс TestConnectionInterface инициализирован")
def init_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(30, 30, 30, 30)
layout.setSpacing(15)
title = SubtitleLabel("Тестирование соединения", self)
layout.addWidget(title)
self.result_text = TextEdit(self)
self.result_text.setReadOnly(True)
self.update_text_theme()
self.result_text.setPlainText("Нажмите 'Запустить тест' для проверки соединения")
layout.addWidget(self.result_text)
buttons_layout = QHBoxLayout()
self.start_button = PrimaryPushButton("Запустить тест", self)
self.start_button.clicked.connect(self.start_test)
buttons_layout.addWidget(self.start_button)
clear_button = PushButton("Очистить", self)
clear_button.clicked.connect(self.clear_results)
buttons_layout.addWidget(clear_button)
layout.addLayout(buttons_layout)
def update_text_theme(self):
if isDarkTheme():
self.result_text.setStyleSheet("""
QTextEdit {
background-color: #2d2d2d;
border: 1px solid #444;
border-radius: 5px;
color: #ccc;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 11px;
padding: 10px;
}
""")
else:
self.result_text.setStyleSheet("""
QTextEdit {
background-color: white;
border: 1px solid #ddd;
border-radius: 5px;
color: #333;
font-family: 'Consolas', 'Monaco', monospace;
font-size: 11px;
padding: 10px;
}
""")
def start_test(self):
self.result_text.setPlainText("Выполняется тестирование...\nПожалуйста, подождите...\n")
self.start_button.setEnabled(False)
self.start_button.setText("Тестирование...")
self.test_thread = TestConnectionThread()
self.test_thread.finished.connect(self.test_finished)
self.test_thread.start()
def test_finished(self, result):
self.result_text.setPlainText(result)
self.start_button.setEnabled(True)
self.start_button.setText("Запустить тест")
def clear_results(self):
self.result_text.setPlainText("Нажмите 'Запустить тест' для проверки соединения")
class SettingsInterface(QWidget):
theme_changed = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.script_dir = os.path.dirname(os.path.abspath(__file__))
self.logger = Logger()
self.setObjectName("settingsInterface")
self.init_ui()
self.load_settings()
self.logger.info("Интерфейс SettingsInterface инициализирован")
def init_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(30, 30, 30, 30)
layout.setSpacing(20)
title = SubtitleLabel("Настройки", self)
layout.addWidget(title)
theme_label = StrongBodyLabel("Тема оформления:", self)
layout.addWidget(theme_label)
self.theme_combo = ComboBox(self)
self.theme_combo.addItems(["Темная", "Светлая"])
self.theme_combo.currentTextChanged.connect(self.change_theme)
layout.addWidget(self.theme_combo)
self.autostart_checkbox = CheckBox("Автозапуск Zapret при старте программы", self)
layout.addWidget(self.autostart_checkbox)
self.app_autostart_checkbox = CheckBox("Автозапуск приложения при входе в Windows", self)
layout.addWidget(self.app_autostart_checkbox)
self.bat_autostart_checkbox = CheckBox("Автозапуск BAT при старте приложения", self)
layout.addWidget(self.bat_autostart_checkbox)
self.update_combo_theme()
self.update_checkbox_theme()
buttons_label = StrongBodyLabel("Дополнительные функции:", self)
layout.addWidget(buttons_label)
self.service_button = PushButton("Настроить service.bat", self)
self.service_button.clicked.connect(self.configure_service)
layout.addWidget(self.service_button)
self.service_183_button = PushButton("Настроить service.bat 1.8.3", self)
self.service_183_button.clicked.connect(self.configure_service_183)
layout.addWidget(self.service_183_button)
self.list_button = PushButton("Настроить списки", self)
self.list_button.clicked.connect(self.configure_lists)
layout.addWidget(self.list_button)
self.warp_button = PushButton("Cloudflare WARP", self)
self.warp_button.clicked.connect(self.open_warp)
layout.addWidget(self.warp_button)
layout.addStretch()
self.save_button = PrimaryPushButton("Сохранить настройки", self)
self.save_button.clicked.connect(self.save_settings)
layout.addWidget(self.save_button)
def update_combo_theme(self):
if isDarkTheme():
self.theme_combo.setStyleSheet("""
QComboBox {
background-color: #2d2d2d;
border: 1px solid #444;
border-radius: 5px;
color: white;
padding: 5px;
min-width: 120px;
}
QComboBox::drop-down {
border: none;
}
QComboBox::down-arrow {
image: none;
border-left: 1px solid #444;
padding: 5px;
}
QComboBox QAbstractItemView {
background-color: #2d2d2d;
border: 1px solid #444;
color: white;
selection-background-color: #2196F3;
}
""")
else:
self.theme_combo.setStyleSheet("""
QComboBox {
background-color: white;
border: 1px solid #ddd;
border-radius: 5px;
color: black;
padding: 5px;
min-width: 120px;
}
QComboBox::drop-down {
border: none;
}
QComboBox::down-arrow {
image: none;
border-left: 1px solid #ddd;
padding: 5px;
}
QComboBox QAbstractItemView {
background-color: white;
border: 1px solid #ddd;
color: black;
selection-background-color: #2196F3;
}
""")
def update_checkbox_theme(self):
if isDarkTheme():
style = """
QCheckBox {
color: #ccc;
spacing: 8px;
}
QCheckBox::indicator {
width: 16px;
height: 16px;
border: 1px solid #444;
border-radius: 3px;
background-color: #2d2d2d;
}
QCheckBox::indicator:checked {
background-color: #2196F3;
border: 1px solid #2196F3;
}
"""
else:
style = """
QCheckBox {
color: #333;
spacing: 8px;
}
QCheckBox::indicator {
width: 16px;
height: 16px;
border: 1px solid #ccc;
border-radius: 3px;
background-color: white;
}
QCheckBox::indicator:checked {
background-color: #2196F3;
border: 1px solid #2196F3;
}
"""
self.autostart_checkbox.setStyleSheet(style)
self.app_autostart_checkbox.setStyleSheet(style)
self.bat_autostart_checkbox.setStyleSheet(style)
def change_theme(self, theme_name):
if theme_name == "Темная":
setTheme(Theme.DARK)
self.logger.info("Тема изменена на темную")
else:
setTheme(Theme.LIGHT)
self.logger.info("Тема изменена на светлую")
self.theme_changed.emit()
def configure_service(self):
bat_path = os.path.join(self.script_dir, "service.bat")
if not os.path.exists(bat_path):
self.logger.error("Файл service.bat не найден")
InfoBar.error(
title="Ошибка",
content=f"Файл service.bat не найден!",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
return
try:
if platform.system() == "Windows":
os.startfile(bat_path)
else:
subprocess.Popen(['open' if platform.system() == "Darwin" else 'xdg-open', bat_path])
self.logger.info("Открыт файл service.bat")
except Exception as e:
self.logger.error(f"Ошибка открытия service.bat: {str(e)}")
InfoBar.error(
title="Ошибка",
content=f"Не удалось открыть файл: {str(e)}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
def configure_service_183(self):
bat_path = os.path.join(self.script_dir, "version 1.8.3", "service.bat")
if not os.path.exists(bat_path):
self.logger.error("Файл service.bat 1.8.3 не найден")
InfoBar.error(
title="Ошибка",
content=f"Файл service.bat в папке version 1.8.3 не найден!",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
return
try:
if platform.system() == "Windows":
os.startfile(bat_path)
else:
subprocess.Popen(['open' if platform.system() == "Darwin" else 'xdg-open', bat_path])
self.logger.info("Открыт файл service.bat 1.8.3")
except Exception as e:
self.logger.error(f"Ошибка открытия service.bat 1.8.3: {str(e)}")
InfoBar.error(
title="Ошибка",
content=f"Не удалось открыть файл: {str(e)}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
def configure_lists(self):
lists_dir = os.path.join(self.script_dir, 'lists')
if os.path.exists(lists_dir):
try:
if platform.system() == "Windows":
os.startfile(lists_dir)
else:
subprocess.Popen(['open' if platform.system() == "Darwin" else 'xdg-open', lists_dir])
self.logger.info("Открыта папка lists")
except Exception as e:
self.logger.error(f"Ошибка открытия папки lists: {str(e)}")
InfoBar.error(
title="Ошибка",
content=f"Не удалось открыть папку: {str(e)}",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
else:
self.logger.warning("Папка lists не найдена")
InfoBar.warning(
title="Предупреждение",
content="Папка lists не найдена!",
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=3000,
parent=self
)
def open_warp(self):
webbrowser.open("https://1.1.1.1")
self.logger.info("Открыта страница Cloudflare WARP")
def load_settings(self):