import json import os import time from datetime import datetime from pathlib import Path DB_PATH = Path(__file__).parent / "database.json" def load_db(): if DB_PATH.exists(): try: with open(DB_PATH, "r", encoding="utf-8") as f: return json.load(f) except Exception: return [] return [] def save_db(users): with open(DB_PATH, "w", encoding="utf-8") as f: json.dump(users, f, indent=2) def get_user_by_username(username: str): for u in load_db(): if u.get("username") == username: return u return None def get_user_by_id(user_id: int): for u in load_db(): if u.get("id") == user_id: return u return None def create_user(user_data: dict): users = load_db() new_user = { **user_data, "id": int(time.time() * 1000), "createdAt": datetime.now().isoformat(), "history": [] } users.append(new_user) save_db(users) return new_user def add_history_record(user_id: int, markdown_text: str): users = load_db() for u in users: if u.get("id") == user_id: if "history" not in u: u["history"] = [] # 取前50个字符作为摘要 summary = markdown_text[:50].replace('\n', ' ') + ('...' if len(markdown_text) > 50 else '') record = { "id": int(time.time() * 1000), "timestamp": datetime.now().isoformat(), "summary": summary if summary.strip() else "空文档", "markdown": markdown_text } # 插入到最前面 u["history"].insert(0, record) # 最多保存 100 条 if len(u["history"]) > 100: u["history"] = u["history"][:100] save_db(users) return record return None def get_history_records(user_id: int): user = get_user_by_id(user_id) if user: return user.get("history", []) return []