Spaces:
Paused

miracle / tasks /notifications.py
dushyantsingh0
Initial commit
d8744fd
Raw History Blame Contribute Delete
3.64 kB
"""
Notification background tasks.
"""
from typing import Optional
from uuid import UUID
from datetime import datetime, timezone
from sqlalchemy import select
from core.database import async_session_factory
from core.logging import get_logger
from core.config import get_settings
from core.email import send_email, template_nexus_email
from core.websockets import manager
from models.notification import Notification
from models.user import User
logger = get_logger(__name__)
settings = get_settings()
async def send_triple_notification(ctx, user_id: UUID, workspace_id: UUID, title: str, message: str, link: Optional[str] = None, **kwargs):
"""Send notification to DB, real-time WebSocket, and simulated Email."""
async with async_session_factory() as db:
user_stmt = select(User.email, User.real_email).where(User.id == user_id)
u_res = (await db.execute(user_stmt)).first()
primary_email, real_email = u_res if u_res else (None, None)
delivery_target = real_email or primary_email
notification = Notification(
workspace_id=workspace_id,
user_id=user_id,
title=title,
message=message,
link=link
)
db.add(notification)
await db.commit()
await manager.send_to_user(user_id, {
"type": "notification",
"id": str(notification.id),
"title": title,
"message": message,
"link": link,
"created_at": datetime.now(timezone.utc).isoformat()
})
if delivery_target:
resource_url = None
if link:
if link.startswith('http'):
resource_url = link
else:
resource_url = f"{settings.effective_frontend_url}/{link.lstrip('/')}"
email_html = template_nexus_email(
title=title,
message=message,
action_link=resource_url or "",
action_label="View Details",
footer_note=f"Workspace: {workspace_id} | Security Alert level: High"
)
email_text = f"Hello,\n\n{message}\n\nAccess it here: {resource_url if resource_url else 'N/A'}"
await send_email(delivery_target, title, email_text, html_body=email_html)
if settings.NOTIFICATION_WEBHOOK_URL:
try:
import httpx
async with httpx.AsyncClient() as client:
payload = {
"content" if "discord" in settings.NOTIFICATION_WEBHOOK_URL.lower() else "text":
f"🔔 *{title}*\n{message}\n{link if link else ''}"
}
await client.post(settings.NOTIFICATION_WEBHOOK_URL, json=payload, timeout=5.0)
except Exception as w_err:
logger.error(f"Failed to push external webhook: {w_err}")
async def notify_mentions(ctx, workspace_id: UUID, title: str, mentions: list, ticket_id: Optional[UUID] = None, **kwargs):
"""
Background task to notify multiple users about a mention.
"""
link = f"/dashboard?ticket={ticket_id}" if ticket_id else None
for mention in mentions:
user_id = UUID(mention["user_id"]) if isinstance(mention["user_id"], str) else mention["user_id"]
await send_triple_notification(
ctx,
user_id=user_id,
workspace_id=workspace_id,
title=title,
message=f"You were mentioned: {title}",
link=link
)