Ejemplo n.º 1
0
Archivo: base.py Proyecto: thoas/pybbm
    def save(self, commit=True):
        if self.instance.pk:
            post = super(PostForm, self).save(commit=False)
            if self.user:
                post.user = self.user

            if post.is_updatable():
                post.updated = tznow()

            if post.topic.head == post:
                topic = post.topic

                topic.name = self.cleaned_data['name']
                topic.updated = tznow()
                topic.save()

                if not defaults.PYBB_DISABLE_POLLS:
                    if self.cleaned_data['poll_type'] != Poll.TYPE_NONE:
                        poll = topic.poll or Poll()
                        poll.type = self.cleaned_data['poll_type']
                        poll.question = self.cleaned_data['poll_question']

                        is_new = poll.pk is None

                        poll.save()

                        if is_new:
                            topic.poll = poll
                            topic.save()
                    else:
                        if topic.poll:
                            topic.poll.answers.all().delete()
                            topic.poll = None
                            topic.save()

            post.save()

            return post

        allow_post = True

        if pybb_premoderation is not None:
            allow_post = pybb_premoderation(self.user, self.cleaned_data)

        if 'forum' in self.cleaned_data and not self._forum:
            self._forum = self.cleaned_data['forum']

        topic = self.get_or_create_topic(allow_post)

        post = self.create_post(topic)

        if not allow_post:
            post.on_moderation = True

        post.save()

        return post
Ejemplo n.º 2
0
    def save(self, commit=True):
        if self.instance.pk:
            post = super(PostForm, self).save(commit=False)
            if self.user:
                post.user = self.user

            if post.is_updatable():
                post.updated = tznow()

            if post.topic.head == post:
                topic = post.topic

                topic.name = self.cleaned_data['name']
                topic.updated = tznow()
                topic.save()

                if not defaults.PYBB_DISABLE_POLLS:
                    if self.cleaned_data['poll_type'] != Poll.TYPE_NONE:
                        poll = topic.poll or Poll()
                        poll.type = self.cleaned_data['poll_type']
                        poll.question = self.cleaned_data['poll_question']

                        is_new = poll.pk is None

                        poll.save()

                        if is_new:
                            topic.poll = poll
                            topic.save()
                    else:
                        if topic.poll:
                            topic.poll.answers.all().delete()
                            topic.poll = None
                            topic.save()

            post.save()

            return post

        allow_post = True

        if pybb_premoderation is not None:
            allow_post = pybb_premoderation(self.user, self.cleaned_data)

        if 'forum' in self.cleaned_data and not self._forum:
            self._forum = self.cleaned_data['forum']

        topic = self.get_or_create_topic(allow_post)

        post = self.create_post(topic)

        if not allow_post:
            post.on_moderation = True

        post.save()

        return post
Ejemplo n.º 3
0
    def save(self, *args, **kwargs):
        new = self.pk is None

        created_at = tznow()

        if self.created is None:
            self.created = created_at

        if (new or 'body' in self._initial_attr and
                self.body != self._initial_attr['body']):
            self.render()

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

        if new:
            self.topic.updated = created_at
            self.topic.forum.updated = created_at

        # If post is topic head and moderated, moderate topic too
        if (self.topic.head == self and self.on_moderation is False and
                self.topic.on_moderation is True):
            self.topic.on_moderation = False

        self.topic.update_counters()

        if new and self.pk == self.topic.first_post_id:
            sync_cover.delay(self.topic_id)
Ejemplo n.º 4
0
    def mark_as_read(self, user):
        from pybb.models import TopicReadTracker, ForumReadTracker, Subscription, Topic

        Subscription.objects.filter(topic=self, user=user).update(sent=False)

        try:
            forum_mark = ForumReadTracker.objects.get(forum=self.forum, user=user)
        except ObjectDoesNotExist:
            forum_mark = None

        if self.updated and ((forum_mark is None) or (forum_mark.time_stamp < self.updated)):
            # Mark topic as readed
            count = TopicReadTracker.objects.filter(topic=self, user=user).update(time_stamp=tznow())

            if not count:
                TopicReadTracker.objects.create(topic=self, user=user)

            # Check, if there are any unread topics in forum
            read = Topic.objects.filter(Q(forum=self.forum) & (Q(topicreadtracker__user=user, topicreadtracker__time_stamp__gt=F('updated'))) |
                                        Q(forum__forumreadtracker__user=user, forum__forumreadtracker__time_stamp__gt=F('updated')))
            unread = Topic.objects.filter(forum=self.forum).exclude(id__in=read)
            if not unread.exists():
                # Clear all topic marks for this forum, mark forum as readed
                TopicReadTracker.objects.filter(
                    user=user,
                    topic__forum=self.forum
                ).delete()

                if not forum_mark:
                    ForumReadTracker.objects.create(forum=self.forum, user=user)

                else:
                    forum_mark.time_stamp = tznow()
                    update_fields(forum_mark, fields=('time_stamp', ))
Ejemplo n.º 5
0
    def compute(self, commit=True):
        self.updated = tznow()
        self.message_count = self.reported_messages.count()

        if self.is_status_closed():
            self.status = self.STATUS_NEW

        if commit:
            self.save()
Ejemplo n.º 6
0
    def mark_updated(self):
        now = tznow()

        self.updated = now
        update_fields(self, fields=('updated', ))

        for topic in self.topics.all():
            topic.updated = now
            update_fields(topic, fields=('updated', ))
Ejemplo n.º 7
0
    def compute(self, commit=True):
        self.updated = tznow()
        self.message_count = self.reported_messages.count()

        if self.is_status_closed():
            self.status = self.STATUS_NEW

        if commit:
            self.save()
Ejemplo n.º 8
0
    def render(self, context):
        context_time = self.time.resolve(context)

        delta = tznow() - context_time
        today = tznow().replace(hour=0, minute=0, second=0)
        yesterday = today - timedelta(days=1)
        tomorrow = today + timedelta(days=1)

        if delta.days == 0:
            if delta.seconds < 60:
                if context['LANGUAGE_CODE'].startswith('ru') and pytils_enabled:
                    msg = _('seconds ago,seconds ago,seconds ago')
                    msg = pytils.numeral.choose_plural(delta.seconds, msg)
                else:
                    msg = _('seconds ago')
                return u'%d %s' % (delta.seconds, msg)

            elif delta.seconds < 3600:
                minutes = int(delta.seconds / 60)
                if context['LANGUAGE_CODE'].startswith('ru') and pytils_enabled:
                    msg = _('minutes ago,minutes ago,minutes ago')
                    msg = pytils.numeral.choose_plural(minutes, msg)
                else:
                    msg = _('minutes ago')
                return u'%d %s' % (minutes, msg)
        if context['user'].is_authenticated:
            if time.daylight:
                tz1 = time.altzone
            else:
                tz1 = time.timezone

            default_tz = load_class(defaults.PYBB_TIMEZONE_FROM_USER)(context['user'])

            tz = tz1 + default_tz * 60 * 60
            context_time = context_time + timedelta(seconds=tz)
        if today < context_time < tomorrow:
            return _('today, %s') % context_time.strftime('%H:%M')

        if yesterday < context_time < today:
            return _('yesterday, %s') % context_time.strftime('%H:%M')

        return dateformat.format(context_time, 'd M, Y H:i')
Ejemplo n.º 9
0
def notify_topic_subscribers(post):
    from pybb.models import Subscription

    topic = post.topic
    if post == topic.head:
        return

    subscriptions = (Subscription.objects.filter(topic=topic,
                                                 type=Subscription.TYPE_INSTANT_ALERT,
                                                 sent=False)
                     .exclude(user=post.user)
                     .select_related('user'))

    params = {
        'post_url': post.get_absolute_url(),
        'post': post,
        'sender': post.user,
        'topic': topic,
        'topic_url': topic.get_absolute_url(),
        'forum': topic.forum,
        'forum_url': topic.forum.get_absolute_url()
    }

    messages = []

    for subscription in subscriptions:
        user = subscription.user

        try:
            email_validator.clean(user.email)
        except Exception as e:
            logging.error(e)
            continue

        subject = render_to_string('pybb/mails/subscription_email_subject.html',
                                   dict(params, **{
                                       'user': user
                                   }))
        message = render_to_string('pybb/mails/subscription_email_body.html',
                                   dict(params, **{
                                       'user': user
                                   }))
        messages.append((''.join(subject.splitlines()), message, settings.DEFAULT_FROM_EMAIL, [user.email]))

    if messages:
        result = send_mass_mail(messages, fail_silently=True)

        subscriptions.update(sent=True, updated=tznow())

        return result

    return False
Ejemplo n.º 10
0
def notify_topic_subscribers(post):
    from pybb.models import Subscription

    topic = post.topic
    if post == topic.head:
        return

    subscriptions = (Subscription.objects.filter(
        topic=topic, type=Subscription.TYPE_INSTANT_ALERT,
        sent=False).exclude(user=post.user).select_related('user'))

    params = {
        'post_url': post.get_absolute_url(),
        'post': post,
        'sender': post.user,
        'topic': topic,
        'topic_url': topic.get_absolute_url(),
        'forum': topic.forum,
        'forum_url': topic.forum.get_absolute_url()
    }

    messages = []

    for subscription in subscriptions:
        user = subscription.user

        try:
            email_validator.clean(user.email)
        except Exception as e:
            logging.error(e)
            continue

        subject = render_to_string(
            'pybb/mails/subscription_email_subject.html',
            dict(params, **{'user': user}))
        message = render_to_string('pybb/mails/subscription_email_body.html',
                                   dict(params, **{'user': user}))
        messages.append((''.join(subject.splitlines()), message,
                         settings.DEFAULT_FROM_EMAIL, [user.email]))

    if messages:
        result = send_mass_mail(messages, fail_silently=True)

        subscriptions.update(sent=True, updated=tznow())

        return result

    return False
Ejemplo n.º 11
0
    def mark_as_read(self, user, forums):
        forum_ids = [tracker[0]
                     for tracker in self.filter(user=user).values_list('forum_id')]

        trackers = []
        updated_ids = []

        for forum in forums:
            if forum.pk not in forum_ids:
                trackers.append(self.model(forum=forum, user=user))
            else:
                updated_ids.append(forum.pk)

        if len(trackers):
            trackers = self.bulk_create(trackers)

        if len(updated_ids):
            self.filter(forum__in=updated_ids, user=user).update(time_stamp=tznow())

        return trackers
Ejemplo n.º 12
0
    def save(self, *args, **kwargs):
        if self.id is None:
            self.created = tznow()

        super(BaseTopic, self).save(*args, **kwargs)
Ejemplo n.º 13
0
    def is_updatable(self):
        delta = (tznow() - self.created).seconds

        return delta > defaults.PYBB_UPDATE_MENTION_POST_DELTA
Ejemplo n.º 14
0
    def save(self, commit=True):
        if self.instance.pk:
            post = super(PostForm, self).save(commit=False)
            if self.user:
                post.user = self.user

            if self.actor and post.user_id == self.actor.pk:
                if post.is_updatable():
                    post.updated = tznow()

            if post.topic.head == post:
                topic = post.topic

                topic.name = self.cleaned_data['name']
                topic.updated = tznow()
                topic.save()

                if not defaults.PYBB_DISABLE_POLLS:
                    if self.cleaned_data['poll_type'] != Poll.TYPE_NONE:
                        poll = topic.poll or Poll()
                        poll.type = self.cleaned_data['poll_type']
                        poll.question = self.cleaned_data['poll_question']

                        is_new = poll.pk is None

                        poll.save()

                        if is_new:
                            topic.poll = poll
                            topic.save()
                    else:
                        if topic.poll:
                            topic.poll.answers.all().delete()
                            topic.poll = None
                            topic.save()

            post.save()

            return post

        allow_post = True

        if defaults.PYBB_PREMODERATION:
            allow_post = defaults.PYBB_PREMODERATION(self.user, self.cleaned_data['body'])

        if 'forum' in self.cleaned_data and not self._forum:
            self._forum = self.cleaned_data['forum']

        if self._forum:
            topic = Topic(
                forum=self._forum,
                user=self.user,
                name=self.cleaned_data['name'],
            )

            if not allow_post:
                topic.on_moderation = True
            topic.save()

            if not defaults.PYBB_DISABLE_POLLS:
                if 'poll_type' in self.cleaned_data and self.cleaned_data['poll_type'] != Poll.TYPE_NONE:
                    poll = Poll(
                        type=self.cleaned_data['poll_type'],
                        question=self.cleaned_data['poll_question']
                    )
                    poll.save()

                    topic.poll = poll
        else:
            topic = self._topic

        post = Post(topic=topic, user=self.user, user_ip=self.ip,
                    body=self.cleaned_data['body'], hash=self.cleaned_data['hash'])

        if not allow_post:
            post.on_moderation = True

        post.save()

        return post