"""
Creates a new subscription for this user
"""
+ _ = self.locale.translate
+
# Decode p256dh
if not isinstance(p256dh, bytes):
p256dh = base64.urlsafe_b64decode(p256dh + "==")
)
# Send a message
- await subscription.send("Hello World!")
+ await subscription.send(
+ self._make_message(
+ _("Hello, %s!") % self,
+ _("You have successfully subscribed to push notifications."),
+ ),
+ )
return subscription
- async def send_push_message(self, message):
+ async def send_push_message(self, title, body, **kwargs):
"""
Sends a message to all active subscriptions
"""
+ # Return False if the user has no subscriptions
+ if not self.subscriptions:
+ return False
+
+ # Format the message
+ message = self._make_message(title, body, **kwargs)
+
+ # Send the message to all subscriptions
async with asyncio.TaskGroup() as tg:
for subscription in self.subscriptions:
tg.create_task(subscription.send(message))
+ return True
+
+ def _make_message(self, title, body, **kwargs):
+ """
+ Formats a push message with the given attributes and some useful defaults
+ """
+ # Format the message as a dictionary
+ message = {
+ "title" : title,
+ "body" : body,
+ } | kwargs
+
+ return message
+
class UserPushSubscription(base.DataObject):
table = "user_push_subscriptions"
// Log what we have received
console.debug("Push notification has been received: " + data);
+ // Extract the title
const title = data.title || event.data.text();
- const options = {
- "body" : data.message,
- };
-
// Show the notification
- const notification = self.registration.showNotification(title, options);
+ const notification = self.registration.showNotification(title, data);
event.waitUntil(notification);
});