-
Notifications
You must be signed in to change notification settings - Fork 366
/
interface.py
980 lines (808 loc) · 40 KB
/
interface.py
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
import asyncio
import ctypes
import os
import random
import sys
import traceback
import importlib
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog
from design import Ui_MainWindow
import aiohttp
from art import text2art
from imap_tools import MailboxLoginError
from termcolor import colored, cprint
from PySide6.QtCore import QThread, Signal, QUrl, Qt, QTimer
from PySide6.QtGui import QDesktopServices, QPixmap
import time
from better_proxy import Proxy
from core import Grass
from core.autoreger import AutoReger
from core.utils import logger, file_to_list
from core.utils.logger import logger, logging_setup
from core.utils.accounts_db import AccountsDB
from core.utils.exception import EmailApproveLinkNotFoundException, LoginException, RegistrationException
from core.utils.generate.person import Person
# Пути по умолчанию
DEFAULT_ACCOUNTS_FILE_PATH = 'data/accounts.txt'
DEFAULT_PROXIES_FILE_PATH = 'data/proxies.txt'
DEFAULT_WALLETS_FILE_PATH = 'data/wallets.txt'
DEFAULT_PROXY_DB_PATH = 'data/proxies_stats.db'
from data.config import (
ACCOUNTS_FILE_PATH, PROXIES_FILE_PATH, REGISTER_ACCOUNT_ONLY, THREADS,
REGISTER_DELAY, CLAIM_REWARDS_ONLY, APPROVE_EMAIL, APPROVE_WALLET_ON_EMAIL,
MINING_MODE, CONNECT_WALLET, WALLETS_FILE_PATH, SEND_WALLET_APPROVE_LINK_TO_EMAIL,
SINGLE_IMAP_ACCOUNT, SEMI_AUTOMATIC_APPROVE_LINK, PROXY_DB_PATH, MIN_PROXY_SCORE,
EMAIL_FOLDER, IMAP_DOMAIN, STOP_ACCOUNTS_WHEN_SITE_IS_DOWN, CHECK_POINTS,
TWO_CAPTCHA_API_KEY, ANTICAPTCHA_API_KEY, CAPMONSTER_API_KEY,
CAPSOLVER_API_KEY, CAPTCHAAI_API_KEY, USE_PROXY_FOR_IMAP, SHOW_LOGS_RARELY, REF_CODE
)
def bot_info(name: str = ""):
cprint(text2art(name), 'green')
if sys.platform == 'win32':
ctypes.windll.kernel32.SetConsoleTitleW(f"{name}")
print(
f"{colored('EnJoYeR <crypto/> moves:', color='light_yellow')} "
f"{colored('https://t.me/+tdC-PXRzhnczNDli', color='light_green')}"
)
async def worker_task(_id, account: str, proxy: str = None, wallet: str = None, db: AccountsDB = None):
consumables = account.split(":")[:3]
imap_pass = None
if SINGLE_IMAP_ACCOUNT:
consumables.append(SINGLE_IMAP_ACCOUNT.split(":")[1])
if len(consumables) == 1:
email = consumables[0]
password = Person().random_string(8)
elif len(consumables) == 2:
email, password = consumables
else:
email, password, imap_pass = consumables
grass = None
try:
grass = Grass(_id, email, password, proxy, db)
if MINING_MODE:
await asyncio.sleep(random.uniform(1, 2) * _id)
logger.info(f"Starting №{_id} | {email} | {password} | {proxy}")
else:
await asyncio.sleep(random.uniform(*REGISTER_DELAY))
logger.info(f"Starting №{_id} | {email} | {password} | {proxy}")
if REGISTER_ACCOUNT_ONLY:
await grass.create_account()
elif APPROVE_EMAIL or CONNECT_WALLET or SEND_WALLET_APPROVE_LINK_TO_EMAIL or APPROVE_WALLET_ON_EMAIL:
await grass.enter_account()
user_info = await grass.retrieve_user()
if APPROVE_EMAIL:
if user_info['result']['data'].get("isVerified"):
logger.info(f"{grass.id} | {grass.email} email already verified!")
else:
if SEMI_AUTOMATIC_APPROVE_LINK:
imap_pass = "placeholder"
elif imap_pass is None:
raise TypeError("IMAP password is not provided")
await grass.confirm_email(imap_pass)
if CONNECT_WALLET:
if user_info['result']['data'].get("walletAddress"):
logger.info(f"{grass.id} | {grass.email} wallet already linked!")
else:
await grass.link_wallet(wallet)
if user_info['result']['data'].get("isWalletAddressVerified"):
logger.info(f"{grass.id} | {grass.email} wallet already verified!")
else:
if SEND_WALLET_APPROVE_LINK_TO_EMAIL:
await grass.send_approve_link(endpoint="sendWalletAddressEmailVerification")
if APPROVE_WALLET_ON_EMAIL:
if SEMI_AUTOMATIC_APPROVE_LINK:
imap_pass = "placeholder"
elif imap_pass is None:
raise TypeError("IMAP password is not provided")
await grass.confirm_wallet_by_email(imap_pass)
elif CLAIM_REWARDS_ONLY:
await grass.claim_rewards()
else:
await grass.start()
return True
except (LoginException, RegistrationException) as e:
error_msg = f"{_id} | {e}"
logger.warning(error_msg)
return False
except MailboxLoginError as e:
error_msg = f"{_id} | {e}"
logger.error(error_msg)
return False
except EmailApproveLinkNotFoundException as e:
logger.warning(e)
return False
except aiohttp.ClientError as e:
error_msg = f"{_id} | Some connection error: {e}..."
logger.warning(error_msg)
return False
except Exception as e:
error_msg = f"{_id} | not handled exception | error: {e}\n{traceback.format_exc()}"
logger.error(error_msg)
return False
finally:
if grass:
try:
await grass.session.close()
except Exception as e:
logger.error(f"Error closing session: {e}")
async def main():
accounts = file_to_list(ACCOUNTS_FILE_PATH)
if not accounts:
logger.warning("No accounts found!")
return
proxies = [Proxy.from_str(proxy).as_url for proxy in file_to_list(PROXIES_FILE_PATH)]
if os.path.exists(PROXY_DB_PATH):
os.remove(PROXY_DB_PATH)
db = AccountsDB(PROXY_DB_PATH)
await db.connect()
for i, account in enumerate(accounts):
account = account.split(":")[0]
proxy = proxies[i] if len(proxies) > i else None
if await db.proxies_exist(proxy) or not proxy:
continue
await db.add_account(account, proxy)
await db.delete_all_from_extra_proxies()
await db.push_extra_proxies(proxies[len(accounts):])
autoreger = AutoReger.get_accounts(
(ACCOUNTS_FILE_PATH, PROXIES_FILE_PATH, WALLETS_FILE_PATH),
with_id=True,
static_extra=(db,)
)
threads = THREADS if not MINING_MODE else len(autoreger.accounts)
mode_msg = {
REGISTER_ACCOUNT_ONLY: "__REGISTER__ MODE",
APPROVE_EMAIL or CONNECT_WALLET or SEND_WALLET_APPROVE_LINK_TO_EMAIL or APPROVE_WALLET_ON_EMAIL: "__APPROVE__ MODE",
CLAIM_REWARDS_ONLY: "__CLAIM__ MODE"
}.get(True, "__MINING__ MODE")
logger.info(mode_msg)
await autoreger.start(worker_task, threads)
await db.close_connection()
class FarmingThread(QThread):
error = Signal(str)
finished = Signal()
account_error = Signal(str)
progress = Signal(str)
def __init__(self):
super().__init__()
self.loop = None
self.should_stop = False
self.db = None
self._cleanup_db()
def _cleanup_db(self):
"""Принудительно очищает соединения с БД"""
try:
import sqlite3
try:
conn = sqlite3.connect(PROXY_DB_PATH)
conn.close()
except:
pass
if os.path.exists(PROXY_DB_PATH):
try:
for _ in range(3):
try:
os.remove(PROXY_DB_PATH)
break
except PermissionError:
time.sleep(0.5)
except:
pass
except Exception as e:
logger.error(f"Error cleaning up database: {e}")
def run(self):
"""Запускает асинхронный код в отдельном потоке"""
try:
# Создаем и настраиваем event loop
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
# Запускаем асинхронный код через nest_asyncio
import nest_asyncio
nest_asyncio.apply(self.loop)
# Запускаем основной код
self.loop.run_until_complete(self._safe_run())
except Exception as e:
error_msg = f"Thread error: {str(e)}\n{traceback.format_exc()}"
logger.error(error_msg)
self.error.emit(error_msg)
finally:
try:
# Очищаем все задачи
pending = asyncio.all_tasks(self.loop)
self.loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
# Закрываем loop
self.loop.close()
except:
pass
self.finished.emit()
async def _safe_run(self):
"""Безопасный запуск асинхронного кода"""
try:
await self.run_main()
except asyncio.CancelledError:
logger.info("Task cancelled")
except Exception as e:
error_msg = f"Error in main loop: {str(e)}\n{traceback.format_exc()}"
logger.error(error_msg)
self.error.emit(error_msg)
def stop(self):
"""Останавливает выполнение"""
self.should_stop = True
if self.loop and self.loop.is_running():
try:
# Отменяем все задачи
for task in asyncio.all_tasks(self.loop):
self.loop.call_soon_threadsafe(task.cancel)
# Останавливаем loop
self.loop.call_soon_threadsafe(self.loop.stop)
except:
pass
# Ждем завершения
self.wait(2000)
# Принудительно завершаем если не завершился
if self.isRunning():
self.terminate()
async def run_main(self):
"""Запускает main() с проверкой флага остановки"""
try:
# Периодически даем управление главному потоку
QApplication.processEvents()
mining_mode, register_only = update_global_config()
self._cleanup_db()
self.db = AccountsDB(PROXY_DB_PATH)
await self.db.connect()
accounts = file_to_list(ACCOUNTS_FILE_PATH)
if not accounts:
self.error.emit("No accounts found!")
return
if self.should_stop:
return
proxies = [Proxy.from_str(proxy).as_url for proxy in file_to_list(PROXIES_FILE_PATH)]
for i, account in enumerate(accounts):
if self.should_stop:
break
account = account.split(":")[0]
proxy = proxies[i] if len(proxies) > i else None
if await self.db.proxies_exist(proxy) or not proxy:
continue
await self.db.add_account(account, proxy)
# Периодически обрабатываем события UI
if i % 5 == 0: # Каждые 5 аккаунтов
QApplication.processEvents()
if not self.should_stop:
await self.db.delete_all_from_extra_proxies()
await self.db.push_extra_proxies(proxies[len(accounts):])
autoreger = AutoReger.get_accounts(
(ACCOUNTS_FILE_PATH, PROXIES_FILE_PATH, WALLETS_FILE_PATH),
with_id=True,
static_extra=(self.db,)
)
if not autoreger:
error_msg = "Failed to initialize AutoReger"
logger.error(error_msg)
self.error.emit(error_msg)
return
threads = THREADS if not MINING_MODE else len(autoreger.accounts)
mode_msg = {
REGISTER_ACCOUNT_ONLY: "__REGISTER__ MODE",
APPROVE_EMAIL or CONNECT_WALLET or SEND_WALLET_APPROVE_LINK_TO_EMAIL or APPROVE_WALLET_ON_EMAIL: "__APPROVE__ MODE",
CLAIM_REWARDS_ONLY: "__CLAIM__ MODE"
}.get(True, "__MINING__ MODE")
logger.info(mode_msg)
# Check captcha API key before starting if in register mode
if REGISTER_ACCOUNT_ONLY:
captcha_key = None
for key_name in [TWO_CAPTCHA_API_KEY, ANTICAPTCHA_API_KEY, CAPMONSTER_API_KEY, CAPSOLVER_API_KEY,
CAPTCHAAI_API_KEY]:
if key_name:
captcha_key = key_name
break
if not captcha_key:
error_msg = "No valid captcha solving service API key found"
logger.error(error_msg)
self.error.emit(error_msg)
return
try:
await autoreger.start(worker_task, threads)
except Exception as e:
error_msg = f"Error in autoreger: {str(e)}\n{traceback.format_exc()}"
logger.error(error_msg)
self.error.emit(error_msg)
# Continue execution despite errors
except Exception as e:
error_msg = f"Critical error: {str(e)}\n{traceback.format_exc()}"
logger.error(error_msg)
self.error.emit(error_msg)
finally:
if self.db:
try:
await self.db.close_connection()
except Exception as e:
logger.error(f"Error closing DB connection: {e}")
def update_global_config():
"""Обновляет глобальные переменные из файла конфига"""
try:
# Принудительно перечитываем файл конфига
with open('data/config.py', 'r', encoding='utf-8') as file:
config_content = file.read()
# Создаем новое пространство имен для выполнения конфига
config_globals = {}
exec(config_content, config_globals)
# Обновляем глобальные переменные в текущем мо��уле
for key, value in config_globals.items():
if not key.startswith('__'):
globals()[key] = value
# Обновляем локальные значения API ключей если они существуют
if hasattr(globals().get('MainApp', None), 'local_captcha_keys'):
for service, param_name in globals()['MainApp'].captcha_services.items():
globals()['MainApp'].local_captcha_keys[service] = config_globals.get(param_name, "")
return config_globals.get('MINING_MODE', False), config_globals.get('REGISTER_ACCOUNT_ONLY', False)
except Exception as e:
logger.error(f"Error updating global config: {e}")
return False, False
class MainApp(QMainWindow):
def __init__(self):
try:
super(MainApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Добавим обработку ошибок при загрузке изображения
try:
pixmap = QPixmap("core/static/image.png")
if not pixmap.isNull():
self.ui.label_13.setPixmap(pixmap)
self.ui.label_13.setFixedSize(pixmap.size())
self.ui.label_13.setScaledContents(False)
else:
logger.error("Failed to load image: image is null")
except Exception as e:
logger.error(f"Error loading image: {e}")
# Остальной код инициализации...
except Exception as e:
logger.error(f"Error initializing MainApp: {e}\n{traceback.format_exc()}")
# Пытаемся продолжить инициализацию
super(MainApp, self).__init__()
# Добавляем атрибуты для управления задачей
self.farming_thread = None
self.is_running = False
# Настройка логирования для GUI
logging_setup(gui_mode=True, text_edit=self.ui.textEdit_Log)
# Устанавлваем первую вкладку активной
self.ui.tabWidget.setCurrentIndex(0)
# Связь значений ComboBox с параметрами конфига
self.captcha_services = {
"TWO_CAPTCHA": "TWO_CAPTCHA_API_KEY",
"ANTICAPTCHA": "ANTICAPTCHA_API_KEY",
"CAPMONSTER": "CAPMONSTER_API_KEY",
"CAPSOLVER": "CAPSOLVER_API_KEY",
"CAPTCHAAI": "CAPTCHAAI_API_KEY"
}
# Локальное хранилище значений API-ключей
self.local_captcha_keys = {
"TWO_CAPTCHA": globals().get("TWO_CAPTCHA_API_KEY", ""),
"ANTICAPTCHA": globals().get("ANTICAPTCHA_API_KEY", ""),
"CAPMONSTER": globals().get("CAPMONSTER_API_KEY", ""),
"CAPSOLVER": globals().get("CAPSOLVER_API_KEY", ""),
"CAPTCHAAI": globals().get("CAPTCHAAI_API_KEY", "")
}
# Сохраняем начальные значения параметров
self.initial_params = {
'THREADS': THREADS,
'MIN_PROXY_SCORE': MIN_PROXY_SCORE,
'EMAIL_FOLDER': EMAIL_FOLDER,
'IMAP_DOMAIN': IMAP_DOMAIN,
'REGISTER_DELAY': REGISTER_DELAY,
'APPROVE_EMAIL': APPROVE_EMAIL,
'CONNECT_WALLET': CONNECT_WALLET,
'SEND_WALLET_APPROVE_LINK_TO_EMAIL': SEND_WALLET_APPROVE_LINK_TO_EMAIL,
'APPROVE_WALLET_ON_EMAIL': APPROVE_WALLET_ON_EMAIL,
'SEMI_AUTOMATIC_APPROVE_LINK': SEMI_AUTOMATIC_APPROVE_LINK,
'SINGLE_IMAP_ACCOUNT': SINGLE_IMAP_ACCOUNT,
'USE_PROXY_FOR_IMAP': USE_PROXY_FOR_IMAP,
'STOP_ACCOUNTS_WHEN_SITE_IS_DOWN': STOP_ACCOUNTS_WHEN_SITE_IS_DOWN,
'CHECK_POINTS': CHECK_POINTS,
'SHOW_LOGS_RARELY': SHOW_LOGS_RARELY,
'CLAIM_REWARDS_ONLY': CLAIM_REWARDS_ONLY,
'REF_CODE': REF_CODE,
}
# Инициализация полей
self.ui.lineEdit_Threads.setText(str(THREADS))
self.ui.lineEdit_MinProxyScore.setText(str(MIN_PROXY_SCORE))
self.ui.lineEdit_EmailFolder.setText(EMAIL_FOLDER)
self.ui.lineEdit_ImapDomain.setText(IMAP_DOMAIN)
self.ui.lineEdit_REFCODE.setText(REF_CODE)
self.ui.lineEdit_Min.setText(str(REGISTER_DELAY[0]))
self.ui.lineEdit_Max.setText(str(REGISTER_DELAY[1]))
# Конвертируем булевы значения из config в Python-формат
'''Tab1'''
self.ui.checkBox_ApproveEmail.setChecked(self.convert_to_bool(APPROVE_EMAIL))
self.ui.checkBox_ConnectWallet.setChecked(self.convert_to_bool(CONNECT_WALLET))
self.ui.checkBox_SendWallerApproveForEmail.setChecked(self.convert_to_bool(SEND_WALLET_APPROVE_LINK_TO_EMAIL))
self.ui.checkBox_ApproveWalletOnEmail.setChecked(self.convert_to_bool(APPROVE_WALLET_ON_EMAIL))
self.ui.checkBox_SemiAutoApproveLink.setChecked(self.convert_to_bool(SEMI_AUTOMATIC_APPROVE_LINK))
self.ui.checkBox_SingleMapAccount.setChecked(self.convert_to_bool(SINGLE_IMAP_ACCOUNT))
self.ui.checkBox_UseProxyForImap.setChecked(self.convert_to_bool(USE_PROXY_FOR_IMAP))
'''Tab2'''
self.ui.checkBox_TimeOutFarm.setChecked(self.convert_to_bool(STOP_ACCOUNTS_WHEN_SITE_IS_DOWN))
self.ui.checkBox_CheckPoints.setChecked(self.convert_to_bool(CHECK_POINTS))
self.ui.checkBox_RarelyShowLogs.setChecked(self.convert_to_bool(SHOW_LOGS_RARELY))
'''Tab3'''
self.ui.checkBox_ClaimRewardOnly.setChecked(self.convert_to_bool(CLAIM_REWARDS_ONLY))
# Очистка comboBox и добавление начений
self.ui.comboBox_CaptchaService.clear()
self.ui.comboBox_CaptchaService.addItems(self.captcha_services.keys())
# Установка текущего значения lineEdit_CapthaAPI
self.update_lineedit_with_local_values()
# Подключение событий
self.ui.pushButton_Save.clicked.connect(self.save_changes)
self.ui.comboBox_CaptchaService.currentTextChanged.connect(self.update_lineedit_with_local_values)
self.ui.lineEdit_CapthaAPI.textChanged.connect(self.update_local_value)
# Привязка кнопок к функции изменения путей
self.ui.pushButton_AccountsFile.clicked.connect(
lambda: self.update_file_path("ACCOUNTS_FILE_PATH", self.ui.pushButton_AccountsFile)
)
self.ui.pushButton_ProxyFile.clicked.connect(
lambda: self.update_file_path("PROXIES_FILE_PATH", self.ui.pushButton_ProxyFile)
)
self.ui.pushButton_WalletsFile.clicked.connect(
lambda: self.update_file_path("WALLETS_FILE_PATH", self.ui.pushButton_WalletsFile)
)
self.ui.pushButton_ProxyDB.clicked.connect(
lambda: self.update_file_path("PROXY_DB_PATH", self.ui.pushButton_ProxyDB)
)
# Привязка кнопки Default
self.ui.pushButton_Default.clicked.connect(self.reset_to_default)
# Привязка изменений REGISTER_DELAY
self.ui.lineEdit_Min.textChanged.connect(self.update_register_delay)
self.ui.lineEdit_Max.textChanged.connect(self.update_register_delay)
# Добавляем подключение кнопки StartFarming
self.ui.pushButton_StartFarming.clicked.connect(self.toggle_farming)
# Добавляем подключение кнопки Registration
self.ui.pushButton_Registration.clicked.connect(self.start_registration)
# Добавьте эти строки после других подключений кнопок
self.ui.pushButton_Instructions.clicked.connect(self.open_instructions)
self.ui.pushButton_more.clicked.connect(self.open_telegram)
self.ui.pushButton_Web3.clicked.connect(self.open_web3)
# Initialize thread
self.farming_thread = None
self.is_running = False
# Setup logging for GUI
logging_setup(gui_mode=True, text_edit=self.ui.textEdit_Log)
# Connect error handlers
self.setup_error_handlers()
# Rest of initialization...
# Добавляем таймер для обновления UI
self.update_timer = QTimer()
self.update_timer.timeout.connect(self.process_events)
self.update_timer.start(100) # Обновляем каждые 100мс
def setup_error_handlers(self):
"""Setup error handlers for the UI"""
if self.farming_thread:
self.farming_thread.error.connect(self.on_error)
self.farming_thread.finished.connect(self.on_finished)
self.farming_thread.account_error.connect(self.on_account_error)
def on_error(self, error_msg):
"""Handle errors in the UI"""
logger.error(error_msg)
# Make sure UI stays responsive
self.stop_farming()
# Show error in UI console
self.ui.textEdit_Log.append(f"ERROR: {error_msg}")
def on_account_error(self, error_msg):
"""Handle individual account errors"""
logger.warning(error_msg)
# Show in UI console but don't stop
self.ui.textEdit_Log.append(f"Account Error: {error_msg}")
def on_finished(self):
"""Handle thread completion"""
logger.info("Process completed")
self.stop_farming()
self.ui.textEdit_Log.append("Process completed")
def update_config_param(self, param_name, value):
try:
with open('data/config.py', 'r', encoding='utf-8') as file:
lines = file.readlines()
with open('data/config.py', 'w', encoding='utf-8') as file:
for line in lines:
if line.startswith(param_name):
if isinstance(value, str):
file.write(f"{param_name} = '{value}'\n")
elif isinstance(value, bool):
file.write(f"{param_name} = {str(value)}\n")
elif isinstance(value, tuple):
file.write(f"{param_name} = {value}\n")
else:
file.write(f"{param_name} = {value}\n")
else:
file.write(line)
logger.info(f"Parameter {param_name} changed to {value}.")
except Exception as e:
logger.error(f"Error updating parameter {param_name}: {e}")
def convert_to_bool(self, value):
if isinstance(value, str):
return value.lower() == "true"
return bool(value)
def update_lineedit_with_local_values(self):
current_service = self.ui.comboBox_CaptchaService.currentText()
if current_service in self.local_captcha_keys:
self.ui.lineEdit_CapthaAPI.setText(self.local_captcha_keys[current_service])
def update_local_value(self):
current_service = self.ui.comboBox_CaptchaService.currentText()
if current_service in self.local_captcha_keys:
self.local_captcha_keys[current_service] = self.ui.lineEdit_CapthaAPI.text()
def update_file_path(self, param_name, button):
file_path, _ = QFileDialog.getOpenFileName(self, "Choose a file", "", "All Files (*)")
if file_path:
self.update_config_param(param_name, file_path)
button.setText(f"Updated: {file_path.split('/')[-1]}")
logger.info(f"{param_name} updated to {file_path}.")
def reset_to_default(self):
default_paths = {
"ACCOUNTS_FILE_PATH": DEFAULT_ACCOUNTS_FILE_PATH,
"PROXIES_FILE_PATH": DEFAULT_PROXIES_FILE_PATH,
"WALLETS_FILE_PATH": DEFAULT_WALLETS_FILE_PATH,
"PROXY_DB_PATH": DEFAULT_PROXY_DB_PATH,
}
for param_name, default_path in default_paths.items():
self.update_config_param(param_name, default_path)
self.initial_params[param_name] = default_path
logger.info(f"{param_name} updated to {default_path}.")
self.ui.pushButton_AccountsFile.setText(f"{DEFAULT_ACCOUNTS_FILE_PATH.split('/')[-1]}")
self.ui.pushButton_ProxyFile.setText(f"{DEFAULT_PROXIES_FILE_PATH.split('/')[-1]}")
self.ui.pushButton_WalletsFile.setText(f"{DEFAULT_WALLETS_FILE_PATH.split('/')[-1]}")
self.ui.pushButton_ProxyDB.setText(f"{DEFAULT_PROXY_DB_PATH.split('/')[-1]}")
def update_register_delay(self):
try:
min_delay = int(self.ui.lineEdit_Min.text())
max_delay = int(self.ui.lineEdit_Max.text())
if min_delay >= 0 and max_delay > min_delay:
self.update_config_param("REGISTER_DELAY", (min_delay, max_delay))
except ValueError:
logger.error("Invalid REGISTER_DELAY.")
def save_changes(self):
try:
params_to_save = {
'THREADS': int(self.ui.lineEdit_Threads.text()),
'MIN_PROXY_SCORE': int(self.ui.lineEdit_MinProxyScore.text()),
'EMAIL_FOLDER': self.ui.lineEdit_EmailFolder.text(),
'IMAP_DOMAIN': self.ui.lineEdit_ImapDomain.text(),
'REF_CODE': self.ui.lineEdit_REFCODE.text(),
'REGISTER_DELAY': (
int(self.ui.lineEdit_Min.text()),
int(self.ui.lineEdit_Max.text())
),
'APPROVE_EMAIL': self.ui.checkBox_ApproveEmail.isChecked(),
'CONNECT_WALLET': self.ui.checkBox_ConnectWallet.isChecked(),
'SEND_WALLET_APPROVE_LINK_TO_EMAIL': self.ui.checkBox_SendWallerApproveForEmail.isChecked(),
'APPROVE_WALLET_ON_EMAIL': self.ui.checkBox_ApproveWalletOnEmail.isChecked(),
'SINGLE_IMAP_ACCOUNT': self.ui.checkBox_SingleMapAccount.isChecked(),
'USE_PROXY_FOR_IMAP': self.ui.checkBox_UseProxyForImap.isChecked(),
'STOP_ACCOUNTS_WHEN_SITE_IS_DOWN': self.ui.checkBox_TimeOutFarm.isChecked(),
'CHECK_POINTS': self.ui.checkBox_CheckPoints.isChecked(),
'SHOW_LOGS_RARELY': self.ui.checkBox_RarelyShowLogs.isChecked(),
'CLAIM_REWARDS_ONLY': self.ui.checkBox_ClaimRewardOnly.isChecked(),
}
# Сохраняем основные параметры
for param_name, new_value in params_to_save.items():
old_value = self.initial_params.get(param_name)
if old_value != new_value:
self.update_config_param(param_name, new_value)
logger.info(f"{param_name} updated from {old_value} to {new_value}.")
self.initial_params[param_name] = new_value
# Сохраняем API ключи капчи
for service, param_name in self.captcha_services.items():
api_key_value = self.local_captcha_keys[service]
old_value = globals().get(param_name)
if old_value != api_key_value:
self.update_config_param(param_name, api_key_value)
# Обновляем глобальную переменную сразу после сохранения
globals()[param_name] = api_key_value
logger.info(f"API-key for {service} updated to {api_key_value}.")
# Принудительно перезагружаем все модули, которые могут использовать конфиг
modules_to_reload = [
'data.config',
'core.grass',
'core.autoreger',
'core.utils.captcha_service'
]
for module_name in modules_to_reload:
try:
module = sys.modules.get(module_name)
if module:
importlib.reload(module)
except Exception as e:
logger.error(f"Error reloading module {module_name}: {e}")
# Обновляем глобальные переменные
update_global_config()
# Очищаем кэш импортов для модулей
importlib.invalidate_caches()
logger.info("All parameters saved and modules reloaded.")
except Exception as e:
logger.error(f"Error saving parameters: {e}")
def toggle_farming(self):
if not self.is_running:
self.ui.pushButton_StartFarming.setEnabled(False) # Блокируем кнопку на время запуска
QApplication.processEvents() # Обрабатываем события UI
try:
# Устанавливаем правильные режимы для фарминга
self.update_config_param("MINING_MODE", True)
self.update_config_param("REGISTER_ACCOUNT_ONLY", False)
# Обновляем конфиг после изменений
update_global_config()
self.is_running = True
self.ui.pushButton_StartFarming.setText("Stop Farming")
self.farming_thread = FarmingThread()
self.farming_thread.error.connect(self.on_farming_error)
self.farming_thread.finished.connect(self.on_farming_finished)
self.farming_thread.start()
finally:
self.ui.pushButton_StartFarming.setEnabled(True)
else:
self.stop_farming()
def start_farming(self):
"""Запускает процесс фарминга"""
try:
# Принудительно обновляем конфиг перед запуском
update_global_config()
self.is_running = True
self.ui.pushButton_StartFarming.setText("Stop Farming")
# Создаем и запускаем поток
self.farming_thread = FarmingThread()
self.farming_thread.error.connect(self.on_farming_error)
self.farming_thread.finished.connect(self.on_farming_finished)
self.farming_thread.start()
except Exception as e:
logger.error(f"Error starting mining: {e}")
self.stop_farming()
def stop_farming(self):
"""Останавливает процесс фарминга"""
try:
if not self.is_running:
return
self.ui.pushButton_StartFarming.setEnabled(False) # Блокируем кнопку
QApplication.processEvents()
try:
self.is_running = False
self.ui.pushButton_StartFarming.setText("Start Farming")
if self.farming_thread:
self.farming_thread.stop()
self.farming_thread.wait()
self.farming_thread = None
# Сбрасываем режимы
self.update_config_param("MINING_MODE", False)
update_global_config()
logger.info("Mining stopped")
finally:
self.ui.pushButton_StartFarming.setEnabled(True)
except Exception as e:
logger.error(f"Error stopping mining: {e}")
def on_farming_error(self, error_msg):
"""Обработчик ошибок фарминга"""
logger.error(f"Error in mining: {error_msg}")
self.stop_farming()
def on_farming_finished(self):
"""Обработчик завершения фарминга"""
logger.info("Mining finished")
self.stop_farming()
def closeEvent(self, event):
"""Обработчик закрытия окна"""
try:
# Останавливаем все процессы
if self.is_running:
try:
self.stop_farming()
except:
pass
try:
self.stop_registration()
except:
pass
# Принудительно завершаем все потоки
if self.farming_thread:
try:
self.farming_thread.stop()
self.farming_thread.wait(1000) # Ждем максимум 1 секунду
if self.farming_thread.isRunning():
self.farming_thread.terminate()
except:
pass
# Закрываем приложение
QApplication.instance().quit()
# Принудительно завершаем процесс
event.accept()
import os
os._exit(0) # Принудительное завершение процесса
except:
# В случае любой ошибки принудительно завершаем процесс
event.accept()
import os
os._exit(0)
def start_registration(self):
"""Запускает процесс регистрации"""
try:
# Принудительно обновляем конфиг перед запуском
update_global_config()
# Проверяем и обновляем режимы
mining_mode, register_only = update_global_config()
if mining_mode or not register_only:
self.update_config_param("MINING_MODE", False)
self.update_config_param("REGISTER_ACCOUNT_ONLY", True)
update_global_config() # Обновляем еще раз после изменений
# Остальной код запуска...
if self.is_running:
self.stop_farming()
self.is_running = True
self.ui.pushButton_Registration.setText("Stop register")
self.ui.pushButton_StartFarming.setEnabled(False)
self.farming_thread = FarmingThread()
self.farming_thread.error.connect(self.on_registration_error)
self.farming_thread.finished.connect(self.on_registration_finished)
self.farming_thread.start()
except Exception as e:
logger.error(f"Error starting registration: {e}")
self.stop_registration()
def stop_registration(self):
"""Останавливает процесс регистрации"""
try:
if not self.is_running:
return
self.is_running = False
self.ui.pushButton_Registration.setText("Start register")
self.ui.pushButton_StartFarming.setEnabled(True)
if self.farming_thread:
self.farming_thread.stop()
self.farming_thread.wait()
self.farming_thread = None
logger.info("Registration stopped")
except Exception as e:
logger.error(f"Error stopping registration: {e}")
def on_registration_error(self, error_msg):
"""Обработчик ошибок регистации"""
# logger.error(f"Error in registration: {error_msg}")
self.stop_registration()
def on_registration_finished(self):
"""Обработчик завершения регистрации"""
# logger.info("Registration finished")
self.stop_registration()
def open_instructions(self):
"""Открывает инструкции в браузере"""
QDesktopServices.openUrl(QUrl("https://teletype.in/@c6zr7/grass_for_EnJoYeR"))
logger.info("Opening instructions page...")
def open_telegram(self):
"""Открывает Telegram канал"""
QDesktopServices.openUrl(QUrl("https://t.me/web3_enjoyer_club"))
logger.info("Opening Telegram channel...")
def open_web3(self):
"""Открывает Web3 продукты"""
QDesktopServices.openUrl(QUrl("https://gemups.com/"))
logger.info("Opening Web3 products page...")
def process_events(self):
"""Обрабатывает события UI"""
QApplication.processEvents()
def global_exception_handler(exctype, value, traceback_obj):
"""Глобальный обработчик исключений"""
error_msg = f"Uncaught exception: {exctype.__name__}: {value}"
logger.error(error_msg)
logger.error("Traceback:", exc_info=(exctype, value, traceback_obj))
def start_ui():
"""Запускает UI с базовой обработкой ошибок"""
try:
# Устанавливаем глобальный обработчик исключений
sys.excepthook = global_exception_handler
# Инициализируем приложение
app = QApplication(sys.argv)
# Отключаем автоматическое закрытие
app.setQuitOnLastWindowClosed(False)
# Создаем и показываем главное окно
window = MainApp()
window.show()
# Запускаем главный цикл
return app.exec()
except Exception as e:
logger.error(f"Critical error in UI: {str(e)}\n{traceback.format_exc()}")
return 1
if __name__ == "__main__":
try:
sys.exit(start_ui())
except Exception as e:
logger.error(f"Fatal error: {str(e)}\n{traceback.format_exc()}")
sys.exit(1)