Spaces:
Paused
Paused
File size: 2,914 Bytes
8dafdf7 |
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 |
from typing import Dict, Any
from datetime import datetime
from ..db.database import db
from ..core.config import settings
from ..utils.cache import cache
from ..services.websocket import create_and_broadcast_notification
class NotificationService:
async def create_notification(
self,
user_id: str,
title: str,
message: str,
notification_type: str,
data: Dict[str, Any] = None
):
"""Create and store a notification"""
return await create_and_broadcast_notification(
user_id=user_id,
title=title,
message=message,
notification_type=notification_type,
data=data
)
async def get_user_notifications(
self,
user_id: str,
skip: int = 0,
limit: int = 50,
unread_only: bool = False
):
"""Get notifications for a user"""
cache_key = f"user_notifications:{user_id}"
if not unread_only:
cached = await cache.get_cache(cache_key)
if cached:
return cached
query = {"user_id": user_id}
if unread_only:
query["read"] = False
cursor = db.db["notifications"].find(query)\
.sort("created_at", -1)\
.skip(skip)\
.limit(limit)
notifications = await cursor.to_list(length=limit)
if not unread_only:
await cache.set_cache(cache_key, notifications, expire=300) # Cache for 5 minutes
return notifications
async def mark_as_read(self, notification_id: str, user_id: str):
"""Mark a notification as read"""
result = await db.db["notifications"].update_one(
{"_id": notification_id, "user_id": user_id},
{"$set": {"read": True}}
)
if result.modified_count > 0:
await cache.delete_cache(f"user_notifications:{user_id}")
return True
return False
async def mark_all_as_read(self, user_id: str):
"""Mark all notifications as read for a user"""
result = await db.db["notifications"].update_many(
{"user_id": user_id, "read": False},
{"$set": {"read": True}}
)
await cache.delete_cache(f"user_notifications:{user_id}")
return result.modified_count
async def delete_notification(self, notification_id: str, user_id: str):
"""Delete a notification"""
result = await db.db["notifications"].delete_one(
{"_id": notification_id, "user_id": user_id}
)
if result.deleted_count > 0:
await cache.delete_cache(f"user_notifications:{user_id}")
return True
return False
notifications = NotificationService() |