-
Notifications
You must be signed in to change notification settings - Fork 18
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
feat: [FC-0047] add functionality to send push notifications #282
Merged
OmarIthawi
merged 17 commits into
openedx:master
from
raccoongang:NiedielnitsevIvan/FC-0047/feature/implement-push-notifications-chanel
Jul 25, 2024
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8c55b82
feat: [FC-0047] add functionality to send push notifications
NiedielnitsevIvan cd9238b
fix: [FC-0047] fix tests
NiedielnitsevIvan 0903211
fix: [FC-0047] unpin django-push-notifications versions and recompile…
NiedielnitsevIvan e38cc86
fix: [FC-0047] fix tests
NiedielnitsevIvan ba5de95
fix: [FC-0047] remove extra import
NiedielnitsevIvan f293a20
refactor: [FC-0047] review issues
NiedielnitsevIvan 0ba2af6
test: [FC-0047] add unit tests
NiedielnitsevIvan e3a08e1
style: [FC-0047] fix code style issues
NiedielnitsevIvan 30486e8
fix: sort imports with isort
GlugovGrGlib bcf5d8b
test: [FC-0047] add missing tests
NiedielnitsevIvan 7c58b64
chore: [FC-0047] recompile requirements
NiedielnitsevIvan 557d47d
style: [FC-0047] fix import ordering
NiedielnitsevIvan 5f52163
Merge branch 'master' into NiedielnitsevIvan/FC-0047/feature/implemen…
NiedielnitsevIvan b18c55a
style: [FC-0047] fix code style issues
NiedielnitsevIvan c1ea794
style: [FC-0047] refactor condition
NiedielnitsevIvan 1026e58
test: [FC-0047] add check for push notif channel
NiedielnitsevIvan 2951c57
chore: [FC-0047] bump version
NiedielnitsevIvan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
""" | ||
Channel for sending push notifications. | ||
""" | ||
import logging | ||
import re | ||
|
||
from firebase_admin.messaging import APNSConfig, APNSPayload, Aps, ApsAlert | ||
from push_notifications.gcm import dict_to_fcm_message, send_message | ||
from push_notifications.models import GCMDevice | ||
|
||
from django.conf import settings | ||
|
||
from edx_ace.channel import Channel, ChannelType | ||
from edx_ace.errors import FatalChannelDeliveryError | ||
from edx_ace.message import Message | ||
from edx_ace.renderers import RenderedPushNotification | ||
|
||
LOG = logging.getLogger(__name__) | ||
APNS_DEFAULT_PRIORITY = '5' | ||
APNS_DEFAULT_PUSH_TYPE = 'alert' | ||
|
||
|
||
class PushNotificationChannel(Channel): | ||
""" | ||
A channel for sending push notifications. | ||
""" | ||
|
||
channel_type = ChannelType.PUSH | ||
|
||
@classmethod | ||
def enabled(cls): | ||
""" | ||
Returns true if the push notification settings are configured. | ||
""" | ||
return bool(getattr(settings, 'PUSH_NOTIFICATIONS_SETTINGS', None)) | ||
|
||
def deliver(self, message: Message, rendered_message: RenderedPushNotification) -> None: | ||
""" | ||
Transmit a rendered message to a recipient. | ||
|
||
Args: | ||
message: The message to transmit. | ||
rendered_message: The rendered content of the message that has been personalized | ||
for this particular recipient. | ||
""" | ||
device_tokens = self.get_user_device_tokens(message.recipient.lms_user_id) | ||
if not device_tokens: | ||
LOG.info( | ||
'Recipient with ID %s has no push token. Skipping push notification.', | ||
message.recipient.lms_user_id | ||
) | ||
return | ||
|
||
for token in device_tokens: | ||
self.send_message(message, token, rendered_message) | ||
|
||
def send_message(self, message: Message, token: str, rendered_message: RenderedPushNotification) -> None: | ||
""" | ||
Send a push notification to a device by token. | ||
""" | ||
notification_data = { | ||
'title': self.compress_spaces(rendered_message.title), | ||
'body': self.compress_spaces(rendered_message.body), | ||
'notification_key': token, | ||
**message.context.get('push_notification_extra_context', {}), | ||
} | ||
message = dict_to_fcm_message(notification_data) | ||
# Note: By default dict_to_fcm_message does not support APNS configuration, | ||
# only Android configuration, so we need to collect and set it manually. | ||
apns_config = self.collect_apns_config(notification_data) | ||
message.apns = apns_config | ||
try: | ||
send_message(token, message, settings.FCM_APP_NAME) | ||
except Exception as e: | ||
LOG.exception('Failed to send push notification to %s', token) | ||
raise FatalChannelDeliveryError(f'Failed to send push notification to {token}') from e | ||
|
||
@staticmethod | ||
def collect_apns_config(notification_data: dict) -> APNSConfig: | ||
""" | ||
Collect APNS configuration with payload for the push notification. | ||
|
||
This APNSConfig must be set to notifications for Firebase to send push notifications to iOS devices. | ||
Notification has default priority and visibility settings, described in Apple's documentation. | ||
(https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns) | ||
""" | ||
apns_alert = ApsAlert(title=notification_data['title'], body=notification_data['body']) | ||
aps = Aps(alert=apns_alert, sound='default') | ||
return APNSConfig( | ||
headers={'apns-priority': APNS_DEFAULT_PRIORITY, 'apns-push-type': APNS_DEFAULT_PUSH_TYPE}, | ||
payload=APNSPayload(aps) | ||
) | ||
|
||
@staticmethod | ||
def get_user_device_tokens(user_id: int) -> list: | ||
""" | ||
Get the device tokens for a user. | ||
""" | ||
return list(GCMDevice.objects.filter( | ||
user_id=user_id, | ||
cloud_message_type='FCM', | ||
active=True, | ||
).values_list('registration_id', flat=True)) | ||
|
||
@staticmethod | ||
def compress_spaces(html_str: str) -> str: | ||
""" | ||
Compress spaces and remove newlines to make it easier to author templates. | ||
""" | ||
return re.sub('\\s+', ' ', html_str, re.UNICODE).strip() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from push_notifications.api.rest_framework import GCMDeviceViewSet |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍🏼