Files
pyrom/app/routes/threads.py
2026-04-16 00:01:18 +03:00

57 lines
1.9 KiB
Python

from flask import Blueprint, redirect, url_for, render_template, request, abort
from ..auth import login_required, get_active_user
from ..models import Threads, Posts, Topics, Users, Reactions
import math
bp = Blueprint('threads', __name__, url_prefix='/threads/')
@bp.get('/<slug>')
def thread(slug):
thread = Threads.find({'slug': slug})
if not thread:
abort(404)
topic = Topics.find({'id': thread.topic_id})
started_by = Users.find({'id': thread.user_id})
PER_PAGE = 10
posts_count = Posts.count({'thread_id': thread.id})
page_count = max(1, math.ceil(posts_count / PER_PAGE))
page = 1
after = request.args.get('after', default=None)
if after is not None:
try:
after_id = int(after)
post_position = Posts.count([
('thread_id', '=', thread.id),
('id', '<=', after_id),
])
page = math.ceil((post_position) / PER_PAGE)
except ValueError:
abort(404)
else:
try:
page = max(1, min(int(request.args.get('page', default=1)), page_count))
except ValueError:
abort(404)
return render_template('threads/thread.html', thread=thread, posts=thread.get_posts(PER_PAGE, page), page=page, page_count=page_count, topic=topic, started_by=started_by, topics=Topics.get_list(), Reactions=Reactions)
@bp.post('/<slug>/reply')
@login_required
def reply(slug):
user = get_active_user()
thread = Threads.find({'slug': slug})
if not thread:
abort(404)
if thread.locked() and not user.is_mod():
# TODO: flash
return redirect(url_for('.thread', slug=slug))
post = Posts.new(user.id, thread.id, request.form.get('babycode_content'))
return redirect(url_for('.thread', slug=slug, after=post.id, _anchor=f'post-{post.id}'))
@bp.get('/<slug>/feed.atom')
def feed(slug):
return 'stub'
@bp.get('/new')
def new():
return 'stub'