first push
This commit is contained in:
0
notification/__init__.py
Normal file
0
notification/__init__.py
Normal file
3
notification/admin.py
Normal file
3
notification/admin.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
||||
6
notification/apps.py
Normal file
6
notification/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class NotificationConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'notification'
|
||||
48
notification/consumers.py
Normal file
48
notification/consumers.py
Normal file
@@ -0,0 +1,48 @@
|
||||
# chat/consumers.py
|
||||
|
||||
from channels.generic.websocket import AsyncWebsocketConsumer
|
||||
import json
|
||||
|
||||
from core.tools import translate_text
|
||||
|
||||
|
||||
class ChatConsumer(AsyncWebsocketConsumer):
|
||||
async def connect(self):
|
||||
# print(self.scope["session"]["_auth_user_id"])
|
||||
print("here connect method started!")
|
||||
# user_id = self.scope["session"]["_auth_user_id"]
|
||||
user_id = self.scope['user']
|
||||
if user_id.is_anonymous:
|
||||
await self.disconnect(0)
|
||||
else:
|
||||
print("user_id first is ::::::, ", user_id)
|
||||
user_id = user_id.id
|
||||
print("user_id is::::::", user_id)
|
||||
self.group_name = "{}".format(user_id)
|
||||
# Join room group
|
||||
await self.channel_layer.group_add(self.group_name, self.channel_name)
|
||||
await self.accept()
|
||||
|
||||
async def disconnect(self, close_code):
|
||||
# Leave room group
|
||||
await self.channel_layer.group_discard(self.group_name, self.channel_name)
|
||||
|
||||
# Receive message from WebSocket
|
||||
async def receive(self, text_data=None, bytes_data=None):
|
||||
|
||||
text_data_json = json.loads(text_data)
|
||||
message = text_data_json["message"]
|
||||
# print("msg is: ", message)
|
||||
# message = translate_text(message)
|
||||
# Send message to room group
|
||||
await self.channel_layer.group_send(
|
||||
self.chat_group_name, {"type": "recieve_group_message", "message": message}
|
||||
)
|
||||
|
||||
async def recieve_group_message(self, event):
|
||||
message = event["message"]
|
||||
# print("msg is: ", message)
|
||||
|
||||
# message = translate_text(message)
|
||||
# Send message to WebSocket
|
||||
await self.send(text_data=json.dumps({"message": message}))
|
||||
56
notification/middleware.py
Normal file
56
notification/middleware.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.db import close_old_connections
|
||||
from channels.auth import AuthMiddleware, AuthMiddlewareStack, UserLazyObject
|
||||
from channels.db import database_sync_to_async
|
||||
from channels.sessions import CookieMiddleware, SessionMiddleware
|
||||
# from rest_framework_simplejwt.tokens import AccessToken
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
"""[summary]
|
||||
plucks the JWT access token from the query string and retrieves the associated user.
|
||||
Once the WebSocket connection is opened, all messages can be sent and received without
|
||||
verifying the user again. Closing the connection and opening it again
|
||||
requires re-authorization.
|
||||
for example:
|
||||
ws://localhost:8000/<route>/?token=<token_of_the_user>
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@database_sync_to_async
|
||||
def get_user(scope):
|
||||
close_old_connections()
|
||||
query_string = parse_qs(scope['query_string'].decode())
|
||||
token = query_string.get('token')
|
||||
# print("token query is::::", token)
|
||||
if not token:
|
||||
return AnonymousUser()
|
||||
try:
|
||||
t = Token.objects.get(key=token[0])
|
||||
access_token = Token(key=token[0])
|
||||
|
||||
#access_token = AccessToken(token[0])
|
||||
|
||||
user = t.user
|
||||
|
||||
# user = User.objects.get(id=access_token['id'])
|
||||
except Exception as exception:
|
||||
return AnonymousUser()
|
||||
if not user.is_active:
|
||||
return AnonymousUser()
|
||||
return user
|
||||
|
||||
|
||||
class TokenAuthMiddleware(AuthMiddleware):
|
||||
async def resolve_scope(self, scope):
|
||||
scope['user']._wrapped = await get_user(scope)
|
||||
|
||||
|
||||
def TokenAuthMiddlewareStack(inner):
|
||||
return CookieMiddleware(SessionMiddleware(TokenAuthMiddleware(inner)))
|
||||
115
notification/migrations/0001_initial.py
Normal file
115
notification/migrations/0001_initial.py
Normal file
@@ -0,0 +1,115 @@
|
||||
# Generated by Django 3.2.13 on 2023-09-18 19:32
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('auth', '0012_alter_user_first_name_max_length'),
|
||||
('authentication', '0001_initial'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='NotificationActions',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, null=True, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(default='', max_length=100, null=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationactions_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationactions_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='NotificationType',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, null=True, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('name', models.CharField(choices=[('user', 'USER'), ('alluser', 'AllUSER'), ('group', 'GROUP'), ('allgroup', 'AllGROUP'), ('usergroup', 'UserGroup'), ('poultry', 'Poultry'), ('province_accept', 'ProvinceAccept'), ('province_rejected', 'ProvinceRejected'), ('city_operator_accept', 'CityOperatorAccept'), ('city_operator_rejected', 'CityOperatorRejected'), ('assignment_accepted', 'AssignmentAccepted'), ('assignment_rejected', 'AssignmentRejected')], default='', max_length=50, null=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationtype_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationtype_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='NotificationToken',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, null=True, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('token', models.CharField(max_length=100)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationtoken_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationtoken_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notification_user', to='authentication.userprofile')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='NotificationButton',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, null=True, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('content', models.CharField(default='', max_length=20, null=True)),
|
||||
('order', models.IntegerField(default=0, null=True)),
|
||||
('action', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='btn_actions', to='notification.notificationactions')),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationbutton_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notificationbutton_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Notification',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, null=True, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('title', models.CharField(default='', max_length=200, null=True)),
|
||||
('content', models.CharField(default='', max_length=500, null=True)),
|
||||
('image', models.CharField(max_length=100, null=True)),
|
||||
('icon', models.CharField(max_length=100, null=True)),
|
||||
('app_ids', models.CharField(default='', max_length=200, null=True)),
|
||||
('device_ids', models.CharField(default='', max_length=200, null=True)),
|
||||
('hash_id', models.CharField(default='', max_length=20, null=True)),
|
||||
('status', models.CharField(choices=[('read', 'Read'), ('pending', 'Pending'), ('sent', 'Sent'), ('unread', 'Unread'), ('silent', 'Silent')], default='', max_length=10, null=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notification_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notification_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('notif_action', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='actions', to='notification.notificationactions')),
|
||||
('notif_button', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='buttons', to='notification.notificationbutton')),
|
||||
('notif_type', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='types', to='notification.notificationtype')),
|
||||
('notification_group', models.ManyToManyField(null=True, related_name='group', to='auth.Group')),
|
||||
('notification_user', models.ManyToManyField(null=True, related_name='notification_token', to='notification.NotificationToken')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
39
notification/migrations/0002_auto_20250121_0857.py
Normal file
39
notification/migrations/0002_auto_20250121_0857.py
Normal file
@@ -0,0 +1,39 @@
|
||||
# Generated by Django 3.2.13 on 2025-01-21 08:57
|
||||
|
||||
from django.db import migrations, models
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('notification', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='notification',
|
||||
name='key',
|
||||
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='notificationactions',
|
||||
name='key',
|
||||
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='notificationbutton',
|
||||
name='key',
|
||||
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='notificationtoken',
|
||||
name='key',
|
||||
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='notificationtype',
|
||||
name='key',
|
||||
field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
|
||||
),
|
||||
]
|
||||
38
notification/migrations/0003_dashboardnotification.py
Normal file
38
notification/migrations/0003_dashboardnotification.py
Normal file
@@ -0,0 +1,38 @@
|
||||
# Generated by Django 3.2.13 on 2025-06-15 12:44
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('auth', '0012_alter_user_first_name_max_length'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('notification', '0002_auto_20250121_0857'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='DashboardNotification',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('create_date', models.DateTimeField(auto_now_add=True)),
|
||||
('modify_date', models.DateTimeField(auto_now=True)),
|
||||
('trash', models.BooleanField(default=False)),
|
||||
('title', models.CharField(max_length=250, null=True)),
|
||||
('text', models.TextField(null=True)),
|
||||
('date', models.DateTimeField(null=True)),
|
||||
('status', models.CharField(max_length=100, null=True)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='dashboardnotification_createdby', to=settings.AUTH_USER_MODEL)),
|
||||
('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='dashboardnotification_modifiedby', to=settings.AUTH_USER_MODEL)),
|
||||
('role', models.ManyToManyField(null=True, related_name='notification_token', to='auth.Group')),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,19 @@
|
||||
# Generated by Django 3.2.13 on 2025-06-15 12:45
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('auth', '0012_alter_user_first_name_max_length'),
|
||||
('notification', '0003_dashboardnotification'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='dashboardnotification',
|
||||
name='role',
|
||||
field=models.ManyToManyField(null=True, related_name='dashboard_notification', to='auth.Group'),
|
||||
),
|
||||
]
|
||||
0
notification/migrations/__init__.py
Normal file
0
notification/migrations/__init__.py
Normal file
151
notification/models.py
Normal file
151
notification/models.py
Normal file
@@ -0,0 +1,151 @@
|
||||
from django.db import models
|
||||
|
||||
from authentication.models import BaseModel
|
||||
from authentication.models import UserProfile, Group
|
||||
|
||||
|
||||
# from numpy import char
|
||||
|
||||
|
||||
# Create your models here.
|
||||
|
||||
|
||||
class NotificationActions(BaseModel):
|
||||
name = models.CharField(max_length=100, default="", null=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(NotificationActions, self).save(*args, **kwargs)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class NotificationButton(BaseModel):
|
||||
content = models.CharField(max_length=20, default="", null=True)
|
||||
order = models.IntegerField(default=0, null=True)
|
||||
action = models.ForeignKey(
|
||||
NotificationActions,
|
||||
on_delete=models.CASCADE,
|
||||
default=None,
|
||||
null=True,
|
||||
related_name="btn_actions",
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.content
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(NotificationButton, self).save(*args, **kwargs)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class NotificationType(BaseModel):
|
||||
notif_types = (
|
||||
("user", "USER"),
|
||||
("alluser", "AllUSER"),
|
||||
("group", "GROUP"),
|
||||
("allgroup", "AllGROUP"),
|
||||
("usergroup", "UserGroup"),
|
||||
("poultry", "Poultry"),
|
||||
("province_accept", "ProvinceAccept"),
|
||||
("province_rejected", "ProvinceRejected"),
|
||||
("city_operator_accept", "CityOperatorAccept"),
|
||||
("city_operator_rejected", "CityOperatorRejected"),
|
||||
("assignment_accepted", "AssignmentAccepted"),
|
||||
("assignment_rejected", "AssignmentRejected"),
|
||||
)
|
||||
name = models.CharField(choices=notif_types, max_length=50, default="", null=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(NotificationType, self).save(*args, **kwargs)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class NotificationToken(BaseModel):
|
||||
token = models.CharField(max_length=100)
|
||||
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="notification_user", null=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.token
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(NotificationToken, self).save(*args, **kwargs)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class Notification(BaseModel):
|
||||
s = (
|
||||
("read", "Read"),
|
||||
("pending", "Pending"),
|
||||
("sent", "Sent"),
|
||||
("unread", "Unread"),
|
||||
("silent", "Silent"),
|
||||
)
|
||||
notif_type = models.ForeignKey(
|
||||
NotificationType,
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
default=None,
|
||||
related_name="types",
|
||||
)
|
||||
notif_action = models.ForeignKey(
|
||||
NotificationActions,
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
default=None,
|
||||
related_name="actions",
|
||||
)
|
||||
notif_button = models.ForeignKey(
|
||||
NotificationButton,
|
||||
on_delete=models.CASCADE,
|
||||
null=True,
|
||||
default=None,
|
||||
related_name="buttons",
|
||||
)
|
||||
notification_user = models.ManyToManyField(
|
||||
NotificationToken,
|
||||
null=True,
|
||||
related_name="notification_token"
|
||||
)
|
||||
notification_group = models.ManyToManyField(
|
||||
Group,
|
||||
null=True,
|
||||
related_name="group"
|
||||
)
|
||||
title = models.CharField(max_length=200, default="", null=True)
|
||||
content = models.CharField(max_length=500, default="", null=True)
|
||||
image = models.CharField(max_length=100, null=True)
|
||||
icon = models.CharField(max_length=100, null=True)
|
||||
app_ids = models.CharField(max_length=200, default="", null=True)
|
||||
device_ids = models.CharField(max_length=200, default="", null=True)
|
||||
hash_id = models.CharField(max_length=20, default="", null=True)
|
||||
status = models.CharField(choices=s, max_length=10, default="", null=True)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.title
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(Notification, self).save(*args, **kwargs)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class DashboardNotification(BaseModel):
|
||||
role = models.ManyToManyField(Group,
|
||||
null=True,
|
||||
related_name="dashboard_notification")
|
||||
title = models.CharField(max_length=250, null=True)
|
||||
text = models.TextField(null=True)
|
||||
date = models.DateTimeField(null=True)
|
||||
status = models.CharField(max_length=100, null=True)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
super(DashboardNotification, self).save(*args, **kwargs)
|
||||
0
notification/najva/__init__.py
Normal file
0
notification/najva/__init__.py
Normal file
17
notification/najva/get_segments_detail.py
Normal file
17
notification/najva/get_segments_detail.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from django.http.response import JsonResponse
|
||||
import requests
|
||||
import json
|
||||
|
||||
|
||||
def get_segments(request):
|
||||
url = "https://app.najva.com/api/v1/websites/65b3a75a-d634-48c5-824f-c80c703534af/segments/"
|
||||
|
||||
headers = {
|
||||
'content-type': "application/json",
|
||||
'authorization': "Token 982c17c1d460fec1eef6270c7d6550e3b9b33d2d",
|
||||
'cache-control': "no-cache",
|
||||
}
|
||||
|
||||
response = requests.request('GET', url=url, headers=headers)
|
||||
resp = json.loads(response.text.encode('utf8'))
|
||||
return JsonResponse(resp, safe=False)
|
||||
75
notification/najva/send_notif_to_segments.py
Normal file
75
notification/najva/send_notif_to_segments.py
Normal file
@@ -0,0 +1,75 @@
|
||||
from django.http.response import JsonResponse
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import requests
|
||||
import json
|
||||
|
||||
|
||||
def send_notification_to_all_segments(
|
||||
title=None,
|
||||
body=None,
|
||||
content=None,
|
||||
icon=None,
|
||||
image=None,
|
||||
segments_include=None,
|
||||
segments_exclude=None,
|
||||
):
|
||||
url = "https://app.najva.com/api/v1/notifications/"
|
||||
|
||||
payload = {
|
||||
"api_key": "65b3a75a-d634-48c5-824f-c80c703534af",
|
||||
"title": "title",
|
||||
"body": "body",
|
||||
"priority": "high",
|
||||
"onclick_action": "open-link",
|
||||
"url": "https://imedstores.ir/",
|
||||
"content": "content",
|
||||
"icon": "",
|
||||
"image": "",
|
||||
# "json": "{"key":"value"}",
|
||||
"sent_time": datetime.now() + timedelta(minutes=1),
|
||||
"segments_include": [],
|
||||
"segments_exclude": [],
|
||||
"one_signal_enabled": False,
|
||||
"one_signal_accounts": []
|
||||
}
|
||||
headers = {
|
||||
'authorization': "Token 982c17c1d460fec1eef6270c7d6550e3b9b33d2d",
|
||||
'content-type': "application/json",
|
||||
'cache-control': "no-cache",
|
||||
}
|
||||
|
||||
response = requests.request("POST", url, data=json.dumps(payload, default=str), headers=headers)
|
||||
resp = json.loads(response.text.encode('utf-8'))
|
||||
return resp
|
||||
|
||||
|
||||
def send_notification_to_specific_segment(
|
||||
title="سامانه سبحان طیور",
|
||||
body="خوش آمدید",
|
||||
content="سامانه مدیریت درخواست های مرغداران",
|
||||
icon="https://user-image-gallery.s3.ir-thr-at1.arvanstorage.com/1WGPTMFND3TREWD.jpg",
|
||||
image="https://user-image-gallery.s3.ir-thr-at1.arvanstorage.com/1WGPTMFND3TREWD.jpg",
|
||||
subscriber_tokens=None,
|
||||
):
|
||||
url = "https://app.najva.com/notification/api/v1/notifications/"
|
||||
payload = {
|
||||
"api_key": "65b3a75a-d634-48c5-824f-c80c703534af",
|
||||
"subscriber_tokens": subscriber_tokens,
|
||||
"title": title,
|
||||
"body": body,
|
||||
"onclick_action": "open-link",
|
||||
"url": "https://imedstores.ir/",
|
||||
"content": content,
|
||||
"icon": icon,
|
||||
"image": image,
|
||||
"sent_time": datetime.now() + timedelta(minutes=3),
|
||||
}
|
||||
headers = {
|
||||
'authorization': "Token 982c17c1d460fec1eef6270c7d6550e3b9b33d2d",
|
||||
'content-type': "application/json",
|
||||
'cache-control': "no-cache",
|
||||
}
|
||||
|
||||
response = requests.request("POST", url, data=json.dumps(payload, default=str), headers=headers)
|
||||
resp = json.loads(response.text.encode('utf-8'))
|
||||
return resp
|
||||
159
notification/najva_views.py
Normal file
159
notification/najva_views.py
Normal file
@@ -0,0 +1,159 @@
|
||||
import datetime
|
||||
|
||||
from django.http import QueryDict
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from rest_framework.permissions import AllowAny
|
||||
from ticket.helper import send_image_to_server
|
||||
from notification.models import (
|
||||
Notification,
|
||||
NotificationToken,
|
||||
NotificationType,
|
||||
Group
|
||||
)
|
||||
from panel.models import (
|
||||
PoultryRequest,
|
||||
CityOperatorCheckRequest,
|
||||
ProvinceCheckOperatorRequest,
|
||||
KillHouseRequest,
|
||||
FunctionExecutor
|
||||
)
|
||||
from notification.serializers import NotificationSerializer
|
||||
from authentication.filterset import UserProfileFilterSet
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from authentication.models import UserProfile
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import viewsets, status
|
||||
from django.shortcuts import render
|
||||
from .najva.send_notif_to_segments import (
|
||||
send_notification_to_all_segments,
|
||||
send_notification_to_specific_segment
|
||||
)
|
||||
from .najva.get_segments_detail import (
|
||||
get_segments
|
||||
)
|
||||
from authentication.views import (
|
||||
CLIENT_ID,
|
||||
CLIENT_SECRET,
|
||||
CACHE_TTL,
|
||||
ARVAN_User_Image_URL
|
||||
)
|
||||
import random
|
||||
import string
|
||||
import os
|
||||
|
||||
ARVAN_NOTIFICATION_GALLERY_URL = "https://profileimagedefault.s3.ir-thr-at1.arvanstorage.ir/"
|
||||
|
||||
|
||||
class NajvaNotificationViewSet(viewsets.ModelViewSet):
|
||||
queryset = NotificationToken.objects.all()
|
||||
serializer_class = NotificationSerializer
|
||||
permission_classes = [AllowAny]
|
||||
filter_backends = [DjangoFilterBackend]
|
||||
filterset_class = UserProfileFilterSet
|
||||
filterset_fields = [
|
||||
'fullname',
|
||||
'mobile',
|
||||
'breeding_unique_id',
|
||||
'address__city',
|
||||
'address__province',
|
||||
'role__name',
|
||||
]
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
if "key" in request.GET:
|
||||
add_obj = Notification.objects.get(key__exact=request.GET["key"])
|
||||
serializer = self.serializer_class(add_obj)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
if "read_notif" in request.GET:
|
||||
add_obj = Notification.objects.filter(
|
||||
user_id=request.user.id, status="read"
|
||||
)
|
||||
query = [x for x in add_obj]
|
||||
serializer = self.serializer_class(query, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
if "unread_notif" in request.GET:
|
||||
add_obj = Notification.objects.filter(
|
||||
user_id=request.user.id, status="unread"
|
||||
)
|
||||
query = [x for x in add_obj]
|
||||
serializer = self.serializer_class(query, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
if "pending_notif" in request.GET:
|
||||
add_obj = Notification.objects.filter(
|
||||
user_id=request.user.id, status="pending"
|
||||
)
|
||||
query = [x for x in add_obj]
|
||||
serializer = self.serializer_class(query, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
else:
|
||||
queryset = Notification.objects.all()
|
||||
serializer = self.serializer_class(queryset, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
segments = []
|
||||
userprofile = UserProfile.objects.get(user=request.user)
|
||||
ran = ''.join(random.choices(string.ascii_uppercase + string.digits, k=15))
|
||||
notification = Notification()
|
||||
if 'image' in request.data.keys():
|
||||
image = request.data['image']
|
||||
notification_image = send_image_to_server(image)
|
||||
if 'icon' in request.data.keys():
|
||||
icon = request.data['icon']
|
||||
notification_icon = send_image_to_server(icon)
|
||||
if 'request_type' in request.data.keys():
|
||||
if request.data['request_type'] == "token":
|
||||
if not NotificationToken.objects.filter(user=userprofile):
|
||||
notification = NotificationToken()
|
||||
notification.token = request.data['token']
|
||||
notification.user = userprofile
|
||||
notification.save()
|
||||
return Response(status=status.HTTP_200_OK)
|
||||
else:
|
||||
return Response({"msg": "user already has token"}, status=status.HTTP_403_FORBIDDEN)
|
||||
if 'value' in request.data.keys():
|
||||
if not request.data['value']:
|
||||
send_notification = send_notification_to_specific_segment(
|
||||
# title=request.data['title'],
|
||||
# body=request.data['body'],
|
||||
# content=request.data['content'],
|
||||
# icon=notification_icon,
|
||||
# image=notification_image,
|
||||
# segments_include=request.data['segments_include'],
|
||||
# segments_exclude=request.data['segments_exclude'],
|
||||
subscriber_tokens=['c22206d3-248a-4c81-b7c2-de2cfe5e5766']
|
||||
# subscriber_tokens=['2cc244fc-1340-4942-bf19-2ba9f66f44e6']
|
||||
)
|
||||
return Response(send_notification)
|
||||
notification.notif_type = NotificationType.objects.get(name="alluser")
|
||||
else:
|
||||
for key in request.data['value']:
|
||||
if UserProfile.objects.filter(key__exact=key):
|
||||
notif_user = NotificationToken.objects.get(user__key__exact=key)
|
||||
segments.append(notif_user.token)
|
||||
if Group.objects.filter(name__exact=key):
|
||||
for item in NotificationToken.objects.filter(user__role__name=key):
|
||||
segments.append(item.token)
|
||||
send_notification = send_notification_to_specific_segment(
|
||||
title=request.data['title'],
|
||||
body=request.data['body'],
|
||||
content=request.data['content'],
|
||||
icon=notification_icon,
|
||||
image=notification_image,
|
||||
subscriber_tokens=segments
|
||||
)
|
||||
notification.notif_type = NotificationType.objects.get(name=request.data['request_type'])
|
||||
notification.title = request.data['title']
|
||||
notification.content = request.data['content']
|
||||
notification.icon = notification_icon
|
||||
notification.image = notification_image
|
||||
notification.save()
|
||||
if 'value' in request.data.keys():
|
||||
for key in request.data['value']:
|
||||
if UserProfile.objects.filter(key__exact=key):
|
||||
notification.notif_user.add(UserProfile.objects.get(key__exact=key))
|
||||
elif Group.objects.filter(name__exact=key):
|
||||
notification.notif_group.add(Group.objects.get(name__exact=key))
|
||||
for item in UserProfile.objects.filter(role=Group.objects.get(name__exact=key)):
|
||||
notification.notif_user.add(item)
|
||||
return Response(send_notification)
|
||||
25
notification/notify.py
Normal file
25
notification/notify.py
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from channels.layers import get_channel_layer
|
||||
|
||||
|
||||
@classmethod
|
||||
def notify_ws_clients(self, message):
|
||||
"""
|
||||
Inform client there is a new message.
|
||||
"""
|
||||
|
||||
notification = {
|
||||
"type": "recieve_group_message",
|
||||
"message": "{}".format(message),
|
||||
}
|
||||
|
||||
channel_layer = get_channel_layer()
|
||||
print("user.id {}".format(self.user.id))
|
||||
print("user.id {}".format(self.recipient.id))
|
||||
|
||||
async_to_sync(channel_layer.group_send)("{}".format(self.user.id), notification)
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
"{}".format(self.recipient.id), notification
|
||||
)
|
||||
|
||||
0
notification/pushe/__init__.py
Normal file
0
notification/pushe/__init__.py
Normal file
3
notification/pushe/constants.py
Normal file
3
notification/pushe/constants.py
Normal file
@@ -0,0 +1,3 @@
|
||||
# Obtain token -> https://docs.pushe.co/docs/web-api/authentication
|
||||
|
||||
TOKEN = "YOUR_TOKEN"
|
||||
53
notification/pushe/send_custom_content_notification.py
Normal file
53
notification/pushe/send_custom_content_notification.py
Normal file
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
# vim: ts=4 sw=4 et
|
||||
|
||||
import requests
|
||||
from notification.pushe.constants import TOKEN
|
||||
|
||||
|
||||
def send_custom_content_notification(data):
|
||||
# set header
|
||||
headers = {"Authorization": "Token " + TOKEN, "Content-Type": "application/json"}
|
||||
|
||||
# Webpush doc -> http://docs.pushe.co/docs/web-api/custom-content-notification/
|
||||
|
||||
data = {
|
||||
"app_ids": [
|
||||
"YOUR_APP_ID",
|
||||
],
|
||||
"data": {
|
||||
"title": "Title",
|
||||
"content": "Content",
|
||||
},
|
||||
"custom_content": {"key1": "value1", "key2": "value2"},
|
||||
}
|
||||
|
||||
# send request
|
||||
response = requests.post(
|
||||
"https://api.pushe.co/v2/messaging/notifications/web/",
|
||||
json=data,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
# get status_code and response
|
||||
print("status code => ", response.status_code)
|
||||
print("response => ", response.json())
|
||||
print("==========")
|
||||
|
||||
if response.status_code == 201:
|
||||
print("Success!")
|
||||
|
||||
data = response.json()
|
||||
|
||||
# hashed_id just generated for Non-Free plan
|
||||
if data["hashed_id"]:
|
||||
report_url = "https://pushe.co/report?id=%s" % data["hashed_id"]
|
||||
else:
|
||||
report_url = "no report url for your plan"
|
||||
|
||||
notif_id = data["wrapper_id"]
|
||||
print("report_url: %s" % report_url)
|
||||
print("notification id: %s" % notif_id)
|
||||
else:
|
||||
print("failed")
|
||||
pass
|
||||
54
notification/pushe/send_filtered_notification.py
Normal file
54
notification/pushe/send_filtered_notification.py
Normal file
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
# vim: ts=4 sw=4 et
|
||||
|
||||
|
||||
import requests
|
||||
from notification.pushe.constants import TOKEN
|
||||
|
||||
|
||||
def send_filtered_notification(data):
|
||||
# set header
|
||||
headers = {"Authorization": "Token " + TOKEN, "Content-Type": "application/json"}
|
||||
|
||||
# Webpush doc -> https://docs.pushe.co/docs/web-api/filtered-notification
|
||||
|
||||
data = {
|
||||
"app_ids": [
|
||||
"YOUR_APP_ID",
|
||||
],
|
||||
"data": {
|
||||
"title": "This is a filtered push",
|
||||
"content": "Only users with specified device_id(s) will see this notification.",
|
||||
},
|
||||
"filters": {"device_id": ["DEIVCE_ID_1", "DEVICE_ID_2"]}
|
||||
# additional keywords -> https://docs.pushe.co/docs/web-api/notification-keys
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
"https://api.pushe.co/v2/messaging/notifications/web/",
|
||||
json=data,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
print("status code => ", response.status_code)
|
||||
print("response => ", response.json())
|
||||
print("==========")
|
||||
|
||||
if response.status_code == 201:
|
||||
print("Success!")
|
||||
|
||||
data = response.json()
|
||||
|
||||
# hashed_id only generated for Non-Free plan
|
||||
if data["hashed_id"]:
|
||||
report_url = "https://pushe.co/report?id=%s" % data["hashed_id"]
|
||||
else:
|
||||
report_url = "no report url for your plan"
|
||||
|
||||
notif_id = data["wrapper_id"]
|
||||
print("report_url: %s" % report_url)
|
||||
print("notification id: %s" % notif_id)
|
||||
else:
|
||||
print("failed")
|
||||
|
||||
pass
|
||||
67
notification/pushe/send_notification_with_action.py
Normal file
67
notification/pushe/send_notification_with_action.py
Normal file
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
# vim: ts=4 sw=4 et
|
||||
|
||||
import requests
|
||||
from notification.pushe.constants import TOKEN
|
||||
|
||||
|
||||
def send_notification_with_action(data):
|
||||
# set header
|
||||
headers = {"Authorization": "Token " + TOKEN, "Content-Type": "application/json"}
|
||||
|
||||
data = {
|
||||
"app_ids": [
|
||||
"YOUR_APP_ID",
|
||||
],
|
||||
"data": {
|
||||
"title": "Title",
|
||||
"content": "Content",
|
||||
# Actions -> https://docs.pushe.co/docs/web-api/notification-actions
|
||||
"action": {
|
||||
"action_type": "U",
|
||||
"url": "https://pushe.co",
|
||||
},
|
||||
"buttons": [
|
||||
{
|
||||
"btn_content": "YOUR_CONTENT",
|
||||
"btn_action": {"action_type": "U", "url": "https://pushe.co"},
|
||||
"btn_order": 0,
|
||||
},
|
||||
{
|
||||
"btn_content": "YOUR_CONTENT",
|
||||
"btn_action": {"action_type": "U", "url": "https://pushe.co"},
|
||||
"btn_order": 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
# send request
|
||||
response = requests.post(
|
||||
"https://api.pushe.co/v2/messaging/notifications/web/",
|
||||
json=data,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
# get status_code and response
|
||||
print("status code => ", response.status_code)
|
||||
print("response => ", response.json())
|
||||
print("==========")
|
||||
|
||||
if response.status_code == 201:
|
||||
print("Success!")
|
||||
|
||||
data = response.json()
|
||||
|
||||
# hashed_id only generated for Non-Free plan
|
||||
if data["hashed_id"]:
|
||||
report_url = "https://pushe.co/report?id=%s" % data["hashed_id"]
|
||||
else:
|
||||
report_url = "no report url for your plan"
|
||||
|
||||
notif_id = data["wrapper_id"]
|
||||
print("report_url: %s" % report_url)
|
||||
print("notification id: %s" % notif_id)
|
||||
else:
|
||||
print("failed")
|
||||
pass
|
||||
52
notification/pushe/send_simple_notification.py
Normal file
52
notification/pushe/send_simple_notification.py
Normal file
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
# vim: ts=4 sw=4 et
|
||||
|
||||
import requests
|
||||
from notification.pushe.constants import TOKEN
|
||||
|
||||
# Webpush doc -> https://docs.pushe.co/docs/web-api/filtered-notification
|
||||
|
||||
|
||||
def send_simple_notification(data):
|
||||
headers = {"Authorization": "Token " + TOKEN, "Content-Type": "application/json"}
|
||||
|
||||
data = {
|
||||
"app_ids": [
|
||||
"YOUR_APP_ID",
|
||||
],
|
||||
"data": {
|
||||
"title": "This is a filtered push",
|
||||
"content": "Only users with specified device_id(s) will see this notification.",
|
||||
},
|
||||
"filters": {"device_id": ["DEIVCE_ID_1", "DEVICE_ID_2"]}
|
||||
# additional keywords -> https://docs.pushe.co/docs/web-api/notification-keys
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
"https://api.pushe.co/v2/messaging/notifications/web/",
|
||||
json=data,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
print("status code => ", response.status_code)
|
||||
print("response => ", response.json())
|
||||
print("==========")
|
||||
|
||||
if response.status_code == 201:
|
||||
print("Success!")
|
||||
|
||||
data = response.json()
|
||||
|
||||
# hashed_id only generated for Non-Free plan
|
||||
if data["hashed_id"]:
|
||||
report_url = "https://pushe.co/report?id=%s" % data["hashed_id"]
|
||||
else:
|
||||
report_url = "no report url for your plan"
|
||||
|
||||
notif_id = data["wrapper_id"]
|
||||
print("report_url: %s" % report_url)
|
||||
print("notification id: %s" % notif_id)
|
||||
else:
|
||||
print("failed")
|
||||
|
||||
pass
|
||||
57
notification/pushe/send_transactional_notification.py
Normal file
57
notification/pushe/send_transactional_notification.py
Normal file
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
# vim: ts=4 sw=4 et
|
||||
|
||||
import requests
|
||||
from notification.pushe.constants import TOKEN
|
||||
|
||||
|
||||
def send_transactional_notification(data):
|
||||
# set header
|
||||
headers = {"Authorization": "Token " + TOKEN, "Content-Type": "application/json"}
|
||||
|
||||
# Webpush doc -> http://docs.pushe.co/docs/web-api/transactional-notification/
|
||||
|
||||
data = {
|
||||
"app_ids": [
|
||||
"YOUR_APP_ID",
|
||||
],
|
||||
"data": {
|
||||
"title": "Title",
|
||||
"content": "Content",
|
||||
},
|
||||
"custom_content": {"key1": "value1", "key2": "value2"},
|
||||
"device_id": [
|
||||
"device_id_1",
|
||||
"device_id_2",
|
||||
],
|
||||
}
|
||||
|
||||
# send request
|
||||
response = requests.post(
|
||||
"https://api.pushe.co/v2/messaging/web-rapid/",
|
||||
json=data,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
# get status_code and response
|
||||
print("status code => ", response.status_code)
|
||||
print("response => ", response.json())
|
||||
print("==========")
|
||||
|
||||
if response.status_code == 201:
|
||||
print("Success!")
|
||||
|
||||
data = response.json()
|
||||
|
||||
# hashed_id just generated for Non-Free plan
|
||||
if data["hashed_id"]:
|
||||
report_url = "https://pushe.co/report?id=%s" % data["hashed_id"]
|
||||
else:
|
||||
report_url = "no report url for your plan"
|
||||
|
||||
notif_id = data["wrapper_id"]
|
||||
print("report_url: %s" % report_url)
|
||||
print("notification id: %s" % notif_id)
|
||||
else:
|
||||
print("failed")
|
||||
pass
|
||||
7
notification/routing.py
Normal file
7
notification/routing.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from core import consumers
|
||||
|
||||
from django.conf.urls import url
|
||||
|
||||
websocket_urlpatterns = [
|
||||
url(r'^ws$', consumers.ChatConsumer.as_asgi()),
|
||||
]
|
||||
27
notification/serializers.py
Normal file
27
notification/serializers.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from notification.models import Notification, NotificationToken, DashboardNotification
|
||||
from authentication.serializers import GroupSerializer
|
||||
|
||||
|
||||
class NotificationTokenSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
Model = NotificationToken
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class NotificationSerializer(serializers.ModelSerializer):
|
||||
notif_user = NotificationTokenSerializer()
|
||||
notif_group = GroupSerializer()
|
||||
|
||||
class Meta:
|
||||
Model = Notification
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class DashboardNotificationSerializer(serializers.ModelSerializer):
|
||||
role = GroupSerializer(read_only=True,many=True)
|
||||
|
||||
class Meta:
|
||||
model = DashboardNotification
|
||||
fields = "__all__"
|
||||
16
notification/signals.py
Normal file
16
notification/signals.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from core.models import Profile
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
def create_user_profile(sender, instance, created, **kwargs):
|
||||
if created:
|
||||
Profile.objects.create(user=instance)
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
def save_user_profile(sender, instance, **kwargs):
|
||||
instance.profile.save()
|
||||
3
notification/tests.py
Normal file
3
notification/tests.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
||||
16
notification/urls.py
Normal file
16
notification/urls.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from notification.najva.get_segments_detail import get_segments
|
||||
from notification.najva.send_notif_to_segments import send_notification_to_all_segments
|
||||
from rest_framework.routers import DefaultRouter
|
||||
from django.urls import include, path
|
||||
from . import najva_views,views
|
||||
|
||||
router = DefaultRouter()
|
||||
router.register(r'notification-user', najva_views.NajvaNotificationViewSet, basename="notification-user")
|
||||
router.register(r'dashboard_notification', views.DashboardNotificationViewSet, basename="dashboard-notification")
|
||||
# router.register(r'get-segments', get_segments(), basename="get-segments")
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
path('get-segments', get_segments),
|
||||
path('all-segments', send_notification_to_all_segments),
|
||||
]
|
||||
103
notification/views.py
Normal file
103
notification/views.py
Normal file
@@ -0,0 +1,103 @@
|
||||
import datetime
|
||||
|
||||
from django.contrib.auth.models import Group
|
||||
from django.shortcuts import render
|
||||
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
|
||||
from notification.serializers import NotificationSerializer, DashboardNotificationSerializer
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.response import Response
|
||||
from notification.models import Notification, DashboardNotification
|
||||
|
||||
|
||||
# Create your views here.
|
||||
class NotificationViewSet(viewsets.ModelViewSet):
|
||||
queryset = Notification.objects.all()
|
||||
serializer_class = NotificationSerializer
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
if "key" in request.GET:
|
||||
add_obj = Notification.objects.get(key__exact=request.GET["key"])
|
||||
serializer = self.serializer_class(add_obj)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
if "read_notif" in request.GET:
|
||||
add_obj = Notification.objects.filter(
|
||||
user_id=request.user.id, status="read"
|
||||
)
|
||||
query = [x for x in add_obj]
|
||||
serializer = self.serializer_class(query, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
if "unread_notif" in request.GET:
|
||||
add_obj = Notification.objects.filter(
|
||||
user_id=request.user.id, status="unread"
|
||||
)
|
||||
query = [x for x in add_obj]
|
||||
serializer = self.serializer_class(query, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
if "pending_notif" in request.GET:
|
||||
add_obj = Notification.objects.filter(
|
||||
user_id=request.user.id, status="pending"
|
||||
)
|
||||
query = [x for x in add_obj]
|
||||
serializer = self.serializer_class(query, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
else:
|
||||
queryset = Notification.objects.all()
|
||||
serializer = self.serializer_class(queryset, many=True)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
obj = serializer.create(validated_data=request.data)
|
||||
obj.save()
|
||||
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors)
|
||||
|
||||
def retrieve(self, request, pk=None, *args, **kwargs):
|
||||
queryset = Notification.objects.get(key__exact=request.GET["key"])
|
||||
serializer = self.serializer_class(queryset)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def update(self, request, pk=None, *args, **kwargs):
|
||||
queryset = Notification.objects.get(key__exact=request.GET["key"])
|
||||
|
||||
queryset.save()
|
||||
serializer = self.serializer_class(queryset)
|
||||
serializer.update(instance=queryset, validated_data=request.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def partial_update(self, request, pk=None, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def destroy(self, request, pk=None, *args, **kwargs):
|
||||
queryset = Notification.objects.get(key__exact=request.GET["key"])
|
||||
queryset.trash = True
|
||||
queryset.save()
|
||||
return Response(status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class DashboardNotificationViewSet(viewsets.ModelViewSet):
|
||||
queryset = DashboardNotification.objects.all()
|
||||
serializer_class = DashboardNotificationSerializer
|
||||
permission_classes = [TokenHasReadWriteScope]
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
role=request.GET.get('role')
|
||||
query=self.queryset.filter(role__name=role,trash=False).order_by('-date')
|
||||
ser_data=self.serializer_class(query,many=True).data
|
||||
return Response(ser_data,status=status.HTTP_200_OK)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
grop=Group.objects.filter(name__in=request.data['role'])
|
||||
request.data.pop('role')
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid():
|
||||
obj = serializer.create(validated_data=request.data)
|
||||
obj.date=datetime.datetime.now()
|
||||
obj.save()
|
||||
obj.role.set(grop)
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
return Response(serializer.errors)
|
||||
Reference in New Issue
Block a user