-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
434 lines (343 loc) · 12.5 KB
/
app.py
File metadata and controls
434 lines (343 loc) · 12.5 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
"""
CleanFiles - Windows Disk Cleanup Tool
主应用程序 - Flask Web界面
"""
import os
import sys
import json
import threading
from datetime import datetime
from pathlib import Path
from flask import Flask, render_template, jsonify, request, send_file
from flask_socketio import SocketIO, emit
# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent))
from scanner.disk_scanner import DiskScanner
from scanner.file_analyzer import FileAnalyzer, CleanupCategory, RiskLevel
from governance.policy import GovernancePolicy, ActionType
from governance.executor import CleanupExecutor
from reports.generator import ReportGenerator
app = Flask(__name__)
app.config['SECRET_KEY'] = 'cleanfiles-secret-key'
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# 全局状态
state = {
'scanner': None,
'analyzer': None,
'policy': None,
'executor': None,
'is_scanning': False,
'is_executing': False,
'scan_results': [],
'cleanup_items': [],
'actions': []
}
@app.route('/')
def index():
"""主页"""
return render_template('index.html')
@app.route('/api/available-drives')
def get_available_drives():
"""获取所有可用的磁盘驱动器"""
try:
drives = DiskScanner.get_available_drives()
drives_info = []
import psutil
for drive in drives:
try:
disk = psutil.disk_usage(drive)
drives_info.append({
'drive': drive,
'label': drive[:2],
'total': disk.total,
'used': disk.used,
'free': disk.free,
'percent': disk.percent,
'total_formatted': format_size(disk.total),
'used_formatted': format_size(disk.used),
'free_formatted': format_size(disk.free)
})
except:
drives_info.append({
'drive': drive,
'label': drive[:2],
'total': 0,
'used': 0,
'free': 0,
'percent': 0,
'total_formatted': 'N/A',
'used_formatted': 'N/A',
'free_formatted': 'N/A'
})
return jsonify({
'success': True,
'data': drives_info
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/disk-info')
def get_disk_info():
"""获取指定磁盘信息(兼容旧版本,默认C盘)"""
try:
import psutil
drive = request.args.get('drive', 'C:\\')
disk = psutil.disk_usage(drive)
return jsonify({
'success': True,
'data': {
'drive': drive,
'total': disk.total,
'used': disk.used,
'free': disk.free,
'percent': disk.percent,
'total_formatted': format_size(disk.total),
'used_formatted': format_size(disk.used),
'free_formatted': format_size(disk.free)
}
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/start-scan', methods=['POST'])
def start_scan():
"""开始扫描"""
if state['is_scanning']:
return jsonify({'success': False, 'error': '扫描正在进行中'})
data = request.json or {}
scan_type = data.get('type', 'quick') # quick or full
max_depth = data.get('max_depth', 4)
drives = data.get('drives', ['C:\\']) # 要扫描的盘符列表
# 验证盘符
available_drives = DiskScanner.get_available_drives()
valid_drives = [d for d in drives if d in available_drives]
if not valid_drives:
return jsonify({'success': False, 'error': '没有有效的盘符可扫描'})
# 在后台线程中执行扫描
thread = threading.Thread(
target=run_scan,
args=(scan_type, max_depth, valid_drives)
)
thread.start()
return jsonify({'success': True, 'message': f'扫描已开始: {", ".join([d[:2] for d in valid_drives])}'})
def run_scan(scan_type: str, max_depth: int, drives: List[str]):
"""执行扫描"""
state['is_scanning'] = True
state['scanner'] = DiskScanner(drives)
def progress_callback(message, progress):
socketio.emit('scan_progress', {
'message': message,
'progress': progress
})
state['scanner'].set_progress_callback(progress_callback)
try:
socketio.emit('scan_started', {
'type': scan_type,
'drives': [d[:2] for d in drives]
})
if scan_type == 'quick':
result = state['scanner'].quick_scan(max_depth=max_depth)
else:
result = state['scanner'].full_scan()
state['scan_results'] = state['scanner'].scan_results
# 分析扫描结果
state['analyzer'] = FileAnalyzer(state['scan_results'])
state['cleanup_items'] = state['analyzer'].analyze()
# 生成治理策略
state['policy'] = GovernancePolicy()
state['actions'] = state['policy'].generate_actions(state['cleanup_items'])
# 发送完成事件
socketio.emit('scan_completed', {
'stats': result['stats'],
'elapsed_time': result['elapsed_time'],
'summary': state['analyzer'].get_summary(),
'policy_summary': state['policy'].get_summary(),
'drives': [d[:2] for d in drives]
})
except Exception as e:
socketio.emit('scan_error', {'error': str(e)})
finally:
state['is_scanning'] = False
@app.route('/api/stop-scan', methods=['POST'])
def stop_scan():
"""停止扫描"""
if state['scanner']:
state['scanner'].stop_scan()
return jsonify({'success': True})
@app.route('/api/cleanup-items')
def get_cleanup_items():
"""获取可清理项目列表"""
category = request.args.get('category')
risk = request.args.get('risk')
items = state['cleanup_items']
# 过滤
if category:
try:
cat = CleanupCategory[category]
items = [i for i in items if i.category == cat]
except:
pass
if risk:
try:
r = RiskLevel[risk]
items = [i for i in items if i.risk_level == r]
except:
pass
# 排序(按大小降序)
items = sorted(items, key=lambda x: x.size, reverse=True)
return jsonify({
'success': True,
'data': [item.to_dict() for item in items[:200]] # 限制返回数量
})
@app.route('/api/actions')
def get_actions():
"""获取治理操作列表"""
status = request.args.get('status')
actions = state['actions']
if status:
actions = [a for a in actions if a.status == status]
return jsonify({
'success': True,
'data': [a.to_dict() for a in actions],
'summary': state['policy'].get_summary() if state['policy'] else {}
})
@app.route('/api/approve-action', methods=['POST'])
def approve_action():
"""批准单个操作"""
data = request.json
action_id = data.get('action_id')
if state['policy'] and state['policy'].approve_action(action_id):
return jsonify({'success': True})
return jsonify({'success': False, 'error': '操作不存在'})
@app.route('/api/reject-action', methods=['POST'])
def reject_action():
"""拒绝单个操作"""
data = request.json
action_id = data.get('action_id')
reason = data.get('reason', '')
if state['policy'] and state['policy'].reject_action(action_id, reason):
return jsonify({'success': True})
return jsonify({'success': False, 'error': '操作不存在'})
@app.route('/api/approve-category', methods=['POST'])
def approve_category():
"""批准某类别的所有操作"""
data = request.json
category = data.get('category')
try:
cat = CleanupCategory[category]
count = state['policy'].approve_by_category(cat)
return jsonify({'success': True, 'count': count})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/approve-safe', methods=['POST'])
def approve_safe():
"""批准所有安全和低风险操作"""
if state['policy']:
count = state['policy'].approve_by_risk(RiskLevel.LOW)
return jsonify({'success': True, 'count': count})
return jsonify({'success': False, 'error': '策略未初始化'})
@app.route('/api/execute', methods=['POST'])
def execute_cleanup():
"""执行清理"""
if state['is_executing']:
return jsonify({'success': False, 'error': '正在执行中'})
data = request.json or {}
dry_run = data.get('dry_run', False)
thread = threading.Thread(
target=run_execute,
args=(dry_run,)
)
thread.start()
return jsonify({'success': True, 'message': '执行已开始'})
def run_execute(dry_run: bool):
"""执行清理操作"""
state['is_executing'] = True
state['executor'] = CleanupExecutor()
def progress_callback(message, progress, action_id=None, success=None):
socketio.emit('execute_progress', {
'message': message,
'progress': progress,
'action_id': action_id,
'success': success
})
state['executor'].set_progress_callback(progress_callback)
try:
socketio.emit('execute_started', {'dry_run': dry_run})
results = state['executor'].execute_actions(state['actions'], dry_run)
summary = state['executor'].get_execution_summary()
# 生成报告
report_gen = ReportGenerator()
report_path = report_gen.generate_governance_report(
state['policy'].get_summary(),
state['actions'],
summary
)
socketio.emit('execute_completed', {
'summary': summary,
'report_path': report_path
})
except Exception as e:
socketio.emit('execute_error', {'error': str(e)})
finally:
state['is_executing'] = False
@app.route('/api/stop-execute', methods=['POST'])
def stop_execute():
"""停止执行"""
if state['executor']:
state['executor'].stop_execution()
return jsonify({'success': True})
@app.route('/api/generate-report', methods=['POST'])
def generate_report():
"""生成报告"""
try:
report_gen = ReportGenerator()
scan_stats = state['scanner'].stats if state['scanner'] else {}
analyzer_summary = state['analyzer'].get_summary() if state['analyzer'] else {}
report_path = report_gen.generate_scan_report(
scan_stats,
analyzer_summary,
state['cleanup_items']
)
return jsonify({
'success': True,
'report_path': report_path
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/download-report')
def download_report():
"""下载报告"""
report_path = request.args.get('path')
if report_path and os.path.exists(report_path):
return send_file(report_path, as_attachment=True)
return jsonify({'success': False, 'error': '报告不存在'})
@app.route('/api/categories')
def get_categories():
"""获取所有类别"""
return jsonify({
'success': True,
'data': [{'key': c.name, 'value': c.value} for c in CleanupCategory]
})
@app.route('/api/risk-levels')
def get_risk_levels():
"""获取所有风险等级"""
return jsonify({
'success': True,
'data': [{'key': r.name, 'value': r.value} for r in RiskLevel]
})
def format_size(size: int) -> str:
"""格式化文件大小"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} PB"
if __name__ == '__main__':
# 创建模板目录
templates_dir = Path(__file__).parent / 'templates'
templates_dir.mkdir(exist_ok=True)
print("=" * 60)
print(" CleanFiles - Windows磁盘清理工具")
print("=" * 60)
print(f" 启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f" 访问地址: http://localhost:5000")
print("=" * 60)
socketio.run(app, host='0.0.0.0', port=5000, debug=False)