forked from Sankar8098/Advanced-File-Store-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
150 lines (124 loc) · 4.29 KB
/
Copy pathmodels.py
File metadata and controls
150 lines (124 loc) · 4.29 KB
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
from typing import Optional, Dict, List
import logging
from datetime import datetime
from pymongo import MongoClient
import os
from urllib.parse import quote_plus, urlparse, parse_qs
import certifi
import json
# Configure logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
def get_mongodb_uri() -> str:
"""Get MongoDB URI from environment variable with proper encoding."""
try:
uri = os.getenv('MONGODB_URI')
if not uri:
raise ValueError("MONGODB_URI environment variable is not set")
# Clean the URI
uri = uri.strip().strip('"\'')
# Parse URI components
parsed = urlparse(uri)
# Validate URI scheme
if parsed.scheme not in ('mongodb', 'mongodb+srv'):
raise ValueError(f"Invalid MongoDB URI scheme: {parsed.scheme}")
# Extract and validate components
username = parsed.username or ''
password = parsed.password or ''
hostname = parsed.hostname
if not hostname:
raise ValueError("MongoDB URI missing hostname")
if not username or not password:
raise ValueError("MongoDB URI missing credentials")
# URL encode username and password
safe_username = quote_plus(username)
safe_password = quote_plus(password)
# Reconstruct the URI with encoded credentials
if parsed.port:
base_uri = f"{parsed.scheme}://{safe_username}:{safe_password}@{hostname}:{parsed.port}"
else:
base_uri = f"{parsed.scheme}://{safe_username}:{safe_password}@{hostname}"
# Add database name and query parameters
query_params = {
'retryWrites': 'true',
'w': 'majority',
'authSource': 'admin',
'ssl': 'true'
}
# Add existing query parameters
if parsed.query:
existing_params = parse_qs(parsed.query)
query_params.update({k: v[0] for k, v in existing_params.items()})
# Build query string
query_string = '&'.join(f"{k}={v}" for k, v in query_params.items())
# Construct final URI
final_uri = f"{base_uri}/movie?{query_string}"
logger.info("MongoDB URI processed successfully")
return final_uri
except Exception as e:
logger.error(f"Error processing MongoDB URI: {str(e)}")
raise
try:
# Get MongoDB URI with validation
MONGODB_URI = get_mongodb_uri()
logger.info("Got MongoDB URI")
# Create MongoDB client with robust settings
client = MongoClient(
MONGODB_URI,
serverSelectionTimeoutMS=5000,
connectTimeoutMS=5000,
socketTimeoutMS=5000,
tlsCAFile=certifi.where(),
retryWrites=True,
maxPoolSize=50,
minPoolSize=10,
maxIdleTimeMS=50000,
waitQueueTimeoutMS=5000
)
logger.info("Created MongoDB client")
# Test connection
client.admin.command('ping')
logger.info("Successfully pinged MongoDB server")
# Get database
db = client.movie # Use the database name directly
logger.info(f"Connected to database: {db.name}")
# Collections
users = db.users
movies = db.movies
files = db.files
statistics = db.statistics
# Create indexes
users.create_index("telegram_id", unique=True)
movies.create_index("stream_id", unique=True)
movies.create_index("title")
files.create_index("stream_id", unique=True)
logger.info("Successfully initialized all collections and indexes")
except Exception as e:
logger.error(f"MongoDB connection error: {str(e)}")
raise
# Model schemas (for reference)
USER_SCHEMA = {
"telegram_id": str,
"is_admin": bool,
"is_banned": bool,
"joined_date": datetime,
"last_search": datetime
}
MOVIE_SCHEMA = {
"title": str,
"description": str,
"year": int,
"genre": str,
"stream_id": str,
"file_url": str,
"file_size": float,
"duration": int,
"views": int,
"created_at": datetime,
"uploader_id": str,
"short_url_get2short": str,
"short_url_modijiurl": str
}