feat: 历史归档按名称默认只保留最近7天

This commit is contained in:
2026-11-09 15:03:28 +08:00
parent f849950c5a
commit 3cd1196010
9 changed files with 219 additions and 1 deletions
+66
View File
@@ -83,6 +83,9 @@ class FtpStorage:
self._call("upload", path, lambda ftp: ftp.storbinary(f"STOR {path}", io.BytesIO(payload)))
return path
def delete(self, path: str) -> None:
self._call("delete", path, lambda ftp: self._remove(ftp, path))
def close(self) -> None:
ftp, self._ftp = self._ftp, None
if ftp is None:
@@ -114,6 +117,54 @@ class FtpStorage:
self._ftp = ftp
return self._ftp
def _remove(self, ftp: ftplib.FTP, path: str) -> None:
children = self._children(ftp, path)
if children is None:
ftp.delete(path)
return
for name, is_dir in children:
child = posixpath.join(path, name)
if is_dir:
self._remove(ftp, child)
else:
ftp.delete(child)
ftp.rmd(path)
@staticmethod
def _children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
try:
listed = list(ftp.mlsd(path))
except ftplib.error_perm as exc:
if str(exc).startswith(FTP_UNSUPPORTED_COMMAND_CODES):
return FtpStorage._nlst_children(ftp, path)
return None
result: list[tuple[str, bool]] = []
for name, facts in listed:
if name in {".", ".."}:
continue
result.append((name, facts.get("type") == "dir"))
return result
@staticmethod
def _nlst_children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
try:
names = ftp.nlst(path)
except ftplib.error_perm:
return None
children: list[tuple[str, bool]] = []
for name in names:
base = posixpath.basename(name.rstrip("/"))
if base in {"", ".", ".."}:
continue
child = name if name.startswith("/") else posixpath.join(path, base)
try:
ftp.cwd(child)
ftp.cwd(path)
children.append((base, True))
except ftplib.error_perm:
children.append((base, False))
return children
def _call(self, operation: str, path: str, action: Callable[[ftplib.FTP], T]) -> T:
last_error: BaseException | None = None
for _ in range(2):
@@ -156,6 +207,9 @@ class SftpStorage:
self._call("upload", path, lambda sftp: sftp.putfo(io.BytesIO(payload), path))
return path
def delete(self, path: str) -> None:
self._call("delete", path, lambda sftp: self._remove(sftp, path))
def close(self) -> None:
transport, self._transport, self._sftp = self._transport, None, None
if transport is not None:
@@ -183,6 +237,18 @@ class SftpStorage:
self._transport, self._sftp = transport, sftp
return self._sftp
def _remove(self, sftp: paramiko.SFTPClient, path: str) -> None:
try:
attrs = sftp.stat(path)
except FileNotFoundError:
return
if stat.S_ISDIR(attrs.st_mode or 0):
for item in sftp.listdir_attr(path):
self._remove(sftp, posixpath.join(path, item.filename))
sftp.rmdir(path)
return
sftp.remove(path)
def _call(self, operation: str, path: str, action: Callable[[paramiko.SFTPClient], T]) -> T:
last_error: BaseException | None = None
for _ in range(2):