models.py 6.42 KB
Newer Older
1
2
from __future__ import unicode_literals

3
from django.conf import settings
4
from django.db import models
5
from django.utils.translation import override
6
from django.utils.translation import ugettext_lazy as _
7
8
from pyfcm import FCMNotification

9
from utils.tasks import revoke_task, schedule_task
10
from utils.translation import MultilingualField, ModelTranslateMeta
11
from .tasks import send_message
12
13
14


class Category(models.Model, metaclass=ModelTranslateMeta):
15
16
    """Describes a Message category"""

17
18
19
20
21
22
23
24
25
26
    key = models.CharField(max_length=16, primary_key=True)

    name = MultilingualField(
        models.CharField,
        _("name"),
        max_length=32,
    )

    def __str__(self):
        return self.name_en
27
28


29
30
31
32
def default_receive_category():
    return Category.objects.filter(key="general")


33
class Device(models.Model):
34
35
    """Describes a device"""

36
37
38
39
40
    DEVICE_TYPES = (
        ('ios', 'iOS'),
        ('android', 'Android')
    )

41
    registration_id = models.TextField(verbose_name=_("registration token"))
42
43
    type = models.CharField(choices=DEVICE_TYPES, max_length=10)
    active = models.BooleanField(
44
        verbose_name=_("active"), default=True,
45
46
        help_text=_("Inactive devices will not be sent notifications")
    )
47
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
Thom Wiggers's avatar
Thom Wiggers committed
48
49
50
                             on_delete=models.CASCADE,
                             blank=False,
                             null=False)
51
    date_created = models.DateTimeField(
52
53
54
55
56
57
        verbose_name=_("registration date"), auto_now_add=True, null=False
    )
    language = models.CharField(
        verbose_name=_('language'),
        max_length=2,
        choices=settings.LANGUAGES,
58
        default='en',
59
60
    )

61
62
63
64
65
    receive_category = models.ManyToManyField(
        Category,
        default=default_receive_category
    )

66
67
68
69
    class Meta:
        unique_together = ('registration_id', 'user',)


70
71
72
73
74
75
76
77
class MessageManager(models.Manager):
    """Returns manual messages only"""

    def get_queryset(self):
        return (super().get_queryset()
                .filter(scheduledmessage__task_id=None))


78
class Message(models.Model, metaclass=ModelTranslateMeta):
79
80
81
82
    """Describes a push notification"""

    objects = MessageManager()

83
    users = models.ManyToManyField(settings.AUTH_USER_MODEL)
84
85
    title = MultilingualField(
        models.CharField,
86
87
88
        max_length=150,
        verbose_name=_('title')
    )
89
90
    body = MultilingualField(
        models.TextField,
91
92
        verbose_name=_('body')
    )
93
94
    category = models.ForeignKey(
        Category,
95
        on_delete=models.CASCADE,
96
        verbose_name=_('category'),
Luko van der Maas's avatar
Luko van der Maas committed
97
98
        default="general"
    )
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    sent = models.BooleanField(
        verbose_name=_('sent'),
        default=False
    )
    failure = models.IntegerField(
        verbose_name=_('failure'),
        blank=True,
        null=True,
    )
    success = models.IntegerField(
        verbose_name=_('success'),
        blank=True,
        null=True,
    )

    def __str__(self):
        return '{}: {}'.format(self.title, self.body)

    def send(self, **kwargs):
        if self:
119
120
121
122
123
124
125
126
            any_reg_ids = False
            success_total = 0
            failure_total = 0
            result_list = []

            for lang in settings.LANGUAGES:
                with override(lang[0]):
                    reg_ids = list(
127
                        Device.objects.filter(
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
                            user__in=self.users.all(),
                            receive_category__key=self.category_id,
                            active=True,
                            language=lang[0]
                        ).values_list('registration_id', flat=True))

                    if len(reg_ids) == 0:
                        continue

                    any_reg_ids = True

                    result = FCMNotification(
                        api_key=settings.PUSH_NOTIFICATIONS_API_KEY
                    ).notify_multiple_devices(
                        registration_ids=reg_ids,
                        message_title=self.title,
                        message_body=str(self.body),
                        color='#E62272',
                        sound='default',
                        **kwargs
                    )

                    results = result['results']
                    for (index, item) in enumerate(results):
                        if 'error' in item:
                            reg_id = reg_ids[index]

                            if (item['error'] == 'NotRegistered'
                                    or item['error'] == 'InvalidRegistration'):
                                Device.objects.filter(
                                    registration_id=reg_id).delete()
                            else:
                                Device.objects.filter(
                                    registration_id=reg_id
                                ).update(active=False)

                    success_total += result['success']
                    failure_total += result['failure']
                    result_list.append(result)

            if any_reg_ids:
                self.sent = True
                self.success = success_total
                self.failure = failure_total
                self.save()

            return result_list
175
        return None
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214


class ScheduledMessageManager(models.Manager):
    """Returns scheduled messages only"""

    def get_queryset(self):
        return super().get_queryset()


class ScheduledMessage(Message, metaclass=ModelTranslateMeta):
    """Describes a scheduled push notification"""

    objects = ScheduledMessageManager()

    task_id = models.CharField(max_length=50, blank=True, null=True)
    time = models.DateTimeField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._time = self.time

    def schedule(self):
        """Schedules a Celery task to send this message"""
        return schedule_task(send_message, args=(self.pk,), eta=self.time)

    def save(self, *args, **kwargs):
        """Custom save method which also schedules the task"""

        if not (self._time == self.time):
            if self.task_id:
                # Revoke that task in case its time has changed
                revoke_task(self.task_id)
            super().save(*args, **kwargs)
            self.task_id = self.schedule()

        super().save(*args, **kwargs)

    def delete(self, using=None, keep_parents=False):
        if self.task_id:
215
            revoke_task(self.task_id)
216
        return super().delete(using, keep_parents)