Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support notification priority in FCM relay #1630

Merged
merged 3 commits into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions engine/apps/mobile_app/fcm_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.conf import settings
from fcm_django.models import FCMDevice
from firebase_admin.exceptions import FirebaseError
from firebase_admin.messaging import APNSConfig, APNSPayload, Aps, ApsAlert, CriticalSound, Message
from firebase_admin.messaging import AndroidConfig, APNSConfig, APNSPayload, Aps, ApsAlert, CriticalSound, Message
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
Expand Down Expand Up @@ -42,18 +42,19 @@ def post(self, request):
token = request.data["token"]
data = request.data["data"]
apns = request.data["apns"]
android = request.data.get("android") # optional
except KeyError:
return Response(status=status.HTTP_400_BAD_REQUEST)

fcm_relay_async.delay(token=token, data=data, apns=apns)
fcm_relay_async.delay(token=token, data=data, apns=apns, android=android)
return Response(status=status.HTTP_200_OK)


@shared_dedicated_queue_retry_task(
autoretry_for=(Exception,), retry_backoff=True, max_retries=1 if settings.DEBUG else 5
)
def fcm_relay_async(token, data, apns):
message = Message(token=token, data=data, apns=deserialize_apns(apns))
def fcm_relay_async(token, data, apns, android=None):
message = _get_message_from_request_data(token, data, apns, android)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need the android argument here? this field should be available on the FCMDevice object fetched just a few lines below. See the type column in the fcm_django_fcmdevice table.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The android field is needed to pass any Android related fields to FCM relay (e.g. priority). We don’t store any OSS device data in FCM relay, so the only way to get this data is to extract it from the request. Does it make sense?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense 👍 I sometimes get confused w/ the relay where certain data is being stored


# https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
response = FCMDevice(registration_id=token).send_message(message)
Expand All @@ -63,7 +64,17 @@ def fcm_relay_async(token, data, apns):
raise response


def deserialize_apns(apns):
def _get_message_from_request_data(token, data, apns, android):
"""
Create Message object from JSON payload from OSS instance.
"""

return Message(
token=token, data=data, apns=_deserialize_apns(apns), android=AndroidConfig(**android) if android else None
)


def _deserialize_apns(apns):
"""
Create APNSConfig object from JSON payload from OSS instance.
"""
Expand Down Expand Up @@ -95,5 +106,6 @@ def deserialize_apns(apns):
sound=sound,
custom_data=aps,
)
)
),
headers=apns.get("headers"),
)
42 changes: 41 additions & 1 deletion engine/apps/mobile_app/tests/test_fcm_relay.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from unittest.mock import patch

import pytest
Expand All @@ -7,7 +8,8 @@
from rest_framework import status
from rest_framework.test import APIClient

from apps.mobile_app.fcm_relay import FCMRelayThrottler, fcm_relay_async
from apps.mobile_app.fcm_relay import FCMRelayThrottler, _get_message_from_request_data, fcm_relay_async
from apps.mobile_app.tasks import _get_fcm_message


@pytest.mark.django_db
Expand Down Expand Up @@ -88,3 +90,41 @@ def test_fcm_relay_async_retry():
):
with pytest.raises(FirebaseError):
fcm_relay_async(token="test_token", data={}, apns={})


def test_get_message_from_request_data():
token = "test_token"
data = {"test_data_key": "test_data_value"}
apns = {"headers": {"apns-priority": "10"}, "payload": {"aps": {"thread-id": "test_thread_id"}}}
android = {"priority": "high"}
message = _get_message_from_request_data(token, data, apns, android)

assert message.token == "test_token"
assert message.data == {"test_data_key": "test_data_value"}
assert message.apns.headers == {"apns-priority": "10"}
assert message.apns.payload.aps.thread_id == "test_thread_id"
assert message.android.priority == "high"


@pytest.mark.django_db
def test_fcm_relay_serialize_deserialize(
make_organization_and_user, make_alert_receive_channel, make_alert_group, make_alert
):
organization, user = make_organization_and_user()
device = FCMDevice.objects.create(user=user, registration_id="test_device_id")

alert_receive_channel = make_alert_receive_channel(organization=organization)
alert_group = make_alert_group(alert_receive_channel)
make_alert(alert_group=alert_group, raw_request_data={})

# Imitate sending a message to the FCM relay endpoint
original_message = _get_fcm_message(alert_group, user, device.registration_id, critical=False)
request_data = json.loads(str(original_message))

# Imitate receiving a message from the FCM relay endpoint
relayed_message = _get_message_from_request_data(
request_data["token"], request_data["data"], request_data["apns"], request_data["android"]
)

# Check that the message is the same after serialization and deserialization
assert json.loads(str(original_message)) == json.loads(str(relayed_message))