diff --git a/app/models.py b/app/models.py
index 116f96c..666e687 100644
--- a/app/models.py
+++ b/app/models.py
@@ -239,6 +239,21 @@ class Threads(Model):
def stickied(self):
return bool(self.is_stickied)
+ @classmethod
+ def new(cls, user_id: int, topic_id: int, title: str, content: str, language: str = 'babycode') -> Threads:
+ from slugify import slugify
+ now = int(time.time())
+ slug = f'{slugify(title)}-{now}'
+ thread = Threads.create({
+ 'topic_id': topic_id,
+ 'user_id': user_id,
+ 'title': title.strip(),
+ 'slug': slug,
+ 'created_at': int(time.time()),
+ })
+ post = Posts.new(user_id, thread.id, content, language)
+ return thread
+
class Posts(Model):
FULL_POSTS_QUERY = """
WITH user_badges AS (
diff --git a/app/routes/threads.py b/app/routes/threads.py
index 1b7ae7f..c845a4b 100644
--- a/app/routes/threads.py
+++ b/app/routes/threads.py
@@ -16,7 +16,7 @@ def thread(slug):
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)
+ after = request.args.get('after')
if after is not None:
try:
after_id = int(after)
@@ -56,7 +56,37 @@ def feed(slug):
def new():
topics = Topics.select()
try:
- selected_topic = int(request.args.get('topic_id', default=None))
+ selected_topic = int(request.args.get('topic_id'))
except ValueError, TypeError:
selected_topic = None
return render_template('threads/new_thread.html', topics=topics, selected_topic=selected_topic)
+
+@bp.post('/new')
+@login_required
+def new_post():
+ try:
+ topic_id = int(request.form.get('topic_id'))
+ except ValueError, TypeError:
+ abort(404)
+ topic_id = int(topic_id)
+ topic = Topics.find({'id': topic_id})
+ if not topic:
+ abort(404)
+
+ user = get_active_user()
+ if not user.can_post_to_topic(topic):
+ abort(404)
+
+ title = request.form.get('title')
+ if not title:
+ abort(404)
+
+ if not title.strip():
+ abort(404)
+
+ title = title.strip()
+
+ content = request.form.get('babycode_content')
+
+ thread = Threads.new(user.id, topic.id, title, content)
+ return redirect(url_for('.thread', slug=thread.slug))
diff --git a/app/templates/threads/new_thread.html b/app/templates/threads/new_thread.html
index b61945f..e2110f7 100644
--- a/app/templates/threads/new_thread.html
+++ b/app/templates/threads/new_thread.html
@@ -7,7 +7,7 @@