返回 VideoClaw
session.py
根目录 / video-claw / video-claw / backend / session.py
1 # -*- coding: utf-8 -*-
2 import json
3 import os
4 import time
5
6 class SessionManager:
7 """Manages chat sessions persistence"""
8 def __init__(self, data_dir="code/data"):
9 self.data_dir = data_dir
10 if not os.path.exists(data_dir):
11 os.makedirs(data_dir)
12
13 def _get_file(self, session_id):
14 return os.path.join(self.data_dir, f"{session_id}.json")
15
16 def list_sessions(self):
17 """List all sessions ordered by modification time"""
18 sessions = []
19 if not os.path.exists(self.data_dir):
20 return sessions
21
22 files = [f for f in os.listdir(self.data_dir) if f.endswith('.json')]
23 for f in files:
24 try:
25 path = os.path.join(self.data_dir, f)
26 with open(path, 'r', encoding='utf-8') as fs:
27 data = json.load(fs)
28 # title, id, last_updated
29 sessions.append({
30 "id": data.get("id"),
31 "title": data.get("title", "Untitled"),
32 "date": "7days", # Simplification. Real logic would calc date diff
33 "timestamp": os.path.getmtime(path)
34 })
35 except Exception:
36 continue
37
38 # Sort by timestamp desc
39 sessions.sort(key=lambda x: x['timestamp'], reverse=True)
40 return sessions
41
42 def get_session(self, session_id):
43 """Get full history of a session"""
44 path = self._get_file(session_id)
45 if os.path.exists(path):
46 try:
47 with open(path, 'r', encoding='utf-8') as f:
48 return json.load(f)
49 except Exception:
50 pass
51 return None
52
53 def save_session(self, session_id, title, messages, asset_library=None):
54 """Save or update session"""
55 data = {
56 "id": session_id,
57 "title": title,
58 "last_updated": time.time(),
59 "messages": messages,
60 "asset_library": asset_library or {}
61 }
62 with open(self._get_file(session_id), 'w', encoding='utf-8') as f:
63 json.dump(data, f, indent=2, ensure_ascii=False)
64
64 lines PYTHON