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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# user_manager.py - User Profile Management System
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from dataclasses import dataclass, asdict
|
| 5 |
+
from typing import List, Optional, Dict, Any
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class UserProfile:
|
| 11 |
+
"""User profile data structure"""
|
| 12 |
+
user_id: str
|
| 13 |
+
username: str
|
| 14 |
+
display_name: str
|
| 15 |
+
expertise_level: str = "Beginner"
|
| 16 |
+
preferred_languages: List[str] = None
|
| 17 |
+
learning_goals: str = ""
|
| 18 |
+
created_at: str = None
|
| 19 |
+
last_active: str = None
|
| 20 |
+
total_chats: int = 0
|
| 21 |
+
favorite_responses: List[str] = None
|
| 22 |
+
theme_preference: str = "light"
|
| 23 |
+
response_format: str = "detailed" # detailed, concise, bullet_points
|
| 24 |
+
|
| 25 |
+
def __post_init__(self):
|
| 26 |
+
if self.preferred_languages is None:
|
| 27 |
+
self.preferred_languages = []
|
| 28 |
+
if self.favorite_responses is None:
|
| 29 |
+
self.favorite_responses = []
|
| 30 |
+
if self.created_at is None:
|
| 31 |
+
self.created_at = datetime.now().isoformat()
|
| 32 |
+
if self.last_active is None:
|
| 33 |
+
self.last_active = datetime.now().isoformat()
|
| 34 |
+
|
| 35 |
+
class UserManager:
|
| 36 |
+
"""Manages user profiles and preferences"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, data_dir: str):
|
| 39 |
+
self.data_dir = Path(data_dir)
|
| 40 |
+
self.data_dir.mkdir(exist_ok=True)
|
| 41 |
+
self.users_file = self.data_dir / "users.json"
|
| 42 |
+
self.ensure_users_file()
|
| 43 |
+
|
| 44 |
+
def ensure_users_file(self):
|
| 45 |
+
"""Ensure users file exists"""
|
| 46 |
+
if not self.users_file.exists():
|
| 47 |
+
with open(self.users_file, 'w') as f:
|
| 48 |
+
json.dump({}, f)
|
| 49 |
+
|
| 50 |
+
def create_user(self, profile: UserProfile) -> bool:
|
| 51 |
+
"""Create a new user profile"""
|
| 52 |
+
try:
|
| 53 |
+
users = self.load_all_users()
|
| 54 |
+
|
| 55 |
+
# Check if username already exists
|
| 56 |
+
for user_data in users.values():
|
| 57 |
+
if user_data.get('username') == profile.username:
|
| 58 |
+
raise ValueError(f"Username '{profile.username}' already exists")
|
| 59 |
+
|
| 60 |
+
# Save user profile
|
| 61 |
+
users[profile.user_id] = asdict(profile)
|
| 62 |
+
|
| 63 |
+
with open(self.users_file, 'w') as f:
|
| 64 |
+
json.dump(users, f, indent=2)
|
| 65 |
+
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
except Exception as e:
|
| 69 |
+
raise Exception(f"Failed to create user: {str(e)}")
|
| 70 |
+
|
| 71 |
+
def load_all_users(self) -> Dict[str, Dict]:
|
| 72 |
+
"""Load all users from storage"""
|
| 73 |
+
try:
|
| 74 |
+
with open(self.users_file, 'r') as f:
|
| 75 |
+
return json.load(f)
|
| 76 |
+
except (FileNotFoundError, json.JSONDecodeError):
|
| 77 |
+
return {}
|
| 78 |
+
|
| 79 |
+
def get_user(self, user_id: str) -> Optional[UserProfile]:
|
| 80 |
+
"""Get user profile by ID"""
|
| 81 |
+
users = self.load_all_users()
|
| 82 |
+
user_data = users.get(user_id)
|
| 83 |
+
|
| 84 |
+
if user_data:
|
| 85 |
+
return UserProfile(**user_data)
|
| 86 |
+
return None
|
| 87 |
+
|
| 88 |
+
def get_user_by_username(self, username: str) -> Optional[UserProfile]:
|
| 89 |
+
"""Get user profile by username"""
|
| 90 |
+
users = self.load_all_users()
|
| 91 |
+
|
| 92 |
+
for user_data in users.values():
|
| 93 |
+
if user_data.get('username') == username:
|
| 94 |
+
return UserProfile(**user_data)
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
def update_user(self, user_id: str, updates: Dict[str, Any]) -> bool:
|
| 98 |
+
"""Update user profile"""
|
| 99 |
+
try:
|
| 100 |
+
users = self.load_all_users()
|
| 101 |
+
|
| 102 |
+
if user_id not in users:
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
# Update fields
|
| 106 |
+
users[user_id].update(updates)
|
| 107 |
+
users[user_id]['last_active'] = datetime.now().isoformat()
|
| 108 |
+
|
| 109 |
+
with open(self.users_file, 'w') as f:
|
| 110 |
+
json.dump(users, f, indent=2)
|
| 111 |
+
|
| 112 |
+
return True
|
| 113 |
+
|
| 114 |
+
except Exception:
|
| 115 |
+
return False
|
| 116 |
+
|
| 117 |
+
def increment_chat_count(self, user_id: str):
|
| 118 |
+
"""Increment user's total chat count"""
|
| 119 |
+
self.update_user(user_id, {'total_chats': self.get_chat_count(user_id) + 1})
|
| 120 |
+
|
| 121 |
+
def get_chat_count(self, user_id: str) -> int:
|
| 122 |
+
"""Get user's total chat count"""
|
| 123 |
+
user = self.get_user(user_id)
|
| 124 |
+
return user.total_chats if user else 0
|
| 125 |
+
|
| 126 |
+
def add_favorite_response(self, user_id: str, response_id: str) -> bool:
|
| 127 |
+
"""Add response to user's favorites"""
|
| 128 |
+
user = self.get_user(user_id)
|
| 129 |
+
if user and response_id not in user.favorite_responses:
|
| 130 |
+
user.favorite_responses.append(response_id)
|
| 131 |
+
return self.update_user(user_id, {'favorite_responses': user.favorite_responses})
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
def remove_favorite_response(self, user_id: str, response_id: str) -> bool:
|
| 135 |
+
"""Remove response from user's favorites"""
|
| 136 |
+
user = self.get_user(user_id)
|
| 137 |
+
if user and response_id in user.favorite_responses:
|
| 138 |
+
user.favorite_responses.remove(response_id)
|
| 139 |
+
return self.update_user(user_id, {'favorite_responses': user.favorite_responses})
|
| 140 |
+
return False
|
| 141 |
+
|
| 142 |
+
def is_favorite_response(self, user_id: str, response_id: str) -> bool:
|
| 143 |
+
"""Check if response is in user's favorites"""
|
| 144 |
+
user = self.get_user(user_id)
|
| 145 |
+
return user and response_id in user.favorite_responses
|
| 146 |
+
|
| 147 |
+
def get_all_usernames(self) -> List[str]:
|
| 148 |
+
"""Get list of all usernames"""
|
| 149 |
+
users = self.load_all_users()
|
| 150 |
+
return [user_data.get('username', '') for user_data in users.values() if user_data.get('username')]
|
| 151 |
+
|
| 152 |
+
def delete_user(self, user_id: str) -> bool:
|
| 153 |
+
"""Delete user profile"""
|
| 154 |
+
try:
|
| 155 |
+
users = self.load_all_users()
|
| 156 |
+
|
| 157 |
+
if user_id in users:
|
| 158 |
+
del users[user_id]
|
| 159 |
+
|
| 160 |
+
with open(self.users_file, 'w') as f:
|
| 161 |
+
json.dump(users, f, indent=2)
|
| 162 |
+
|
| 163 |
+
return True
|
| 164 |
+
return False
|
| 165 |
+
|
| 166 |
+
except Exception:
|
| 167 |
+
return False
|
| 168 |
+
|
| 169 |
+
def get_user_stats(self, user_id: str) -> Dict[str, Any]:
|
| 170 |
+
"""Get user statistics"""
|
| 171 |
+
user = self.get_user(user_id)
|
| 172 |
+
if not user:
|
| 173 |
+
return {}
|
| 174 |
+
|
| 175 |
+
return {
|
| 176 |
+
'total_chats': user.total_chats,
|
| 177 |
+
'favorite_count': len(user.favorite_responses),
|
| 178 |
+
'member_since': user.created_at,
|
| 179 |
+
'last_active': user.last_active,
|
| 180 |
+
'expertise_level': user.expertise_level,
|
| 181 |
+
'preferred_languages': user.preferred_languages
|
| 182 |
+
}
|