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.

140 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import os
import json
import time
import uuid
import re
from flask import render_template, request, url_for
from common.logger import system_logger
STORE_FILE = os.path.join(
os.path.dirname(__file__),
"temp_text_store.json"
)
EXPIRE_SECONDS = 3600 # 1小时
# =========================
# load
# =========================
def load_store():
if not os.path.exists(STORE_FILE):
return {}
try:
with open(STORE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except:
return {}
# =========================
# save
# =========================
def save_store(data):
with open(STORE_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# =========================
# markdown轻量格式化V2新增
# =========================
def normalize_markdown(text: str) -> str:
if not text:
return ""
text = text.replace("\r\n", "\n").replace("\r", "\n")
# 去掉多余空行最多保留1个空行
text = re.sub(r"\n{3,}", "\n\n", text)
# 行首尾空格清理
lines = [line.rstrip() for line in text.split("\n")]
return "\n".join(lines).strip()
# =========================
# cleanup
# =========================
def cleanup(store):
now = time.time()
expired = [
k for k, v in store.items()
if v["expires_at"] < now
]
for k in expired:
del store[k]
return store
# =========================
# 创建页面
# =========================
def temp_text_create_page():
message = None
share_link = None
if request.method == "POST":
content = request.form.get("content", "")
if not content.strip():
return render_template("temp_text.html", message="内容不能为空")
# ✔ markdown规范化
content = normalize_markdown(content)
store = load_store()
store = cleanup(store)
text_id = uuid.uuid4().hex[:8]
now = time.time()
store[text_id] = {
"content": content,
"created_at": now,
"expires_at": now + EXPIRE_SECONDS
}
save_store(store)
share_link = url_for("temp_text_view_route", text_id=text_id, _external=True)
system_logger.info(f"[TempTextV2] create id={text_id}")
message = "创建成功1小时有效"
return render_template(
"temp_text.html",
message=message,
share_link=share_link
)
# =========================
# 查看页面
# =========================
def temp_text_view(text_id):
store = load_store()
store = cleanup(store)
if text_id not in store:
return "内容不存在或已过期"
content = store[text_id]["content"]
system_logger.info(f"[TempTextV2] view id={text_id}")
return render_template(
"temp_text_view.html",
content=content,
text_id=text_id
)