From: Michael Tremer Date: Sun, 26 Jan 2025 10:57:52 +0000 (+0000) Subject: users: Simplify passing around push messages X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=87f6d5a991b862a2f90e457d07880c51728ae719;p=pbs.git users: Simplify passing around push messages Signed-off-by: Michael Tremer --- diff --git a/src/buildservice/users.py b/src/buildservice/users.py index 23f7abf3..b4a79147 100644 --- a/src/buildservice/users.py +++ b/src/buildservice/users.py @@ -961,17 +961,9 @@ class User(database.Base, database.BackendMixin, database.SoftDeleteMixin): # Log action log.info("%s subscribed to push notifications" % self) - # Send a message - await subscription.send( - self._make_message( - _("Hello, %s!") % self, - _("You have successfully subscribed to push notifications."), - ), - ) - return subscription - async def send_push_message(self, title, body, **kwargs): + async def send_push_message(self, *args, **kwargs): """ Sends a message to all active subscriptions """ @@ -981,27 +973,12 @@ class User(database.Base, database.BackendMixin, database.SoftDeleteMixin): if not subscriptions: return False - # Format the message - message = self._make_message(title, body, **kwargs) - # Send the message to all subscriptions for subscription in subscriptions: - await subscription.send(message) + await subscription.send(*args, **kwargs) 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(database.Base, database.BackendMixin): __tablename__ = "user_push_subscriptions" @@ -1056,23 +1033,21 @@ class UserPushSubscription(database.Base, database.BackendMixin): def vapid_public_key(self): return self.vapid_private_key.public_key() - async def send(self, message, ttl=0): + async def send(self, title, body, ttl=None): """ Sends a message to the user using the push service """ - # Convert strings into a message object - if isinstance(message, str): - message = { - "message" : message, - } + message = { + "title" : title, + "body" : body, + } - # Convert dict() to JSON - if isinstance(message, dict): - message = json.dumps(message) + # Optionally add the TTL + if ttl: + message["ttl"] = ttl - # Encode everything as bytes - if not isinstance(message, bytes): - message = message.encode() + # Convert dict() to JSON + message = json.dumps(message) # Encrypt the message message = self._encrypt(message) @@ -1218,6 +1193,10 @@ class UserPushSubscription(database.Base, database.BackendMixin): """ headers = {} + # Encode everything as bytes + if not isinstance(message, bytes): + message = message.encode() + # Generate some salt salt = os.urandom(16)