Spaces:
Runtime error
Runtime error
Create manager.py
Browse files- database/manager.py +123 -0
database/manager.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# filename: database/manager.py
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
from .connection import db
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
# --- Index Creation ---
|
| 10 |
+
async def setup_database_indexes():
|
| 11 |
+
"""Create indexes on collections for faster queries. Should be run on startup."""
|
| 12 |
+
try:
|
| 13 |
+
# Indexes for the primary database (cache, groups)
|
| 14 |
+
await db.primary_db.file_cache.create_index("short_id", unique=True)
|
| 15 |
+
await db.primary_db.authorized_groups.create_index("group_id", unique=True)
|
| 16 |
+
|
| 17 |
+
# Indexes for all user databases
|
| 18 |
+
for user_db in db.databases:
|
| 19 |
+
await user_db.users.create_index("user_id", unique=True)
|
| 20 |
+
await user_db.users.create_index("is_premium")
|
| 21 |
+
await user_db.users.create_index("is_banned")
|
| 22 |
+
|
| 23 |
+
logger.info("Database indexes have been configured.")
|
| 24 |
+
except Exception as e:
|
| 25 |
+
logger.error(f"Error setting up database indexes: {e}", exc_info=True)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# --- User Management ---
|
| 29 |
+
async def add_or_update_user(user_id: int, username: str | None, first_name: str):
|
| 30 |
+
"""Adds a new user or updates the last_seen time for an existing one."""
|
| 31 |
+
user_db = await db.find_user_db(user_id)
|
| 32 |
+
|
| 33 |
+
if user_db:
|
| 34 |
+
# User exists, update their info in their assigned DB
|
| 35 |
+
await user_db.users.update_one(
|
| 36 |
+
{"user_id": user_id},
|
| 37 |
+
{"$set": {"username": username, "first_name": first_name, "last_seen": datetime.utcnow()}}
|
| 38 |
+
)
|
| 39 |
+
else:
|
| 40 |
+
# New user, assign them to a DB using round-robin
|
| 41 |
+
user_db = db.get_next_db_for_new_user()
|
| 42 |
+
await user_db.users.insert_one({
|
| 43 |
+
"user_id": user_id,
|
| 44 |
+
"username": username,
|
| 45 |
+
"first_name": first_name,
|
| 46 |
+
"is_premium": False,
|
| 47 |
+
"premium_expiry_date": None,
|
| 48 |
+
"is_banned": False,
|
| 49 |
+
"join_date": datetime.utcnow(),
|
| 50 |
+
"last_seen": datetime.utcnow()
|
| 51 |
+
})
|
| 52 |
+
return await get_user(user_id)
|
| 53 |
+
|
| 54 |
+
async def get_user(user_id: int) -> dict | None:
|
| 55 |
+
"""Finds a user across all available databases."""
|
| 56 |
+
for user_db in db.databases:
|
| 57 |
+
user_doc = await user_db.users.find_one({"user_id": user_id})
|
| 58 |
+
if user_doc:
|
| 59 |
+
return user_doc
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
async def grant_premium(user_id: int, duration: timedelta):
|
| 63 |
+
"""Grants or extends premium for a user."""
|
| 64 |
+
user = await get_user(user_id)
|
| 65 |
+
if not user: return False
|
| 66 |
+
|
| 67 |
+
user_db = await db.get_user_db(user['user_id']) # Get the correct DB for this user
|
| 68 |
+
|
| 69 |
+
# If user is already premium, extend their current subscription. Otherwise, start from now.
|
| 70 |
+
current_expiry = user.get("premium_expiry_date")
|
| 71 |
+
start_time = current_expiry if current_expiry and current_expiry > datetime.utcnow() else datetime.utcnow()
|
| 72 |
+
|
| 73 |
+
new_expiry_date = start_time + duration
|
| 74 |
+
|
| 75 |
+
await user_db.users.update_one(
|
| 76 |
+
{"user_id": user_id},
|
| 77 |
+
{"$set": {"is_premium": True, "premium_expiry_date": new_expiry_date}}
|
| 78 |
+
)
|
| 79 |
+
return True
|
| 80 |
+
|
| 81 |
+
async def ban_user(user_id: int, ban_status: bool = True):
|
| 82 |
+
"""Bans or unbans a user."""
|
| 83 |
+
user_db = await db.find_user_db(user_id)
|
| 84 |
+
if not user_db: return False
|
| 85 |
+
|
| 86 |
+
await user_db.users.update_one({"user_id": user_id}, {"$set": {"is_banned": ban_status}})
|
| 87 |
+
return True
|
| 88 |
+
|
| 89 |
+
# --- Cache Management (uses primary DB) ---
|
| 90 |
+
async def get_cached_file(short_id: str) -> dict | None:
|
| 91 |
+
"""Retrieves a cached file's data from the primary database."""
|
| 92 |
+
return await db.primary_db.file_cache.find_one({"short_id": short_id})
|
| 93 |
+
|
| 94 |
+
async def add_to_cache(short_id: str, file_id: str, file_name: str, file_size: int):
|
| 95 |
+
"""Adds a new file to the cache in the primary database."""
|
| 96 |
+
await db.primary_db.file_cache.update_one(
|
| 97 |
+
{"short_id": short_id},
|
| 98 |
+
{"$set": {
|
| 99 |
+
"file_id": file_id,
|
| 100 |
+
"file_name": file_name,
|
| 101 |
+
"file_size": file_size,
|
| 102 |
+
"cached_at": datetime.utcnow()
|
| 103 |
+
}},
|
| 104 |
+
upsert=True # Creates the document if it doesn't exist
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# --- Group Management (uses primary DB) ---
|
| 108 |
+
async def is_group_authorized(group_id: int) -> bool:
|
| 109 |
+
"""Checks if a group is authorized."""
|
| 110 |
+
doc = await db.primary_db.authorized_groups.find_one({"group_id": group_id})
|
| 111 |
+
return bool(doc)
|
| 112 |
+
|
| 113 |
+
async def authorize_group(group_id: int, status: bool = True):
|
| 114 |
+
"""Authorizes or de-authorizes a group."""
|
| 115 |
+
if status:
|
| 116 |
+
await db.primary_db.authorized_groups.update_one(
|
| 117 |
+
{"group_id": group_id},
|
| 118 |
+
{"$set": {"authorized_at": datetime.utcnow()}},
|
| 119 |
+
upsert=True
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
await db.primary_db.authorized_groups.delete_one({"group_id": group_id})
|
| 123 |
+
return True
|