forked from django-wiki/django-nyt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
318 lines (265 loc) · 9.42 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
175
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
from django_nyt import settings
_notification_type_cache = {}
class NotificationType(models.Model):
"""
Notification types are added on-the-fly by the
applications adding new notifications
"""
key = models.CharField(
max_length=128,
primary_key=True,
verbose_name=_('unique key'),
unique=True
)
# TODO: This isn't translatable
label = models.CharField(
max_length=128,
verbose_name=_('optional label'),
blank=True,
null=True
)
content_type = models.ForeignKey(
ContentType,
blank=True,
null=True,
on_delete=models.SET_NULL
)
def __str__(self):
return self.key
class Meta:
db_table = settings.DB_TABLE_PREFIX + '_notificationtype'
verbose_name = _('type')
verbose_name_plural = _('types')
@classmethod
def get_by_key(cls, key, content_type=None):
if key in _notification_type_cache:
return _notification_type_cache[key]
try:
nt = cls.objects.get(key=key)
except cls.DoesNotExist:
nt = cls.objects.create(key=key, content_type=content_type)
_notification_type_cache[key] = nt
return nt
@receiver([post_save, post_delete], sender=NotificationType)
def clear_notification_type_cache(*args, **kwargs):
global _notification_type_cache
_notification_type_cache = {}
class Settings(models.Model):
"""
Reusable settings object for a subscription
"""
user = models.ForeignKey(
settings.USER_MODEL,
on_delete=models.CASCADE, # If a user is deleted, remove all settings
verbose_name=_("user"),
related_name='nyt_settings',
)
interval = models.SmallIntegerField(
choices=settings.INTERVALS,
verbose_name=_('interval'),
default=settings.INTERVALS_DEFAULT,
)
is_default = models.BooleanField(
default=False,
verbose_name=_("Default for new subscriptions"),
)
def __str__(self):
obj_name = _("Settings for %s") % getattr(
self.user, self.user.USERNAME_FIELD)
return obj_name
class Meta:
db_table = settings.DB_TABLE_PREFIX + '_settings'
verbose_name = _('settings')
verbose_name_plural = _('settings')
def clean(self):
if not self.is_default:
default_settings = Settings.objects.filter(
user=self.user,
is_default=True,
).exclude(pk=self.pk)
if not default_settings.exists():
raise ValidationError(
_("At minimum one default setting must exist for the user")
)
def save(self, *args, **kwargs):
# We should check that it's the only default setting manually because
# it's not possible to create a database constraint for this.
# Instead of having a constraint, we unset all other is_default for
# the user.
if self.is_default:
default_settings = Settings.objects.filter(
user=self.user,
is_default=True,
).exclude(pk=self.pk)
default_settings.update(is_default=False)
else:
non_default_settings = Settings.objects.filter(
user=self.user,
is_default=False,
).exclude(pk=self.pk)
if non_default_settings.exists():
non_default_settings[0].is_default = True
non_default_settings[0].save()
else:
raise ValueError("A user must have a default settings object")
super(Settings, self).save(*args, **kwargs)
@classmethod
def get_default_setting(cls, user):
return cls.objects.get_or_create(
user=user,
is_default=True
)[0]
class Subscription(models.Model):
# If settings are deleted, remove all subscriptions (CASCADE)
settings = models.ForeignKey(
Settings,
verbose_name=_("settings"),
on_delete=models.CASCADE,
)
notification_type = models.ForeignKey(
NotificationType,
verbose_name=_("notification type"),
on_delete=models.CASCADE
)
object_id = models.CharField(
max_length=64,
null=True,
blank=True,
help_text=_('Leave this blank to subscribe to any kind of object'),
verbose_name=_("object ID"),
)
send_emails = models.BooleanField(
default=True,
verbose_name=_("send emails"),
)
latest = models.ForeignKey(
'Notification',
null=True,
blank=True,
related_name='latest_for',
verbose_name=_("latest notification"),
on_delete=models.CASCADE,
)
def __str__(self):
obj_name = _("Subscription for: %s") % (
getattr(self.settings.user, self.settings.user.USERNAME_FIELD))
return obj_name
class Meta:
db_table = settings.DB_TABLE_PREFIX + '_subscription'
verbose_name = _('subscription')
verbose_name_plural = _('subscriptions')
class Notification(models.Model):
#: Either set the subscription
subscription = models.ForeignKey(
Subscription,
null=True,
blank=True,
on_delete=models.SET_NULL,
verbose_name=_("subscription"),
)
#: Or the user to receive the notification
# If a user is deleted, remove all notifications (CASCADE)
user = models.ForeignKey(
settings.USER_MODEL,
null=True,
blank=True,
on_delete=models.CASCADE,
verbose_name=_("user"),
related_name='nyt_notifications',
)
message = models.TextField()
# TODO: Why 200?
url = models.CharField(
verbose_name=_('link for notification'),
blank=True,
null=True,
max_length=200,
)
is_viewed = models.BooleanField(default=False)
is_emailed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
occurrences = models.PositiveIntegerField(
default=1,
verbose_name=_('occurrences'),
help_text=_(
'If the same notification was fired multiple '
'times with no intermediate notifications'
),
)
def save(self, *args, **kwargs):
assert self.user or self.subscription
if not self.user:
self.user = self.subscription.settings.user
super(Notification, self).save(*args, **kwargs)
@classmethod
def create_notifications(cls, key, **kwargs):
"""
Creates notifications directly in database -- do not call directly,
use django_nyt.notify(...)
This is the old interface.
"""
if not key or not isinstance(key, str):
raise KeyError('No notification key (string) specified.')
object_id = kwargs.pop('object_id', None)
filter_exclude = kwargs.pop('filter_exclude', {})
recipient_users = kwargs.pop('recipient_users', None)
objects_created = []
subscriptions = Subscription.objects.filter(
notification_type__key=key
).exclude(
**filter_exclude
)
if object_id:
subscriptions = subscriptions.filter(
Q(object_id=object_id) |
Q(object_id=None)
)
if recipient_users:
subscriptions = subscriptions.filter(
settings__user__in=recipient_users,
)
subscriptions = subscriptions.prefetch_related('latest', 'settings')
subscriptions = subscriptions.order_by('settings__user')
prev_user = None
for subscription in subscriptions:
# Don't alert the same user several times even though overlapping
# subscriptions occur.
if subscription.settings.user == prev_user:
continue
# Check if it's the same as the previous message
latest = subscription.latest
if latest and (latest.message == kwargs.get('message', None) and
latest.url == kwargs.get('url', None) and
latest.is_viewed is False):
# Both message and URL are the same, and it hasn't been viewed
# so just increment occurrence count.
latest.occurrences = latest.occurrences + 1
latest.is_emailed = False
latest.save()
else:
# Insert a new notification
new_obj = cls.objects.create(
subscription=subscription,
**kwargs)
objects_created.append(
new_obj
)
subscription.latest = new_obj
subscription.save()
prev_user = subscription.settings.user
return objects_created
def __str__(self):
return "%s: %s" % (self.user, self.message)
class Meta:
db_table = settings.DB_TABLE_PREFIX + '_notification'
verbose_name = _('notification')
verbose_name_plural = _('notifications')
ordering = ('-id',)