chore: 基线提交(重构前代码快照)
- git 初始化 + .gitignore 补全(根 .env / logs / instance / __pycache__ 等) - 修复 utils/.gitignore 误将整个 utils/ 源码层忽略的问题,补入全部工具源码(含 ip2region.xdb) - 含后端全部代码:application / extensions / utils / config / migrations - 含前端 ui/(后续整体迁走) - 不含根 .env(含密钥,本地保留) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
富文本与文件处理模块
|
||||
=============================================================
|
||||
|
||||
提供文件URL处理、临时文件迁移和富文本编辑器内容处理:
|
||||
- get_file_url: 拼接文件域名生成完整URL
|
||||
- save_file: 将临时目录文件迁移到正式存储目录
|
||||
- save_content: 处理富文本HTML内容,提取并保存其中的图片文件
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import html
|
||||
|
||||
from config import FLASK_FILE_URL, FLASK_UPLOAD_DIR, FLASK_TEMP_PATH
|
||||
from utils.file import mkdir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_file_url(path):
|
||||
"""
|
||||
获取完整的文件访问URL
|
||||
|
||||
Args:
|
||||
path: 文件的相对路径,可以是空字符串、None或有效路径
|
||||
|
||||
Returns:
|
||||
完整的文件访问URL,如果path为空则返回None
|
||||
"""
|
||||
if not path:
|
||||
return None
|
||||
return FLASK_FILE_URL + path
|
||||
|
||||
|
||||
def save_file(url, directory):
|
||||
"""
|
||||
保存文件到指定目录
|
||||
|
||||
处理本站临时文件迁移:将临时目录中的文件移动到正式存储目录。
|
||||
|
||||
Args:
|
||||
url: 文件的完整URL或相对路径
|
||||
directory: 目标子目录名称,用于分类存储
|
||||
|
||||
Returns:
|
||||
文件的相对路径,失败时返回空字符串
|
||||
"""
|
||||
if not url:
|
||||
return "文件地址不能为空"
|
||||
|
||||
if url.find(FLASK_FILE_URL) != -1:
|
||||
if url.find("/temp") != -1:
|
||||
path = FLASK_UPLOAD_DIR + "/" + directory + "/" + time.strftime('%Y%m%d')
|
||||
mkdir(path)
|
||||
|
||||
old_path = url.replace(FLASK_FILE_URL, FLASK_UPLOAD_DIR)
|
||||
new_path = FLASK_UPLOAD_DIR + "/" + directory + old_path.replace(FLASK_TEMP_PATH, "")
|
||||
|
||||
os.rename(old_path, new_path)
|
||||
return new_path.replace(FLASK_UPLOAD_DIR, "")
|
||||
else:
|
||||
return url.replace(FLASK_FILE_URL, "")
|
||||
else:
|
||||
logger.warning(f"远程文件暂不支持保存: {url}")
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def save_content(content, title, directory):
|
||||
"""
|
||||
保存富文本编辑器内容
|
||||
|
||||
处理富文本HTML内容,提取其中的图片文件并保存,
|
||||
同时将文件alt属性设置为文章标题(已做HTML转义防XSS)。
|
||||
|
||||
Args:
|
||||
content: 富文本HTML内容
|
||||
title: 文章标题,用于设置文件alt属性
|
||||
directory: 文件存储的子目录名称
|
||||
|
||||
Returns:
|
||||
处理后的富文本内容,文件地址已被替换
|
||||
"""
|
||||
image_urls = re.findall('img src="(.*?)"', content, re.S)
|
||||
|
||||
for url in image_urls:
|
||||
image = save_file(url, directory)
|
||||
if image:
|
||||
content = content.replace(url, "[IMG_URL]" + image)
|
||||
|
||||
title = html.escape(str(title) if title else "", quote=True)
|
||||
if "alt=\"\"" in content and title:
|
||||
content = content.replace("alt=\"\"", "alt=\"" + title + "\"")
|
||||
|
||||
return content
|
||||
Reference in New Issue
Block a user