-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
4770 lines (4109 loc) · 185 KB
/
server.py
File metadata and controls
4770 lines (4109 loc) · 185 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 os
import sys
import base64
import json
import mimetypes
import signal
import logging
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs, unquote
from urllib.parse import quote as urlquote
from pathlib import Path
import threading
import time
import psutil
from datetime import datetime, timedelta
try:
import qrcode
except ImportError:
qrcode = None
# 添加正确的MIME类型映射
mimetypes.add_type("video/x-msvideo", ".avi") # 标准.avi文件MIME类型
mimetypes.add_type("video/mp4", ".mp4") # 确保mp4映射正确
mimetypes.add_type("video/webm", ".webm") # 确保webm映射正确
mimetypes.add_type("video/ogg", ".ogg") # 确保ogg映射正确
mimetypes.add_type("video/x-matroska", ".mkv") # 确保mkv映射正确
mimetypes.add_type("video/x-ms-wmv", ".wmv") # 确保wmv映射正确
mimetypes.add_type("video/x-flv", ".flv") # 确保flv映射正确
from config import get_config_manager
from color_logger import get_rich_logger
# 获取配置管理器实例
config_manager = get_config_manager()
# 配置日志记录 - 使用彩色日志系统
log_level = getattr(
logging, config_manager.logging_config["LOG_LEVEL"].upper(), logging.INFO
)
# 初始化富文本日志器
logger = get_rich_logger("LANFileServer", log_level)
# 文件大小格式化缓存
_size_format_cache = {}
_MAX_SIZE_CACHE = 100 # 限制缓存条数,内存占用可忽略
def format_file_size(size):
"""缓存文件大小格式化结果,减少重复计算
Args:
size (int): 文件大小(字节)
Returns:
str: 格式化后的文件大小
"""
# 缓存键:文件大小数值(字符串类型,避免类型冲突)
cache_key = str(size)
if cache_key in _size_format_cache:
return _size_format_cache[cache_key]
# 原有大小格式化逻辑
if size == 0:
formatted = "0 B"
else:
for unit in ["B", "KB", "MB", "GB"]:
if size < 1024.0:
formatted = f"{size:.2f} {unit}"
break
size /= 1024.0
else:
formatted = f"{size:.2f} TB"
# 写入缓存,超出数量时删除最旧条目
_size_format_cache[cache_key] = formatted
if len(_size_format_cache) > _MAX_SIZE_CACHE:
_size_format_cache.pop(next(iter(_size_format_cache)))
return formatted
class HTTPError(Exception):
"""HTTP错误异常类
Args:
status_code (int): HTTP状态码
message (str): 错误信息
details (dict, optional): 详细错误信息
"""
def __init__(self, status_code, message, details=None):
self.status_code = status_code
self.message = message
self.details = details or {}
super().__init__(f"HTTP {status_code}: {message}")
def error_handler(func):
"""统一错误处理装饰器
捕获函数执行过程中的所有异常,记录详细日志,并返回适当的错误响应
"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except HTTPError as e:
# 处理HTTP错误
logger.error(f"HTTP错误: {e}")
if hasattr(args[0], "send_response"):
handler = args[0]
try:
# 使用HTML模板生成友好的错误页面
if e.status_code == 404:
html = HTMLTemplate.get_404_page()
elif e.status_code == 429:
remaining_time = handler.config_manager.server_config[
"FAILED_AUTH_BLOCK_TIME"
]
html = HTMLTemplate.get_blocked_page(remaining_time)
else:
# 生成通用错误页面
content = f"""
<div class="error-container glass-effect">
<div class="error-card glass-card">
<h2>{e.status_code} - {e.message}</h2>
<p>抱歉,服务器遇到了一个错误。</p>
<div class="error-details">
<p>{e.details.get('description', '')}</p>
</div>
<div class="error-actions">
<a href="/index" class="action-button">返回首页</a>
<a href="/browse" class="action-button">浏览目录</a>
</div>
</div>
</div>
"""
html = HTMLTemplate.get_base_template(
f"{e.status_code} - {e.message}", content
)
handler._send_html_response(html, e.status_code)
except Exception as e2:
logger.error(f"发送HTTP错误响应时出错: {e2}", exc_info=True)
except Exception as e:
# 记录详细错误日志
logger.error(f"执行 {func.__name__} 时出错: {e}", exc_info=True)
# 对于HTTP请求处理函数,返回500错误
if hasattr(args[0], "send_response"):
handler = args[0]
try:
# 生成500错误页面
content = f"""
<div class="error-container glass-effect">
<div class="error-card glass-card">
<h2>500 - 服务器内部错误</h2>
<p>抱歉,服务器遇到了一个意外的错误。</p>
<div class="error-details">
<p>错误信息: {str(e)}</p>
<p>请联系管理员或稍后重试。</p>
</div>
<div class="error-actions">
<a href="/index" class="action-button">返回首页</a>
<a href="/browse" class="action-button">浏览目录</a>
</div>
</div>
</div>
"""
html = HTMLTemplate.get_base_template(
"500 - 服务器内部错误", content
)
handler._send_html_response(html, 500)
except Exception as e2:
logger.error(f"发送错误响应时出错: {e2}", exc_info=True)
return
return wrapper
class AuthenticationManager:
"""认证管理器 - 处理用户认证和密码验证"""
def __init__(self, config_manager):
self.config_manager = config_manager
# 存储已使用的密码时间戳,用于防重放攻击
self.used_timestamps = set()
# 已使用时间戳的清理周期(秒)
self.timestamp_cleanup_interval = 3600 # 1小时
# 启动清理线程
self._start_timestamp_cleanup_thread()
def _start_timestamp_cleanup_thread(self):
"""启动定期清理已使用时间戳的线程"""
def cleanup_thread_func():
while True:
time.sleep(self.timestamp_cleanup_interval)
self._cleanup_used_timestamps()
thread = threading.Thread(
target=cleanup_thread_func, daemon=True, name="TimestampCleanup"
)
thread.start()
def _cleanup_used_timestamps(self):
"""清理已过期的时间戳(超过5分钟)"""
current_time = time.time()
expired_timestamps = [
ts for ts in self.used_timestamps if current_time - ts > 360
] # 6分钟
for ts in expired_timestamps:
self.used_timestamps.discard(ts)
logger.debug(
f"清理已过期时间戳,清理了 {len(expired_timestamps)} 个,剩余 {len(self.used_timestamps)} 个"
)
def verify_credentials(self, username, password):
"""验证用户名和密码
基于用户当前登录时间前后5分钟的动态密码验证机制
Args:
username (str): 用户名
password (str): 密码
Returns:
bool: 认证是否成功
"""
# 从配置文件获取用户名
config_username = self.config_manager.auth_config.get("username", "admin")
if username != config_username:
logger.info(f"用户认证失败 - 用户名不正确: {username}")
return False
current_time = datetime.now()
expected_passwords = []
used_timestamps = []
# 生成前后5分钟内的所有可能密码和对应的时间戳
for minutes_offset in range(-5, 6):
# 计算偏移后的时间
offset_time = current_time + timedelta(minutes=minutes_offset)
# 生成密码格式 yyyymmddHHMM
offset_password = offset_time.strftime("%Y%m%d%H%M")
expected_passwords.append(offset_password)
# 生成对应的时间戳(用于防重放攻击)
timestamp = offset_time.strftime("%Y%m%d%H%M")
used_timestamps.append(timestamp)
logger.info(f"用户认证尝试 - 用户名: {username}")
logger.debug(f"输入密码: {password}")
logger.debug(f"预期密码范围: {expected_passwords}")
# 检查密码是否在预期范围内
if password not in expected_passwords:
logger.info("用户认证失败 - 密码不正确")
return False
# 防重放攻击检查:验证该时间戳是否已被使用
timestamp_index = expected_passwords.index(password)
timestamp = used_timestamps[timestamp_index]
if timestamp in self.used_timestamps:
logger.warning("用户认证失败 - 密码已被使用(防重放攻击)")
return False
# 记录已使用的时间戳
self.used_timestamps.add(timestamp)
logger.info(f"用户认证成功 - 用户名: {username}")
return True
def extract_credentials(self, auth_header):
"""从HTTP Authorization头提取认证信息
Args:
auth_header (str): Authorization头值
Returns:
tuple: (用户名, 密码) 或 (None, None)
"""
if not auth_header:
return None, None
try:
# 解析 "Basic base64(username:password)" 格式
auth_type, credentials = auth_header.split(" ", 1)
if auth_type.lower() != "basic":
return None, None
# 解码base64
decoded_credentials = base64.b64decode(credentials).decode("utf-8")
username, password = decoded_credentials.split(":", 1)
return username, password
except Exception:
return None, None
def create_session(self, username, device_info=""):
"""创建新会话
Args:
username (str): 用户名
device_info (str): 设备标识信息
Returns:
str: 会话ID
"""
return self.config_manager.create_session(username, device_info)
def validate_session(self, session_id):
"""验证会话有效性
Args:
session_id (str): 会话ID
Returns:
bool: 会话是否有效
"""
return self.config_manager.validate_session(session_id)
def get_session_username(self, session_id):
"""获取会话对应的用户名
Args:
session_id (str): 会话ID
Returns:
str or None: 用户名或None
"""
return self.config_manager.get_session_username(session_id)
def delete_session(self, session_id):
"""删除会话
Args:
session_id (str): 会话ID
"""
self.config_manager.delete_session(session_id)
def cleanup_expired_sessions(self):
"""清理过期会话"""
self.config_manager.cleanup_expired_sessions()
class FileIndexer:
"""文件索引器 - 生成和管理文件索引
支持增量索引、异步索引和多级缓存机制
"""
def __init__(self, config_manager):
self.config_manager = config_manager
self.share_dirs = [
Path(dir) for dir in config_manager.server_config["SHARE_DIRS"]
]
self.cache = {}
self.cache_time = 0
self.cache_duration = 300 # 5分钟缓存
# 增量索引相关
self.last_index_time = 0
self.file_metadata = {} # 存储文件元数据,用于增量索引
# 异步索引相关
self.thread_pool = None
self.current_index_task = None
self.index_lock = threading.Lock()
# 多级缓存相关
self.enable_multi_level_cache = config_manager.caching_config.get(
"ENABLE_MULTI_LEVEL_CACHE", True
)
self.memory_cache_size = config_manager.caching_config.get(
"MEMORY_CACHE_SIZE", 100
)
self.disk_cache_enabled = config_manager.caching_config.get(
"DISK_CACHE_ENABLED", False
)
# 内存缓存 - 使用LRU策略
self.memory_cache = {}
self.cache_access_order = [] # 用于LRU缓存
# 磁盘缓存目录
self.disk_cache_dir = Path(".cache")
if self.disk_cache_enabled:
self.disk_cache_dir.mkdir(exist_ok=True)
# SQLite索引相关
self.sqlite_enabled = config_manager.caching_config.get(
"ENABLE_SQLITE_INDEX", True
)
self.sqlite_db_path = Path(".cache/index.db")
self.sqlite_conn = None
self.sqlite_cursor = None
self.fts5_supported = False # 标记FTS5是否支持
# 初始化SQLite数据库
if self.sqlite_enabled:
self._init_sqlite_db()
# 初始化线程池
self._init_thread_pool()
def _init_sqlite_db(self):
"""初始化SQLite数据库"""
try:
import sqlite3
# 确保缓存目录存在
self.sqlite_db_path.parent.mkdir(exist_ok=True)
# 建立数据库连接
self.sqlite_conn = sqlite3.connect(
str(self.sqlite_db_path), check_same_thread=False
)
self.sqlite_conn.row_factory = sqlite3.Row
self.sqlite_cursor = self.sqlite_conn.cursor()
# 创建文件索引表
self.sqlite_cursor.execute(
"""
CREATE TABLE IF NOT EXISTS file_index (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
path TEXT NOT NULL,
full_path TEXT NOT NULL UNIQUE,
type TEXT NOT NULL,
size INTEGER NOT NULL,
extension TEXT NOT NULL,
modified_time INTEGER NOT NULL,
is_directory INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
)
"""
)
# 创建索引以提高查询性能
self.sqlite_cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_file_index_name ON file_index(name)"
)
self.sqlite_cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_file_index_path ON file_index(path)"
)
self.sqlite_cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_file_index_full_path ON file_index(full_path)"
)
self.sqlite_cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_file_index_type ON file_index(type)"
)
self.sqlite_cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_file_index_extension ON file_index(extension)"
)
self.sqlite_cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_file_index_is_directory ON file_index(is_directory)"
)
# 创建全文搜索虚拟表(如果支持)
try:
self.sqlite_cursor.execute(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS file_fts USING fts5(
name,
content=file_index,
content_rowid=id
)
"""
)
self.fts5_supported = True # FTS5创建成功,标记为支持
except sqlite3.OperationalError:
# 不支持FTS5,跳过
logger.warning("SQLite FTS5不支持,全文搜索功能将受限")
self.fts5_supported = False # 明确标记为不支持
self.sqlite_conn.commit()
logger.info("SQLite索引数据库初始化成功")
except Exception as e:
logger.error(f"初始化SQLite数据库失败: {e}")
# 禁用SQLite功能
self.sqlite_enabled = False
self.sqlite_conn = None
self.sqlite_cursor = None
return
# 初始化数据库后,执行首次填充
self._populate_sqlite_db()
# 启动定期更新线程
self._start_sqlite_update_thread()
def _start_sqlite_update_thread(self):
"""启动定期更新SQLite数据库的后台线程"""
if not self.sqlite_enabled:
return
try:
# 每30分钟更新一次数据库
update_interval = 30 * 60 # 30分钟,单位:秒
# 添加停止标志
self._stop_update_thread = False
def update_thread_func():
"""定期更新数据库的线程函数"""
while not self._stop_update_thread:
time.sleep(update_interval)
if not self._stop_update_thread:
logger.info("执行SQLite数据库定期更新...")
self._populate_sqlite_db()
# 创建并启动后台线程
self.sqlite_update_thread = threading.Thread(
target=update_thread_func, daemon=True, name="SQLiteUpdateThread"
)
self.sqlite_update_thread.start()
logger.info("SQLite数据库定期更新线程已启动")
except Exception as e:
logger.error(f"启动SQLite更新线程失败: {e}")
def _cleanup(self):
"""清理资源,关闭线程池和SQLite连接,确保数据完整性"""
logger.info("开始清理FileIndexer资源...")
# 停止SQLite定期更新线程
if hasattr(self, "_stop_update_thread"):
self._stop_update_thread = True
logger.info("SQLite定期更新线程已停止")
# 等待更新线程退出
if (
hasattr(self, "sqlite_update_thread")
and self.sqlite_update_thread.is_alive()
):
logger.info("等待SQLite更新线程退出...")
self.sqlite_update_thread.join(timeout=10) # 最多等待10秒
if self.sqlite_update_thread.is_alive():
logger.warning("SQLite更新线程未能及时退出")
# 等待当前索引任务完成
if hasattr(self, "current_index_task") and self.current_index_task:
try:
# 等待当前索引任务完成,最多等待5秒
self.current_index_task.result(timeout=5)
logger.info("当前索引任务已完成")
except Exception as e:
logger.warning(f"等待索引任务完成超时: {e}")
# 关闭线程池
if self.thread_pool:
try:
self.thread_pool.shutdown(wait=True, cancel_futures=True)
logger.info("线程池已关闭")
except Exception as e:
logger.error(f"关闭线程池失败: {e}")
# 在关闭前执行最后一次SQLite数据库更新,确保所有更改都被保存
if self.sqlite_enabled:
logger.info("执行最后一次SQLite数据库更新,确保数据完整性...")
self._populate_sqlite_db()
# 确保所有未提交的SQLite事务都被提交
if self.sqlite_conn:
try:
self.sqlite_conn.commit()
logger.info("所有未提交的SQLite事务已提交")
except Exception as e:
logger.error(f"提交SQLite事务失败: {e}")
# 发生错误时回滚
try:
self.sqlite_conn.rollback()
logger.info("SQLite事务已回滚")
except Exception as e2:
logger.error(f"回滚SQLite事务失败: {e2}")
# 关闭SQLite游标
if self.sqlite_cursor:
try:
self.sqlite_cursor.close()
logger.info("SQLite游标已关闭")
except Exception as e:
logger.error(f"关闭SQLite游标失败: {e}")
# 关闭SQLite连接
if self.sqlite_conn:
try:
self.sqlite_conn.close()
logger.info("SQLite连接已关闭")
except Exception as e:
logger.error(f"关闭SQLite连接失败: {e}")
logger.info("FileIndexer资源清理完成")
def _populate_sqlite_db(self):
"""增量更新SQLite数据库 - 只更新变化的文件和目录"""
if not self.sqlite_enabled:
return
logger.info("开始增量更新SQLite数据库...")
start_time = time.time()
try:
# 获取数据库中当前的文件和目录信息,包含size字段
self.sqlite_cursor.execute(
"SELECT full_path, modified_time, is_directory, size FROM file_index"
)
db_files = {
row[0]: (row[1], row[2], row[3])
for row in self.sqlite_cursor.fetchall()
}
# 存储当前扫描到的所有文件和目录路径
current_files = set()
def scan_directory_recursive(share_dir, dir_path, relative_path=""):
"""递归扫描目录"""
try:
with os.scandir(str(dir_path)) as scandir_iter:
for item in scandir_iter:
# 处理以点开头的文件和目录
if item.name.startswith("."):
if item.is_dir():
# 跳过隐藏目录
continue
else:
# 对于以点开头的文件,允许白名单内的文件(如 .mp4)
file_path = Path(item.path)
file_name = file_path.name
file_ext = file_path.suffix.lower()
# 检查是否为白名单文件
is_whitelisted = False
if file_name.startswith(".") and len(file_name) > 1:
# 对于 .mp4 这样的文件名,检查文件名本身是否在白名单中
dot_ext = file_name.lower()
is_whitelisted = (
dot_ext
in self.config_manager.ALL_WHITELIST_EXTENSIONS
)
else:
is_whitelisted = (
file_ext
in self.config_manager.ALL_WHITELIST_EXTENSIONS
)
if not is_whitelisted:
# 跳过不在白名单中的隐藏文件
continue
# 确保item_name使用UTF-8编码
try:
item_name = str(item.name)
except UnicodeDecodeError:
logger.warning(f"文件名编码错误,跳过: {item}")
continue
# 构建相对路径
if relative_path and relative_path.strip():
item_relative_path = str(
Path(relative_path) / item_name
)
else:
item_relative_path = item_name
# 检查路径安全性
if not self.config_manager.is_path_safe(
str(item), str(share_dir)
):
logger.warning(f"跳过不安全的路径: {item}")
continue
# 添加到当前扫描的文件集合
current_files.add(item.path)
# 获取文件/目录的修改时间
try:
stat_info = item.stat()
modified_time = int(stat_info.st_mtime)
except Exception as e:
logger.warning(f"获取文件信息失败: {item} - {e}")
continue
if item.is_dir():
# 目录处理
is_dir = 1
# 检查是否需要更新
if (
item.path not in db_files
or db_files[item.path][0] != modified_time
or db_files[item.path][1] != is_dir
):
# 插入或更新目录
try:
self.sqlite_cursor.execute(
"""
INSERT OR REPLACE INTO file_index
(name, path, full_path, type, size, extension, modified_time, is_directory, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%s', 'now'))
""",
(
item_name,
item_relative_path,
item.path,
"directory",
0,
"",
modified_time,
is_dir,
),
)
except Exception as e:
logger.error(f"更新目录失败: {item} - {e}")
# 递归扫描子目录 - 传递实际路径而不是DirEntry对象
scan_directory_recursive(
share_dir, item.path, item_relative_path
)
elif item.is_file():
# 文件处理
is_dir = 0
file_size = stat_info.st_size
# 检查是否需要更新
if (
item.path not in db_files
or db_files[item.path][0] != modified_time
or db_files[item.path][1] != is_dir
or db_files[item.path][2] != file_size
):
# 插入或更新文件
try:
# 正确获取文件扩展名
file_ext = Path(item.name).suffix.lower()
self.sqlite_cursor.execute(
"""
INSERT OR REPLACE INTO file_index
(name, path, full_path, type, size, extension, modified_time, is_directory, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, strftime('%s', 'now'))
""",
(
item_name,
item_relative_path,
item.path,
self.config_manager.get_file_type(
item.path
),
file_size,
file_ext,
modified_time,
is_dir,
),
)
except Exception as e:
logger.error(f"更新文件失败: {item} - {e}")
except PermissionError:
logger.warning(f"权限不足,跳过目录: {dir_path}")
except Exception as e:
logger.error(f"扫描目录失败: {dir_path} - {e}")
# 遍历所有共享目录
for share_dir in self.share_dirs:
if share_dir.exists():
# 开始扫描根目录
scan_directory_recursive(share_dir, share_dir)
# 删除数据库中存在但当前文件系统中不存在的文件和目录
files_to_delete = db_files.keys() - current_files
if files_to_delete:
for file_path in files_to_delete:
try:
self.sqlite_cursor.execute(
"DELETE FROM file_index WHERE full_path = ?", (file_path,)
)
except Exception as e:
logger.error(f"删除文件记录失败: {file_path} - {e}")
# 提交所有更改
self.sqlite_conn.commit()
end_time = time.time()
logger.info(
f"SQLite数据库增量更新完成,耗时: {end_time - start_time:.2f}秒"
)
logger.info(
f"新增/更新文件数: {len(current_files) - len(db_files) + len(files_to_delete)}, 删除文件数: {len(files_to_delete)}"
)
except Exception as e:
logger.error(f"更新SQLite数据库失败: {e}", exc_info=True)
# 发生错误时回滚
self.sqlite_conn.rollback()
def _init_thread_pool(self):
"""初始化线程池"""
try:
from concurrent.futures import ThreadPoolExecutor
import multiprocessing
import psutil
# 获取CPU核心数
cpu_count = multiprocessing.cpu_count()
# 获取系统内存大小(GB)
total_memory = psutil.virtual_memory().total / (1024**3)
# 索引和搜索任务是IO密集型的,线程数可以设置为CPU核心数的2-4倍
# 根据内存大小调整上限:内存越大,允许的线程数越多
if total_memory < 4:
# 小于4GB内存,限制线程数
max_workers = min(4, cpu_count * 2)
elif total_memory < 8:
# 4-8GB内存,中等线程数
max_workers = min(8, cpu_count * 3)
else:
# 大于8GB内存,更多线程数
max_workers = min(12, cpu_count * 4)
logger.info(
f"初始化线程池,CPU核心数: {cpu_count}, 内存: {total_memory:.2f}GB, 线程数: {max_workers}"
)
self.thread_pool = ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix="IndexWorker",
# 设置线程池线程的最大空闲时间,避免资源浪费
# Python 3.8+支持timeout参数,这里暂时不使用
)
except ImportError:
# psutil模块未安装,使用默认值
cpu_count = multiprocessing.cpu_count()
max_workers = min(6, cpu_count * 2)
logger.info(
f"psutil模块未安装,使用默认线程池设置,CPU核心数: {cpu_count}, 线程数: {max_workers}"
)
self.thread_pool = ThreadPoolExecutor(
max_workers=max_workers, thread_name_prefix="IndexWorker"
)
except Exception as e:
logger.error(f"初始化线程池失败: {e}")
self.thread_pool = None
def generate_index(
self, search_term="", sort_by="name", sort_order="asc", use_async=False
):
"""生成文件索引
Args:
search_term (str): 搜索关键词(可选)
sort_by (str): 排序字段 (name, size, modified, type)
sort_order (str): 排序顺序 (asc, desc)
use_async (bool): 是否使用异步索引
Returns:
dict: 索引数据
"""
# 优化:先检查是否为简单情况(空搜索),快速返回缓存
if not search_term:
# 对于空搜索,直接返回根目录内容,不进行递归
cached_data = self._get_cache("", sort_by, sort_order) # 使用特殊缓存键
if cached_data:
return cached_data
# 检查多级缓存,加入排序参数
cached_data = self._get_cache(search_term, sort_by, sort_order)
if cached_data:
return cached_data
# 移除短关键词限制,允许单字符搜索
# 优化:SQLite已处理性能问题,无需手动限制
if use_async and self.thread_pool:
# 使用异步索引
return self._generate_index_async(search_term, sort_by, sort_order)
else:
# 同步索引,添加超时保护
start_time = time.time()
index_data = self._generate_index_sync(search_term, sort_by, sort_order)
# 记录索引生成时间
generation_time = time.time() - start_time
logger.debug(
f"索引生成耗时: {
generation_time:.2f}秒,搜索词: '{search_term}'"
)
return index_data
def _generate_index_sync(self, search_term="", sort_by="name", sort_order="asc"):
"""同步生成文件索引"""
with self.index_lock:
return self._generate_index_impl(search_term, sort_by, sort_order)
def _generate_index_async(self, search_term="", sort_by="name", sort_order="asc"):
"""异步生成文件索引"""
# 如果有当前任务且未完成,返回当前任务
if self.current_index_task and not self.current_index_task.done():
return self.cache # 返回旧缓存
# 提交新任务,包含排序参数
self.current_index_task = self.thread_pool.submit(
self._generate_index_impl, search_term, sort_by, sort_order
)
return self.cache # 返回旧缓存,异步任务完成后会更新缓存
def _generate_index_impl(self, search_term="", sort_by="name", sort_order="asc"):
"""索引生成实现"""
current_time = time.time()
index_data = {
"search_term": search_term,
"timestamp": current_time,
"directories": [],
"files": [],
}
# 检查是否有可用的共享目录
if not self.share_dirs:
return index_data
try:
# 首先尝试使用SQLite进行索引和搜索
if self.sqlite_enabled:
# 优化:如果排序字段是size,确保SQLite数据库中的size字段是最新的
if sort_by == "size":
logger.debug("排序字段为size,更新SQLite数据库中的文件大小信息...")
self._populate_sqlite_db()
# 使用SQLite索引加速搜索
sqlite_index_data = self._generate_index_from_sqlite(
search_term, sort_by, sort_order
)
if sqlite_index_data["directories"] or sqlite_index_data["files"]:
# 更新缓存
self.cache = sqlite_index_data
self.cache_time = current_time
self.last_index_time = current_time
# 使用多级缓存,缓存键包含排序参数
self._set_cache(search_term, sqlite_index_data, sort_by, sort_order)
return sqlite_index_data
# SQLite索引未命中或禁用,回退到传统文件系统遍历
# 只显示根目录内容,模仿手机文件管理器体验
for share_dir in self.share_dirs:
if share_dir.exists():
self._index_directory_flat(
share_dir, share_dir, "", index_data, search_term
)
# 为文件添加修改时间信息
for file_info in index_data["files"]:
try:
file_path = Path(file_info["full_path"])
file_info["modified_time"] = file_path.stat().st_mtime
except Exception as e:
logger.warning(
f"获取文件修改时间失败: {
file_info['full_path']} - {e}"
)
file_info["modified_time"] = 0
# 排序函数定义
def get_sort_key(item, item_type):
"""获取排序键"""
if item_type == "directory":
if sort_by == "name":
return item["name"].lower()
elif sort_by == "modified":
# 目录的修改时间使用最新子项的时间,这里简化处理
return 0
elif sort_by == "size":
# 目录大小,这里简化处理
return 0
elif sort_by == "type":
return "directory"
else:
return item["name"].lower()
else:
if sort_by == "name":
return item["name"].lower()
elif sort_by == "size":
# 确保size字段的值是数字类型
return int(item.get("size", 0))
elif sort_by == "modified":
return item["modified_time"]
elif sort_by == "type":
return f"{item['type']}_{item['name'].lower()}"
else:
return item["name"].lower()
# 执行排序
reverse = sort_order == "desc"