Add functional previews, change line endings to Unix. Fixes #2

This commit is contained in:
nukeop 2018-06-28 22:17:43 +02:00
parent 601a45c8ae
commit 29151553cc
2 changed files with 322 additions and 308 deletions

View file

@ -1,53 +1,55 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
{% if numpages>1 %} {% if numpages>1 %}
<ul class="pagination pagination-sm"> <ul class="pagination pagination-sm">
{% for page in range(numpages) %} {% for page in range(numpages) %}
<li {% if curpage==page %} class="active" {% endif %} > <li {% if curpage==page %} class="active" {% endif %} >
<a {% if curpage!=page %}href="/{{page_type}}/{{page+1}}"{% endif %}>{{page+1}}</a> <a {% if curpage!=page %}href="/{{page_type}}/{{page+1}}"{% endif %}>{{page+1}}</a>
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% endif %} {% endif %}
{% if quotes %} {% if quotes %}
{% for quote in quotes %} {% for quote in quotes %}
{% if quote.approved %} {% if quote.approved %}
<div class="quote-header"> <div class="quote-header">
<a class="quote-link" href="/quote/{{ quote.id }}">#{{ quote.id }}</a> {% if quote.id %}
<a class="rate-positive">+</a> ({{quote.rating}}) <a class="rate-negative">-</a> <a class="quote-link" href="/quote/{{ quote.id }}">#{{ quote.id }}</a>
<div class="pull-right quote-date">{{ quote.time }}</div> {% endif %}
<a class="rate-positive">+</a> ({{quote.rating}}) <a class="rate-negative">-</a>
{% if session.authorized %} <div class="pull-right quote-date">{{ quote.time }}</div>
<form class="mod-form" action="/moderate" name="moderate" method="post">
<input type="hidden" name="quoteid" value={{quote.id}} /> {% if session.authorized and quote.id %}
<button type="submit" name="submit" class="btn btn-danger btn-sm btn-mod" value="Delete">Delete</button> <form class="mod-form" action="/moderate" name="moderate" method="post">
</form> <input type="hidden" name="quoteid" value={{quote.id}} />
{% endif %} <button type="submit" name="submit" class="btn btn-danger btn-sm btn-mod" value="Delete">Delete</button>
</div> </form>
{% endif %}
</div>
<div class="quote">
<p>{{ quote.content|safe }}</p>
</div> <div class="quote">
<p>{{ quote.content|safe }}</p>
<div class="tags"> </div>
Tags: <div class="tags">
{% if quote.tags|length > 0 and quote.tags[0].name|length>0%}
{% for tag in quote.tags %} Tags:
<a href="/tag/{{tag.name}}" class="badge"> {{tag.name}} </a> {% if quote.tags|length > 0 and quote.tags[0].name|length>0%}
{% endfor %} {% for tag in quote.tags %}
{% else %} <a href="/tag/{{tag.name}}" class="badge"> {{tag.name}} </a>
<strong> No tags </strong> {% endfor %}
{% endif %} {% else %}
<strong> No tags </strong>
</div> {% endif %}
{% endif %}
{% endfor %} </div>
{% endif %} {% endif %}
{% endfor %}
{% endblock %} {% endif %}
{% endblock %}

View file

@ -1,16 +1,16 @@
import datetime import datetime
import logging import logging
import psycopg2 import psycopg2
from flask import render_template, Markup, request, abort, session, g from flask import render_template, Markup, request, abort, session, g
from smash.models_sqlalchemy import * from smash.models_sqlalchemy import *
from smash import app, conf, db from smash import app, conf, db
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def timestamp(): def timestamp():
return datetime.datetime.now().strftime("%H:%M:%S %d/%m/%y") return datetime.datetime.now().strftime("%H:%M:%S %d/%m/%y")
def message(level, msg): def message(level, msg):
@ -24,246 +24,258 @@ def message(level, msg):
@app.before_request @app.before_request
def before_request(): def before_request():
g.appname = conf.config['APPNAME'] g.appname = conf.config['APPNAME']
g.appbrand = conf.config['APPBRAND'] g.appbrand = conf.config['APPBRAND']
@app.route('/') @app.route('/')
def index(): def index():
welcome = conf.config['MOTD'] welcome = conf.config['MOTD']
news = ("<p><b>{}</b></p><h4>{} running on smash quote database" news = ("<p><b>{}</b></p><h4>{} running on smash quote database"
" engine launched today</h4>").format( " engine launched today</h4>").format(
datetime.datetime.now().strftime("%d/%m/%y"), datetime.datetime.now().strftime("%d/%m/%y"),
conf.config['APPNAME'] conf.config['APPNAME']
) )
return render_template( return render_template(
"index.html", "index.html",
title="Quotes", title="Quotes",
welcometext=welcome, welcometext=welcome,
newstext=news newstext=news
) )
@app.route('/login', methods=['GET', 'POST']) @app.route('/login', methods=['GET', 'POST'])
def login_page(): def login_page():
if request.method == 'POST': if request.method == 'POST':
if request.form["secret"] == conf.config['ADMINSECRET']: if request.form["secret"] == conf.config['ADMINSECRET']:
session['authorized'] = True session['authorized'] = True
return render_template( return render_template(
"login.html", "login.html",
) )
@app.route('/latest') @app.route('/latest')
def latest(): def latest():
quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all() quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()
allquotes = len(quotes) allquotes = len(quotes)
quotes = quotes[:10] quotes = quotes[:10]
if len(quotes)>0: if len(quotes)>0:
# Replace line breaks with html breaks and escape special characters # Replace line breaks with html breaks and escape special characters
for quote in quotes: for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Latest", title="Latest",
quotes=quotes, quotes=quotes,
numpages=1 + allquotes//10, numpages=1 + allquotes//10,
curpage=0, curpage=0,
page_type="latest" page_type="latest"
) )
else: else:
return message("alert-warning", "No quotes in the database.") return message("alert-warning", "No quotes in the database.")
@app.route('/latest/<int:page>') @app.route('/latest/<int:page>')
def latest_page(page): def latest_page(page):
allquotes = len(Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()) allquotes = len(Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all())
quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()[(page-1)*10:page*10] quotes = Quote.query.filter_by(approved=True).order_by(Quote.id.desc()).all()[(page-1)*10:page*10]
for quote in quotes: for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Latest - page {}".format(page), title="Latest - page {}".format(page),
quotes=quotes, quotes=quotes,
numpages=1 + allquotes//10, numpages=1 + allquotes//10,
curpage=page-1, curpage=page-1,
page_type="latest" page_type="latest"
) )
@app.route('/queue') @app.route('/queue')
def queue(): def queue():
if not session.get('authorized'): if not session.get('authorized'):
return message("alert-danger", "You are not authorized to view this page.") return message("alert-danger", "You are not authorized to view this page.")
quotes = Quote.query.filter_by(approved=False).order_by(Quote.id).all() quotes = Quote.query.filter_by(approved=False).order_by(Quote.id).all()
if len(quotes)>0: if len(quotes)>0:
# Replace line breaks with html breaks and escape special characters # Replace line breaks with html breaks and escape special characters
for quote in quotes: for quote in quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"queue.html", "queue.html",
title="Queue", title="Queue",
quotes=quotes quotes=quotes
) )
else: else:
return message("alert-warning", "No quotes in the database.") return message("alert-warning", "No quotes in the database.")
@app.route('/moderate', methods=['POST']) @app.route('/moderate', methods=['POST'])
def moderate(): def moderate():
if not session.get('authorized'): if not session.get('authorized'):
return message("alert-danger", "You are not authorized to perform this action.") return message("alert-danger", "You are not authorized to perform this action.")
if request.form['submit'] == "Approve": if request.form['submit'] == "Approve":
quote = Quote.query.filter_by(id=request.form['quoteid']).first() quote = Quote.query.filter_by(id=request.form['quoteid']).first()
quote.approved = True quote.approved = True
db.session.commit() db.session.commit()
return message("alert-success", "Quote approved.") return message("alert-success", "Quote approved.")
elif request.form['submit'] == "Delete": elif request.form['submit'] == "Delete":
quote = Quote.query.filter_by(id=request.form['quoteid']).first() quote = Quote.query.filter_by(id=request.form['quoteid']).first()
db.session.delete(quote) db.session.delete(quote)
db.session.commit() db.session.commit()
return message("alert-success", "Quote deleted.") return message("alert-success", "Quote deleted.")
abort(501) abort(501)
@app.route('/quote/<int:id>') @app.route('/quote/<int:id>')
def quote(id): def quote(id):
quote = Quote.query.filter_by(id=id, approved=True).first() quote = Quote.query.filter_by(id=id, approved=True).first()
if quote is None: if quote is None:
return render_template( return render_template(
"message.html", "message.html",
alertclass="alert-warning", alertclass="alert-warning",
message="No such quote." message="No such quote."
) )
else: else:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Quote #{}".format(quote.id), title="Quote #{}".format(quote.id),
quotes=[quote,], quotes=[quote,],
numpages=1, numpages=1,
curpage=0, curpage=0,
page_type="quote" page_type="quote"
) )
@app.route('/tag/<tagname>') @app.route('/tag/<tagname>')
def tag(tagname): def tag(tagname):
tag = Tag.query.filter_by(name=tagname).first() tag = Tag.query.filter_by(name=tagname).first()
if len(list(tag.quotes))>0: if len(list(tag.quotes))>0:
allquotes = len(list(tag.quotes)) allquotes = len(list(tag.quotes))
tag.quotes = tag.quotes[:10] tag.quotes = tag.quotes[:10]
# Replace line breaks with html breaks and escape special characters # Replace line breaks with html breaks and escape special characters
for quote in tag.quotes: for quote in tag.quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Tag - {}".format(tagname), title="Tag - {}".format(tagname),
quotes=tag.quotes, quotes=tag.quotes,
numpages=1 + allquotes//10, numpages=1 + allquotes//10,
curpage=0, curpage=0,
page_type="tag/{}".format(tagname) page_type="tag/{}".format(tagname)
) )
else: else:
return message("alert-warning", "No quotes with this tag.") return message("alert-warning", "No quotes with this tag.")
@app.route('/tag/<tagname>/<int:page>') @app.route('/tag/<tagname>/<int:page>')
def tag_page(tagname, page): def tag_page(tagname, page):
tag = Tag.query.filter_by(name=tagname).first() tag = Tag.query.filter_by(name=tagname).first()
if len(list(tag.quotes))>0: if len(list(tag.quotes))>0:
allquotes = len(list(tag.quotes)) allquotes = len(list(tag.quotes))
tag.quotes = tag.quotes[(page-1)*10:page*10] tag.quotes = tag.quotes[(page-1)*10:page*10]
for quote in tag.quotes: for quote in tag.quotes:
quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>') quote.content = str(Markup.escape(quote.content)).replace('\n', '</br>')
return render_template( return render_template(
"latest.html", "latest.html",
title="Tag - {} - page {}".format(tagname, page), title="Tag - {} - page {}".format(tagname, page),
quotes=tag.quotes, quotes=tag.quotes,
numpages=1 + allquotes//10, numpages=1 + allquotes//10,
curpage=0, curpage=0,
page_type="tag/{}".format(tagname) page_type="tag/{}".format(tagname)
) )
@app.route('/tags') @app.route('/tags')
def tags(): def tags():
tags = Tag.query.order_by(Tag.name).distinct().all() tags = Tag.query.order_by(Tag.name).distinct().all()
tags = list(set([x.name for x in tags])) tags = list(set([x.name for x in tags]))
return render_template( return render_template(
"tags.html", "tags.html",
title="Tags", title="Tags",
tags=tags tags=tags
) )
@app.route('/search', methods=['POST']) @app.route('/search', methods=['POST'])
def search(): def search():
if request.method == 'POST': if request.method == 'POST':
return render_template( return render_template(
"message.html", "message.html",
alertclass="alert-warning", alertclass="alert-warning",
message="Not implemented yet. " message="Not implemented yet. "
) )
else: else:
return 'Invalid request.' return 'Invalid request.'
@app.route('/add', methods=['GET', 'POST']) @app.route('/add', methods=['GET', 'POST'])
def add_new(): def add_new():
if request.method == 'POST': if request.method == 'POST':
if request.form['submit'] == "Submit": if request.form['submit'] == "Submit":
quote_body = request.form["newquote"] quote_body = request.form["newquote"]
quote_tags = request.form["tags"].split(',') quote_tags = request.form["tags"].split(',')
quote = Quote(quote_body, request.remote_addr, timestamp()) quote = Quote(quote_body, request.remote_addr, timestamp())
quote_tags = [Tag(tag) for tag in quote_tags] quote_tags = [Tag(tag) for tag in quote_tags]
for tag in quote_tags: for tag in quote_tags:
dbtag = Tag.query.filter_by(name=tag.name).first() dbtag = Tag.query.filter_by(name=tag.name).first()
if dbtag is not None: if dbtag is not None:
quote.tags.append(dbtag) quote.tags.append(dbtag)
else: else:
quote.tags.append(tag) quote.tags.append(tag)
#quote.tags.extend(quote_tags) #quote.tags.extend(quote_tags)
db.session.add(quote) db.session.add(quote)
db.session.commit() db.session.commit()
return render_template( return render_template(
"message.html", "message.html",
alertclass="alert-success", alertclass="alert-success",
message="Quote added succesfully. It will need to be reviewed by the administrators before it shows up." message="Quote added succesfully. It will need to be reviewed by the administrators before it shows up."
) )
elif request.form['submit'] == "Preview": elif request.form['submit'] == "Preview":
return str(request.form) preview = Quote(request.form['newquote'], request.remote_addr, timestamp())
else: preview_tags = request.form["tags"].split(',')
abort(501) preview.approved = True
preview.tags = [Tag(tag) for tag in preview_tags]
elif request.method == 'GET':
return render_template( return render_template(
"add.html", "latest.html",
title="Add new" title="Quote preview",
) quotes=[preview,],
numpages=1,
curpage=0,
page_type="quote"
)
else:
abort(501)
elif request.method == 'GET':
return render_template(
"add.html",
title="Add new"
)