# history_manager.py # # Copyright 2025 Pavel Baksy # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # SPDX-License-Identifier: GPL-3.0-or-later import json import os from pathlib import Path from typing import List import gi gi.require_version('GLib', '2.0') from gi.repository import GLib from .models import HistoryEntry class HistoryManager: """Manages request history persistence to JSON file.""" def __init__(self): # Use XDG config directory (works for both Flatpak and native) # Flatpak: ~/.var/app/cz.vesp.roster/config/cz.vesp.roster # Native: ~/.config/cz.vesp.roster self.config_dir = Path(GLib.get_user_config_dir()) / 'cz.vesp.roster' self.history_file = self.config_dir / 'history.json' self._ensure_config_dir() def _ensure_config_dir(self): """Create config directory if it doesn't exist.""" self.config_dir.mkdir(parents=True, exist_ok=True) def load_history(self) -> List[HistoryEntry]: """Load history from JSON file.""" if not self.history_file.exists(): return [] try: with open(self.history_file, 'r') as f: data = json.load(f) return [HistoryEntry.from_dict(entry) for entry in data.get('entries', [])] except Exception as e: print(f"Error loading history: {e}") return [] def save_history(self, entries: List[HistoryEntry]): """Save history to JSON file.""" try: data = { 'version': 1, 'entries': [entry.to_dict() for entry in entries] } with open(self.history_file, 'w') as f: json.dump(data, f, indent=2) except Exception as e: print(f"Error saving history: {e}") def add_entry(self, entry: HistoryEntry): """Add new entry to history and save.""" entries = self.load_history() entries.insert(0, entry) # Most recent first # Limit history size to 100 entries entries = entries[:100] self.save_history(entries)