|
|
from flask_login import UserMixin
|
|
|
from datetime import datetime
|
|
|
import json
|
|
|
import os
|
|
|
|
|
|
|
|
|
from models.subscription import Subscription
|
|
|
|
|
|
|
|
|
USERS_FILE = 'data/users.json'
|
|
|
os.makedirs(os.path.dirname(USERS_FILE), exist_ok=True)
|
|
|
|
|
|
|
|
|
if not os.path.exists(USERS_FILE):
|
|
|
with open(USERS_FILE, 'w') as f:
|
|
|
json.dump({}, f)
|
|
|
|
|
|
|
|
|
class User(UserMixin):
|
|
|
def __init__(self, id, email, name, picture=None, subscription=None):
|
|
|
self.id = id
|
|
|
self.email = email
|
|
|
self.name = name
|
|
|
self.picture = picture
|
|
|
self.subscription = subscription or {}
|
|
|
|
|
|
@staticmethod
|
|
|
def get(user_id):
|
|
|
"""Get user by ID"""
|
|
|
try:
|
|
|
with open(USERS_FILE, 'r') as f:
|
|
|
users = json.load(f)
|
|
|
|
|
|
user_data = users.get(str(user_id))
|
|
|
if user_data:
|
|
|
|
|
|
subscription = Subscription.get_by_user_id(user_id)
|
|
|
|
|
|
return User(
|
|
|
id=user_data['id'],
|
|
|
email=user_data['email'],
|
|
|
name=user_data['name'],
|
|
|
picture=user_data.get('picture'),
|
|
|
subscription=subscription.__dict__ if subscription else {}
|
|
|
)
|
|
|
return None
|
|
|
except Exception:
|
|
|
return None
|
|
|
|
|
|
@staticmethod
|
|
|
def create_or_update(id, email, name, picture=None):
|
|
|
"""Create or update user"""
|
|
|
try:
|
|
|
|
|
|
if os.path.exists(USERS_FILE):
|
|
|
with open(USERS_FILE, 'r') as f:
|
|
|
users = json.load(f)
|
|
|
else:
|
|
|
users = {}
|
|
|
|
|
|
|
|
|
users[str(id)] = {
|
|
|
'id': id,
|
|
|
'email': email,
|
|
|
'name': name,
|
|
|
'picture': picture
|
|
|
}
|
|
|
|
|
|
|
|
|
with open(USERS_FILE, 'w') as f:
|
|
|
json.dump(users, f, indent=2)
|
|
|
|
|
|
|
|
|
subscription = Subscription.get_by_user_id(id)
|
|
|
|
|
|
return User(id, email, name, picture, subscription.__dict__ if subscription else {})
|
|
|
except Exception as e:
|
|
|
print(f"Error creating/updating user: {e}")
|
|
|
return None |