# backend/history.py import json import logging import shutil import time from pathlib import Path from typing import Any logger = logging.getLogger("obsigate.history") HISTORY_DIR = Path("data/history") def _get_history_file(username: str) -> Path: HISTORY_DIR.mkdir(parents=True, exist_ok=True) return HISTORY_DIR / f"{username}.json" def _get_bookmarks_file(username: str) -> Path: HISTORY_DIR.mkdir(parents=True, exist_ok=True) return HISTORY_DIR / f"{username}_bookmarks.json" def _read_data(file: Path) -> list[dict[str, Any]]: if not file.exists(): return [] try: return json.loads(file.read_text(encoding="utf-8")) except Exception as e: logger.error(f"Failed to read data from {file.name}: {e}") return [] def _write_data(file: Path, data: list[dict[str, Any]]): try: tmp = file.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8") shutil.move(str(tmp), str(file)) except Exception as e: logger.error(f"Failed to write data to {file.name}: {e}") def record_open(username: str, vault: str, path: str, title: str = ""): """Record that a file was opened by a user.""" if not username: return history = _read_data(_get_history_file(username)) # Remove existing entry for the same file if any history = [item for item in history if not (item["vault"] == vault and item["path"] == path)] # Add new entry at the beginning history.insert(0, { "vault": vault, "path": path, "title": title, "opened_at": time.time() }) # Limit history size (e.g., 100 entries) history = history[:100] _write_data(_get_history_file(username), history) def get_recent_opened(username: str, vault_filter: str | None = None, limit: int = 20) -> list[dict[str, Any]]: """Get the most recently opened files for a user.""" if not username: return [] history = _read_data(_get_history_file(username)) if vault_filter: history = [item for item in history if item["vault"] == vault_filter] return history[:limit] def remove_recent(username: str, vault: str, path: str): """Remove a file from the recent history (e.g., after deletion).""" if not username: return history = _read_data(_get_history_file(username)) history = [item for item in history if not (item["vault"] == vault and item["path"] == path)] _write_data(_get_history_file(username), history) def toggle_bookmark(username: str, vault: str, path: str, title: str = ""): """Toggle a file as bookmark for a user. Returns True if bookmarked, False if removed.""" if not username: return False b_file = _get_bookmarks_file(username) bookmarks = _read_data(b_file) # Check if already bookmarked existing = [b for b in bookmarks if b["vault"] == vault and b["path"] == path] if existing: # Remove bookmarks = [b for b in bookmarks if not (b["vault"] == vault and b["path"] == path)] _write_data(b_file, bookmarks) return False else: # Add bookmarks.insert(0, { "vault": vault, "path": path, "title": title or path.split("/")[-1], "bookmarked_at": time.time() }) _write_data(b_file, bookmarks) return True def get_bookmarks(username: str, vault_filter: str | None = None) -> list[dict[str, Any]]: """Get the bookmarks for a user.""" if not username: return [] bookmarks = _read_data(_get_bookmarks_file(username)) if vault_filter: bookmarks = [b for b in bookmarks if b["vault"] == vault_filter] return bookmarks def is_bookmarked(username: str, vault: str, path: str) -> bool: """Fast check if a file is bookmarked by a user.""" if not username: return False bookmarks = _read_data(_get_bookmarks_file(username)) return any(b["vault"] == vault and b["path"] == path for b in bookmarks) def update_bookmarks_after_rename(vault: str, old_path: str, new_path: str): """Update all users' bookmarks when a file is renamed.""" if not HISTORY_DIR.exists(): return for bfile in HISTORY_DIR.glob("*_bookmarks.json"): try: bookmarks = _read_data(bfile) updated = False for b in bookmarks: if b.get("vault") == vault and b.get("path") == old_path: b["path"] = new_path # Update title from new path new_title = new_path.split("/")[-1].replace(".md", "").replace("-", " ").replace("_", " ") b["title"] = new_title updated = True if updated: _write_data(bfile, bookmarks) logger.info(f"Updated bookmarks in {bfile.name}: {vault}/{old_path} -> {new_path}") except Exception as e: logger.error(f"Failed to update bookmarks in {bfile.name}: {e}") def update_history_after_rename(vault: str, old_path: str, new_path: str): """Update all users' history entries when a file is renamed.""" if not HISTORY_DIR.exists(): return for hfile in HISTORY_DIR.glob("*.json"): if "_bookmarks" in hfile.name: continue try: history = _read_data(hfile) updated = False for h in history: if h.get("vault") == vault and h.get("path") == old_path: h["path"] = new_path updated = True if updated: _write_data(hfile, history) logger.info(f"Updated history in {hfile.name}: {vault}/{old_path} -> {new_path}") except Exception as e: logger.error(f"Failed to update history in {hfile.name}: {e}")