combo/combo/apps/pwa/signals.py

64 lines
2.3 KiB
Python

# combo - content management system
# Copyright (C) 2015-2018 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import logging
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from py_vapid import Vapid
import pywebpush
from combo.apps.notifications.models import Notification
from .models import PushSubscription, PwaSettings
@receiver(post_save, sender=Notification)
def notification(sender, instance=None, created=False, **kwargs):
if not created:
return
pwa_settings = PwaSettings.singleton()
if not pwa_settings.push_notifications:
return
if settings.PWA_VAPID_PRIVATE_KEY: # legacy
pwa_vapid_private_key = settings.PWA_VAPID_PRIVATE_KEY
else:
pwa_vapid_private_key = Vapid.from_pem(pwa_settings.push_notifications_infos['private_key'].encode('ascii'))
if settings.PWA_VAPID_CLAIMS: # legacy
claims = settings.PWA_VAPID_CLAIMS
else:
claims = {'sub': 'mailto:%s' % settings.DEFAULT_FROM_EMAIL}
message = json.dumps({
'summary': instance.summary,
'body': instance.body,
'url': instance.url,
})
for subscription in PushSubscription.objects.filter(user_id=instance.user_id):
try:
pywebpush.webpush(
subscription_info=subscription.subscription_info,
data=message,
vapid_private_key=pwa_vapid_private_key,
vapid_claims=claims,
)
except pywebpush.WebPushException as e:
logger = logging.getLogger(__name__)
logger.exception('webpush error (%r)', e)