Esempio n. 1
0
    def find_mode(self, request, *args, **kwargs):
        """
        First step: guess from request what kind of view we are
        """
        is_submit = request.method == 'POST' and 'submit' in request.POST
        if is_submit:
            request.user.lock()

        forum = self.get_forum(request, lock=is_submit, **kwargs)

        thread = None
        post = None

        if 'thread_id' in kwargs:
            thread = self.get_thread(request,
                                     lock=is_submit,
                                     queryset=forum.thread_set,
                                     **kwargs)

        if thread:
            mode = REPLY
        else:
            mode = START
            thread = Thread(forum=forum)

        if not post:
            post = Post(forum=forum, thread=thread)

        return mode, forum, thread, post
Esempio n. 2
0
    def create(self, request):
        # Initialize empty instances for new thread
        thread = Thread()
        post = Post(thread=thread)
        tag = Tag(thread=thread)

        # Put them through posting pipeline
        posting = PostingEndpoint(
            request,
            PostingEndpoint.START,
            tree_name=THREADS_ROOT_NAME,
            thread=thread,
            post=post,
            tag=tag,
        )

        if posting.is_valid():
            posting.save()

            return Response({
                'id': thread.pk,
                'title': thread.title,
                'url': thread.get_absolute_url(),
            })
        else:
            return Response(posting.errors, status=400)
Esempio n. 3
0
def split_posts_to_new_thread(request, thread, validated_data):
    new_thread = Thread(
        category=validated_data['category'],
        started_on=thread.started_on,
        last_post_on=thread.last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    for post in validated_data['posts']:
        post.move(new_thread)
        post.save()

    thread.synchronize()
    thread.save()

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    thread.category.synchronize()
    thread.category.save()

    if new_thread.category != thread.category:
        new_thread.category.synchronize()
        new_thread.category.save()
Esempio n. 4
0
    def create(self, request):
        allow_use_private_threads(request.user)
        if not request.user.acl_cache['can_start_private_threads']:
            raise PermissionDenied(_("You can't start private threads."))

        request.user.lock()

        # Initialize empty instances for new thread
        thread = Thread()
        post = Post(thread=thread)

        # Put them through posting pipeline
        posting = PostingEndpoint(
            request,
            PostingEndpoint.START,
            tree_name=PRIVATE_THREADS_ROOT_NAME,
            thread=thread,
            post=post,
        )

        if posting.is_valid():
            posting.save()

            return Response({
                'id': thread.pk,
                'title': thread.title,
                'url': thread.get_absolute_url(),
            })
        else:
            return Response(posting.errors, status=400)
Esempio n. 5
0
    def setUp(self):
        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(forum=self.forum,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(forum=self.forum,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()
Esempio n. 6
0
    def setUp(self):
        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()

        post = Post.objects.create(category=self.category,
                                   thread=self.thread,
                                   poster_name='Tester',
                                   poster_ip='127.0.0.1',
                                   original="Hello! I am test message!",
                                   parsed="<p>Hello! I am test message!</p>",
                                   checksum="nope",
                                   posted_on=datetime,
                                   updated_on=datetime)

        self.thread.first_post = post
        self.thread.last_post = post
        self.thread.save()
Esempio n. 7
0
    def action_merge(self, request, threads):
        if len(threads) == 1:
            message = _("You have to select at least two threads to merge.")
            raise moderation.ModerationError(message)

        form = MergeThreadsForm()

        if 'submit' in request.POST:
            form = MergeThreadsForm(request.POST)
            if form.is_valid():
                with atomic():
                    merged_thread = Thread()
                    merged_thread.forum = self.forum
                    merged_thread.set_title(
                        form.cleaned_data['merged_thread_title'])
                    merged_thread.starter_name = "-"
                    merged_thread.starter_slug = "-"
                    merged_thread.last_poster_name = "-"
                    merged_thread.last_poster_slug = "-"
                    merged_thread.started_on = timezone.now()
                    merged_thread.last_post_on = timezone.now()
                    merged_thread.is_pinned = max(t.is_pinned for t in threads)
                    merged_thread.is_closed = max(t.is_closed for t in threads)
                    merged_thread.save()

                    for thread in threads:
                        moderation.merge_thread(
                            request.user, merged_thread, thread)

                    merged_thread.synchronize()
                    merged_thread.save()

                    self.forum.lock()
                    self.forum.synchronize()
                    self.forum.save()

                changed_threads = len(threads)
                message = ungettext(
                    '%(changed)d thread was merged into "%(thread)s".',
                    '%(changed)d threads were merged into "%(thread)s".',
                changed_threads)
                messages.success(request, message % {
                    'changed': changed_threads,
                    'thread': merged_thread.title
                })

                return None # trigger threads list refresh

        if request.is_ajax():
            template = self.merge_threads_modal_template
        else:
            template = self.merge_threads_full_template

        return render(request, template, {
            'form': form,
            'forum': self.forum,
            'path': get_forum_path(self.forum),
            'threads': threads
        })
Esempio n. 8
0
def merge_threads(request, validated_data, threads, poll):
    new_thread = Thread(category=validated_data['category'],
                        started_on=threads[0].started_on,
                        last_post_on=threads[0].last_post_on)

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(request,
                     new_thread,
                     'merged', {
                         'merged_thread': thread.title,
                     },
                     commit=False)

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    # add top category to thread
    if validated_data.get('top_category'):
        categories = list(Category.objects.all_categories().filter(
            id__in=request.user.acl['visible_categories']))
        add_categories_to_items(validated_data['top_category'], categories,
                                [new_thread])
    else:
        new_thread.top_category = None

    add_acl(request.user, new_thread)
    return new_thread
Esempio n. 9
0
def merge_threads(request, validated_data, threads, poll):
    new_thread = Thread(
        category=validated_data['category'],
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(
            request,
            new_thread,
            'merged',
            {
                'merged_thread': thread.title,
            },
            commit=False,
        )

    new_thread.synchronize()
    new_thread.save()

    if validated_data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif validated_data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if validated_data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if validated_data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    add_acl(request.user, new_thread)
    return new_thread
Esempio n. 10
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(category=self.category,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()
Esempio n. 11
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.forum = Forum.objects.filter(role="forum")[:1][0]
        self.thread = Thread(forum=self.forum,
                             started_on=datetime,
                             starter_name='Tester',
                             starter_slug='tester',
                             last_post_on=datetime,
                             last_poster_name='Tester',
                             last_poster_slug='tester')

        self.thread.set_title("Test thread")
        self.thread.save()
Esempio n. 12
0
def merge_threads(user, validated_data, threads):
    new_thread = Thread(
        category=validated_data['category'],
        weight=validated_data.get('weight', 0),
        is_closed=validated_data.get('is_closed', False),
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(validated_data['title'])
    new_thread.save()

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

    new_thread.synchronize()
    new_thread.save()

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    # add top category to thread
    if validated_data.get('top_category'):
        categories = list(Category.objects.all_categories().filter(
            id__in=user.acl['visible_categories']))
        add_categories_to_threads(validated_data['top_category'], categories,
                                  [new_thread])
    else:
        new_thread.top_category = None

    new_thread.save()

    add_acl(user, new_thread)
    return new_thread
Esempio n. 13
0
    def test_merge(self):
        """merge(other_thread) moves other thread content to this thread"""
        with self.assertRaises(ValueError):
            self.thread.merge(self.thread)

        datetime = timezone.now() + timedelta(5)

        other_thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester',
        )

        other_thread.set_title("Other thread")
        other_thread.save()

        post = Post.objects.create(
            category=self.category,
            thread=other_thread,
            poster_name='Admin',
            poster_ip='127.0.0.1',
            original="Hello! I am other message!",
            parsed="<p>Hello! I am other message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime,
        )

        other_thread.first_post = post
        other_thread.last_post = post
        other_thread.save()

        self.thread.merge(other_thread)

        self.thread.synchronize()
        self.assertEqual(self.thread.replies, 1)
        self.assertEqual(self.thread.last_post, post)
        self.assertEqual(self.thread.last_post_on, post.posted_on)
        self.assertEqual(self.thread.last_poster_name, "Admin")
        self.assertEqual(self.thread.last_poster_slug, "admin")
Esempio n. 14
0
    def find_mode(self, request, *args, **kwargs):
        """
        First step: guess from request what kind of view we are
        """
        is_post = request.method == 'POST'

        if 'forum_id' in kwargs:
            mode = START
            user = request.user

            forum = self.get_forum(request, lock=is_post, **kwargs)
            thread = Thread(forum=forum)
            post = Post(forum=forum, thread=thread)
            quote = Post(0)
        elif 'thread_id' in kwargs:
            thread = self.get_thread(request, lock=is_post, **kwargs)
            forum = thread.forum

        return mode, forum, thread, post, quote
Esempio n. 15
0
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user("Bob", "*****@*****.**", "Pass.123")

        datetime = timezone.now()

        self.category = Category.objects.all_categories()[:1][0]
        self.thread = Thread(
            category=self.category,
            started_on=datetime,
            starter_name='Tester',
            starter_slug='tester',
            last_post_on=datetime,
            last_poster_name='Tester',
            last_poster_slug='tester'
        )

        self.thread.set_title("Test thread")
        self.thread.save()

        self.post = Post.objects.create(
            category=self.category,
            thread=self.thread,
            poster=self.user,
            poster_name=self.user.username,
            poster_ip='127.0.0.1',
            original="Hello! I am test message!",
            parsed="<p>Hello! I am test message!</p>",
            checksum="nope",
            posted_on=datetime,
            updated_on=datetime
        )

        update_post_checksum(self.post)
        self.post.save(update_fields=['checksum'])

        self.thread.first_post = self.post
        self.thread.last_post = self.post
        self.thread.save()
Esempio n. 16
0
def threads_merge_endpoint(request):
    serializer = MergeThreadsSerializer(
        data=request.data,
        context={'user': request.user},
    )

    serializer.is_valid(raise_exception=True)

    threads = serializer.validated_data['threads']

    data = serializer.validated_data
    threads = data['threads']

    new_thread = Thread(
        category=data['category'],
        started_on=threads[0].started_on,
        last_post_on=threads[0].last_post_on,
    )

    new_thread.set_title(data['title'])
    new_thread.save()

    # handle merge conflict
    best_answer = data.get('best_answer')
    if best_answer:
        new_thread.best_answer_id = best_answer.best_answer_id
        new_thread.best_answer_is_protected = best_answer.best_answer_is_protected
        new_thread.best_answer_marked_on = best_answer.best_answer_marked_on
        new_thread.best_answer_marked_by_id = best_answer.best_answer_marked_by_id
        new_thread.best_answer_marked_by_name = best_answer.best_answer_marked_by_name
        new_thread.best_answer_marked_by_slug = best_answer.best_answer_marked_by_slug

    poll = data.get('poll')
    if poll:
        poll.move(new_thread)

    categories = []
    for thread in threads:
        categories.append(thread.category)
        new_thread.merge(thread)
        thread.delete()

        record_event(
            request,
            new_thread,
            'merged',
            {'merged_thread': thread.title},
            commit=False,
        )

    new_thread.synchronize()
    new_thread.save()

    if data.get('weight') == Thread.WEIGHT_GLOBAL:
        moderation.pin_thread_globally(request, new_thread)
    elif data.get('weight'):
        moderation.pin_thread_locally(request, new_thread)
    if data.get('is_hidden', False):
        moderation.hide_thread(request, new_thread)
    if data.get('is_closed', False):
        moderation.close_thread(request, new_thread)

    if new_thread.category not in categories:
        categories.append(new_thread.category)

    for category in categories:
        category.synchronize()
        category.save()

    # set extra attrs on thread for UI
    new_thread.is_read = False
    new_thread.subscription = None

    add_acl(request.user, new_thread)

    return Response(ThreadsListSerializer(new_thread).data)
Esempio n. 17
0
    def handle(self, *args, **options):
        items_to_create = options['threads']

        categories = list(Category.objects.all_categories())

        fake = Factory.create()

        User = get_user_model()
        total_users = User.objects.count()

        self.stdout.write('Creating fake threads...\n')

        message = '\nSuccessfully created %s fake threads in %s'

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, items_to_create)

        while created_threads < items_to_create:
            with atomic():
                datetime = timezone.now()
                category = random.choice(categories)
                user = User.objects.order_by('?')[:1][0]

                thread_is_unapproved = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(
                    category=category,
                    started_on=datetime,
                    starter_name='-',
                    starter_slug='-',
                    last_post_on=datetime,
                    last_poster_name='-',
                    last_poster_slug='-',
                    replies=0,
                    is_unapproved=thread_is_unapproved,
                    is_hidden=thread_is_hidden,
                    is_closed=thread_is_closed
                )
                thread.set_title(fake.sentence())
                thread.save()

                fake_message = "\n\n".join(fake.paragraphs())
                post = Post.objects.create(
                    category=category,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    poster_ip=fake.ipv4(),
                    original=fake_message,
                    parsed=linebreaks_filter(fake_message),
                    posted_on=datetime,
                    updated_on=datetime
                )
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                user.threads += 1
                user.posts += 1
                user.save()

                thread_type = random.randint(0, 100)
                if thread_type > 95:
                    thread_replies = random.randint(200, 2500)
                elif thread_type > 50:
                    thread_replies = random.randint(5, 30)
                else:
                    thread_replies = random.randint(0, 10)

                for x in range(thread_replies):
                    datetime = timezone.now()
                    user = User.objects.order_by('?')[:1][0]
                    fake_message = "\n\n".join(fake.paragraphs())

                    is_unapproved = random.randint(0, 100) > 97
                    if not is_unapproved:
                        is_hidden = random.randint(0, 100) > 97
                    else:
                        is_hidden = False

                    post = Post.objects.create(
                        category=category,
                        thread=thread,
                        poster=user,
                        poster_name=user.username,
                        poster_ip=fake.ipv4(),
                        original=fake_message,
                        parsed=linebreaks_filter(fake_message),
                        is_hidden=is_hidden,
                        is_unapproved=is_unapproved,
                        posted_on=datetime,
                        updated_on=datetime
                    )
                    update_post_checksum(post)
                    post.save(update_fields=['checksum'])

                    user.posts += 1
                    user.save()

                thread.synchronize()
                thread.save()

                created_threads += 1
                show_progress(
                    self, created_threads, items_to_create, start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        for i in range(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            if random.randint(0, 100) > 75:
                thread.weight = 2
            else:
                thread.weight = 1
            thread.save()

        for category in categories:
            category.synchronize()
            category.save()

        total_time = time.time() - start_time
        total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
        self.stdout.write(message % (created_threads, total_humanized))
Esempio n. 18
0
    def action_split(self, request, posts):
        if posts[0].id == self.thread.first_post_id:
            message = _("You can't split thread's first post.")
            raise moderation.ModerationError(message)

        form = SplitThreadForm(acl=request.user.acl)

        if 'submit' in request.POST or 'follow' in request.POST:
            form = SplitThreadForm(request.POST, acl=request.user.acl)
            if form.is_valid():
                split_thread = Thread()
                split_thread.forum = form.cleaned_data['forum']
                split_thread.set_title(
                    form.cleaned_data['thread_title'])
                split_thread.starter_name = "-"
                split_thread.starter_slug = "-"
                split_thread.last_poster_name = "-"
                split_thread.last_poster_slug = "-"
                split_thread.started_on = timezone.now()
                split_thread.last_post_on = timezone.now()
                split_thread.save()

                for post in posts:
                    post.move(split_thread)
                    post.save()

                split_thread.synchronize()
                split_thread.save()

                if split_thread.forum != self.forum:
                    split_thread.forum.lock()
                    split_thread.forum.synchronize()
                    split_thread.forum.save()

                changed_posts = len(posts)
                message = ungettext(
                    '%(changed)d post was split to "%(thread)s".',
                    '%(changed)d posts were split to "%(thread)s".',
                changed_posts)
                messages.success(request, message % {
                    'changed': changed_posts,
                    'thread': split_thread.title
                })

                if 'follow' in request.POST:
                    return redirect(split_thread.get_absolute_url())
                else:
                    return None # trigger thread refresh

        if request.is_ajax():
            template = self.split_thread_modal_template
        else:
            template = self.split_thread_full_template

        return render(request, template, {
            'form': form,
            'forum': self.forum,
            'thread': self.thread,
            'path': get_forum_path(self.forum),

            'posts': posts
        })
Esempio n. 19
0
    def handle(self, *args, **options):
        try:
            fake_threads_to_create = int(args[0])
        except IndexError:
            fake_threads_to_create = 5
        except ValueError:
            self.stderr.write("\nOptional argument should be integer.")
            sys.exit(1)

        forums = [f for f in Forum.objects.all_forums().filter(role='forum')]

        fake = Factory.create()

        User = get_user_model()
        total_users = User.objects.count()

        self.stdout.write('Creating fake threads...\n')

        message = '\nSuccessfully created %s fake threads'

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, fake_threads_to_create)
        for i in xrange(fake_threads_to_create):
            with atomic():
                datetime = timezone.now()
                forum = random.choice(forums)
                user = User.objects.order_by('?')[:1][0]

                thread_is_moderated = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(forum=forum,
                                started_on=datetime,
                                starter_name='-',
                                starter_slug='-',
                                last_post_on=datetime,
                                last_poster_name='-',
                                last_poster_slug='-',
                                replies=0,
                                is_moderated=thread_is_moderated,
                                is_hidden=thread_is_hidden,
                                is_closed=thread_is_closed)
                thread.set_title(fake.sentence())
                thread.save()

                fake_message = "\n\n".join(fake.paragraphs())
                post = Post.objects.create(
                    forum=forum,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    poster_ip=fake.ipv4(),
                    original=fake_message,
                    parsed=linebreaks_filter(fake_message),
                    posted_on=datetime,
                    updated_on=datetime)
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                user.threads += 1
                user.posts += 1
                user.save()

                thread_type = random.randint(0, 100)
                if thread_type > 95:
                    thread_replies = random.randint(200, 500)
                elif thread_type > 50:
                    thread_replies = random.randint(5, 30)
                else:
                    thread_replies = random.randint(0, 10)

                for x in xrange(thread_replies):
                    datetime = timezone.now()
                    user = User.objects.order_by('?')[:1][0]
                    fake_message = "\n\n".join(fake.paragraphs())

                    is_moderated = random.randint(0, 100) > 97
                    if not is_moderated:
                        is_hidden = random.randint(0, 100) > 97
                    else:
                        is_hidden = False

                    post = Post.objects.create(
                        forum=forum,
                        thread=thread,
                        poster=user,
                        poster_name=user.username,
                        poster_ip=fake.ipv4(),
                        original=fake_message,
                        parsed=linebreaks_filter(fake_message),
                        is_hidden=is_hidden,
                        is_moderated=is_moderated,
                        posted_on=datetime,
                        updated_on=datetime)
                    update_post_checksum(post)
                    post.save(update_fields=['checksum'])

                    user.posts += 1
                    user.save()

                thread.synchronize()
                thread.save()

                created_threads += 1
                show_progress(self, created_threads, fake_threads_to_create,
                              start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        for i in xrange(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            thread.is_pinned = True
            thread.save()

        for forum in forums:
            forum.synchronize()
            forum.save()

        self.stdout.write(message % created_threads)
Esempio n. 20
0
    def handle(self, *args, **options):
        items_to_create = options['threads']

        categories = list(Category.objects.all_categories())

        fake = Factory.create()

        message = 'Creating %s fake threads...\n'
        self.stdout.write(message % items_to_create)

        created_threads = 0
        start_time = time.time()
        show_progress(self, created_threads, items_to_create)

        while created_threads < items_to_create:
            with atomic():
                datetime = timezone.now()
                category = random.choice(categories)
                user = UserModel.objects.order_by('?')[:1][0]

                thread_is_unapproved = random.randint(0, 100) > 90
                thread_is_hidden = random.randint(0, 100) > 90
                thread_is_closed = random.randint(0, 100) > 90

                thread = Thread(
                    category=category,
                    started_on=datetime,
                    starter_name='-',
                    starter_slug='-',
                    last_post_on=datetime,
                    last_poster_name='-',
                    last_poster_slug='-',
                    replies=0,
                    is_unapproved=thread_is_unapproved,
                    is_hidden=thread_is_hidden,
                    is_closed=thread_is_closed,
                )
                thread.set_title(corpus_short.random_choice())
                thread.save()

                original, parsed = self.fake_post_content()

                post = Post.objects.create(
                    category=category,
                    thread=thread,
                    poster=user,
                    poster_name=user.username,
                    original=original,
                    parsed=parsed,
                    posted_on=datetime,
                    updated_on=datetime,
                )
                update_post_checksum(post)
                post.save(update_fields=['checksum'])

                thread.set_first_post(post)
                thread.set_last_post(post)
                thread.save()

                user.threads += 1
                user.posts += 1
                user.save()

                thread_type = random.randint(0, 100)
                if thread_type > 98:
                    thread_replies = random.randint(200, 2500)
                elif thread_type > 50:
                    thread_replies = random.randint(5, 30)
                else:
                    thread_replies = random.randint(0, 10)

                for _ in range(thread_replies):
                    datetime = timezone.now()
                    user = UserModel.objects.order_by('?')[:1][0]

                    original, parsed = self.fake_post_content()

                    is_unapproved = random.randint(0, 100) > 97

                    post = Post.objects.create(
                        category=category,
                        thread=thread,
                        poster=user,
                        poster_name=user.username,
                        original=original,
                        parsed=parsed,
                        is_unapproved=is_unapproved,
                        posted_on=datetime,
                        updated_on=datetime,
                    )

                    if not is_unapproved:
                        is_hidden = random.randint(0, 100) > 97
                    else:
                        is_hidden = False

                    if is_hidden:
                        post.is_hidden = True

                        if random.randint(0, 100) < 80:
                            user = UserModel.objects.order_by('?')[:1][0]
                            post.hidden_by = user
                            post.hidden_by_name = user.username
                            post.hidden_by_slug = user.username
                        else:
                            post.hidden_by_name = fake.first_name()
                            post.hidden_by_slug = post.hidden_by_name.lower()

                    update_post_checksum(post)
                    post.save()

                    user.posts += 1
                    user.save()

                thread.synchronize()
                thread.save()

                created_threads += 1
                show_progress(self, created_threads, items_to_create, start_time)

        pinned_threads = random.randint(0, int(created_threads * 0.025)) or 1
        self.stdout.write('\nPinning %s threads...' % pinned_threads)
        
        for _ in range(0, pinned_threads):
            thread = Thread.objects.order_by('?')[:1][0]
            if random.randint(0, 100) > 75:
                thread.weight = 2
            else:
                thread.weight = 1
            thread.save()

        for category in categories:
            category.synchronize()
            category.save()

        total_time = time.time() - start_time
        total_humanized = time.strftime('%H:%M:%S', time.gmtime(total_time))
        message = '\nSuccessfully created %s fake threads in %s'
        self.stdout.write(message % (created_threads, total_humanized))