Ejemplo n.º 1
0
class File(TimeStampedModel):
    id = RegularUDIDField()
    owner = models.ForeignKey(to='accounts.Entity',
                              verbose_name=_('owner'),
                              on_delete=models.SET_NULL,
                              blank=True,
                              null=True)
    file = models.FileField(verbose_name=_('file'), upload_to=uuid_dir)
    is_stored = models.BooleanField(verbose_name=_('is stored'), default=False)
    size = models.PositiveIntegerField(verbose_name=_('file_size'), default=0)

    @property
    def basename(self):
        return os.path.basename(self.file.name)

    class Meta:
        verbose_name = _('file')
        verbose_name_plural = _('uploaded files')

    def __init__(self, *args, **kwargs):
        if (not (kwargs.get('id'))):
            kwargs['id'] = generate_regular_udid()
        super().__init__(*args, **kwargs)

    def __str__(self):
        return self.basename

    def save(self, *args, **kwargs):
        self.size = self.file.size
        return super().save(*args, **kwargs)

    def store(self):
        self.is_stored = True
        self.save(update_fields={'is_stored', 'size'})
Ejemplo n.º 2
0
class Message(TimeStampedModel):
    id = RegularUDIDField()
    chat = models.ForeignKey(to=Chat,
                             verbose_name=_('chat'),
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True)
    sender = models.ForeignKey(to=Entity,
                               verbose_name=_('sender'),
                               on_delete=models.PROTECT,
                               blank=True,
                               null=True)
    text = models.TextField(verbose_name=_('message'),
                            max_length=50000,
                            validators=[MaxLengthValidator(limit_value=50000)])

    objects = MessageManager()

    class Meta:
        verbose_name = _('message')
        verbose_name_plural = _('messages')
        ordering = ('-date_created', )
        get_latest_by = 'date_created'

    def __str__(self):
        return '{}: {}'.format(
            self.sender.user if self.sender else str(_("Unknown")),
            self.text[:140])
Ejemplo n.º 3
0
class Message(TimeStampedModel):
    id = RegularUDIDField()
    chat = models.ForeignKey(to=Chat,
                             verbose_name=_('chat'),
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True)
    sender = models.ForeignKey(to=Entity,
                               verbose_name=_('sender'),
                               on_delete=models.SET_NULL,
                               blank=True,
                               null=True)
    text = models.TextField(verbose_name=_('message'))

    objects = MessageManager()

    class Meta:
        verbose_name = _('message')
        verbose_name_plural = _('messages')
        ordering = ('-date_created', )
        get_latest_by = 'date_created'

    def __str__(self):
        return '{}: {}'.format(self.sender.user, self.text[:140])
Ejemplo n.º 4
0
class Chat(TimeStampedModel):
    id = RegularUDIDField()
    site = models.ForeignKey(to=Site,
                             verbose_name=_('site'),
                             on_delete=models.PROTECT)
    ent1 = models.ForeignKey(to=Entity,
                             verbose_name=_('participant 1'),
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True,
                             related_name='+')
    ent2 = models.ForeignKey(to=Entity,
                             verbose_name=_('participant 2'),
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True,
                             related_name='+')
    group = models.ManyToManyField(to=Entity, verbose_name=_('participants'))
    is_group = models.BooleanField(verbose_name=_('is group chat'),
                                   default=False)
    last_message = models.ForeignKey(to='Message',
                                     verbose_name=_('last message'),
                                     on_delete=models.SET_NULL,
                                     blank=True,
                                     null=True,
                                     related_name='+')

    objects = ChatManager()

    @property
    def is_private(self):
        return (not (self.is_group))

    @property
    def participants(self):
        if (self.is_private):
            return (self.ent1, self.ent2)
        else:
            return self.group.order_by('date_created')

    @property
    def participants_count(self):
        return len(self.participants)

    class Meta:
        verbose_name = _('chat')
        verbose_name_plural = _('chats')
        ordering = ('-last_message__date_created', '-date_updated')

    def __str__(self):
        return ', '.join(str(ent.user) for ent in self.participants)

    def save(self, *args, **kwargs):
        if (self.is_private):
            assert self.ent1
            assert self.ent2
            assert self.ent1 != self.ent2
            assert self.group.count() == 0
        self.site = Site.objects.get_current()
        return super().save(*args, **kwargs)

    def get_slug(self, current_user: Entity):
        if (self.is_private):
            if (self.ent1_id == current_user.id):
                return self.ent2.slug
            elif (self.ent2_id == current_user.id):
                return self.ent1.slug
        return self.id

    def get_other_participants(self, entity):
        return [p for p in self.participants if (p.id != entity.id)]

    def mark_read(self, entity):
        return ReadMark.objects.mark(self, entity)
Ejemplo n.º 5
0
class UserEmailAddress(CleanAndValidateAllFieldsMixin, TimeStampedModel):
    id = RegularUDIDField()
    user = models.ForeignKey(to=django_settings.AUTH_USER_MODEL,
                             verbose_name=_('user'),
                             on_delete=models.CASCADE,
                             related_name='email_addresses')
    email = models.EmailField(verbose_name=_('email'), unique=True)
    is_confirmed = models.BooleanField(verbose_name=_('is confirmed'),
                                       default=False)
    is_primary = models.BooleanField(verbose_name=_('is primary'),
                                     default=False)
    confirmation_token = models.CharField(verbose_name=_('confirmation token'),
                                          max_length=32,
                                          blank=True)
    confirmation_sent = models.IntegerField(
        verbose_name=_('confirmation sent'), default=0)
    access = UserAccessField(verbose_name=_('Who can see this email'),
                             default=UserAccessField.ACCESS_ME)

    @classproperty
    def validators(cls):
        validators = {
            'email': ["validate_email"],
        }
        return validators

    class Meta:
        verbose_name = _('email address')
        verbose_name_plural = _('email addresses')
        ordering = (
            'date_created',
            'id',
        )

    def __str__(self):
        return self.email

    def save(self, *args, **kwargs):
        if (not (self.confirmation_token)):
            self.confirmation_token = self._generate_confirmation_token()
        return super().save(*args, **kwargs)

    def clean_all_fields(self, exclude=None):
        super().clean_all_fields(exclude=exclude)

        self.normalize_email()

    def normalize_email(self):
        self.email = normalize_email(email=self.email)

    def validate_email(self):
        self.validate_email_unique()

    def validate_email_unique(self):
        validate_email_unique(email=self.email, user_email_address_pk=self.pk)

    def _generate_confirmation_token(self):
        return generate_confirmation_token()

    def mail(self, template_name_prefix, context=None):
        site = Site.objects.get_current()
        context = context or {}
        context.update({
            'site_name': _(site.name),
            'user': self.user,
            'email_address': self,
        })
        return send_mail(to=[self.email],
                         template_name_prefix=template_name_prefix,
                         context=context)

    def send_confirmation_email(self):
        if (self.user.has_confirmed_email):
            msg_count = self.mail(
                template_name_prefix='email/accounts/confirm_second_email')
        else:
            msg_count = self.mail(
                template_name_prefix='email/accounts/confirm_first_email')
        self.confirmation_sent += 1
        self.save(update_fields={'confirmation_sent'})
        return msg_count

    def verify(self):
        self.is_confirmed = True
        self.save(update_fields={'is_confirmed'})
        if (UserEmailAddress.objects.filter(user=self.user,
                                            is_confirmed=True).count() == 1):
            # If this user doesn't have a confirmed primary email address, make this one primary.
            if (UserEmailAddress.objects.filter(
                    user=self.user, is_primary=True,
                    is_confirmed=True).count() == 0):
                self.make_primary()
            self.user.profile.call_after_verify_email_address()

    def make_primary(self):
        self.user.email_addresses.update(is_primary=False)
        self.is_primary = True
        self.save(update_fields={'is_primary'})