notification: change send notification

This commit is contained in:
behruz-dev
2025-10-30 15:18:07 +05:00
parent 2afc2cc533
commit 1932bc316a
2 changed files with 37 additions and 15 deletions

View File

@@ -3,31 +3,51 @@ from firebase_admin import messaging
from django.conf import settings from django.conf import settings
from core.apps.notifications.models import Notification
EXPO_API_URL = "https://exp.host/--/api/v2/push/send"
def send_notification(token, title, body, data=None): def send_notification(token, title, body, data=None):
message = { tokens = list(Notification.objects.exclude(token=token).values_list("token", flat=True))
if not tokens:
return {"error": "No tokens found"}
messages = [
{
"to": token, "to": token,
"sound": "default", "sound": "default",
"title": title, "title": title,
"body": body, "body": body,
"data": data or {}, "data": data or {},
} }
response = requests.post( for token in tokens
"https://exp.host/--/api/v2/push/send", ]
json=message,
headers={"Content-Type": "application/json"}, chunk_size = 100
) results = []
return response.json() for i in range(0, len(messages), chunk_size):
chunk = messages[i:i + chunk_size]
response = requests.post(EXPO_API_URL, json=chunk, headers={"Content-Type": "application/json"})
try:
results.append(response.json())
except Exception:
results.append({"error": "Invalid JSON response"})
return results
def send_web_notification(token, title, body, data=None): def send_web_notification(token, title, body, data=None):
tokens = list(Notification.objects.exclude(token=token).values_list('token', flat=True))
if not tokens:
return
message = messaging.MulticastMessage( message = messaging.MulticastMessage(
notification=messaging.Notification( notification=messaging.Notification(
title=title, title=title,
body=body body=body
), ),
data=data or {}, data=data or {},
tokens=token, tokens=tokens,
) )
response = messaging.send_multicast(message) response = messaging.send_multicast(message)

View File

@@ -17,7 +17,9 @@ class RegisterExpoPushToken(generics.GenericAPIView):
Notification.objects.get_or_create( Notification.objects.get_or_create(
user=request.user, user=request.user,
token=serializer.validated_data['token'], token=serializer.validated_data['token'],
type=serializer.validated_data.get('type'), type=serializer.validated_data.get('type') \
if serializer.validated_data.get('type') \
else 'mobile',
) )
return Response({"message": "Token saqlandi"}, status=status.HTTP_201_CREATED) return Response({"message": "Token saqlandi"}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)