-
Notifications
You must be signed in to change notification settings - Fork 247
/
main.py
467 lines (411 loc) · 18 KB
/
main.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
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsDropShadowEffect, QListWidgetItem, QListView, QWidget, \
QLabel, QHBoxLayout, QFileDialog
from PyQt5.QtCore import Qt, QPropertyAnimation, QEasingCurve, QThread, pyqtSignal, QMutex, QSize, QEvent, QPoint, QTimer
from PyQt5.QtGui import QMouseEvent, QCursor, QColor
from PyQt5.uic import loadUi
from pathlib import Path, PureWindowsPath
from dateutil import relativedelta
import utils.resources
import os, datetime, time, re, math, shutil, json
from utils.deleteThread import *
from utils.multiDeleteThread import multiDeleteThread
from utils.selectVersion import *
from utils.selectVersion import check_dir, existing_user_config
# 设置应用程序在高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):
working_dir = os.path.dirname(os.path.realpath(sys.executable))
elif __file__:
working_dir = os.path.split(os.path.realpath(__file__))[0]
# 主窗口
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:
pass
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:
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 setWarninginfo(self, text):
self.lab_info.setStyleSheet("""
.QLabel {
border:1px solid #ffccc7;
border-radius:3px;
line-height: 140px;
padding: 5px;
color: #434343;
background: #fff2f0;
}
""")
self.lab_info.setWordWrap(True) # 启用自动换行
self.lab_info.setText(text)
def setSuccessinfo(self, text):
self.lab_info.setStyleSheet("""
.QLabel {
border:1px solid #b7eb8f;
border-radius:3px;
line-height: 140px;
padding: 5px;
color: #434343;
background: #f6ffed;
}
""")
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)
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('读取路径成功!')
list_ = os.listdir(openfile_path)
user_list = [
elem for elem in list_
if elem != 'All Users' and elem != 'Applet' and elem != 'WMPF'
]
# 如果已有用户配置,那么写入新的用户配置,否则默认写入新配置
dir_list = []
user_config = []
existing_user_config_dic = existing_user_config()
for user_wx_id in user_list:
dir_list.append(os.path.join(openfile_path, user_wx_id))
if user_wx_id in existing_user_config_dic:
user_config.append(existing_user_config_dic[user_wx_id])
else:
user_config.append({
"wechat_id": user_wx_id,
"clean_days": "365",
"is_clean": True,
"clean_pic_cache": True,
"clean_file": False,
"clean_pic": True,
"clean_video": True,
"is_timer": True,
"timer": "0h"
})
config = {"data_dir": dir_list, "users": user_config}
with open(
working_dir + "/config.json", "w", encoding="utf-8") as f:
json.dump(config, f)
self.load_config()
else:
self.setWarninginfo('请选择正确的文件夹!\n一般是WeChat Files文件夹。')
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):
fd = open(working_dir + "/config.json", encoding="utf-8")
self.config = json.load(fd)
self.combo_user.clear()
for value in self.config["users"]:
self.combo_user.addItem(value["wechat_id"])
self.line_gobackdays.setText(
str(self.config["users"][0]["clean_days"]))
self.check_is_clean.setChecked(self.config["users"][0]["is_clean"])
self.check_picdown.setChecked(self.config["users"][0]["clean_pic"])
self.check_files.setChecked(self.config["users"][0]["clean_file"])
self.check_video.setChecked(self.config["users"][0]["clean_video"])
self.check_picscache.setChecked(
self.config["users"][0]["clean_pic_cache"])
self.setSuccessinfo("请确认每个账号的删除内容及时间,以防误删!")
def refresh_ui(self):
self.config = open(working_dir + "/config.json", encoding="utf-8")
self.config = json.load(self.config)
for value in self.config["users"]:
if value["wechat_id"] == self.combo_user.currentText():
self.line_gobackdays.setText(str(value["clean_days"]))
self.check_is_clean.setChecked(value["is_clean"])
self.check_picdown.setChecked(value["clean_pic"])
self.check_files.setChecked(value["clean_file"])
self.check_video.setChecked(value["clean_video"])
self.check_picscache.setChecked(value["clean_pic_cache"])
def create_config(self):
if not os.path.exists(working_dir + "/config.json"):
if not self.check_wechat_exists():
self.setWarninginfo("默认位置没有微信,请自定义位置")
return
self.config = {"data_dir": self.version_scan, "users": []}
for value in self.users_scan:
self.config["users"].append({
"wechat_id": value,
"clean_days": 365,
"is_clean": True,
"clean_pic_cache": True,
"clean_file": False,
"clean_pic": True,
"clean_video": True,
"is_timer": True,
"timer": "0h"
})
with open(
working_dir + "/config.json", "w", encoding="utf-8") as f:
json.dump(self.config, f)
self.load_config()
self.setSuccessinfo("请确认每个账号的删除内容及时间,以防误删!")
else:
self.setSuccessinfo("请确认每个账号的删除内容及时间,以防误删!")
self.load_config()
def update_config(self):
if not len(self.config):
return
else:
for value in self.config["users"]:
if value["wechat_id"] == self.combo_user.currentText():
try:
days = int(self.line_gobackdays.text())
if days < 0:
value["clean_days"] = "0"
else:
value["clean_days"] = self.line_gobackdays.text()
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()
with open(working_dir + "/config.json", "w", encoding="utf-8") as f:
json.dump(self.config, f)
self.setSuccessinfo("更新配置文件成功")
self.Signal_OneParameter.emit(1)
def __init__(self):
super().__init__()
loadUi(working_dir + "/images/config.ui", self)
self._frame()
self._connect()
self.doFadeIn()
self.create_config()
self.show()
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 closeEvent(self, event):
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:
self.setWarninginfo("清理失败,请检查配置文件后重试")
return True
elif object == self.lab_config:
cw = ConfigWindow()
cw.Signal_OneParameter.connect(self.deal_emit_slot)
return True
return False
def _eventfilter(self):
# 事件过滤
self.lab_close.installEventFilter(self)
self.lab_clean.installEventFilter(self)
self.lab_config.installEventFilter(self)
def get_fileNum(self, path, day, picCacheCheck, fileCheck, picCheck,
videoCheck, file_list, dir_list):
dir_name = PureWindowsPath(path)
# Convert path to the right format for the current operating system
correct_path = Path(dir_name)
now = datetime.datetime.now()
if picCacheCheck:
path_one = correct_path / 'Attachment'
path_two = correct_path / 'FileStorage/Cache'
self.getPathFileNum(now, day, path_one, path_two, file_list,
dir_list)
if fileCheck:
path_one = correct_path / 'Files'
path_two = correct_path / 'FileStorage/File'
self.getPathFileNum(now, day, path_one, path_two, file_list,
dir_list)
if picCheck:
path_one = correct_path / 'Image/Image'
path_two = correct_path / 'FileStorage/Image'
self.getPathFileNum(now, day, path_one, path_two, file_list,
dir_list)
if videoCheck:
path_one = correct_path / 'Video'
path_two = correct_path / 'FileStorage/Video'
self.getPathFileNum(now, day, path_one, path_two, file_list,
dir_list)
def pathFileDeal(self, now, day, path, file_list, dir_list):
if os.path.exists(path):
filelist = [
f for f in os.listdir(path)
if os.path.isfile(os.path.join(path, f))
]
for i in range(0, len(filelist)):
file_path = os.path.join(path, filelist[i])
if os.path.isdir(file_path):
continue
timestamp = datetime.datetime.fromtimestamp(
os.path.getmtime(file_path))
diff = (now - timestamp).days
if diff >= day:
file_list.append(file_path)
def getPathFileNum(self, now, day, path_one, path_two, file_list,
dir_list):
# caculate path_one
self.pathFileDeal(now, day, path_one, file_list, dir_list)
td = datetime.datetime.now() - datetime.timedelta(days=day)
td_year = td.year
td_month = td.month
# caculate path_two
if os.path.exists(path_two):
osdir = os.listdir(path_two)
dirlist = []
for i in range(0, len(osdir)):
file_path = os.path.join(path_two, osdir[i])
if os.path.isdir(file_path):
dirlist.append(osdir[i])
for i in range(0, len(dirlist)):
file_path = os.path.join(path_two, dirlist[i])
if os.path.isfile(file_path):
continue
if re.match('\d{4}(\-)\d{2}', dirlist[i]) != None:
cyear = int(dirlist[i].split('-', 1)[0])
cmonth = int(dirlist[i].split('-', 1)[1])
if self.__before_deadline(cyear, cmonth, td_year,
td_month):
dir_list.append(file_path)
else:
if cmonth == td_month:
self.pathFileDeal(now, day, file_path, file_list,
dir_list)
def __before_deadline(self, cyear, cmonth, td_year, td_month):
if cyear < td_year:
return True
elif cyear > td_year:
return False
elif cyear == td_year:
return cmonth < td_month
def callback(self, v):
value = v / int((self.total_file + self.total_dir)) * 100
self.bar_progress.setValue(int(value))
if value == 100:
out = "本次共清理文件" + str(self.total_file) + "个,文件夹" + str(
self.total_dir) + "个。\n请前往回收站检查并清空。"
self.setSuccessinfo(out)
return
def justdoit(self):
fd = open(working_dir + "/config.json", encoding="utf-8")
self.config = json.load(fd)
i = 0
need_clean = False
thread_list = []
total_file = 0
total_dir = 0
share_thread_arr = [0]
for value in self.config["users"]:
file_list = []
dir_list = []
if value["is_clean"]:
self.get_fileNum(self.config["data_dir"][i],
int(value["clean_days"]),
value["clean_pic_cache"], value["clean_file"],
value["clean_pic"], value["clean_video"],
file_list, dir_list)
if len(file_list) + len(dir_list) != 0:
need_clean = True
total_file += len(file_list)
total_dir += len(dir_list)
thread_list.append(
multiDeleteThread(file_list, dir_list, share_thread_arr))
thread_list[-1].delete_process_signal.connect(self.callback)
i = i + 1
if not need_clean:
self.setWarninginfo("没有需要清理的文件")
else:
self.total_file = total_file
self.total_dir = total_dir
for thread in thread_list:
thread.run()
def show_config_window(self):
self.config_window = ConfigWindow()
self.setSuccessinfo("已经准备好,可以开始了!")
def __init__(self):
super().__init__()
loadUi(working_dir + "/images/main.ui", self)
self._frame()
self._eventfilter()
self.doFadeIn()
self.config_exists = True
self.show()
# 判断配置文件是否存在
if not os.path.exists(working_dir + "/config.json"):
self.setWarninginfo("首次使用,即将自动弹出配置窗口")
self.config_exists = False
timer = QTimer(self)
timer.timeout.connect(self.show_config_window)
timer.setSingleShot(True) # 只执行一次
# 设置定时器的时间间隔,这里设置为 1000ms(1秒)
timer.start(1000)
if __name__ == '__main__':
app = QApplication([])
win = MainWindow()
app.exec_()