combo-plugin-gnm/combo_plugin_gnm/management/commands/send_webpush.py

67 lines
2.4 KiB
Python

# -*- coding: utf-8 -*-
# combo-plugin-gnm - Combo WebPush App
# Copyright (C) 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/>.
from dateutil.parser import parse
from datetime import timedelta, datetime
import argparse
from django.core.management.base import BaseCommand
from django.utils.timezone import make_aware, now
from combo.apps.notifications.models import Notification
from combo_plugin_gnm.push import send_web_push
def to_datetime_argument(string):
try:
return make_aware(parse(string))
except ValueError as verr:
raise argparse.ArgumentTypeError(verr)
class Command(BaseCommand):
help = u'''Send push notification for the last notifications, for example :
> python manage.py send_webpush --since=2018-03-03T00:00:00
will all waiting web push notifications from march 3rd 2018 until now
'''
def add_arguments(self, parser):
# Named (optional) arguments
parser.add_argument(
'--since',
dest='since',
default=None,
type=to_datetime_argument,
help='Send push notification created since this datetime',
)
def handle(self, *args, **options):
''' Send visible and new web-push notifications
'''
since = options.get('since')
if since is None:
since = now() - timedelta(days=1)
verbosity = options.get('verbosity')
notif_query = Notification.objects.new().visible().filter(start_timestamp__gte=since)
for notif in notif_query:
if verbosity > 0:
print('Pushing notification %s' % str(notif).decode('utf-8'))
answer = [str(response_obj) for response_obj in send_web_push(notif, since=since)]
if verbosity > 0:
print('Web Push Responses : %s' % " | ".join(answer))