diff --git a/app/api/endpoints/storage.py b/app/api/endpoints/storage.py index 8f9b64b0..c8b3fa8e 100644 --- a/app/api/endpoints/storage.py +++ b/app/api/endpoints/storage.py @@ -15,6 +15,7 @@ from app.db.models import User from app.db.user_oper import get_current_active_superuser, get_current_active_superuser_async from app.helper.progress import ProgressHelper from app.schemas.types import ProgressKey +from app.utils.string import StringUtils router = APIRouter() @@ -80,7 +81,7 @@ def list_files(fileitem: schemas.FileItem, file_list = StorageChain().list_files(fileitem) if file_list: if sort == "name": - file_list.sort(key=lambda x: x.name or "") + file_list.sort(key=lambda x: StringUtils.natural_sort_key(x.name or "")) else: file_list.sort(key=lambda x: x.modify_time or datetime.min, reverse=True) return file_list diff --git a/app/utils/string.py b/app/utils/string.py index 353f807c..7f48d975 100644 --- a/app/utils/string.py +++ b/app/utils/string.py @@ -938,3 +938,19 @@ class StringUtils: if isinstance(content, bytes) and content.startswith(b"magnet:"): return True return False + + @staticmethod + def natural_sort_key(text: str) -> List[Union[int, str]]: + """ + 自然排序 + 将字符串拆分为数字和非数字部分,数字部分转换为整数,非数字部分转换为小写字母 + :param text: 要处理的字符串 + :return 用于排序的数字和字符串列表 + """ + if text is None: + return [] + + if not isinstance(text, str): + text = str(text) + + return [int(part) if part.isdigit() else part.lower() for part in re.split(r'(\d+)', text)]