-
Notifications
You must be signed in to change notification settings - Fork 412
Expand file tree
/
Copy pathmain.py
More file actions
1903 lines (1710 loc) · 78.8 KB
/
Copy pathmain.py
File metadata and controls
1903 lines (1710 loc) · 78.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QGraphicsDropShadowEffect, QListWidgetItem, QListView, \
QWidget, QLabel, QFrame, QHBoxLayout, QVBoxLayout, QGridLayout, QFileDialog, QMessageBox, QTableWidget, \
QTableWidgetItem, QHeaderView, QPushButton, QAbstractItemView
from PyQt5.QtCore import Qt, QPropertyAnimation, QEasingCurve, QThread, pyqtSignal, QMutex, QSize, QEvent, QPoint, QTimer, QUrl
from PyQt5.QtGui import QMouseEvent, QCursor, QColor, QDesktopServices, QIcon
from PyQt5.uic import loadUi
from pathlib import Path
from dateutil import relativedelta
import utils.resources
import os, datetime, time, re, math, shutil, json, logging
import tempfile
from utils.deleteThread import *
from utils.multiDeleteThread import multiDeleteThread
from utils.selectVersion import *
from utils.selectVersion import check_dir, existing_user_config, find_all_wechat_paths, get_dir_name, is_wechat_like_account_dir
from utils.scanThread import ScanThread
# 设置应用程序在高DPI屏幕上启用高DPI缩放。Set the application to enable high DPI scaling on high DPI screens
# 注意事项:此行代码必须在QApplication实例化之前调用,否则会调用失败。Notes: This line of code must be called before the instantiation of the QApplication object; otherwise, it will fail
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
resource_dir = getattr(sys, "_MEIPASS", os.path.dirname(os.path.realpath(sys.executable)))
if sys.platform == "darwin":
working_dir = os.path.join(str(Path.home()), "Library", "Application Support", "Clean My WeChat")
else:
working_dir = os.path.dirname(os.path.realpath(sys.executable))
elif __file__:
resource_dir = os.path.split(os.path.realpath(__file__))[0]
working_dir = resource_dir
def ensure_writable_dir(path):
os.makedirs(path, exist_ok=True)
test_path = os.path.join(path, ".write_test")
with open(test_path, "w", encoding="utf-8") as f:
f.write("")
os.remove(test_path)
return path
try:
working_dir = ensure_writable_dir(working_dir)
except OSError:
working_dir = ensure_writable_dir(os.path.join(tempfile.gettempdir(), "Clean My WeChat"))
# 统一配置、日志、白名单、自动清理状态文件的位置,避免不同模块各读各的。
CONFIG_PATH = os.path.join(working_dir, "config.json")
LOG_PATH = os.path.join(working_dir, "cleanmywechat.log")
STATE_PATH = os.path.join(working_dir, "clean_state.json")
WHITELIST_PATH = os.path.join(working_dir, "whitelist.txt")
PREVIEW_PATH = os.path.join(working_dir, "last_scan_preview.txt")
APP_NAME = "Clean My WeChat"
APP_ORG = "CleanMyWechat"
APP_ICON_PATH = os.path.join(resource_dir, "images", "wechat.png")
logging.basicConfig(
handlers=[logging.FileHandler(LOG_PATH, encoding="utf-8")],
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
# 按扩展名分组,后续扫描预览和白名单判断都用这一套规则。
IMAGE_EXTS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tif', '.tiff', '.heic', '.dat'}
VIDEO_EXTS = {'.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv', '.m4v', '.3gp'}
DOCUMENT_EXTS = {'.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt', '.csv'}
ARCHIVE_EXTS = {'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'}
CACHE_EXTS = {'.cache', '.tmp', '.temp', '.log', '.old'}
# 这些属于数据库或程序运行组件,任何清理模式下都直接跳过。
SAFE_SKIP_EXTS = {
'.db', '.sqlite', '.sqlite3', '.db-shm', '.db-wal', '.ldb', '.sst',
'.dll', '.exe', '.msi', '.sys', '.ocx', '.pyd', '.so', '.dylib',
'.bat', '.cmd', '.ps1', '.vbs', '.js', '.jar', '.pak'
}
# 这些目录通常放运行组件或程序资源,不当成缓存目录递归。
PROTECTED_DIR_NAMES = {
'bin', 'runtime', 'runtimes', 'plugin', 'plugins', 'xplugin', 'module', 'modules',
'framework', 'frameworks', 'locales', 'resources', 'swiftshader', 'installer',
'update', 'updates', 'crashpad', 'web_shell', 'multitab'
}
# 只把名字明确指向缓存、日志、临时文件的目录加入新版微信系统区清理范围。
SAFE_CACHE_DIR_NAMES = {
'cache', 'code cache', 'gpucache', 'dawncache', 'shadercache', 'logs', 'log',
'temp', 'tmp', 'blob_storage'
}
CATEGORY_NAME = {
'cache': '缓存/日志',
'image': '图片',
'video': '视频',
'file': '普通文件',
'document': '文档',
'archive': '压缩包',
'other': '其他'
}
DEFAULT_GLOBAL_CONFIG = {
# 定时清理默认关闭,用户确认后可以在 config.json 里打开,避免第一次运行就自动清理。
"auto_clean_enable": False,
"auto_clean_interval_days": 30,
"auto_clean_confirm": True,
"run_at_startup": False,
"startup_clean_cache_only": False,
"direct_delete": False
}
LEGACY_GLOBAL_CONFIG_KEYS = (
"scan_system_cache",
"scan_wechat4_cache",
"scan_mini_program_cache",
"scan_wxwork_cache",
)
DEFAULT_USER_EXTRA = {
# 新增新版微信和企业微信常见目录,默认开启扫描,但仍受“保留天数”和“清理前确认”控制。
"client_type": "wechat",
"clean_msg_attach": True,
"clean_system_cache": True,
"clean_log_cache": True,
"clean_web_cache": True,
"clean_miniprogram_cache": True,
"clean_wxwork_cache": True,
# 白名单默认开启,重要办公文件默认不清理,降低误删风险。
"use_whitelist": True,
"whitelist_paths": [],
"whitelist_exts": [
".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf",
".dll", ".exe", ".msi", ".sys", ".ocx", ".pyd", ".pak"
],
# 文件类型细分,用户可以在 config.json 中精确控制。
"clean_ext_groups": {
"image": True,
"video": True,
"document": True,
"archive": True,
"cache": True,
"other": True
}
}
def load_json(path, default_value):
try:
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logging.exception("读取 JSON 失败:%s", path)
return default_value
def save_json(path, data):
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
def format_size(size):
try:
size = float(size)
except Exception:
return "0 B"
units = ["B", "KB", "MB", "GB", "TB"]
index = 0
while size >= 1024 and index < len(units) - 1:
size = size / 1024
index += 1
if index == 0:
return f"{int(size)} {units[index]}"
return f"{size:.2f} {units[index]}"
def app_icon():
return QIcon(APP_ICON_PATH)
def configure_application(app):
app.setApplicationName(APP_NAME)
app.setApplicationDisplayName(APP_NAME)
app.setOrganizationName(APP_ORG)
app.setWindowIcon(app_icon())
def normalize_ext(ext):
if not ext:
return ""
ext = ext.lower().strip()
if ext and not ext.startswith('.'):
ext = '.' + ext
return ext
def ensure_whitelist_file():
# 提供一个可直接编辑的白名单文件,不影响原有界面。
if not os.path.exists(WHITELIST_PATH):
with open(WHITELIST_PATH, "w", encoding="utf-8") as f:
f.write("# 一行一个白名单路径或扩展名,示例:\n")
f.write("# D:/重要文件\n")
f.write("# .pdf\n")
f.write("# .docx\n")
def read_whitelist_file():
ensure_whitelist_file()
paths = []
exts = []
try:
with open(WHITELIST_PATH, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('.') or (not os.path.sep in line and len(line) <= 8):
exts.append(normalize_ext(line))
else:
paths.append(os.path.abspath(os.path.expandvars(line)))
except Exception:
logging.exception("读取白名单失败")
return paths, exts
def ensure_config_defaults(config):
# 兼容旧 config.json,老配置不用手动删,启动后自动补齐新字段。
if not isinstance(config, dict):
config = {}
config.setdefault("data_dir", [])
config.setdefault("users", [])
global_config = config.setdefault("global", {})
for key, value in DEFAULT_GLOBAL_CONFIG.items():
global_config.setdefault(key, value)
for key in LEGACY_GLOBAL_CONFIG_KEYS:
global_config.pop(key, None)
for index, user in enumerate(config.get("users", [])):
for key, value in DEFAULT_USER_EXTRA.items():
if isinstance(value, dict):
user.setdefault(key, {})
for k2, v2 in value.items():
user[key].setdefault(k2, v2)
elif isinstance(value, list):
user.setdefault(key, list(value))
else:
user.setdefault(key, value)
# 账号和目录直接绑定,保留旧 data_dir 列表只是为了兼容旧版本。
if "data_dir" not in user and index < len(config.get("data_dir", [])):
user["data_dir"] = config["data_dir"][index]
valid_users = []
valid_data_dirs = []
for user in config.get("users", []):
data_dir = user.get("data_dir")
if data_dir and is_wechat_like_account_dir(data_dir):
valid_users.append(user)
valid_data_dirs.append(data_dir)
config["users"] = valid_users
config["data_dir"] = valid_data_dirs
return config
def load_config_file():
config = load_json(CONFIG_PATH, {"data_dir": [], "users": []})
config = ensure_config_defaults(config)
config = merge_detected_accounts(config)
try:
save_json(CONFIG_PATH, config)
except Exception:
logging.exception("写入配置默认值失败")
return config
def merge_detected_accounts(config):
try:
known_dirs = {
os.path.normcase(os.path.abspath(user.get("data_dir", "")))
for user in config.get("users", [])
if user.get("data_dir")
}
known_ids = {user.get("wechat_id") for user in config.get("users", [])}
for root_path in find_all_wechat_paths():
dir_list, user_list = get_dir_name(root_path)
for index, wechat_id in enumerate(user_list):
data_dir = dir_list[index]
dir_key = os.path.normcase(os.path.abspath(data_dir))
if dir_key in known_dirs or wechat_id in known_ids:
continue
config["users"].append(make_default_user_config(wechat_id, data_dir))
config["data_dir"].append(data_dir)
known_dirs.add(dir_key)
known_ids.add(wechat_id)
except Exception:
logging.exception("自动合并微信账号目录失败")
return ensure_config_defaults(config)
def make_default_user_config(wechat_id, data_dir):
user = {
"wechat_id": wechat_id,
"data_dir": data_dir,
"client_type": detect_client_type(data_dir),
"clean_days": "365",
"is_clean": True,
"clean_pic_cache": True,
"clean_file": False,
"clean_pic": True,
"clean_video": True,
"is_timer": True,
"timer": "0h"
}
ensure_config_defaults({"users": [user], "data_dir": [data_dir], "global": {}})
return user
def get_file_type(file_path, default_category="other"):
ext = os.path.splitext(str(file_path))[1].lower()
if ext in IMAGE_EXTS:
return "image"
if ext in VIDEO_EXTS:
return "video"
if ext in DOCUMENT_EXTS:
return "document"
if ext in ARCHIVE_EXTS:
return "archive"
if ext in CACHE_EXTS:
return "cache"
return default_category
def safe_file_size(path):
try:
return os.path.getsize(path)
except Exception:
logging.exception("读取文件大小失败:%s", path)
return 0
def is_sub_path(path, root):
try:
path = os.path.abspath(path).lower()
root = os.path.abspath(root).lower()
return path == root or path.startswith(root + os.sep)
except Exception:
return False
def detect_client_type(path):
path_lower = str(path or '').lower()
if 'wxwork' in path_lower or 'wework' in path_lower:
return 'wxwork'
return 'wechat'
def is_safe_cache_dir_name(name):
base_name = str(name).lower().strip()
if base_name in SAFE_CACHE_DIR_NAMES:
return True
return 'cache' in base_name or base_name.endswith('log') or base_name.endswith('logs')
def is_protected_file_path(path):
path_str = str(path)
ext = normalize_ext(os.path.splitext(path_str)[1])
if ext in SAFE_SKIP_EXTS:
return True
parts = [p.lower() for p in Path(path_str).parts]
return any(p in PROTECTED_DIR_NAMES for p in parts)
def apply_startup_setting(config):
# 支持开机启动。默认不打开;用户在 config.json 中把 run_at_startup 改成 true 后生效。
if os.name != 'nt':
return
try:
import winreg
key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
app_name = "CleanMyWechat"
global_config = config.get("global", {})
if getattr(sys, 'frozen', False):
command = '"{}" --startup'.format(sys.executable)
else:
command = '"{}" "{}" --startup'.format(sys.executable, os.path.abspath(__file__))
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE)
if global_config.get("run_at_startup", False):
winreg.SetValueEx(key, app_name, 0, winreg.REG_SZ, command)
else:
try:
winreg.DeleteValue(key, app_name)
except FileNotFoundError:
pass
winreg.CloseKey(key)
except Exception:
logging.exception("设置开机启动失败")
def open_local_path(path):
return QDesktopServices.openUrl(QUrl.fromLocalFile(str(Path(path).expanduser())))
# 主窗口
class Window(QMainWindow):
def mousePressEvent(self, event):
# 重写一堆方法使其支持拖动
if event.button() == Qt.LeftButton:
self.m_drag = True
self.m_DragPosition = event.globalPos() - self.pos()
event.accept()
# self.setCursor(QCursor(Qt.OpenHandCursor))
def mouseMoveEvent(self, QMouseEvent):
try:
if Qt.LeftButton and self.m_drag:
self.move(QMouseEvent.globalPos() - self.m_DragPosition)
QMouseEvent.accept()
except Exception:
logging.exception("窗口拖动失败")
def mouseReleaseEvent(self, QMouseEvent):
self.m_drag = False
# self.setCursor(QCursor(Qt.ArrowCursor))
def _frame(self):
# 边框
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground, True)
# 阴影
effect = QGraphicsDropShadowEffect(blurRadius=12, xOffset=0, yOffset=0)
effect.setColor(QColor(25, 25, 25, 170))
self.mainFrame.setGraphicsEffect(effect)
def doFadeIn(self):
# 动画
self.animation = QPropertyAnimation(self, b'windowOpacity')
# 持续时间250ms
self.animation.setDuration(250)
try:
# 尝试先取消动画完成后关闭窗口的信号
self.animation.finished.disconnect(self.close)
except Exception:
pass
self.animation.stop()
# 透明度范围从0逐渐增加到1
self.animation.setEasingCurve(QEasingCurve.InOutCubic)
self.animation.setStartValue(0)
self.animation.setEndValue(1)
self.animation.start()
def doFadeOut(self):
self.animation.stop()
# 动画完成则关闭窗口
self.animation.finished.connect(self.close)
# 透明度范围从1逐渐减少到0s
self.animation.setEasingCurve(QEasingCurve.InOutCubic)
self.animation.setStartValue(1)
self.animation.setEndValue(0)
self.animation.start()
def center_on_screen(self):
try:
screen = QApplication.desktop().availableGeometry(self)
self.move(screen.center() - self.rect().center())
except Exception:
pass
def setWarninginfo(self, text):
self.lab_info.setStyleSheet("""
.QLabel {
color: #614a22;
background-color: #fff4df;
border: 1px solid #f0d39a;
border-radius: 14px;
padding: 10px 18px;
font-size: 14px;
line-height: 150%;
}
""")
self.lab_info.setWordWrap(True) # 启用自动换行
self.lab_info.setText(text)
def setSuccessinfo(self, text):
self.lab_info.setStyleSheet("""
.QLabel {
color: #395246;
background-color: #e8f6ed;
border: 1px solid #c8e8d2;
border-radius: 14px;
padding: 10px 18px;
font-size: 14px;
line-height: 150%;
}
""")
self.lab_info.setWordWrap(True) # 启用自动换行
self.lab_info.setText(text)
class ConfigWindow(Window):
Signal_OneParameter = pyqtSignal(int)
config = {}
def _connect(self):
self.combo_user.currentIndexChanged.connect(self.refresh_ui)
self.btn_close.clicked.connect(self.save_config)
self.btn_file.clicked.connect(self.open_file)
if hasattr(self, "btn_open_account"):
self.btn_open_account.clicked.connect(self.open_current_account_dir)
def simplify_config_ui(self):
self.setMinimumSize(780, 960)
self.btn_file.setText("重新选择目录")
if hasattr(self, "btn_open_account"):
self.btn_open_account.setText("打开文件夹")
self.btn_close.setText("保存设置")
self.check_is_clean.setText("启用这个账号的清理")
self.check_picdown.setText("图片")
self.check_files.setText("收到的文档")
self.check_video.setText("视频")
self.check_picscache.setText("图片缓存、小程序和公众号缓存")
if hasattr(self, "check_direct_delete"):
self.check_direct_delete.setText("直接删除,不移动到回收站")
if hasattr(self, "check_run_at_startup"):
self.check_run_at_startup.setText("开机自启动")
if hasattr(self, "check_auto_clean"):
self.check_auto_clean.setText("定期自动清理")
def open_current_account_dir(self):
self.config = load_config_file()
current_user = self.combo_user.currentText()
for value in self.config.get("users", []):
if value.get("wechat_id") == current_user:
data_dir = value.get("data_dir")
if data_dir and os.path.isdir(data_dir):
if not open_local_path(data_dir):
self.setWarninginfo("打开文件夹失败。")
return
self.setSuccessinfo(f"已打开账号文件夹:{data_dir}")
return
self.setWarninginfo("当前账号文件夹不存在,请重新选择目录。")
return
self.setWarninginfo("没有找到当前账号的文件夹路径。")
def open_file(self):
openfile_path = QFileDialog.getExistingDirectory(self, '选择微信数据目录', '')
if not openfile_path or openfile_path == '':
return False
if check_dir(openfile_path) == 0:
self.setSuccessinfo('读取路径成功!')
dir_list, user_list = get_dir_name(openfile_path)
# 如果已有用户配置,那么写入新的用户配置,否则默认写入新配置
user_config = []
existing_user_config_dic = existing_user_config()
for index, user_wx_id in enumerate(user_list):
user_dir = dir_list[index]
if user_wx_id in existing_user_config_dic:
uc = existing_user_config_dic[user_wx_id]
uc["data_dir"] = user_dir
uc["client_type"] = detect_client_type(user_dir)
user_config.append(uc)
else:
user_config.append(make_default_user_config(user_wx_id, user_dir))
config = ensure_config_defaults({"data_dir": dir_list, "users": user_config})
save_json(CONFIG_PATH, config)
self.load_config()
else:
self.setWarninginfo('请选择正确的文件夹!\n微信一般选 WeChat Files,企业微信一般选 WXWork。')
def save_config(self):
self.update_config()
self.doFadeOut()
def check_wechat_exists(self):
self.selectVersion = selectVersion()
self.scan = self.selectVersion.getAllPath()
self.version_scan = self.scan[0]
self.users_scan = self.scan[1]
if len(self.version_scan) == 0:
return False
else:
return True
def load_config(self):
self.config = load_config_file()
self._loading_config = True
self.combo_user.blockSignals(True)
self.combo_user.clear()
for value in self.config["users"]:
self.combo_user.addItem(value["wechat_id"])
self.combo_user.blockSignals(False)
if not self.config["users"]:
self._loading_config = False
self.setWarninginfo("没有检测到微信账号,请手动选择 WeChat Files 文件夹。")
return
self.apply_user_config_to_ui(self.config["users"][0])
self.apply_global_config_to_ui(self.config.get("global", {}))
self.current_account_id = self.config["users"][0]["wechat_id"]
self._loading_config = False
self.check_is_clean.setText("启用这个账号的清理")
if self.config.get("global", {}).get("direct_delete", False):
self.setSuccessinfo("当前已开启直接删除。清理前会再次确认。")
else:
self.setSuccessinfo("推荐使用默认选项。文件会先进入回收站,清理前会再次确认。")
self.simplify_config_ui()
def apply_user_config_to_ui(self, user_config):
self.line_gobackdays.setText(str(user_config.get("clean_days", 365)))
self.check_is_clean.setChecked(user_config.get("is_clean", True))
self.check_picdown.setChecked(user_config.get("clean_pic", True))
self.check_files.setChecked(user_config.get("clean_file", False))
self.check_video.setChecked(user_config.get("clean_video", True))
self.check_picscache.setChecked(user_config.get("clean_pic_cache", True))
def apply_global_config_to_ui(self, global_config):
if hasattr(self, "check_direct_delete"):
self.check_direct_delete.setChecked(global_config.get("direct_delete", False))
if hasattr(self, "check_run_at_startup"):
self.check_run_at_startup.setChecked(global_config.get("run_at_startup", False))
if hasattr(self, "check_auto_clean"):
self.check_auto_clean.setChecked(global_config.get("auto_clean_enable", False))
if hasattr(self, "line_auto_days"):
self.line_auto_days.setText(str(global_config.get("auto_clean_interval_days", 30)))
def refresh_ui(self):
if getattr(self, "_loading_config", False):
return
previous_account_id = getattr(self, "current_account_id", "")
current_account_id = self.combo_user.currentText()
if previous_account_id and previous_account_id != current_account_id:
self.persist_current_config(previous_account_id)
self.config = load_config_file()
for value in self.config["users"]:
if value["wechat_id"] == current_account_id:
self.apply_user_config_to_ui(value)
self.current_account_id = current_account_id
return
def persist_current_config(self, account_id=None, notify=False, emit_signal=False):
if not len(self.config):
return False
self.config = ensure_config_defaults(self.config)
global_config = self.config.setdefault("global", {})
if hasattr(self, "check_direct_delete"):
global_config["direct_delete"] = self.check_direct_delete.isChecked()
if hasattr(self, "check_run_at_startup"):
global_config["run_at_startup"] = self.check_run_at_startup.isChecked()
if hasattr(self, "check_auto_clean"):
global_config["auto_clean_enable"] = self.check_auto_clean.isChecked()
if hasattr(self, "line_auto_days"):
try:
interval_days = int(self.line_auto_days.text())
global_config["auto_clean_interval_days"] = str(max(interval_days, 1))
except ValueError:
global_config["auto_clean_interval_days"] = "30"
target_account_id = account_id or self.combo_user.currentText()
for value in self.config["users"]:
if value["wechat_id"] == target_account_id:
try:
days = int(self.line_gobackdays.text())
value["clean_days"] = str(max(days, 0))
except ValueError:
value["clean_days"] = "0"
value["is_clean"] = self.check_is_clean.isChecked()
value["clean_pic"] = self.check_picdown.isChecked()
value["clean_file"] = self.check_files.isChecked()
value["clean_video"] = self.check_video.isChecked()
value["clean_pic_cache"] = self.check_picscache.isChecked()
value["clean_miniprogram_cache"] = value["clean_pic_cache"]
value["clean_system_cache"] = value["clean_pic_cache"]
value["clean_log_cache"] = value["clean_pic_cache"]
value["clean_web_cache"] = value["clean_pic_cache"]
value["clean_ext_groups"] = {
"image": value["clean_pic"],
"video": value["clean_video"],
"document": value["clean_file"],
"archive": value["clean_file"],
"cache": value["clean_pic_cache"],
"other": value["clean_file"]
}
save_json(CONFIG_PATH, self.config)
apply_startup_setting(self.config)
if notify:
self.setSuccessinfo("更新配置文件成功")
if emit_signal:
self.Signal_OneParameter.emit(1)
return True
return False
def create_config(self):
if not os.path.exists(CONFIG_PATH):
if not self.check_wechat_exists():
self.setWarninginfo("默认位置没有微信,请自定义位置")
return
self.config = ensure_config_defaults({"data_dir": self.version_scan, "users": []})
for index, value in enumerate(self.users_scan):
data_dir = self.version_scan[index] if index < len(self.version_scan) else ""
self.config["users"].append(make_default_user_config(value, data_dir))
save_json(CONFIG_PATH, self.config)
self.load_config()
self.setSuccessinfo("请确认每个账号的删除内容及时间,以防误删!")
else:
self.setSuccessinfo("请确认每个账号的删除内容及时间,以防误删!")
self.load_config()
def update_config(self):
self.persist_current_config(notify=True, emit_signal=True)
def __init__(self):
super().__init__()
loadUi(os.path.join(resource_dir, "images", "config.ui"), self)
self.setWindowTitle(f"{APP_NAME} · 设置")
self.setWindowIcon(app_icon())
self._frame()
self._connect()
self.simplify_config_ui()
self.doFadeIn()
self.create_config()
self.show()
QTimer.singleShot(0, self.center_on_screen)
class MainWindow(Window):
def deal_emit_slot(self, set_status):
if set_status and not self.config_exists:
self.setSuccessinfo("已经准备好,可以开始了!")
self.config_exists = True
def keep_ui_responsive(self):
self.scan_tick = getattr(self, "scan_tick", 0) + 1
if self.scan_tick % 250 == 0:
self.bar_progress.setRange(0, 0)
QApplication.processEvents()
def closeEvent(self, event):
if hasattr(self, 'scan_thread') and self.scan_thread.isRunning():
self.scan_thread.stop()
self.scan_thread.wait()
sys.exit(0)
def eventFilter(self, object, event):
if event.type() == QEvent.MouseButtonPress:
if object == self.lab_close:
self.doFadeOut()
return True
elif object == self.lab_clean:
try:
self.setSuccessinfo("正在扫描可清理文件...")
self.justdoit()
except Exception as e:
logging.exception("清理失败")
self.setWarninginfo("清理失败:" + str(e) + "\n详情请查看 cleanmywechat.log")
return True
elif object == self.lab_config:
cw = ConfigWindow()
cw.Signal_OneParameter.connect(self.deal_emit_slot)
return True
elif hasattr(self, "lab_preview") and object == self.lab_preview:
try:
self.start_preview()
except Exception as e:
self.setWarninginfo(f"预览失败:{str(e)}")
return True
elif hasattr(self, "lab_execute_delete") and object == self.lab_execute_delete:
try:
self.execute_delete()
except Exception as e:
self.setWarninginfo(f"删除失败:{str(e)}")
return True
return False
def _eventfilter(self):
# 事件过滤
self.lab_close.installEventFilter(self)
self.lab_clean.installEventFilter(self)
self.lab_config.installEventFilter(self)
if hasattr(self, "lab_preview"):
self.lab_preview.installEventFilter(self)
if hasattr(self, "lab_execute_delete"):
self.lab_execute_delete.installEventFilter(self)
def simplify_home_ui(self):
self.setMinimumSize(560, 620)
self.centralwidget.setStyleSheet("""
QWidget#centralwidget {
background-color: #eef7f1;
}
""")
self.mainFrame.setStyleSheet("""
QFrame#mainFrame {
background-color: #f8fbf7;
border: 1px solid #dcebe1;
border-radius: 18px;
}
""")
self.lab_info.setMinimumHeight(72)
self.lab_info.setText("扫描微信缓存、日志和旧文件,清理前会再次确认。")
self.lab_info.setStyleSheet("""
.QLabel {
color: #395246;
background-color: #e8f6ed;
border: 1px solid #c8e8d2;
border-radius: 14px;
padding: 10px 18px;
font-size: 14px;
line-height: 150%;
}
""")
self.lab_clean.setText("扫描并清理")
self.lab_config.setText("设置")
self.lab_close.setText("退出")
self.lab_about.setText(f"{APP_NAME} · 简单、安全地释放微信占用空间")
self.lab_about.setStyleSheet("""
.QLabel {
color: #6a7d72;
font-size: 13px;
padding: 8px 0 2px 0;
}
""")
if hasattr(self, "lab_logo"):
self.lab_logo.show()
self.lab_logo.setMinimumSize(196, 196)
self.lab_logo.setStyleSheet("""
.QLabel {
image: url(:/icon/wechat.png);
background-color: #eaf8ee;
border: 1px solid #c9ecd3;
border-radius: 98px;
padding: 18px;
}
""")
self.bar_progress.setMinimumHeight(26)
self.bar_progress.setStyleSheet("""
.QProgressBar {
background-color: #e5efe8;
border: 1px solid #d1e2d6;
border-radius: 13px;
color: #395246;
font-size: 12px;
text-align: center;
}
QProgressBar::chunk {
background-color: #2fbf68;
border-radius: 12px;
}
""")
self.lab_clean.setMinimumHeight(48)
self.lab_clean.setStyleSheet("""
.QLabel {
color: #f8fbf7;
background-color: #16a85a;
border: 1px solid #149550;
border-radius: 24px;
font-size: 16px;
font-weight: 600;
padding: 0 34px;
}
.QLabel:hover {
background-color: #20b966;
border: 1px solid #18a75a;
}
""")
secondary_style = """
.QLabel {
color: #486256;
background-color: #f1f7f3;
border: 1px solid #d3e4d8;
border-radius: 18px;
font-size: 14px;
padding: 0 16px;
}
.QLabel:hover {
color: #159452;
background-color: #e8f6ed;
border: 1px solid #b9dfc5;
}
"""
self.lab_config.setStyleSheet(secondary_style)
self.lab_close.setStyleSheet(secondary_style)
for widget_name in ("check_select_all", "table_files", "lab_preview", "lab_execute_delete"):
widget = getattr(self, widget_name, None)
if widget is not None:
widget.hide()
def init_table(self):
self.table_files.setColumnCount(3)
self.table_files.setHorizontalHeaderLabels(["选择", "文件路径", "大小"])
self.table_files.horizontalHeader().setSectionResizeMode(0, QHeaderView.Fixed)
self.table_files.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
self.table_files.horizontalHeader().setSectionResizeMode(2, QHeaderView.Fixed)
self.table_files.setColumnWidth(0, 50)
self.table_files.setColumnWidth(2, 100)
self.table_files.setRowCount(0)
self.file_data = []
def clear_table(self):
self.table_files.setRowCount(0)
self.file_data = []
self.check_select_all.setChecked(False)
def add_file_to_table(self, file_path, file_size, file_type):
row = self.table_files.rowCount()
self.table_files.insertRow(row)
checkbox_item = QTableWidgetItem()
checkbox_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
checkbox_item.setCheckState(Qt.Checked)
self.table_files.setItem(row, 0, checkbox_item)
path_item = QTableWidgetItem(file_path)
path_item.setToolTip(file_path)
self.table_files.setItem(row, 1, path_item)
size_item = QTableWidgetItem(file_size)
self.table_files.setItem(row, 2, size_item)
self.file_data.append({"path": file_path, "type": file_type})
def start_preview(self):
if not os.path.exists(CONFIG_PATH):
self.setWarninginfo("请先配置微信数据目录")
return
if hasattr(self, 'scan_thread') and self.scan_thread.isRunning():
self.setWarninginfo("正在扫描中,请稍候...")
return
self.clear_table()
self.bar_progress.setValue(0)
self.setSuccessinfo("正在扫描文件,请稍候...")
config = load_config_file()
self.scan_thread = ScanThread(config)
self.scan_thread.scan_progress_signal.connect(self.on_scan_progress)
self.scan_thread.scan_file_found_signal.connect(self.on_scan_file_found)
self.scan_thread.scan_finished_signal.connect(self.on_scan_finished)
self.scan_thread.scan_error_signal.connect(self.on_scan_error)
self.scan_thread.start()
def on_scan_progress(self, progress):
self.bar_progress.setValue(progress)
def on_scan_file_found(self, file_path, file_size, file_type):
self.add_file_to_table(file_path, file_size, file_type)
def on_scan_finished(self, file_count, dir_count):
total = file_count + dir_count
if total == 0:
self.setSuccessinfo("扫描完成,没有找到需要清理的文件")
else:
self.setSuccessinfo(f"扫描完成,共找到 {total} 个文件/文件夹")
self.bar_progress.setValue(100)
def on_scan_error(self, error_msg):
self.setWarninginfo(f"扫描出错:{error_msg}")
def toggle_select_all(self, state):
check_state = Qt.Checked if state == Qt.Checked else Qt.Unchecked
for row in range(self.table_files.rowCount()):
item = self.table_files.item(row, 0)
if item:
item.setCheckState(check_state)
def execute_delete(self):
selected_files = []
selected_dirs = []
for row in range(self.table_files.rowCount()):
item = self.table_files.item(row, 0)
if item and item.checkState() == Qt.Checked:
file_info = self.file_data[row]
if file_info["type"] == "file":
selected_files.append(file_info["path"])
else:
selected_dirs.append(file_info["path"])
if len(selected_files) + len(selected_dirs) == 0:
self.setWarninginfo("请先选择要删除的文件")
return
self.setSuccessinfo("正在删除选中的文件...")
self.total_file = len(selected_files)
self.total_dir = len(selected_dirs)
self.total_size = 0
share_thread_arr = [0]
direct_delete = load_config_file().get("global", {}).get("direct_delete", False)