models.py 15.8 KB
Newer Older
1
2
3
4
# -*- coding:utf-8 -*
#
# Copyright 2016,2017
# - Skia <skia@libskia.so>
Sli's avatar
Sli committed
5
# - Sli <antoine@bartuccio.fr>
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#
# Ce fichier fait partie du site de l'Association des Étudiants de l'UTBM,
# http://ae.utbm.fr.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License a 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 General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.
#
#

26
27
28
29
from django.db import models
from django.core import validators
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
Sli's avatar
Sli committed
30
from django.core.exceptions import ValidationError, ObjectDoesNotExist
Krophil's avatar
Krophil committed
31
from django.db import transaction
32
from django.urls import reverse
Skia's avatar
Skia committed
33
from django.utils import timezone
Sli's avatar
Sli committed
34
from django.core.validators import RegexValidator, validate_email
Sli's avatar
Sli committed
35
from django.utils.functional import cached_property
36

Sli's avatar
Sli committed
37
from core.models import User, MetaGroup, Group, SithFile, RealGroup, Notification, Page
Krophil's avatar
Krophil committed
38

39
40
# Create your models here.

Sli's avatar
Sli committed
41

42
43
44
45
class Club(models.Model):
    """
    The Club class, made as a tree to allow nice tidy organization
    """
Sli's avatar
Sli committed
46

Skia's avatar
Skia committed
47
    id = models.AutoField(primary_key=True, db_index=True)
Sli's avatar
Sli committed
48
    name = models.CharField(_("name"), max_length=64)
49
50
51
    parent = models.ForeignKey(
        "Club", related_name="children", null=True, blank=True, on_delete=models.CASCADE
    )
Sli's avatar
Sli committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    unix_name = models.CharField(
        _("unix name"),
        max_length=30,
        unique=True,
        validators=[
            validators.RegexValidator(
                r"^[a-z0-9][a-z0-9._-]*[a-z0-9]$",
                _(
                    "Enter a valid unix name. This value may contain only "
                    "letters, numbers ./-/_ characters."
                ),
            )
        ],
        error_messages={"unique": _("A club with that unix name already exists.")},
    )
    logo = models.ImageField(
        upload_to="club_logos", verbose_name=_("logo"), null=True, blank=True
    )
    is_active = models.BooleanField(_("is active"), default=True)
    short_description = models.CharField(
        _("short description"), max_length=1000, default="", blank=True, null=True
Krophil's avatar
Krophil committed
73
    )
Sli's avatar
Sli committed
74
    address = models.CharField(_("address"), max_length=254)
75
    # This function prevents generating migration upon settings change
Sli's avatar
Sli committed
76
77
78
79
    def get_default_owner_group():
        return settings.SITH_GROUP_ROOT_ID

    owner_group = models.ForeignKey(
80
81
82
83
        Group,
        related_name="owned_club",
        default=get_default_owner_group,
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    )
    edit_groups = models.ManyToManyField(
        Group, related_name="editable_club", blank=True
    )
    view_groups = models.ManyToManyField(
        Group, related_name="viewable_club", blank=True
    )
    home = models.OneToOneField(
        SithFile,
        related_name="home_of_club",
        verbose_name=_("home"),
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )
99
100
101
    page = models.OneToOneField(
        Page, related_name="club", blank=True, null=True, on_delete=models.CASCADE
    )
102

103
    class Meta:
Sli's avatar
Sli committed
104
        ordering = ["name", "unix_name"]
105

Sli's avatar
Sli committed
106
107
    @cached_property
    def president(self):
Sli's avatar
Sli committed
108
109
110
        return self.members.filter(
            role=settings.SITH_CLUB_ROLES_ID["President"], end_date=None
        ).first()
Sli's avatar
Sli committed
111

112
113
114
115
116
117
    def check_loop(self):
        """Raise a validation error when a loop is found within the parent list"""
        objs = []
        cur = self
        while cur.parent is not None:
            if cur in objs:
Sli's avatar
Sli committed
118
                raise ValidationError(_("You can not make loops in clubs"))
119
120
121
122
123
124
            objs.append(cur)
            cur = cur.parent

    def clean(self):
        self.check_loop()

Skia's avatar
Skia committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    def _change_unixname(self, new_name):
        c = Club.objects.filter(unix_name=new_name).first()
        if c is None:
            if self.home:
                self.home.name = new_name
                self.home.save()
        else:
            raise ValidationError(_("A club with that unix_name already exists"))

    def make_home(self):
        if not self.home:
            home_root = SithFile.objects.filter(parent=None, name="clubs").first()
            root = User.objects.filter(username="root").first()
            if home_root and root:
                home = SithFile(parent=home_root, name=self.unix_name, owner=root)
                home.save()
                self.home = home
                self.save()

Sli's avatar
Sli committed
144
    def make_page(self):
Sli's avatar
Sli committed
145
        root = User.objects.filter(username="root").first()
Sli's avatar
Sli committed
146
147
148
149
150
151
        if not self.page:
            club_root = Page.objects.filter(name=settings.SITH_CLUB_ROOT_PAGE).first()
            if root and club_root:
                public = Group.objects.filter(id=settings.SITH_GROUP_PUBLIC_ID).first()
                p = Page(name=self.unix_name)
                p.parent = club_root
Sli's avatar
Sli committed
152
                p.save(force_lock=True)
Sli's avatar
Sli committed
153
154
                if public:
                    p.view_groups.add(public)
Sli's avatar
Sli committed
155
                p.save(force_lock=True)
Sli's avatar
Sli committed
156
157
                if self.parent and self.parent.page:
                    p.parent = self.parent.page
Sli's avatar
Sli committed
158
159
                self.page = p
                self.save()
Sli's avatar
Sli committed
160
161
162
        elif self.page and self.page.name != self.unix_name:
            self.page.unset_lock()
            self.page.name = self.unix_name
Sli's avatar
Sli committed
163
            self.page.save(force_lock=True)
Sli's avatar
Sli committed
164
165
166
167
168
169
        elif (
            self.page
            and self.parent
            and self.parent.page
            and self.page.parent != self.parent.page
        ):
Sli's avatar
Sli committed
170
171
            self.page.unset_lock()
            self.page.parent = self.parent.page
Sli's avatar
Sli committed
172
            self.page.save(force_lock=True)
Sli's avatar
Sli committed
173

Skia's avatar
Skia committed
174
175
176
    def save(self, *args, **kwargs):
        with transaction.atomic():
            creation = False
Skia's avatar
Skia committed
177
178
            old = Club.objects.filter(id=self.id).first()
            if not old:
Skia's avatar
Skia committed
179
180
181
182
183
184
                creation = True
            else:
                if old.unix_name != self.unix_name:
                    self._change_unixname(self.unix_name)
            super(Club, self).save(*args, **kwargs)
            if creation:
Krophil's avatar
Krophil committed
185
                board = MetaGroup(name=self.unix_name + settings.SITH_BOARD_SUFFIX)
Skia's avatar
Skia committed
186
                board.save()
Krophil's avatar
Krophil committed
187
                member = MetaGroup(name=self.unix_name + settings.SITH_MEMBER_SUFFIX)
Skia's avatar
Skia committed
188
                member.save()
Sli's avatar
Sli committed
189
190
191
                subscribers = Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP
                ).first()
Skia's avatar
Skia committed
192
193
194
195
                self.make_home()
                self.home.edit_groups = [board]
                self.home.view_groups = [member, subscribers]
                self.home.save()
Sli's avatar
Sli committed
196
            self.make_page()
Skia's avatar
Skia committed
197

198
199
200
    def __str__(self):
        return self.name

201
    def get_absolute_url(self):
Sli's avatar
Sli committed
202
        return reverse("club:club_view", kwargs={"club_id": self.id})
203

Skia's avatar
Skia committed
204
205
206
    def get_display_name(self):
        return self.name

Skia's avatar
Skia committed
207
208
209
210
    def is_owned_by(self, user):
        """
        Method to see if that object can be super edited by the given user
        """
Skia's avatar
Skia committed
211
        return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP)
Skia's avatar
Skia committed
212

Krophil's avatar
Krophil committed
213
214
215
    def get_full_logo_url(self):
        return "https://%s%s" % (settings.SITH_URL, self.logo.url)

Skia's avatar
Skia committed
216
217
218
219
    def can_be_edited_by(self, user):
        """
        Method to see if that object can be edited by the given user
        """
220
        return self.has_rights_in_club(user)
Skia's avatar
Skia committed
221
222
223
224
225

    def can_be_viewed_by(self, user):
        """
        Method to see if that object can be seen by the given user
        """
Skia's avatar
Skia committed
226
        sub = User.objects.filter(pk=user.pk).first()
Skia's avatar
Skia committed
227
228
        if sub is None:
            return False
229
        return sub.was_subscribed
Skia's avatar
Skia committed
230

Skia's avatar
Skia committed
231
    _memberships = {}
Krophil's avatar
Krophil committed
232

Skia's avatar
Skia committed
233
234
235
236
    def get_membership_for(self, user):
        """
        Returns the current membership the given user
        """
Skia's avatar
Skia committed
237
238
239
240
241
242
243
244
245
246
        try:
            return Club._memberships[self.id][user.id]
        except:
            m = self.members.filter(user=user.id).filter(end_date=None).first()
            try:
                Club._memberships[self.id][user.id] = m
            except:
                Club._memberships[self.id] = {}
                Club._memberships[self.id][user.id] = m
            return m
Skia's avatar
Skia committed
247

248
249
250
251
    def has_rights_in_club(self, user):
        m = self.get_membership_for(user)
        return m is not None and m.role > settings.SITH_MAXIMUM_FREE_ROLE

Krophil's avatar
Krophil committed
252

253
254
255
256
257
258
259
260
261
262
263
class Membership(models.Model):
    """
    The Membership class makes the connection between User and Clubs

    Both Users and Clubs can have many Membership objects:
       - a user can be a member of many clubs at a time
       - a club can have many members at a time too

    A User is currently member of all the Clubs where its Membership has an end_date set to null/None.
    Otherwise, it's a past membership kept because it can be very useful to see who was in which Club in the past.
    """
Sli's avatar
Sli committed
264
265
266
267
268
269
270

    user = models.ForeignKey(
        User,
        verbose_name=_("user"),
        related_name="memberships",
        null=False,
        blank=False,
271
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
272
273
    )
    club = models.ForeignKey(
274
275
276
277
278
279
        Club,
        verbose_name=_("club"),
        related_name="members",
        null=False,
        blank=False,
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
280
281
282
283
284
285
286
287
288
289
290
    )
    start_date = models.DateField(_("start date"), default=timezone.now)
    end_date = models.DateField(_("end date"), null=True, blank=True)
    role = models.IntegerField(
        _("role"),
        choices=sorted(settings.SITH_CLUB_ROLES.items()),
        default=sorted(settings.SITH_CLUB_ROLES.items())[0][0],
    )
    description = models.CharField(
        _("description"), max_length=128, null=False, blank=True
    )
291
292

    def __str__(self):
Sli's avatar
Sli committed
293
294
295
296
297
298
299
        return (
            self.club.name
            + " - "
            + self.user.username
            + " - "
            + str(settings.SITH_CLUB_ROLES[self.role])
            + str(" - " + str(_("past member")) if self.end_date is not None else "")
Krophil's avatar
Krophil committed
300
        )
301

Skia's avatar
Skia committed
302
303
304
305
306
307
    def is_owned_by(self, user):
        """
        Method to see if that object can be super edited by the given user
        """
        return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP)

Sli's avatar
Sli committed
308
    def can_be_edited_by(self, user, membership=None):
Skia's avatar
Skia committed
309
310
311
        """
        Method to see if that object can be edited by the given user
        """
Skia's avatar
Skia committed
312
        if user.memberships:
Sli's avatar
Sli committed
313
314
315
316
            if membership:  # This is for optimisation purpose
                ms = membership
            else:
                ms = user.memberships.filter(club=self.club, end_date=None).first()
Sli's avatar
Sli committed
317
318
319
            return (ms and ms.role >= self.role) or user.is_in_group(
                settings.SITH_MAIN_BOARD_GROUP
            )
Skia's avatar
Skia committed
320
321
        return user.is_in_group(settings.SITH_MAIN_BOARD_GROUP)

Skia's avatar
Skia committed
322
    def get_absolute_url(self):
Sli's avatar
Sli committed
323
        return reverse("club:club_members", kwargs={"club_id": self.club.id})
Sli's avatar
Sli committed
324
325
326
327
328


class Mailing(models.Model):
    """
    This class correspond to a mailing list
Sli's avatar
Sli committed
329
    Remember that mailing lists should be validated by UTBM
Sli's avatar
Sli committed
330
    """
Sli's avatar
Sli committed
331
332

    club = models.ForeignKey(
333
334
335
336
337
338
        Club,
        verbose_name=_("Club"),
        related_name="mailings",
        null=False,
        blank=False,
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    )
    email = models.CharField(
        _("Email address"),
        unique=True,
        null=False,
        blank=False,
        max_length=256,
        validators=[
            RegexValidator(
                validate_email.user_regex,
                _("Enter a valid address. Only the root of the address is needed."),
            )
        ],
    )
    is_moderated = models.BooleanField(_("is moderated"), default=False)
    moderator = models.ForeignKey(
355
356
357
358
359
        User,
        related_name="moderated_mailings",
        verbose_name=_("moderator"),
        null=True,
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
360
    )
Sli's avatar
Sli committed
361

Sli's avatar
Sli committed
362
    def clean(self):
363
364
        if Mailing.objects.filter(email=self.email).exists():
            raise ValidationError(_("This mailing list already exists."))
Sli's avatar
Sli committed
365
366
367
368
369
370
        if self.can_moderate(self.moderator):
            self.is_moderated = True
        else:
            self.moderator = None
        super(Mailing, self).clean()

Sli's avatar
Sli committed
371
372
    @property
    def email_full(self):
Sli's avatar
Sli committed
373
        return self.email + "@" + settings.SITH_MAILING_DOMAIN
Sli's avatar
Sli committed
374

Sli's avatar
Sli committed
375
376
    def can_moderate(self, user):
        return user.is_root or user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID)
Sli's avatar
Sli committed
377

Sli's avatar
Sli committed
378
    def is_owned_by(self, user):
Sli's avatar
Sli committed
379
380
381
382
383
        return (
            user.is_in_group(self)
            or user.is_root
            or user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID)
        )
Sli's avatar
Sli committed
384

Sli's avatar
Sli committed
385
386
387
    def can_view(self, user):
        return self.club.has_rights_in_club(user)

Sli's avatar
Sli committed
388
389
390
    def can_be_edited_by(self, user):
        return self.club.has_rights_in_club(user)

Sli's avatar
Sli committed
391
392
393
394
    def delete(self):
        for sub in self.subscriptions.all():
            sub.delete()
        super(Mailing, self).delete()
Sli's avatar
Sli committed
395

Sli's avatar
Sli committed
396
    def fetch_format(self):
Sli's avatar
Sli committed
397
        resp = self.email + ": "
Sli's avatar
Sli committed
398
399
400
401
        for sub in self.subscriptions.all():
            resp += sub.fetch_format()
        return resp

Sli's avatar
Sli committed
402
403
    def save(self):
        if not self.is_moderated:
Sli's avatar
Sli committed
404
405
406
407
408
409
410
411
412
413
414
415
416
            for user in (
                RealGroup.objects.filter(id=settings.SITH_GROUP_COM_ADMIN_ID)
                .first()
                .users.all()
            ):
                if not user.notifications.filter(
                    type="MAILING_MODERATION", viewed=False
                ).exists():
                    Notification(
                        user=user,
                        url=reverse("com:mailing_admin"),
                        type="MAILING_MODERATION",
                    ).save()
Sli's avatar
Sli committed
417
418
        super(Mailing, self).save()

Sli's avatar
Sli committed
419
    def __str__(self):
Sli's avatar
Sli committed
420
        return "%s - %s" % (self.club, self.email_full)
Sli's avatar
Sli committed
421
422
423
424


class MailingSubscription(models.Model):
    """
Sli's avatar
Sli committed
425
    This class makes the link between user and mailing list
Sli's avatar
Sli committed
426
    """
Sli's avatar
Sli committed
427
428
429
430
431
432
433

    mailing = models.ForeignKey(
        Mailing,
        verbose_name=_("Mailing"),
        related_name="subscriptions",
        null=False,
        blank=False,
434
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
435
436
437
438
439
440
441
    )
    user = models.ForeignKey(
        User,
        verbose_name=_("User"),
        related_name="mailing_subscriptions",
        null=True,
        blank=True,
442
        on_delete=models.CASCADE,
Sli's avatar
Sli committed
443
444
    )
    email = models.EmailField(_("Email address"), blank=False, null=False)
Sli's avatar
Sli committed
445
446

    class Meta:
Sli's avatar
Sli committed
447
        unique_together = (("user", "email", "mailing"),)
Sli's avatar
Sli committed
448
449
450
451

    def clean(self):
        if not self.user and not self.email:
            raise ValidationError(_("At least user or email is required"))
Sli's avatar
Sli committed
452
453
454
        try:
            if self.user and not self.email:
                self.email = self.user.email
Sli's avatar
Sli committed
455
456
457
458
459
460
                if MailingSubscription.objects.filter(
                    mailing=self.mailing, email=self.email
                ).exists():
                    raise ValidationError(
                        _("This email is already suscribed in this mailing")
                    )
Sli's avatar
Sli committed
461
462
        except ObjectDoesNotExist:
            pass
Sli's avatar
Sli committed
463
        super(MailingSubscription, self).clean()
Sli's avatar
Sli committed
464
465

    def is_owned_by(self, user):
Sli's avatar
Sli committed
466
467
468
469
470
        return (
            self.mailing.club.has_rights_in_club(user)
            or user.is_root
            or self.user.is_in_group(settings.SITH_GROUP_COM_ADMIN_ID)
        )
Sli's avatar
Sli committed
471
472

    def can_be_edited_by(self, user):
Sli's avatar
Sli committed
473
        return self.user is not None and user.id == self.user.id
Sli's avatar
Sli committed
474

475
    @cached_property
476
477
478
479
480
    def get_email(self):
        if self.user and not self.email:
            return self.user.email
        return self.email

481
482
483
484
485
486
    @cached_property
    def get_username(self):
        if self.user:
            return str(self.user)
        return _("Unregistered user")

Sli's avatar
Sli committed
487
    def fetch_format(self):
Sli's avatar
Sli committed
488
        return self.get_email + " "
Sli's avatar
Sli committed
489

Sli's avatar
Sli committed
490
    def __str__(self):
491
        return "(%s) - %s : %s" % (self.mailing, self.get_username, self.email)