from abc import ABCMeta, abstractmethod from pathlib import Path, PurePosixPath from typing import Any, Callable, Dict, List, Optional, Tuple, Union from tqdm import tqdm from app.application.storage import StorageHelper from app.foundation.crypto import HashUtils from app.runtime.log import logger from app.runtime.progress import ProgressHelper from app.schemas.exception import StorageQueryError from app.schemas.file import StorageUsage as _SchemaStorageUsage from app.schemas.system import StorageConf as _SchemaStorageConf from app.schemas.workflow import FileItem as _SchemaFileItem _SnapshotInfo = Dict[str, Dict[str, Any]] def transfer_process(path: str) -> Callable[[int | float], None]: """ 传输进度回调 """ pbar = tqdm(total=100, desc="进度", unit="%") progress = ProgressHelper(HashUtils.md5(path)) progress.start() def update_progress(percent: Union[int, float]) -> None: """ 更新进度百分比 """ percent_value = round(percent, 2) if isinstance(percent, float) else percent pbar.n = percent_value # 更新进度 pbar.refresh() progress.update(value=percent_value, text=f"{path} 进度:{percent_value}%") # 完成时结束 if percent_value >= 100: progress.end() pbar.close() return update_progress class StorageBase(metaclass=ABCMeta): """ 存储基类 """ schema = None transtype = {} @property def snapshot_check_folder_modtime(self) -> bool: """返回存储快照目录时间检查的默认开关。""" return True @property def snapshot_strict_query(self) -> bool: """声明快照是否使用严格查询;未适配的存储沿用原查询合同。""" return False def __init__(self): self.storagehelper = StorageHelper() def close(self) -> bool | None: """关闭外部资源;返回 False 表示 owner 尚未收敛且必须保留。""" return None @abstractmethod def init_storage(self): """ 初始化 """ pass def generate_qrcode(self, *args, **kwargs) -> Optional[Tuple[dict, str]]: """生成存储登录二维码""" pass def generate_auth_url(self, *args, **kwargs) -> Optional[Tuple[dict, str]]: """ 生成 OAuth2 授权 URL """ return {}, "此存储不支持 OAuth2 授权" def check_login(self, *args, **kwargs) -> Optional[Dict[str, str]]: """检查存储登录状态""" pass def get_config(self) -> Optional[_SchemaStorageConf]: """ 获取配置 """ return self.storagehelper.get_storage(self.schema.value) def get_conf(self) -> dict: """ 获取配置 """ conf = self.get_config() return conf.config if conf else {} def set_config(self, conf: dict): """ 设置配置 """ self.storagehelper.set_storage(self.schema.value, conf) self.init_storage() def support_transtype(self) -> dict: """ 支持的整理方式 """ return self.transtype def is_support_transtype(self, transtype: str) -> bool: """ 是否支持整理方式 """ return transtype in self.transtype def reset_config(self): """ 重置置配置 """ self.storagehelper.reset_storage(self.schema.value) self.init_storage() @staticmethod def _safe_download_name(name: Optional[str]) -> Optional[str]: """ 提取可安全落盘的文件名。 """ if not name: return None safe_name = PurePosixPath(str(name).replace("\\", "/")).name if safe_name in ("", ".", ".."): return None return safe_name def _build_download_path( self, fileitem: _SchemaFileItem, path: Path ) -> Optional[Path]: """ 构造本地下载路径,避免远端文件名携带目录片段时越过目标目录。 """ safe_name = self._safe_download_name(fileitem.name) if not safe_name: logger.error(f"【存储】下载文件名无效:{fileitem.name}") return None local_path = path / safe_name try: local_path.resolve().relative_to(path.resolve()) except ValueError: logger.error(f"【存储】下载路径越界:{fileitem.name} -> {local_path}") return None return local_path @abstractmethod def check(self) -> bool: """ 检查存储是否可用 """ pass @abstractmethod def list(self, fileitem: _SchemaFileItem) -> List[_SchemaFileItem]: """ 浏览文件 """ pass def list_strict(self, fileitem: _SchemaFileItem) -> List[_SchemaFileItem]: """完整列举目录;空列表表示确认无子项,无法确认时抛出 StorageQueryError。""" raise StorageQueryError(f"存储 {self.schema} 未实现严格目录查询: {fileitem.path}") @abstractmethod def create_folder(self, fileitem: _SchemaFileItem, name: str) -> Optional[_SchemaFileItem]: """ 创建目录 :param fileitem: 父目录 :param name: 目录名 """ pass @abstractmethod def get_folder(self, path: Path) -> Optional[_SchemaFileItem]: """ 获取目录,如目录不存在则创建 """ pass @abstractmethod def get_item(self, path: Path) -> Optional[_SchemaFileItem]: """ 获取文件或目录,不存在返回None """ pass def get_item_strict(self, path: Path) -> Optional[_SchemaFileItem]: """ 获取文件或目录,确认不存在返回None;无法确认状态时抛出 StorageQueryError。 默认保守失败:未覆写的存储无法区分「不存在」与「查询失败」,沿用 get_item() 会让 overwrite_mode=size 的覆盖保护在查询失败时被绕过, 把「无法确认」当成「目标不存在」而放行覆盖。具体存储必须先实现 「确认不存在」的判定,再覆写本方法。 """ raise StorageQueryError(f"存储 {self.schema} 未实现严格查询,无法确认目标状态: {path}") def get_parent(self, fileitem: _SchemaFileItem) -> Optional[_SchemaFileItem]: """ 获取父目录 """ return self.get_item(Path(fileitem.path).parent) @abstractmethod def delete(self, fileitem: _SchemaFileItem) -> bool: """ 删除文件 """ pass @abstractmethod def rename(self, fileitem: _SchemaFileItem, name: str) -> bool: """ 重命名文件 """ pass @abstractmethod def download(self, fileitem: _SchemaFileItem, path: Path = None) -> Path: """ 下载文件,保存到本地,返回本地临时文件地址 :param fileitem: 文件项 :param path: 文件保存路径 """ pass @abstractmethod def upload(self, fileitem: _SchemaFileItem, path: Path, new_name: Optional[str] = None) -> Optional[_SchemaFileItem]: """ 上传文件 :param fileitem: 上传目录项 :param path: 本地文件路径 :param new_name: 上传后文件名 """ pass @abstractmethod def detail(self, fileitem: _SchemaFileItem) -> Optional[_SchemaFileItem]: """ 获取文件详情 """ pass @abstractmethod def copy(self, fileitem: _SchemaFileItem, path: Path, new_name: str) -> bool: """ 复制文件 :param fileitem: 文件项 :param path: 目标目录 :param new_name: 新文件名 """ pass @abstractmethod def move(self, fileitem: _SchemaFileItem, path: Path, new_name: str) -> bool: """ 移动文件 :param fileitem: 文件项 :param path: 目标目录 :param new_name: 新文件名 """ pass @abstractmethod def link(self, fileitem: _SchemaFileItem, target_file: Path) -> bool: """ 硬链接文件 """ pass @abstractmethod def softlink(self, fileitem: _SchemaFileItem, target_file: Path) -> bool: """ 软链接文件 """ pass @abstractmethod def usage(self) -> Optional[_SchemaStorageUsage]: """ 存储使用情况 """ pass def _snapshot_list(self, fileitem: _SchemaFileItem) -> Optional[List[_SchemaFileItem]]: """按存储能力读取目录,严格快照不能把无结果当作可以跳过的子树。""" if not self.snapshot_strict_query: return self.list(fileitem) items = self.list_strict(fileitem) if items is None: raise StorageQueryError(f"目录查询没有返回完整结果: {fileitem.path}") return items def _snapshot_read_error(self, fileitem: _SchemaFileItem, error: Exception) -> None: """严格快照传播读取故障;未适配的存储保留原来的子树容错行为。""" if self.snapshot_strict_query: if isinstance(error, StorageQueryError): raise error raise StorageQueryError(f"读取快照路径失败: {fileitem.path} - {error}") from error logger.debug(f"Snapshot error for {fileitem.path}: {error}") @staticmethod def _snapshot_previous_state( root_path: PurePosixPath, previous_snapshot: Optional[_SnapshotInfo], ) -> Tuple[ _SnapshotInfo, Dict[PurePosixPath, set[PurePosixPath]], Dict[PurePosixPath, str], ]: """ 为增量快照建立旧文件和目录直接子项索引。 :param root_path: 本轮快照的根路径 :param previous_snapshot: 上一轮完整快照 :return: 当前文件信息、目录直接子项索引和路径反向索引 """ files_info = { file_path: file_info for file_path, file_info in (previous_snapshot or {}).items() if PurePosixPath(file_path).is_relative_to(root_path) } previous_children: Dict[PurePosixPath, set[PurePosixPath]] = {} previous_files: Dict[PurePosixPath, str] = {} for file_path in files_info: file_posix_path = PurePosixPath(file_path) previous_files[file_posix_path] = file_path try: relative_parts = file_posix_path.relative_to(root_path).parts except ValueError: # files_info 已经按 root_path 过滤;保留防御性判断,避免 # 非标准路径对象让增量索引中断整轮监控。 continue for depth in range(len(relative_parts)): directory_path = root_path.joinpath(*relative_parts[:depth]) child_path = directory_path / relative_parts[depth] previous_children.setdefault(directory_path, set()).add(child_path) return files_info, previous_children, previous_files @staticmethod def _snapshot_remove_previous_subtree( path: PurePosixPath, files_info: _SnapshotInfo, previous_children: Dict[PurePosixPath, set[PurePosixPath]], previous_files: Dict[PurePosixPath, str], ) -> None: """沿旧快照索引移除一个已经消失的直接子树。""" pending = [path] while pending: current_path = pending.pop() old_file_path = previous_files.pop(current_path, None) if old_file_path is not None: files_info.pop(old_file_path, None) pending.extend(previous_children.pop(current_path, ())) def _snapshot_remove_deleted_children( self, fileitem: _SchemaFileItem, sub_files: List[_SchemaFileItem], files_info: _SnapshotInfo, previous_children: Dict[PurePosixPath, set[PurePosixPath]], previous_files: Dict[PurePosixPath, str], ) -> None: """ 清理已确认遍历目录中不再存在的直接子项。 :param fileitem: 当前已列举的目录 :param sub_files: 当前目录返回的直接子项 :param files_info: 当前正在构建的快照 :param previous_children: 旧快照目录直接子项索引 :param previous_files: 旧快照路径反向索引 """ directory_path = PurePosixPath(fileitem.path) child_paths = {PurePosixPath(sub_file.path) for sub_file in sub_files} for direct_child_path in previous_children.pop(directory_path, ()): if direct_child_path not in child_paths: StorageBase._snapshot_remove_previous_subtree( direct_child_path, files_info, previous_children, previous_files ) def _snapshot_file( self, fileitem: _SchemaFileItem, files_info: _SnapshotInfo, previous_children: Dict[PurePosixPath, set[PurePosixPath]], previous_files: Dict[PurePosixPath, str], last_snapshot_time: float, max_depth: int, current_depth: int = 0, ) -> None: """ 递归读取目录并更新快照文件信息。 :param fileitem: 当前文件或目录 :param files_info: 当前正在构建的快照 :param previous_children: 旧快照目录直接子项索引 :param previous_files: 旧快照路径反向索引 :param last_snapshot_time: 上次快照时间 :param max_depth: 最大递归深度 :param current_depth: 当前递归深度 """ try: if fileitem.type == "dir": if current_depth >= max_depth: return # 根目录每轮至少列举一次;子目录按修改时间跳过未变化分支。 if (current_depth > 0 and self.snapshot_check_folder_modtime and last_snapshot_time and fileitem.modify_time and fileitem.modify_time <= last_snapshot_time): return # 只有目录列表成功返回后才清理旧基线,查询异常时保留待下轮重试。 sub_files = self._snapshot_list(fileitem) if sub_files is None: return sub_files = list(sub_files) StorageBase._snapshot_remove_deleted_children( self, fileitem, sub_files, files_info, previous_children, previous_files ) for sub_file in sub_files: StorageBase._snapshot_file( self, sub_file, files_info, previous_children, previous_files, last_snapshot_time, max_depth, current_depth + 1, ) else: # 始终记录文件完整信息,由 compare_snapshots 负责检测变化。 files_info[fileitem.path] = { 'size': fileitem.size or 0, 'modify_time': getattr(fileitem, 'modify_time', 0), 'fileid': getattr(fileitem, 'fileid', None), 'type': fileitem.type } except Exception as error: self._snapshot_read_error(fileitem, error) def snapshot(self, path: Path, last_snapshot_time: float = None, max_depth: int = 5, previous_snapshot: Optional[Dict[str, Dict]] = None) -> Optional[Dict[str, Dict]]: """ 快照文件系统,输出所有层级文件信息(不含目录) :param path: 路径 :param last_snapshot_time: 上次快照时间,用于增量快照 :param max_depth: 最大递归深度,避免过深遍历 :param previous_snapshot: 上次完整快照,用于保留未变化目录并清理已删除文件 :return: 有效快照(允许为空);严格查询失败返回 None,调用方必须保留旧基线 """ strict_query = self.snapshot_strict_query root_path = PurePosixPath(path.as_posix()) files_info, previous_children, previous_files = StorageBase._snapshot_previous_state( root_path, previous_snapshot ) try: fileitem = self.get_item_strict(path) if strict_query else self.get_item(path) if not fileitem: return {} StorageBase._snapshot_file( self, fileitem, files_info, previous_children, previous_files, last_snapshot_time, max_depth, ) except StorageQueryError as err: logger.warning(f"存储快照失败,保留上次基线: {self.schema}:{path} - {err}") return None return files_info