Skip to content

Commit

Permalink
Update firebase notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
AlbertoMoreta committed Mar 18, 2024
1 parent 68e7425 commit 699a8d7
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 36 deletions.
9 changes: 9 additions & 0 deletions appmes/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from django.urls import reverse_lazy

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from firebase_admin import initialize_app

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir))

Expand Down Expand Up @@ -287,3 +289,10 @@
traces_sample_rate=1.0,
profiles_sample_rate=0.5,
)

# ======= Firebase Configuration ========
FIREBASE_APP = initialize_app()
FCM_DJANGO_SETTINGS = {
"ONE_DEVICE_PER_USER": False,
"DELETE_INACTIVE_DEVICES": False,
}
100 changes: 65 additions & 35 deletions helpers/fcm.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,85 @@
from helpers import is_package_installed
import logging

if is_package_installed('fcm_django'):
from fcm_django.models import FCMDevice
from firebase_admin.messaging import Message, Notification

def notify_user(user, data, title=None, message=None, silent=True):
'''
Sends an FCM notification to a user
If the message is silent, title and message are included in the data dictionary
'''
if not user:
return
from fcm_django.models import FCMDevice
from django.utils.translation import gettext_lazy as _

if not data:
data = {}
if not message and not title:
silent = True
if title and silent:
data['title'] = title
if message and silent:
data['message'] = message
logger = logging.getLogger(__name__)

device = FCMDevice.objects.filter(user=user).first()
if device is None:
return
if silent:
result = device.send_message(data=data)
else:
result = device.send_message(title=title, body=message, data=data)

class NotificationEvent:
class Event:
def __init__(self, title, prefix):
self.title = title
self.prefix = prefix

OTHER = Event(_("Otro"), "other")
NEWS_ADDED = Event(_("Nueva noticia"), "news")

def broadcast_notification(users=None, data=None, title=None, body=None, silent=True):

def notify_user(user, data, event=NotificationEvent.OTHER, title=None, body=None, image=None, silent=True):
'''
Sends an FCM notification to a user
If the message is silent, title and message are included in the data dictionary
'''
logger.info("Sending FCM notification...")

if not user:
return

data = data or {}
data["event"] = str(event.title)

if not body and not title:
silent = True
if title and silent:
data['title'] = title
if body and silent:
data['message'] = body

device = FCMDevice.objects.filter(user=user).first()
if device is None:
return
if silent:
result = device.send_message(
Message(data=data)
)
else:
result = device.send_message(
Message(notification=Notification(title=title, body=body, image=image), data=data)
)
logger.info(f"FCM Notification sent: {result}")


def broadcast_notification(node_shortname=None, data=None, event=NotificationEvent.OTHER, title=None, body=None, image=None, silent=False):
'''
Sends an FCM notification to a user
Sends an FCM notification broadcast to all devices subscribed to topic
If the message is silent, title and message are included in the data dictionary
'''
devices = FCMDevice.objects.all()
if users is not None:
devices.filter(user__in=users)
logger.info("Sending FCM broadcast...")

data = data or {}
data["event"] = str(event.title)

if not data:
data = {}
if not body and not title:
silent = True
if title and silent:
data['title'] = title
if body and silent:
data['message'] = body

topic = node_shortname + "_" + event.prefix

if silent:
result = devices.send_message(data=data)
result = FCMDevice.send_topic_message(
Message(data=data),
topic
)
else:
result = devices.send_message(title=title, body=body, data=data)
result = FCMDevice.send_topic_message(
Message(notification=Notification(title=title, body=body, image=image), data=data),
topic
)

print(result)
logger.info(f"FCM Broadcast sent: {result}")
11 changes: 10 additions & 1 deletion news/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.utils.translation import gettext as _
from django.views.generic import ListView, DetailView, UpdateView, CreateView, DeleteView
from django.views.generic import ListView, UpdateView, CreateView, DeleteView

from core.mixins.AjaxTemplateResponseMixin import AjaxTemplateResponseMixin
from core.mixins.ListItemUrlMixin import ListItemUrlMixin
from helpers.fcm import broadcast_notification, NotificationEvent
from market.mixins.current_market import MarketMixin
from news.forms.news import NewsForm
from news.models import News
Expand Down Expand Up @@ -35,6 +36,14 @@ def form_valid(self, form):
news.published_by = self.request.user
news.save()

broadcast_notification(
node_shortname=news.node.shortname,
event=NotificationEvent.NEWS_ADDED,
title=news.title,
body=news.short_description,
image=self.request.build_absolute_uri(news.banner_thumbnail.url),
)

return HttpResponseRedirect(self.get_success_url())

def get_success_url(self):
Expand Down

0 comments on commit 699a8d7

Please sign in to comment.