コード例 #1
0
ファイル: posts.py プロジェクト: tibik/vas3k.club
def edit_post(request, post_slug):
    post = get_object_or_404(Post, slug=post_slug)
    if post.author != request.me and not request.me.is_moderator:
        raise AccessDenied()

    PostFormClass = POST_TYPE_MAP.get(post.type) or PostTextForm

    if request.method == "POST":
        form = PostFormClass(request.POST, request.FILES, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            if not post.author:
                post.author = request.me
            post.html = None  # flush cache
            post.save()

            SearchIndex.update_post_index(post)
            LinkedPost.create_links_from_text(post, post.text)

            if post.is_visible:
                return redirect("show_post", post.type, post.slug)
            else:
                return redirect("compose")
    else:
        form = PostFormClass(instance=post)

    return render(request, f"posts/compose/{post.type}.html", {
        "mode": "edit",
        "form": form
    })
コード例 #2
0
ファイル: posts.py プロジェクト: thelebster/vas3k.club
def create_or_edit(request, post_type, post=None, mode="create"):
    FormClass = POST_TYPE_MAP.get(post_type) or PostTextForm

    # show blank form on GET
    if request.method != "POST":
        form = FormClass(instance=post)
        return render(request, f"posts/compose/{post_type}.html", {
            "mode": mode,
            "post_type": post_type,
            "form": form,
        })

    # validate form on POST
    form = FormClass(request.POST, request.FILES, instance=post)
    if form.is_valid():
        if not request.me.is_moderator:
            if Post.check_duplicate(user=request.me,
                                    title=form.cleaned_data["title"],
                                    ignore_post_id=post.id if post else None):
                raise ContentDuplicated()

            is_ok = Post.check_rate_limits(request.me)
            if not is_ok:
                raise RateLimitException(
                    title="🙅‍♂️ Слишком много постов",
                    message=
                    "В последнее время вы создали слишком много постов. Потерпите, пожалуйста."
                )

        post = form.save(commit=False)
        if not post.author_id:
            post.author = request.me
        post.type = post_type
        post.html = None  # flush cache
        post.save()

        if mode == "create" or not post.is_visible:
            PostSubscription.subscribe(request.me,
                                       post,
                                       type=PostSubscription.TYPE_ALL_COMMENTS)

        if post.is_visible:
            if post.topic:
                post.topic.update_last_activity()

            SearchIndex.update_post_index(post)
            LinkedPost.create_links_from_text(post, post.text)

        action = request.POST.get("action")
        if action == "publish":
            post.publish()
            LinkedPost.create_links_from_text(post, post.text)

        return redirect("show_post", post.type, post.slug)

    return render(request, f"posts/compose/{post_type}.html", {
        "mode": mode,
        "post_type": post_type,
        "form": form,
    })
コード例 #3
0
def compose_type(request, post_type):
    if post_type not in dict(Post.TYPES):
        raise Http404()

    FormClass = POST_TYPE_MAP.get(post_type) or PostTextForm

    if request.method == "POST":
        form = FormClass(request.POST, request.FILES)
        if form.is_valid():

            if not request.me.is_moderator:
                if Post.check_duplicate(user=request.me,
                                        title=form.cleaned_data["title"]):
                    raise ContentDuplicated()

                is_ok = Post.check_rate_limits(request.me)
                if not is_ok:
                    raise RateLimitException(
                        title="🙅‍♂️ Слишком много постов",
                        message=
                        "В последнее время вы создали слишком много постов. Потерпите, пожалуйста."
                    )

            post = form.save(commit=False)
            post.author = request.me
            post.type = post_type
            post.save()

            PostSubscription.subscribe(request.me, post)

            if post.is_visible:
                if post.topic:
                    post.topic.update_last_activity()

                SearchIndex.update_post_index(post)
                LinkedPost.create_links_from_text(post, post.text)

            if post.is_visible or request.POST.get("show_preview"):
                return redirect("show_post", post.type, post.slug)
            else:
                return redirect("compose")
    else:
        form = FormClass()

    return render(request, f"posts/compose/{post_type}.html", {
        "mode": "create",
        "form": form
    })
コード例 #4
0
def continue_posting(update: Update, started_post: dict, user: User):
    if update.callback_query:
        if update.callback_query.data == "nope":
            # cancel posting
            cached_post_delete(update.effective_user.id)
            return "Ок, забыли 👌"

        elif update.callback_query.data in {"post", "link", "question"}:
            # ask for title
            started_post["type"] = update.callback_query.data
            cached_post_set(update.effective_user.id, started_post)
            return f"Отлично. Теперь надо придумать заголовок, чтобы всем было понятно о чем это. " \
                   f"Подумайте и пришлите его следующим сообщением 👇"

        elif update.callback_query.data == "go":
            # go-go-go, post the post
            FormClass = POST_TYPE_MAP.get(started_post["type"]) or PostTextForm

            form = FormClass(started_post)
            if not form.is_valid():
                return f"🤦‍♂️ Что-то пошло не так. Пришлите нам багрепорт. " \
                       f"Вот ошибка:\n```{str(form.errors)}```"

            if Post.check_duplicate(user=user,
                                    title=form.cleaned_data["title"]):
                return "🤔 Выглядит как дубликат вашего прошлого поста. " \
                       "Проверьте всё ли в порядке и пришлите ниже другой заголовок 👇"

            is_ok = Post.check_rate_limits(user)
            if not is_ok:
                return "🙅‍♂️ Извините, вы сегодня запостили слишком много постов. Попробуйте попозже"

            post = form.save(commit=False)
            post.author = user
            post.type = started_post["type"]
            post.meta = {"telegram": update.to_json()}
            post.save()

            post_url = settings.APP_HOST + reverse("show_post",
                                                   kwargs={
                                                       "post_type": post.type,
                                                       "post_slug": post.slug
                                                   })
            cached_post_delete(update.effective_user.id)
            return f"Запостили 🚀🚀🚀\n\n{post_url}"

    if update.message:
        started_post["title"] = str(update.message.text
                                    or update.message.caption
                                    or "").strip()[:128]
        if len(started_post["title"]) < 7:
            send_telegram_message(
                chat=Chat(id=update.effective_chat.id),
                text=f"Какой-то короткий заголовок. Пришлите другой, подлинее",
                reply_markup=telegram.InlineKeyboardMarkup([[
                    telegram.InlineKeyboardButton("❌ Отменить всё",
                                                  callback_data=f"nope"),
                ]]))
            return

        cached_post_set(update.effective_user.id, started_post)
        emoji = Post.TYPE_TO_EMOJI.get(started_post["type"]) or "🔥"
        send_telegram_message(
            chat=Chat(id=update.effective_chat.id),
            text=f"Заголовок принят. Теперь пост выглядит как-то так:\n\n"
            f"{emoji} <b>{started_post['title']}</b>\n\n"
            f"{started_post['text'] or ''}\n\n"
            f"{started_post['url'] or ''}\n\n"
            f"<b>Будем постить?</b> (после публикации его можно будет подредактировать на сайте)",
            reply_markup=telegram.InlineKeyboardMarkup([
                [
                    telegram.InlineKeyboardButton("✅ Поехали",
                                                  callback_data=f"go"),
                    telegram.InlineKeyboardButton("❌ Отмена",
                                                  callback_data=f"nope"),
                ],
            ]))