File size: 7,709 Bytes
bacbdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# database.py
import os
import datetime
from motor.motor_asyncio import AsyncIOMotorClient

# MongoDB Connection
MONGO_URL = os.getenv("MONGO_URL", "mongodb://localhost:27017")
DB_NAME = os.getenv("DB_NAME", "razor_x_bot")

client = AsyncIOMotorClient(
    MONGO_URL,
    serverSelectionTimeoutMS=30000
)
db = client[DB_NAME]

# Collections
users_col = db["users"]
keys_col = db["keys"]
proxies_col = db["proxies"]
sites_col = db["sites"]
cards_col = db["cards"]
global_sites_col = db["global_sites"]
joined_col = db["joined_users"]


async def init_db():
    try:
        await users_col.create_index("user_id", unique=True)
        await keys_col.create_index("key", unique=True)
        await proxies_col.create_index([("user_id", 1), ("proxy_url", 1)])
        await sites_col.create_index([("user_id", 1), ("site", 1)])
        await global_sites_col.create_index("site", unique=True)
        await cards_col.create_index("created_at")
        await joined_col.create_index("user_id", unique=True)
        print("✅ RAZOR X Database initialized successfully!")
    except Exception as e:
        print(f"⚠️ DB init warning: {e}")


async def ensure_user(user_id: int):
    existing = await users_col.find_one({"user_id": user_id})
    if not existing:
        await users_col.insert_one({
            "user_id": user_id,
            "plan": "Bronze",
            "expiry": None,
            "banned": False,
            "banned_by": None,
            "created_at": datetime.datetime.utcnow()
        })


async def get_user_plan(user_id: int) -> str:
    user = await users_col.find_one({"user_id": user_id})
    if not user:
        return "Bronze"
    plan = user.get("plan", "Bronze")
    expiry = user.get("expiry")
    if expiry and datetime.datetime.utcnow() > expiry:
        await users_col.update_one(
            {"user_id": user_id},
            {"$set": {"plan": "Bronze", "expiry": None}}
        )
        return "Bronze"
    return plan


async def set_user_plan(user_id: int, plan: str, days: int = 0):
    expiry = None
    if days > 0:
        expiry = datetime.datetime.utcnow() + datetime.timedelta(days=days)
    await users_col.update_one(
        {"user_id": user_id},
        {"$set": {
            "plan": plan,
            "expiry": expiry,
            "premium_days": days,
            "updated_at": datetime.datetime.utcnow()
        }},
        upsert=True
    )


async def is_premium_user(user_id: int) -> bool:
    plan = await get_user_plan(user_id)
    return plan in ["Core", "Elite", "Root", "X"]


async def is_banned_user(user_id: int) -> bool:
    user = await users_col.find_one({"user_id": user_id})
    return user.get("banned", False) if user else False


async def mark_user_joined(user_id: int):
    await joined_col.update_one(
        {"user_id": user_id},
        {"$set": {"user_id": user_id, "joined_at": datetime.datetime.utcnow()}},
        upsert=True
    )


async def is_user_marked_joined(user_id: int) -> bool:
    doc = await joined_col.find_one({"user_id": user_id})
    return doc is not None


async def remove_joined_mark(user_id: int):
    await joined_col.delete_one({"user_id": user_id})


async def add_proxy_db(user_id: int, proxy_data: dict):
    proxy_doc = {
        "user_id": user_id,
        "ip": proxy_data.get("ip"),
        "port": proxy_data.get("port"),
        "username": proxy_data.get("username"),
        "password": proxy_data.get("password"),
        "proxy_url": proxy_data.get("proxy_url"),
        "proxy_type": proxy_data.get("type", "http"),
        "added_at": datetime.datetime.utcnow()
    }
    await proxies_col.insert_one(proxy_doc)


async def get_all_user_proxies(user_id: int):
    cursor = proxies_col.find({"user_id": user_id}).sort("added_at", 1)
    return await cursor.to_list(length=200)


async def get_proxy_count(user_id: int) -> int:
    return await proxies_col.count_documents({"user_id": user_id})


async def get_random_proxy(user_id: int):
    import random
    proxies = await get_all_user_proxies(user_id)
    if not proxies:
        return None
    return random.choice(proxies)


async def remove_proxy_by_index(user_id: int, index: int):
    proxies = await get_all_user_proxies(user_id)
    if 0 <= index < len(proxies):
        proxy = proxies[index]
        await proxies_col.delete_one({"_id": proxy["_id"]})
        return proxy
    return None


async def remove_proxy_by_url(user_id: int, proxy_url: str):
    result = await proxies_col.delete_one({
        "user_id": user_id,
        "proxy_url": proxy_url
    })
    return result.deleted_count > 0


async def clear_all_proxies(user_id: int) -> int:
    result = await proxies_col.delete_many({"user_id": user_id})
    return result.deleted_count


async def add_site_db(user_id: int, site: str) -> bool:
    existing = await sites_col.find_one({"user_id": user_id, "site": site})
    if existing:
        return False
    await sites_col.insert_one({
        "user_id": user_id,
        "site": site,
        "added_at": datetime.datetime.utcnow()
    })
    return True


async def get_user_sites(user_id: int):
    cursor = sites_col.find({"user_id": user_id})
    docs = await cursor.to_list(length=50000)
    return [doc["site"] for doc in docs]


async def remove_site_db(user_id: int, site: str) -> bool:
    result = await sites_col.delete_one({"user_id": user_id, "site": site})
    return result.deleted_count > 0


async def add_global_site(site: str) -> bool:
    try:
        await global_sites_col.insert_one({
            "site": site,
            "added_at": datetime.datetime.utcnow()
        })
        return True
    except:
        return False


async def get_global_sites():
    cursor = global_sites_col.find()
    docs = await cursor.to_list(length=10000)
    return [doc["site"] for doc in docs]


async def remove_global_site(site: str) -> bool:
    result = await global_sites_col.delete_one({"site": site})
    return result.deleted_count > 0


async def save_card_to_db(card: str, status: str, gateway: str = "", extra: str = "", price: str = "-"):
    await cards_col.insert_one({
        "card": card,
        "status": status,
        "gateway": gateway,
        "extra": extra,
        "price": price,
        "created_at": datetime.datetime.utcnow()
    })


async def get_total_cards_count() -> int:
    return await cards_col.count_documents({})


async def get_charged_count() -> int:
    return await cards_col.count_documents({"status": "charged"})


async def get_approved_count() -> int:
    return await cards_col.count_documents({"status": "approved"})


async def get_total_users() -> int:
    return await users_col.count_documents({})


async def get_premium_count() -> int:
    return await users_col.count_documents({
        "plan": {"$in": ["Core", "Elite", "Root", "X"]}
    })


async def get_all_premium_users():
    cursor = users_col.find({"plan": {"$in": ["Core", "Elite", "Root", "X"]}})
    return await cursor.to_list(length=1000)


async def get_total_sites_count() -> int:
    return await sites_col.count_documents({})


async def get_users_with_sites() -> int:
    pipeline = [{"$group": {"_id": "$user_id"}}]
    result = await sites_col.aggregate(pipeline).to_list(length=10000)
    return len(result)


async def get_sites_per_user():
    pipeline = [
        {"$group": {"_id": "$user_id", "cnt": {"$sum": 1}}},
        {"$project": {"user_id": "$_id", "cnt": 1, "_id": 0}}
    ]
    return await sites_col.aggregate(pipeline).to_list(length=1000)


async def get_all_sites_detail():
    cursor = sites_col.find().sort("user_id", 1)
    return await cursor.to_list(length=10000)

async def Get_Sites_Per_User():
    return await get_sites_per_user()