Projet

Général

Profil

0004-pwa-create-a-management-command-send_webpush-25462.patch

Anonyme, 24 août 2018 17:21

Télécharger (6,68 ko)

Voir les différences:

Subject: [PATCH 4/6] pwa: create a management command send_webpush (#25462)

 combo/apps/pwa/management/__init__.py         |  0
 .../apps/pwa/management/commands/__init__.py  |  0
 .../pwa/management/commands/send_webpush.py   | 81 +++++++++++++++++++
 combo/apps/pwa/push.py                        | 37 +++++++++
 debian/combo.cron.hourly                      |  1 +
 5 files changed, 119 insertions(+)
 create mode 100644 combo/apps/pwa/management/__init__.py
 create mode 100644 combo/apps/pwa/management/commands/__init__.py
 create mode 100644 combo/apps/pwa/management/commands/send_webpush.py
 create mode 100644 combo/apps/pwa/push.py
combo/apps/pwa/management/commands/send_webpush.py
1
# -*- coding: utf-8 -*-
2
# combo - Combo PWA App
3
# Copyright (C) 2018  Entr'ouvert
4
#
5
# This program is free software: you can redistribute it and/or modify it
6
# under the terms of the GNU Affero General Public License as published
7
# by the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU Affero General Public License for more details.
14
#
15
# You should have received a copy of the GNU Affero General Public License
16
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17

  
18
from dateutil.parser import parse
19
from datetime import timedelta
20
import argparse
21

  
22
import django
23
from django.db import transaction
24
from django.core.management.base import BaseCommand
25
from django.utils.timezone import make_aware, now, is_naive
26

  
27
from combo.apps.notifications.models import Notification
28
from combo.apps.pwa.push import send_web_push
29
from combo.apps.pwa.models import WebPushRecord
30

  
31
from push_notifications.models import WebPushDevice
32

  
33
def to_datetime_argument(string):
34
    try:
35
        return make_aware(parse(string))
36
    except ValueError as verr:
37
        raise argparse.ArgumentTypeError(verr)
38

  
39

  
40
class Command(BaseCommand):
41
    help = u'''Send push notification for the last notifications, for example :
42

  
43
        $ combo-manage tenant_command send_webpush --all-tenants --since=2018-03-03T00:00:00
44

  
45
    this will send all waiting web push notifications from march 3rd 2018 until now
46
    '''
47

  
48
    def add_arguments(self, parser):
49
        # Named (optional) arguments
50
        parser.add_argument(
51
            '--since',
52
            dest='since',
53
            default=None,
54
            type=to_datetime_argument,
55
            help='Send push notifications created since this datetime',
56
        )
57

  
58
    def handle(self, *args, **options):
59
        ''' Send visible and new web-push notifications
60
        '''
61
        if django.VERSION < (1, 11):
62
            print('Exiting send_webpush : running an incompatible version of Django (%s)' % (django.VERSION))
63
            return
64
        verbosity = options.get('verbosity', 1)
65
        since = options.get('since')
66
        if since is None:
67
            since = now() - timedelta(hours=24)
68

  
69
        if is_naive(since):
70
            since = make_aware(since)
71
        for notification in Notification.objects.new().visible().filter(start_timestamp__gte=since):
72
            for device in WebPushDevice.objects.filter(user=notification.user, active=True):
73
                with transaction.atomic():
74
                    web_push_record, created = WebPushRecord.objects.select_for_update().get_or_create(
75
                        notification=notification,
76
                        subscription=device)
77
                    if web_push_record.status == WebPushRecord.DEFAULT_STATUS:
78
                        if verbosity > 0:
79
                            print('Found a device id =  %s to push the notification id = %s' % (device.id, notification.id))
80

  
81
                        web_push_record = send_web_push(web_push_record, device)
combo/apps/pwa/push.py
1
# -*- coding: utf-8 -*-
2
# combo - Combo PWA App
3
# Copyright (C) 2018  Entr'ouvert
4
#
5
# This program is free software: you can redistribute it and/or modify it
6
# under the terms of the GNU Affero General Public License as published
7
# by the Free Software Foundation, either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU Affero General Public License for more details.
14
#
15
# You should have received a copy of the GNU Affero General Public License
16
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17

  
18
from push_notifications.webpush import WebPushError
19

  
20

  
21
def send_web_push(web_push_record, device):
22
    '''
23
    Send a push notification to every susbcribed device
24
    Save to status into web_push_record
25
    '''
26
    try:
27
        # send the request to the endpoint
28
        web_push_record.response = device.send_message(web_push_record.payload, ttl=web_push_record.ttl)
29
        if 'success' in web_push_record.response and web_push_record.response['success'] == 1:
30
            web_push_record.set_status_ok()
31
        else:
32
            web_push_record.set_status_err()
33
    except WebPushError as wperr:
34
        web_push_record.set_status_err()
35
        raise
36

  
37
    return web_push_record
debian/combo.cron.hourly
5 5
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command update_momo_manifest --all-tenants -v0
6 6
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command update_index --remove --all-tenants -v0
7 7
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command notify_payments --all-tenants -v0
8
/sbin/runuser -u combo /usr/bin/combo-manage -- tenant_command send_webpush --all-tenants
8
-