#!./venv/bin/python3
import bleach
import bottle
import configparser
import functools
import importlib
import json
import markdown
import timeago
import urllib3
import yaml
from datetime import datetime, timezone
from bottle import abort, get, jinja2_template as template, post, redirect, request, response, static_file
from urllib.parse import urlparse
# This is used to export the bottle object for a WSGI server
# See passenger_wsgi.py
application = bottle.app ()
# Load user settings for this app
with open ('settings.yaml', encoding='UTF-8') as file:
settings = yaml.load (file)
# Directories to search for app templates
bottle.TEMPLATE_PATH = [ './freepost/templates' ]
# Custom settings and functions for templates
template = functools.partial (
template,
template_settings = {
'filters': {
'ago': lambda date: timeago.format (date),
'datetime': lambda date: date.strftime ('%b %-d, %Y - %H:%M%p%z%Z'),
'title': lambda date: date.strftime ('%b %-d, %Y - %H:%M%z%Z'),
# Convert markdown to html
'md2html': lambda text: bleach.clean (markdown.markdown (
text,
# https://python-markdown.github.io/extensions/
extensions=[ 'extra', 'admonition', 'nl2br', 'smarty' ],
output_format='html5')),
# Get the domain part of a URL
'netloc': lambda url: urlparse (url).netloc
},
'globals': {
'new_messages': lambda user_id: database.count_unread_messages (user_id),
'now': lambda: datetime.now (timezone.utc),
'url': application.get_url,
'session_user': lambda: session.user ()
},
'autoescape': True
})
# "bleach" library is used to sanitize the HTML output of jinja2's "md2html"
# filter. The library has only a very restrictive list of white-listed
# tags, so we add some more here.
bleach.sanitizer.ALLOWED_TAGS += [ 'p', 'pre', 'img' ]
bleach.sanitizer.ALLOWED_ATTRIBUTES.update ({
'img': [ 'src' ]
})
from freepost import database, session
# Decorator.
# Make sure user is logged in
def requires_login (controller):
def wrapper ():
session_token = request.get_cookie (
key = settings['session']['name'],
secret = settings['cookies']['secret'])
if database.is_valid_session (session_token):
return controller ()
else:
redirect (application.get_url ('login'))
return wrapper
# Decorator.
# Make sure user is logged out
def requires_logout (controller):
def wrapper ():
session_token = request.get_cookie (
key = settings['session']['name'],
secret = settings['cookies']['secret'])
if database.is_valid_session (session_token):
redirect (application.get_url ('user'))
else:
return controller ()
return wrapper
# Routes
@get ('/', name='homepage')
def homepage ():
# Page number
page = int (request.query.page or 0)
if page < 0:
redirect (application.get_url ('homepage'))
user = session.user ()
posts = database.get_hot_posts (page, user['id'] if user else None)
return template (
'homepage.html',
page_number=page,
posts=posts,
sorting='hot')
@get ('/new', name='new')
def new ():
# Page number
page = int (request.query.page or 0)
if page < 0:
redirect (application.get_url ('homepage'))
user = session.user ()
posts = database.get_new_posts (page, user['id'] if user else None)
return template (
'homepage.html',
page_number=page,
posts=posts,
sorting='new')
@get ('/about', name='about')
def about ():
return template ('about.html')
@get ('/login', name='login')
@requires_logout
def login ():
return template ('login.html')
@post ('/login')
@requires_logout
def login_check ():
username = request.forms.get ('username')
password = request.forms.get ('password')
remember = 'remember' in request.forms
if not username or not password:
return template (
'login.html',
flash = 'Bad login!')
# Check if user exists
user = database.check_user_credentials (username, password)
# Username/Password not working
if not user:
return template (
'login.html',
flash = 'Bad login!')
session.start (user['id'], remember)
redirect (application.get_url ('homepage'))
@get ('/register', name='register')
@requires_logout
def register ():
return template ('register.html')
@post ('/register')
@requires_logout
def register_new_account ():
username = request.forms.get ('username')
password = request.forms.get ('password')
# Normalize username
username = username.strip ()
if len (username) == 0 or database.username_exists (username):
return template (
'register.html',
flash='Name taken, please choose another.')
# Password too short?
if len (password) < 8:
return template (
'register.html',
flash = 'Password too short')
# Username OK, Password OK: create new user
database.new_user (username, password)
# Retrieve user (check if it was created)
user = database.check_user_credentials (username, password)
# Something bad happened...
if user is None:
return template (
'register.html',
flash = 'An error has occurred, please try again.')
# Start session...
session.start (user['id'])
# ... and go to the homepage of the new user
redirect (application.get_url ('user'))
@get ('/logout', name='logout')
@requires_login
def logout ():
session.close ()
redirect (application.get_url ('homepage'))
@get ('/user', name='user')
@requires_login
def user_private_homepage ():
return template ('user_private_homepage.html')
@post ('/user')
@requires_login
def update_user ():
user = session.user ()
about = request.forms.get ('about')
email = request.forms.get ('email')
if about is None or email is None:
redirect (application.get_url ('user'))
database.update_user (user['id'], about, email, False)
redirect (application.get_url ('user'))
@get ('/user_activity/posts')
@requires_login
def user_posts ():
user = session.user ()
posts = database.get_user_posts (user['id'])
return template ('user_posts.html', posts=posts)
@get ('/user_activity/comments')
@requires_login
def user_comments ():
user = session.user ()
comments = database.get_user_comments (user['id'])
return template ('user_comments.html', comments=comments)
@get ('/user_activity/replies')
@requires_login
def user_replies ():
user = session.user ()
replies = database.get_user_replies (user['id'])
database.set_replies_as_read (user['id'])
return template ('user_replies.html', replies=replies)
@get ('/user/<username>', name='user_public')
def user_public_homepage (username):
account = database.get_user_by_username (username)
if account is None:
redirect (application.get_url ('user'))
return template ('user_public_homepage.html', account=account)
@get ('/post/<hash_id>', name='post')
def post_thread (hash_id):
user = session.user ()
post = database.get_post (hash_id, user['id'] if user else None)
comments = database.get_post_comments (post['id'], user['id'] if user else None)
# Group comments by parent
comments_tree = {}
for comment in comments:
if comment['parentId'] is None:
if 0 not in comments_tree:
comments_tree[0] = []
comments_tree[0].append (comment)
else:
if comment['parentId'] not in comments_tree:
comments_tree[comment['parentId']] = []
comments_tree[comment['parentId']].append (comment)
# Build ordered list of comments (recourse tree)
def children (parent_id = 0, depth = 0):
temp_comments = []
if parent_id in comments_tree:
for comment in comments_tree[parent_id]:
comment['depth'] = depth
temp_comments.append (comment)
temp_comments.extend (children (comment['id'], depth + 1))
return temp_comments
comments = children ()
return template (
'post.html',
post=post,
comments=comments,
votes = {
'post': {},
'comment': {}
})
@requires_login
@post ('/post/<hash_id>')
def new_comment (hash_id):
user = session.user ()
# The comment text
comment = request.forms.get ('new_comment').strip ()
# Empty comment
if len (comment) == 0:
redirect (application.get_url ('post', hash_id=hash_id))
comment_hash_id = database.new_comment (comment, hash_id, user['id'])
# Retrieve new comment
comment = database.get_comment (comment_hash_id)
# Automatically add an upvote for the original poster
database.vote_comment (comment['id'], user['id'], +1)
redirect (application.get_url ('post', hash_id=hash_id))
@requires_login
@get ('/edit/post/<hash_id>', name='edit_post')
def edit_post (hash_id):
user = session.user ()
post = database.get_post (hash_id, user['id'])
# Make sure the session user is the actual poster/commenter
if post['userId'] != user['id']:
redirect (application.get_url ('post', hash_id=hash_id))
return template ('edit_post.html', post=post)
@requires_login
@post ('/edit/post/<hash_id>')
def edit_post_check (hash_id):
user = session.user ()
post = database.get_post (hash_id, user['id'])
# Make sure the session user is the actual poster/commenter
if post['userId'] != user['id']:
redirect (application.get_url ('homepage'))
# MUST have a title. If empty, use original title
title = request.forms.get ('title').strip ()
if len (title) == 0: title = post['title']
link = request.forms.get ('link').strip () if 'link' in request.forms else ''
text = request.forms.get ('text').strip () if 'text' in request.forms else ''
# If there is a URL, make sure it has a "scheme"
if len (link) > 0 and urlparse (link).scheme == '':
link = 'http://' + link
# Update post
database.update_post (title, link, text, hash_id, user['id'])
redirect (application.get_url ('post', hash_id=hash_id))
@requires_login
@get ('/edit/comment/<hash_id>', name='edit_comment')
def edit_comment (hash_id):
user = session.user ()
comment = database.get_comment (hash_id, user['id'])
# Make sure the session user is the actual poster/commenter
if comment['userId'] != user['id']:
redirect (application.get_url ('post', hash_id=comment['postHashId']))
return template ('edit_comment.html', comment=comment)
@requires_login
@post ('/edit/comment/<hash_id>')
def edit_comment_check (hash_id):
user = session.user ()
comment = database.get_comment (hash_id, user['id'])
# Make sure the session user is the actual poster/commenter
if comment['userId'] != user['id']:
redirect (application.get_url ('homepage'))
text = request.forms.get ('text').strip () if 'text' in request.forms else ''
# Only update if the text is not empty
if len (text) > 0:
database.update_comment (text, hash_id, user['id'])
redirect (application.get_url ('post', hash_id=comment['postHashId']) + '#comment-' + hash_id)
@get ('/submit')
@requires_login
def submit ():
return template ('submit.html')
@post ('/submit')
@requires_login
def submit_check ():
# Somebody sent a <form> without a title???
if 'title' not in request.forms or \
'link' not in request.forms or \
'text' not in request.forms:
abort ()
user = session.user ()
# Retrieve title
title = request.forms.get ('title').strip ()
# Bad title?
if len (title) == 0:
return template ('submit.html', flash='Title is missing.')
# Retrieve link
link = request.forms.get ('link').strip ()
# If there is a URL, make sure it has a "scheme"
if len (link) > 0 and urlparse (link).scheme == '':
link = 'http://' + link
# Retrieve text
text = request.forms.get ('text')
# Add the new post
post_hash_id = database.new_post (title, link, text, user['id'])
# Retrieve new post
post = database.get_post (post_hash_id)
# Automatically add an upvote for the original poster
database.vote_post (post['id'], user['id'], +1)
# Posted. Now go the new post's page
redirect (application.get_url ('post', hash_id=post_hash_id))
@requires_login
@get ('/reply/<hash_id>', name='reply')
def reply (hash_id):
user = session.user ()
# The comment to reply to
comment = database.get_comment (hash_id)
# Does the comment exist?
if not comment:
redirect (application.get_url ('homepage'))
return template ('reply.html', comment=comment)
@requires_login
@post ('/reply/<hash_id>')
def reply_check (hash_id):
user = session.user ()
# The comment to reply to
comment = database.get_comment (hash_id)
# The text of the reply
text = request.forms.get ('text').strip ()
# Empty comment. Redirect to parent post
if len (text) == 0:
redirect (application.get_url ('post', hash_id=comment['postHashId']))
# We have a text, add the reply and redirect to the new reply
reply_hash_id = database.new_comment (text, comment['postHashId'], user['id'], comment['id'])
# TODO upvote comment
# TODO Increase comments count for post
redirect (application.get_url ('post', hash_id=comment['postHashId']) + '#comment-' + reply_hash_id)
@requires_login
@post ('/vote', name='vote')
def vote ():
user = session.user ()
# Vote a post
if request.forms.get ('target') == 'post':
# Retrieve the post
post = database.get_post (request.forms.get ('post'), user['id'])
if not post:
return
# If user clicked the "upvote" button...
if request.forms.get ('updown') == 'up':
# If user has upvoted this post before...
if post['user_vote'] == 1:
# Remove +1
database.vote_post (post['id'], user['id'], -1)
# If user has downvoted this post before...
elif post['user_vote'] == -1:
# Change vote from -1 to +1
database.vote_post (post['id'], user['id'], +2)
# If user hasn't voted this post...
else:
# Add +1
database.vote_post (post['id'], user['id'], +1)
# If user clicked the "downvote" button...
if request.forms.get ('updown') == 'down':
# If user has downvoted this post before...
if post['user_vote'] == -1:
# Remove -1
database.vote_post (post['id'], user['id'], +1)
# If user has upvoted this post before...
elif post['user_vote'] == 1:
# Change vote from +1 to -1
database.vote_post (post['id'], user['id'], -2)
# If user hasn't voted this post...
else:
# Add -1
database.vote_post (post['id'], user['id'], -1)
# Vote a comment
if request.forms.get ('target') == 'comment':
# Retrieve the comment
comment = database.get_comment (request.forms.get ('comment'), user['id'])
if not comment:
return
# If user clicked the "upvote" button...
if request.forms.get ('updown') == 'up':
# If user has upvoted this comment before...
if comment['user_vote'] == 1:
# Remove +1
database.vote_comment (comment['id'], user['id'], -1)
# If user has downvoted this comment before...
elif comment['user_vote'] == -1:
# Change vote from -1 to +1
database.vote_comment (comment['id'], user['id'], +2)
# If user hasn't voted this comment...
else:
# Add +1
database.vote_comment (comment['id'], user['id'], +1)
# If user clicked the "downvote" button...
if request.forms.get ('updown') == 'down':
# If user has downvoted this comment before...
if comment['user_vote'] == -1:
# Remove -1
database.vote_comment (comment['id'], user['id'], +1)
# If user has upvoted this comment before...
elif comment['user_vote'] == 1:
# Change vote from +1 to -1
database.vote_comment (comment['id'], user['id'], -2)
# If user hasn't voted this comment...
else:
# Add -1
database.vote_comment (comment['id'], user['id'], -1)
@get ('/search')
def search ():
# Get the search query
query = request.query.get ('q')
# Results order
order = request.query.get ('order')
if order not in [ 'newest', 'points' ]:
order = 'newest'
results = database.search (query, order=order)
if not results:
results = []
return template ('search.html', results=results, query=query, order=order)
@get ('/rss')
def rss_default ():
return redirect (application.get_url ('rss', sorting='hot'))
# TODO check if <description> is correctly displayed in RSS aggregators
@get ('/rss/<sorting>', name='rss')
def rss (sorting):
posts = []
# Retrieve the hostname from the HTTP request.
# This is used to build absolute URLs in the RSS feed.
base_url = request.urlparts.scheme + '://' + request.urlparts.netloc
if sorting == 'new':
posts = database.get_new_posts ()
if sorting == 'hot':
posts = database.get_hot_posts ()
# Set correct Content-Type header for this RSS feed
response.content_type = 'application/rss+xml; charset=UTF-8'
return template ('rss.xml', base_url=base_url, posts=posts)
@get ('/<filename:path>')
def static (filename):
return static_file (filename, root='freepost/static/')