48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
from __future__ import annotations
|
|
|
|
import structlog
|
|
|
|
from app.tasks.celery_app import celery_app
|
|
|
|
logger = structlog.get_logger("tasks.notification")
|
|
|
|
|
|
@celery_app.task(name="app.tasks.notification_tasks.send_push_notification")
|
|
def send_push_notification(user_id: int, title: str, message: str) -> dict:
|
|
"""Send push notification to a user via Socket.IO."""
|
|
import asyncio
|
|
|
|
from app.communication.socketio.server import sio
|
|
|
|
async def _send() -> None:
|
|
await sio.emit(
|
|
"notification",
|
|
{"title": title, "message": message},
|
|
room=f"user:{user_id}",
|
|
namespace="/notification",
|
|
)
|
|
|
|
asyncio.get_event_loop().run_until_complete(_send())
|
|
logger.info("push_sent", user_id=user_id)
|
|
return {"status": "sent", "user_id": user_id}
|
|
|
|
|
|
@celery_app.task(name="app.tasks.notification_tasks.send_bulk_notification")
|
|
def send_bulk_notification(user_ids: list[int], title: str, message: str) -> dict:
|
|
"""Send notification to multiple users and store in MongoDB."""
|
|
import asyncio
|
|
|
|
from app.models.mongodb.notification import Notification
|
|
|
|
async def _bulk() -> int:
|
|
notifications = [
|
|
Notification(user_id=uid, title=title, message=message)
|
|
for uid in user_ids
|
|
]
|
|
await Notification.insert_many(notifications)
|
|
return len(notifications)
|
|
|
|
count = asyncio.get_event_loop().run_until_complete(_bulk())
|
|
logger.info("bulk_notification_sent", count=count)
|
|
return {"sent": count}
|