push notificantion test
This commit is contained in:
@@ -7,7 +7,7 @@ from django.utils import timezone
|
||||
from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken, OutstandingToken
|
||||
import hashlib
|
||||
from django.contrib import admin
|
||||
|
||||
from django.conf import settings
|
||||
class UserManager(BaseUserManager):
|
||||
def create_user(self, phone, password=None):
|
||||
if not phone:
|
||||
@@ -135,4 +135,65 @@ class UserAddressModel(models.Model):
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'ادرس کاربر'
|
||||
verbose_name_plural = 'ادرس های کاربر'
|
||||
verbose_name_plural = 'ادرس های کاربر'
|
||||
|
||||
|
||||
import os
|
||||
import json
|
||||
from pywebpush import webpush, WebPushException
|
||||
|
||||
class PushSubscription(models.Model):
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
endpoint = models.TextField()
|
||||
keys = models.JSONField()
|
||||
created_at = models.DateField(auto_now_add=True)
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.user} push'
|
||||
|
||||
def send_notif(self, title, body):
|
||||
payload = {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"icon": ''
|
||||
}
|
||||
|
||||
try:
|
||||
webpush(
|
||||
subscription_info={
|
||||
"endpoint": self.endpoint,
|
||||
"keys": self.keys
|
||||
},
|
||||
data=json.dumps(payload),
|
||||
vapid_private_key=settings.VAPID_PRIVATE_KEY,
|
||||
vapid_claims={
|
||||
"sub": "mailto:admin@example.com"
|
||||
}
|
||||
)
|
||||
except WebPushException as ex:
|
||||
print("Failed to send notification:", ex)
|
||||
|
||||
@classmethod
|
||||
def send_group_notification(cls, user, title, body):
|
||||
payload = {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"icon": ''
|
||||
}
|
||||
|
||||
subscriptions = PushSubscription.objects.filter(user=user)
|
||||
for sub in subscriptions:
|
||||
try:
|
||||
webpush(
|
||||
subscription_info={
|
||||
"endpoint": sub.endpoint,
|
||||
"keys": sub.keys
|
||||
},
|
||||
data=json.dumps(payload),
|
||||
vapid_private_key=settings.VAPID_PRIVATE_KEY,
|
||||
vapid_claims={
|
||||
"sub": "mailto:admin@example.com"
|
||||
}
|
||||
)
|
||||
except WebPushException as ex:
|
||||
print(f"Failed to send notification to {sub.user}:", ex)
|
||||
Reference in New Issue
Block a user