File size: 11,045 Bytes
ea44208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e136d4a
 
 
 
 
 
 
ea44208
e136d4a
 
ea44208
 
e136d4a
ea44208
 
 
 
e136d4a
ea44208
 
 
 
e136d4a
ea44208
 
 
e136d4a
 
 
 
 
ea44208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""MongoDB client module for play history, activity logs, and analytics."""

import os
from datetime import datetime
from typing import Optional, List, Dict, Any
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
from pymongo import ASCENDING, DESCENDING


# MongoDB configuration from environment variables
MONGO_URI = os.getenv("MONGO_URI", "mongodb://localhost:27017")
MONGO_DB_NAME = os.getenv("MONGO_DB_NAME", "music_memories")

# Global MongoDB client and database instances
_mongo_client: Optional[AsyncIOMotorClient] = None
_mongo_db: Optional[AsyncIOMotorDatabase] = None


def get_mongo_client() -> Optional[AsyncIOMotorClient]:
    """Get the MongoDB client instance."""
    return _mongo_client


def get_mongo_db() -> Optional[AsyncIOMotorDatabase]:
    """Get the MongoDB database instance."""
    return _mongo_db


async def init_mongodb() -> None:
    """Initialize MongoDB connection."""
    global _mongo_client, _mongo_db
    try:
        # Use serverSelectionTimeoutMS to fail fast if MongoDB is not available
        _mongo_client = AsyncIOMotorClient(
            MONGO_URI,
            serverSelectionTimeoutMS=3000,
            connectTimeoutMS=5000,
            socketTimeoutMS=5000
        )
        _mongo_db = _mongo_client[MONGO_DB_NAME]

        # Test connection with ping
        await _mongo_client.admin.command('ping')
        print(f"✓ Connected to MongoDB at {MONGO_URI}")

        # Create indexes for play_history collection
        await _mongo_db.play_history.create_index([("user_id", ASCENDING), ("played_at", DESCENDING)])
        await _mongo_db.play_history.create_index([("song_id", ASCENDING)])
        await _mongo_db.play_history.create_index([("played_at", DESCENDING)])

        # Create indexes for activity_logs collection
        await _mongo_db.activity_logs.create_index([("user_id", ASCENDING), ("timestamp", DESCENDING)])
        await _mongo_db.activity_logs.create_index([("action_type", ASCENDING)])
        await _mongo_db.activity_logs.create_index([("timestamp", DESCENDING)])

        # Create indexes for analytics collection
        await _mongo_db.analytics.create_index([("event_type", ASCENDING), ("timestamp", DESCENDING)])
        await _mongo_db.analytics.create_index([("timestamp", DESCENDING)])

        # Create indexes for search_history collection
        await _mongo_db.search_history.create_index([("query", ASCENDING)])
        await _mongo_db.search_history.create_index([("timestamp", DESCENDING)])

        print("✓ MongoDB indexes created")
    except Exception as e:
        print(f"⚠ MongoDB connection failed: {e}")
        print("⚠ Running without MongoDB (using Redis/SQLite fallback)")
        _mongo_client = None
        _mongo_db = None


async def close_mongodb() -> None:
    """Close MongoDB connection."""
    global _mongo_client, _mongo_db
    if _mongo_client:
        _mongo_client.close()
        _mongo_client = None
        _mongo_db = None


# ============== Play History (MongoDB) ==============

async def store_play_history_mongo(
    user_id: int,
    song_id: int,
    song_title: str = None,
    song_artist: str = None,
    context_id: int = None,
    duration_seconds: int = None,
    completed: bool = True
) -> Dict[str, Any]:
    """Store a play history event in MongoDB."""
    if _mongo_db is None:
        return None
    
    document = {
        "user_id": user_id,
        "song_id": song_id,
        "song_title": song_title,
        "song_artist": song_artist,
        "context_id": context_id,
        "duration_seconds": duration_seconds,
        "completed": completed,
        "played_at": datetime.utcnow(),
        "created_at": datetime.utcnow()
    }
    
    result = await _mongo_db.play_history.insert_one(document)
    return {
        "id": str(result.inserted_id),
        **document
    }


async def get_user_play_history_mongo(
    user_id: int,
    limit: int = 50
) -> List[Dict[str, Any]]:
    """Get play history for a user from MongoDB."""
    if _mongo_db is None:
        return []
    
    cursor = _mongo_db.play_history.find(
        {"user_id": user_id}
    ).sort("played_at", DESCENDING).limit(limit)
    
    results = []
    async for doc in cursor:
        results.append({
            "id": str(doc["_id"]),
            "user_id": doc["user_id"],
            "song_id": doc["song_id"],
            "song_title": doc.get("song_title"),
            "song_artist": doc.get("song_artist"),
            "context_id": doc.get("context_id"),
            "duration_seconds": doc.get("duration_seconds"),
            "completed": doc.get("completed", True),
            "played_at": doc["played_at"].isoformat() if doc.get("played_at") else None
        })
    
    return results


async def get_global_play_history_mongo(
    limit: int = 50
) -> List[Dict[str, Any]]:
    """Get global play history from MongoDB."""
    if _mongo_db is None:
        return []
    
    cursor = _mongo_db.play_history.find({}).sort("played_at", DESCENDING).limit(limit)
    
    results = []
    async for doc in cursor:
        results.append({
            "id": str(doc["_id"]),
            "user_id": doc["user_id"],
            "song_id": doc["song_id"],
            "song_title": doc.get("song_title"),
            "song_artist": doc.get("song_artist"),
            "context_id": doc.get("context_id"),
            "duration_seconds": doc.get("duration_seconds"),
            "completed": doc.get("completed", True),
            "played_at": doc["played_at"].isoformat() if doc.get("played_at") else None
        })
    
    return results


async def get_song_play_count_mongo(song_id: int) -> int:
    """Get total play count for a song."""
    if _mongo_db is None:
        return 0
    
    count = await _mongo_db.play_history.count_documents({"song_id": song_id})
    return count


async def get_top_songs_mongo(limit: int = 10) -> List[Dict[str, Any]]:
    """Get top played songs from MongoDB analytics."""
    if _mongo_db is None:
        return []
    
    pipeline = [
        {"$group": {
            "_id": "$song_id",
            "play_count": {"$sum": 1},
            "song_title": {"$first": "$song_title"},
            "song_artist": {"$first": "$song_artist"}
        }},
        {"$sort": {"play_count": -1}},
        {"$limit": limit}
    ]
    
    results = []
    async for doc in _mongo_db.play_history.aggregate(pipeline):
        results.append({
            "song_id": doc["_id"],
            "song_title": doc.get("song_title"),
            "song_artist": doc.get("song_artist"),
            "play_count": doc["play_count"]
        })
    
    return results


# ============== Activity Logs (MongoDB) ==============

async def log_user_activity(
    user_id: int,
    action_type: str,
    details: Dict[str, Any] = None
) -> Dict[str, Any]:
    """Log a user activity event."""
    if _mongo_db is None:
        return None
    
    document = {
        "user_id": user_id,
        "action_type": action_type,
        "details": details or {},
        "timestamp": datetime.utcnow()
    }
    
    result = await _mongo_db.activity_logs.insert_one(document)
    return {
        "id": str(result.inserted_id),
        **document
    }


async def get_user_activity_mongo(
    user_id: int,
    limit: int = 50,
    action_type: str = None
) -> List[Dict[str, Any]]:
    """Get activity logs for a user."""
    if _mongo_db is None:
        return []
    
    query = {"user_id": user_id}
    if action_type:
        query["action_type"] = action_type
    
    cursor = _mongo_db.activity_logs.find(query).sort("timestamp", DESCENDING).limit(limit)
    
    results = []
    async for doc in cursor:
        results.append({
            "id": str(doc["_id"]),
            "user_id": doc["user_id"],
            "action_type": doc["action_type"],
            "details": doc.get("details", {}),
            "timestamp": doc["timestamp"].isoformat() if doc.get("timestamp") else None
        })
    
    return results


# ============== Analytics Events (MongoDB) ==============

async def track_analytics_event(
    event_type: str,
    properties: Dict[str, Any] = None
) -> Dict[str, Any]:
    """Track an analytics event."""
    if _mongo_db is None:
        return None
    
    document = {
        "event_type": event_type,
        "properties": properties or {},
        "timestamp": datetime.utcnow()
    }
    
    result = await _mongo_db.analytics.insert_one(document)
    return {
        "id": str(result.inserted_id),
        **document
    }


async def get_analytics_summary(
    event_type: str = None,
    hours: int = 24
) -> Dict[str, Any]:
    """Get analytics summary for the last N hours."""
    if _mongo_db is None:
        return {}
    
    from datetime import timedelta
    since = datetime.utcnow() - timedelta(hours=hours)
    
    query = {"timestamp": {"$gte": since}}
    if event_type:
        query["event_type"] = event_type
    
    total_events = await _mongo_db.analytics.count_documents(query)
    
    # Get event type breakdown
    pipeline = [
        {"$match": query},
        {"$group": {
            "_id": "$event_type",
            "count": {"$sum": 1}
        }},
        {"$sort": {"count": -1}}
    ]
    
    breakdown = []
    async for doc in _mongo_db.analytics.aggregate(pipeline):
        breakdown.append({
            "event_type": doc["_id"],
            "count": doc["count"]
        })
    
    return {
        "total_events": total_events,
        "period_hours": hours,
        "breakdown": breakdown
    }


# ============== User Search History (MongoDB) ==============

async def log_search(
    user_id: int = None,
    search_type: str = None,
    query: str = None,
    results_count: int = 0
) -> Dict[str, Any]:
    """Log a search event."""
    if _mongo_db is None:
        return None
    
    document = {
        "user_id": user_id,
        "search_type": search_type,
        "query": query,
        "results_count": results_count,
        "timestamp": datetime.utcnow()
    }
    
    result = await _mongo_db.search_history.insert_one(document)
    return {
        "id": str(result.inserted_id),
        **document
    }


async def get_popular_searches(
    hours: int = 24,
    limit: int = 10
) -> List[Dict[str, Any]]:
    """Get popular search queries."""
    if _mongo_db is None:
        return []
    
    from datetime import timedelta
    since = datetime.utcnow() - timedelta(hours=hours)
    
    pipeline = [
        {"$match": {"timestamp": {"$gte": since}}},
        {"$group": {
            "_id": "$query",
            "count": {"$sum": 1},
            "search_type": {"$first": "$search_type"}
        }},
        {"$sort": {"count": -1}},
        {"$limit": limit}
    ]
    
    results = []
    async for doc in _mongo_db.search_history.aggregate(pipeline):
        results.append({
            "query": doc["_id"],
            "search_type": doc.get("search_type"),
            "count": doc["count"]
        })
    
    return results