You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.4 KiB
53 lines
1.4 KiB
"""文件消息解析"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_WECHAT_FILE_DIRS = [
|
|
Path(os.environ.get("USERPROFILE", "")) / "Documents" / "WeChat Files",
|
|
]
|
|
|
|
|
|
class FileParser:
|
|
"""解析文件消息"""
|
|
|
|
@staticmethod
|
|
def is_file_message(content: str) -> bool:
|
|
tag = content.strip("[]")
|
|
return "文件" in tag or "file" in tag.lower()
|
|
|
|
@staticmethod
|
|
def extract_filename(content: str) -> str:
|
|
"""从消息内容中提取文件名"""
|
|
# 去除 [文件] 等标签
|
|
name = content.strip("[]").strip()
|
|
# 去除 "文件:" 等前缀
|
|
for prefix in ("文件:", "文件:", "file:", "File:"):
|
|
if name.startswith(prefix):
|
|
name = name[len(prefix):].strip()
|
|
return name
|
|
|
|
@staticmethod
|
|
def find_cached_file(filename: str) -> Path | None:
|
|
for base_dir in _WECHAT_FILE_DIRS:
|
|
if not base_dir.exists():
|
|
continue
|
|
for p in base_dir.rglob(filename):
|
|
if p.is_file():
|
|
return p
|
|
return None
|
|
|
|
@staticmethod
|
|
def get_file_info(path: Path) -> dict:
|
|
stat = path.stat()
|
|
return {
|
|
"path": str(path),
|
|
"size": stat.st_size,
|
|
"suffix": path.suffix,
|
|
"name": path.name,
|
|
}
|
|
|