File size: 3,537 Bytes
2d52e7a
 
 
 
 
 
608e601
 
 
 
 
2d52e7a
608e601
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d52e7a
 
 
 
 
 
608e601
2d52e7a
 
 
 
 
 
 
 
 
 
 
 
 
608e601
 
2d52e7a
 
 
 
 
 
 
 
 
 
608e601
2d52e7a
 
 
 
 
 
 
 
 
 
608e601
 
2d52e7a
54a200e
608e601
 
 
 
 
 
 
 
2d52e7a
 
608e601
 
 
2d52e7a
 
608e601
 
 
 
 
 
 
 
2d52e7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608e601
2d52e7a
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""
Session management with AES encryption.
Each session is encrypted with the user's password.
Session ID is derived from password — only the right password unlocks the right session.
File contents are persisted to disk so map works after refresh.
"""

import json
import os
from datetime import datetime
from app.config import SESSION_STORE_PATH
from app.utils.crypto import encrypt, decrypt, derive_session_id


def _load_all() -> dict:
    if os.path.exists(SESSION_STORE_PATH):
        try:
            with open(SESSION_STORE_PATH, "r") as f:
                return json.load(f)
        except Exception:
            return {}
    return {}


def _save_all(data: dict):
    try:
        with open(SESSION_STORE_PATH, "w") as f:
            json.dump(data, f)
    except Exception as e:
        print(f"[SESSION] Save failed: {e}")


def get_session(session_id: str, password: str) -> dict:
    """
    Load and decrypt a session.
    Returns empty session if not found.
    Raises ValueError if password is wrong.
    """
    all_sessions = _load_all()
    if session_id not in all_sessions:
        return {
            "messages": [],
            "linked_files": [],
            "file_contents": {},
            "map_data": None,
            "label": "untitled session",
            "created_at": datetime.now().isoformat(),
            "last_active": datetime.now().isoformat(),
        }
    token = all_sessions[session_id]
    # decrypt raises ValueError on wrong password
    return decrypt(token, password)


def save_session(
    session_id: str,
    password: str,
    messages: list,
    linked_files: list,
    file_contents: dict,
    label: str = "",
    map_data: dict = None,
):
    """Encrypt and persist session data."""
    all_sessions = _load_all()

    # Reconstruct existing metadata if available
    existing = {}
    try:
        if session_id in all_sessions:
            existing = decrypt(all_sessions[session_id], password)
    except Exception:
        pass

    data = {
        "messages": messages,
        "linked_files": linked_files,
        "file_contents": file_contents,   # {filename: [text, language]}
        "map_data": map_data,
        "label": label or existing.get("label", "untitled session"),
        "created_at": existing.get("created_at", datetime.now().isoformat()),
        "last_active": datetime.now().isoformat(),
        "preview": next(
            (m["content"][:60] for m in messages if m["role"] == "user"),
            "no messages yet"
        ),
    }

    all_sessions[session_id] = encrypt(data, password)
    _save_all(all_sessions)


def session_exists(session_id: str) -> bool:
    return session_id in _load_all()


def delete_session(session_id: str):
    all_sessions = _load_all()
    all_sessions.pop(session_id, None)
    _save_all(all_sessions)


def rename_session(session_id: str, password: str, new_label: str):
    try:
        data = get_session(session_id, password)
        data["label"] = new_label
        save_session(
            session_id, password,
            data["messages"], data["linked_files"],
            data.get("file_contents", {}),
            new_label, data.get("map_data"),
        )
    except Exception:
        pass


def list_sessions() -> list:
    """
    Returns only session IDs and last_active timestamps.
    Cannot read labels/previews without password — by design.
    """
    all_sessions = _load_all()
    return [
        {"id": sid, "last_active": "encrypted"}
        for sid in all_sessions.keys()
    ]