From 54b3ae5d0b59797589cc9f6f96cd6c632c0ceebf Mon Sep 17 00:00:00 2001 From: LY <51789698+Young-Lord@users.noreply.github.com> Date: Wed, 16 Aug 2023 22:03:20 +0800 Subject: [PATCH 1/2] misc: update `get_safe_path` --- main.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/main.py b/main.py index 9523b94..c61d165 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,4 @@ import json - import typer from pathlib import Path import requests @@ -7,20 +6,19 @@ app = typer.Typer() -# Credits: YoungLord https://github.com/Young-Lord/QQ-History-Backup/blob/b7d7f136020d0699c8dd802b3dff65247aeb6698/QQ_History.py#L99 -def getSafePath(ans: str) -> str: +def get_safe_path(s: str) -> str: + """ + Remove invalid characters & prefixes to sanitize a path. + :param s: str to sanitize + :returns: sanitized str + """ ban_words = "\\ / : * ? \" ' < > | $ \r \n".replace( ' ', '') ban_strips = "#/~" - while True: - ans_bak = ans - for i in ban_words: - ans = ans.replace(i, "") - for i in ban_strips: - ans = ans.strip(i) - if ans == ans_bak: # 多次匹配 - break - return ans + for i in ban_words: + s = s.replace(i, "") + s = s.strip(i) + return s def export_chathistory(user_id: str): res = requests.get("http://localhost:48065/wechat/chatlog", params={ @@ -38,9 +36,9 @@ def export_all(dest: Path): for user in tqdm(all_users['items']): usr_chatlog = export_chathistory(user['arg']) - out_path = dest/getSafePath((user['title'] or "")+"-"+user['arg']+'.json') - with open(out_path, 'w') as f: + out_path = dest/get_safe_path((user['title'] or "")+"-"+user['arg']+'.json') + with open(out_path, 'w', encoding='utf-8') as f: json.dump(usr_chatlog, f) if __name__ == "__main__": - app() \ No newline at end of file + app() From 1605fbd874d8420a15e5b68257eef415cbae15cc Mon Sep 17 00:00:00 2001 From: LY <51789698+Young-Lord@users.noreply.github.com> Date: Thu, 17 Aug 2023 13:20:38 +0800 Subject: [PATCH 2/2] feat: remove prefix sanitization in `get_safe_path` --- main.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/main.py b/main.py index c61d165..0b22ecc 100644 --- a/main.py +++ b/main.py @@ -8,16 +8,14 @@ def get_safe_path(s: str) -> str: """ - Remove invalid characters & prefixes to sanitize a path. + Remove invalid characters to sanitize a path. :param s: str to sanitize :returns: sanitized str """ - ban_words = "\\ / : * ? \" ' < > | $ \r \n".replace( + ban_chars = "\\ / : * ? \" ' < > | $ \r \n".replace( ' ', '') - ban_strips = "#/~" - for i in ban_words: + for i in ban_chars: s = s.replace(i, "") - s = s.strip(i) return s def export_chathistory(user_id: str):