Skip to content

Commit 1b6a548

Browse files
committed
feat(monitor): enhance file handling with transfer history checks
1 parent 52c5f29 commit 1b6a548

2 files changed

Lines changed: 277 additions & 166 deletions

File tree

app/monitor.py

Lines changed: 50 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from app.chain.transfer import TransferChain
1818
from app.core.cache import TTLCache, FileCache
1919
from app.core.config import settings
20+
from app.db.transferhistory_oper import TransferHistoryOper
2021
from app.helper.directory import DirectoryHelper
2122
from app.helper.message import MessageHelper
2223
from app.log import logger
@@ -328,10 +329,9 @@ def force_full_scan(self, storage: str, mon_path: Path) -> bool:
328329
try:
329330
if not self.__is_transfer_candidate_path(Path(file_path)):
330331
continue
331-
logger.info(f"处理文件:{file_path}")
332332
file_size = file_info.get('size', 0) if isinstance(file_info, dict) else file_info
333-
self.__handle_file(storage=storage, event_path=Path(file_path), file_size=file_size)
334-
processed_count += 1
333+
if self.__handle_file(storage=storage, event_path=Path(file_path), file_size=file_size):
334+
processed_count += 1
335335
except Exception as e:
336336
logger.error(f"处理文件 {file_path} 失败: {e}")
337337
continue
@@ -453,6 +453,26 @@ def __is_transfer_candidate_path(self, file_path: Path) -> bool:
453453
return False
454454
return self.__has_suffix_in(file_path, self.all_exts)
455455

456+
@staticmethod
457+
def __build_transfer_src_path(event_path: Path, is_bluray_folder: bool) -> str:
458+
"""
459+
生成整理记录使用的源路径。
460+
"""
461+
if is_bluray_folder:
462+
return f"{event_path.as_posix()}/"
463+
return event_path.as_posix()
464+
465+
@staticmethod
466+
def __has_transfer_history(storage: str, src_path: str) -> Optional[bool]:
467+
"""
468+
判断源文件是否已经存在整理记录。
469+
"""
470+
try:
471+
return bool(TransferHistoryOper().get_by_src(src_path, storage=storage))
472+
except Exception as err:
473+
logger.error(f"查询整理历史失败: {src_path} - {err}")
474+
return None
475+
456476
@staticmethod
457477
def count_directory_files(directory: Path, max_check: int = 10000) -> int:
458478
"""
@@ -761,22 +781,24 @@ def polling_observer(self, storage: str, mon_paths: List[Path]):
761781
]
762782

763783
# 处理新增文件
784+
handled_added_count = 0
764785
for new_file in added_files:
765-
logger.info(f"发现新增文件:{new_file}")
766786
file_info = new_snapshot.get(new_file, {})
767787
file_size = file_info.get('size', 0) if isinstance(file_info, dict) else file_info
768-
self.__handle_file(storage=storage, event_path=Path(new_file), file_size=file_size)
788+
if self.__handle_file(storage=storage, event_path=Path(new_file), file_size=file_size):
789+
handled_added_count += 1
769790

770791
# 处理修改文件
792+
handled_modified_count = 0
771793
for modified_file in modified_files:
772-
logger.info(f"发现修改文件:{modified_file}")
773794
file_info = new_snapshot.get(modified_file, {})
774795
file_size = file_info.get('size', 0) if isinstance(file_info, dict) else file_info
775-
self.__handle_file(storage=storage, event_path=Path(modified_file), file_size=file_size)
796+
if self.__handle_file(storage=storage, event_path=Path(modified_file), file_size=file_size):
797+
handled_modified_count += 1
776798

777-
if added_files or modified_files:
799+
if handled_added_count or handled_modified_count:
778800
logger.info(
779-
f"{storage} 发现 {len(added_files)} 个新增文件,{len(modified_files)} 个修改文件")
801+
f"{storage} 发现 {handled_added_count} 个新增文件,{handled_modified_count} 个修改文件")
780802
else:
781803
logger.debug(f"{storage} 无文件变化")
782804
else:
@@ -813,17 +835,16 @@ def event_handler(self, event, text: str, event_path: str, file_size: float = No
813835
if not event.is_directory:
814836
if not self.__is_transfer_candidate_path(Path(event_path)):
815837
return
816-
# 文件发生变化
817-
logger.debug(f"检测到文件变化: {event_path} [{text}]")
818838
# 整理文件
819839
self.__handle_file(storage="local", event_path=Path(event_path), file_size=file_size)
820840

821-
def __handle_file(self, storage: str, event_path: Path, file_size: float = None):
841+
def __handle_file(self, storage: str, event_path: Path, file_size: float = None) -> bool:
822842
"""
823843
整理一个文件
824844
:param storage: 存储
825845
:param event_path: 事件文件路径
826846
:param file_size: 文件大小
847+
:return: 是否进入整理链
827848
"""
828849
# 全程加锁
829850
with lock:
@@ -832,17 +853,27 @@ def __handle_file(self, storage: str, event_path: Path, file_size: float = None)
832853
if self.__is_bluray_sub(event_path):
833854
event_path = self.__get_bluray_dir(event_path)
834855
if not event_path:
835-
return
856+
return False
836857
is_bluray_folder = True
837858
elif not self.__is_transfer_candidate_path(event_path):
838-
return
859+
return False
839860

840861
# TTL缓存控重
841862
if self._cache.get(str(event_path)):
842-
logger.debug(f"文件 {event_path} 在缓存中,跳过处理")
843-
return
863+
return False
844864
self._cache[str(event_path)] = True
845865

866+
src_path = self.__build_transfer_src_path(
867+
event_path=event_path,
868+
is_bluray_folder=is_bluray_folder,
869+
)
870+
has_transfer_history = self.__has_transfer_history(
871+
storage=storage,
872+
src_path=src_path,
873+
)
874+
if has_transfer_history is not False:
875+
return False
876+
846877
try:
847878
if is_bluray_folder:
848879
logger.info(f"开始整理蓝光原盘: {event_path}")
@@ -852,20 +883,18 @@ def __handle_file(self, storage: str, event_path: Path, file_size: float = None)
852883
TransferChain().do_transfer(
853884
fileitem=FileItem(
854885
storage=storage,
855-
path=(
856-
event_path.as_posix()
857-
if not is_bluray_folder
858-
else event_path.as_posix() + "/"
859-
),
886+
path=src_path,
860887
type="file" if not is_bluray_folder else "dir",
861888
name=event_path.name,
862889
basename=event_path.stem,
863890
extension=event_path.suffix[1:],
864891
size=file_size
865892
)
866893
)
894+
return True
867895
except Exception as e:
868896
logger.error("目录监控整理文件发生错误:%s - %s" % (str(e), traceback.format_exc()))
897+
return False
869898

870899
def stop(self):
871900
"""

0 commit comments

Comments
 (0)