File size: 2,534 Bytes
d05a9d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask_login import UserMixin
from datetime import datetime
import json
import os

# Import the Subscription model
from models.subscription import Subscription

# Simple file-based storage for users
USERS_FILE = 'data/users.json'
os.makedirs(os.path.dirname(USERS_FILE), exist_ok=True)

# Create empty users file if it doesn't exist
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:
                # Get subscription info
                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:
            # Load existing users
            if os.path.exists(USERS_FILE):
                with open(USERS_FILE, 'r') as f:
                    users = json.load(f)
            else:
                users = {}
            
            # Update or create user
            users[str(id)] = {
                'id': id,
                'email': email,
                'name': name,
                'picture': picture
            }
            
            # Save users
            with open(USERS_FILE, 'w') as f:
                json.dump(users, f, indent=2)
            
            # Get subscription info
            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