From d21f1f1b878337356959d66acdabf9dacede8c45 Mon Sep 17 00:00:00 2001 From: Aqr-K <95741669+Aqr-K@users.noreply.github.com> Date: Sat, 30 Aug 2025 08:44:41 +0800 Subject: [PATCH 1/3] feat(string): add `natural_sort_key` function --- app/utils/string.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/app/utils/string.py b/app/utils/string.py index 353f807c..6c0b5437 100644 --- a/app/utils/string.py +++ b/app/utils/string.py @@ -938,3 +938,15 @@ 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: 要处理的字符串 + """ + if not isinstance(text, str): + return [text] + + return [int(part) if part.isdigit() else part.lower() for part in re.split(r'(\d+)', text)] From 26cc6da6506e456441cd69cf96de5aec938afa63 Mon Sep 17 00:00:00 2001 From: Aqr-K <95741669+Aqr-K@users.noreply.github.com> Date: Sat, 30 Aug 2025 08:48:38 +0800 Subject: [PATCH 2/3] fix(storage): Adjust to use `natural_stort_key` --- app/api/endpoints/storage.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 From f22bc68af487458cc176b1c19f413878a4a9ae87 Mon Sep 17 00:00:00 2001 From: Aqr-K <95741669+Aqr-K@users.noreply.github.com> Date: Sat, 30 Aug 2025 08:59:35 +0800 Subject: [PATCH 3/3] Update string.py --- app/utils/string.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/utils/string.py b/app/utils/string.py index 6c0b5437..7f48d975 100644 --- a/app/utils/string.py +++ b/app/utils/string.py @@ -945,8 +945,12 @@ class StringUtils: 自然排序 将字符串拆分为数字和非数字部分,数字部分转换为整数,非数字部分转换为小写字母 :param text: 要处理的字符串 + :return 用于排序的数字和字符串列表 """ + if text is None: + return [] + if not isinstance(text, str): - return [text] + text = str(text) return [int(part) if part.isdigit() else part.lower() for part in re.split(r'(\d+)', text)]