Converted files to unix format

This commit is contained in:
socks 2017-04-20 18:42:36 +01:00
parent c29ad49dbb
commit 911333d9d3
8 changed files with 668 additions and 668 deletions

View file

@ -1,49 +1,49 @@
import os import os
from flask import Flask, g from flask import Flask, g
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from . import config, log from . import config, log
log.configure_logging() log.configure_logging()
app = Flask(__name__) app = Flask(__name__)
conf = config.Config('config.json') conf = config.Config('config.json')
# Load database URL for SQLAlchemy from environment # Load database URL for SQLAlchemy from environment
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
# This flag tells the program it's deployed on heroku # This flag tells the program it's deployed on heroku
if 'HEROKU' in os.environ: if 'HEROKU' in os.environ:
conf.add(('HEROKU', 1)) conf.add(('HEROKU', 1))
# Load app name from environment if it's not in the config # Load app name from environment if it's not in the config
if ('APPNAME' in conf.config and if ('APPNAME' in conf.config and
conf.config['APPNAME']=="" and conf.config['APPNAME']=="" and
'APPNAME' in os.environ): 'APPNAME' in os.environ):
conf.add(('APPNAME', os.environ['APPNAME'])) conf.add(('APPNAME', os.environ['APPNAME']))
# Load app brand name from environment if it's not in the config # Load app brand name from environment if it's not in the config
if ('APPBRAND' in conf.config and if ('APPBRAND' in conf.config and
conf.config['APPBRAND']=="" and conf.config['APPBRAND']=="" and
'APPBRAND' in os.environ): 'APPBRAND' in os.environ):
conf.add(('APPBRAND', os.environ['APPBRAND'])) conf.add(('APPBRAND', os.environ['APPBRAND']))
# Load admin key and secret key from environment # Load admin key and secret key from environment
if 'ADMINSECRET' in os.environ: if 'ADMINSECRET' in os.environ:
conf.add(('ADMINSECRET', os.environ['ADMINSECRET'])) conf.add(('ADMINSECRET', os.environ['ADMINSECRET']))
if 'SECRETKEY' in os.environ: if 'SECRETKEY' in os.environ:
conf.add(('SECRETKEY', os.environ['SECRETKEY'])) conf.add(('SECRETKEY', os.environ['SECRETKEY']))
# Set the secret key # Set the secret key
if 'SECRETKEY' in conf.config: if 'SECRETKEY' in conf.config:
app.secret_key = conf.config['SECRETKEY'] app.secret_key = conf.config['SECRETKEY']
else: else:
exit("Secret key not set.") exit("Secret key not set.")
db = SQLAlchemy(app) db = SQLAlchemy(app)
from smash.models_sqlalchemy import * from smash.models_sqlalchemy import *
db.create_all() db.create_all()
from . import views from . import views

View file

@ -1,31 +1,31 @@
import json import json
class Config(object): class Config(object):
def __init__(self, filename): def __init__(self, filename):
self.filename = filename self.filename = filename
self.config = json.loads(open(self.filename, 'r').read()) self.config = json.loads(open(self.filename, 'r').read())
def save(self): def save(self):
with open(self.filename, 'w') as outf: with open(self.filename, 'w') as outf:
outf.write( outf.write(
json.dumps( json.dumps(
self.config, self.config,
indent=4, indent=4,
sort_keys=True) sort_keys=True)
) )
def reload(self): def reload(self):
self.config = json.loads(open(self.filename, 'r').read()) self.config = json.loads(open(self.filename, 'r').read())
def add(self, param): def add(self, param):
self.config[param[0]] = param[1] self.config[param[0]] = param[1]
self.save() self.save()
def remove(self, paramname): def remove(self, paramname):
if self.config.get(paramname) is not None: if self.config.get(paramname) is not None:
del self.config[paramname] del self.config[paramname]
self.save() self.save()

View file

@ -1,161 +1,161 @@
html, body { html, body {
font-family: 'Montserrat'; font-family: 'Montserrat';
margin: 0; margin: 0;
padding: 0; padding: 0;
height: 100%; height: 100%;
background-image: url("../images/bg.png"); background-image: url("../images/bg.png");
} }
.content { .content {
min-height: 100%; min-height: 100%;
position: relative; position: relative;
} }
.navbar-upper{ .navbar-upper{
margin-bottom: 0px; margin-bottom: 0px;
min-height: 25px; min-height: 25px;
border-radius: 0px; border-radius: 0px;
background-color: #03A9F4; background-color: #03A9F4;
border: 0px; border: 0px;
} }
.navbar-default .navbar-brand-upper{ .navbar-default .navbar-brand-upper{
font-family: 'Rubik Mono One'; font-family: 'Rubik Mono One';
color: #FAFAFA; color: #FAFAFA;
height: 25px; height: 25px;
padding: 0px; padding: 0px;
padding-left: 5px; padding-left: 5px;
line-height: 25px; line-height: 25px;
text-shadow: -2px 2px 2px rgba(33, 33, 33, 0.85); text-shadow: -2px 2px 2px rgba(33, 33, 33, 0.85);
} }
.navbar-default .navbar-brand:hover{ .navbar-default .navbar-brand:hover{
color: #FAFAFA; color: #FAFAFA;
} }
.navbar-lower{ .navbar-lower{
min-height: 30px; min-height: 30px;
background-color: #212121; background-color: #212121;
border: 0px; border: 0px;
box-shadow: 0px 2px 10px 0px rgba(33, 33, 33, 0.85); box-shadow: 0px 2px 10px 0px rgba(33, 33, 33, 0.85);
} }
.navbar-nav > li > a{ .navbar-nav > li > a{
padding: 10px 15px 10px 15px; padding: 10px 15px 10px 15px;
color: #FAFAFA; color: #FAFAFA;
} }
.nav > li > a:hover{ .nav > li > a:hover{
background-color: #424242; background-color: #424242;
} }
.navbar-right{ .navbar-right{
margin: 0; margin: 0;
} }
.navbar-form { .navbar-form {
margin: 0; margin: 0;
padding: 0; padding: 0;
height: 40px; height: 40px;
} }
.navbar-form > .form-group{ .navbar-form > .form-group{
height: 100%; height: 100%;
} }
.navbar-form > .form-group > .form-control { .navbar-form > .form-group > .form-control {
border-radius: 0px; border-radius: 0px;
border: 0; border: 0;
border-bottom: 2px solid #FAFAFA; border-bottom: 2px solid #FAFAFA;
background-color: inherit; background-color: inherit;
height: 100%; height: 100%;
color: #FAFAFA color: #FAFAFA
} }
.navbar-form > .form-group > .form-control:focus { .navbar-form > .form-group > .form-control:focus {
box-shadow: none; box-shadow: none;
border-bottom: 2px solid #03A9F4; border-bottom: 2px solid #03A9F4;
} }
.footer { .footer {
background-color: #212121; background-color: #212121;
box-shadow: 0 -2px 10px 0px rgba(33, 33, 33, 0.85); box-shadow: 0 -2px 10px 0px rgba(33, 33, 33, 0.85);
position: absolute; position: absolute;
padding: 0; padding: 0;
margin-top: 50px; margin-top: 50px;
right: 0; right: 0;
left: 0; left: 0;
bottom: -50px; bottom: -50px;
} }
.footer-copyright { .footer-copyright {
text-align: center; text-align: center;
color: #FAFAFA; color: #FAFAFA;
font-variant: small-caps; font-variant: small-caps;
bottom: 0; bottom: 0;
} }
.quote-link { .quote-link {
color: #424242; color: #424242;
font-weight: bold; font-weight: bold;
padding-left: 8px; padding-left: 8px;
} }
.quote { .quote {
font-family: 'Inconsolata', monospace; font-family: 'Inconsolata', monospace;
} }
.quote-header { .quote-header {
background-color: #b3e5fc; background-color: #b3e5fc;
border-bottom: 1px solid; border-bottom: 1px solid;
border-color: #4fc3f7; border-color: #4fc3f7;
margin-bottom: 2px; margin-bottom: 2px;
} }
.quote-date { .quote-date {
padding-right: 8px; padding-right: 8px;
} }
.rate-positive { .rate-positive {
color: #4caf50; color: #4caf50;
} }
.rate-negative { .rate-negative {
color: #f44336; color: #f44336;
} }
.table-separator{ .table-separator{
background-color: #03A9F4; background-color: #03A9F4;
padding: 0!important; padding: 0!important;
width: 3px; width: 3px;
height: 100%; height: 100%;
} }
.table{ .table{
height: 100%; height: 100%;
} }
.table > tbody > tr > td{ .table > tbody > tr > td{
border-top: 0; border-top: 0;
} }
.tags { .tags {
margin-bottom: 4px; margin-bottom: 4px;
} }
.badge { .badge {
background-color: #03A9F4; background-color: #03A9F4;
} }
.mod-form { .mod-form {
padding-left: 8px; padding-left: 8px;
display: inline; display: inline;
} }
.btn-mod { .btn-mod {
padding: 0px 4px; padding: 0px 4px;
border-radius: 0px; border-radius: 0px;
display: inline; display: inline;
} }
.pagination { .pagination {
@ -165,9 +165,9 @@ html, body {
.pagination>li>a { .pagination>li>a {
color: #03A9F4; color: #03A9F4;
} }
.pagination>.active>a { .pagination>.active>a {
background-color: #03A9F4; background-color: #03A9F4;
border-color: #03A9F4; border-color: #03A9F4;
} }

View file

@ -1,42 +1,42 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<center> <center>
<form action="/add" name="add" method="post"> <form action="/add" name="add" method="post">
<table width="60%"> <table width="60%">
<tbody> <tbody>
<tr> <tr>
<td> <td>
</br> </br>
<textarea class="form-control" rows="10" name="newquote"></textarea> <textarea class="form-control" rows="10" name="newquote"></textarea>
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td>
</br> </br>
<label for="tags" >Tags:</label> <label for="tags" >Tags:</label>
<input class="form-control" type="text" name="tags" id="tags" value="" data-role="tagsinput" /> <input class="form-control" type="text" name="tags" id="tags" value="" data-role="tagsinput" />
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td>
</br> </br>
<input type="submit" name="submit" value="Preview" class="btn btn-default"></input> <input type="submit" name="submit" value="Preview" class="btn btn-default"></input>
<input type="submit" name="submit" value="Submit" class="btn btn-default"></input> <input type="submit" name="submit" value="Submit" class="btn btn-default"></input>
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td>
</br> </br>
IP and connection time are logged. IP and connection time are logged.
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</form> </form>
</center> </center>
{% endblock %} {% endblock %}

View file

@ -1,73 +1,73 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
{% block head %} {% block head %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='font-awesome/css/font-awesome.min.css') }}" /> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='font-awesome/css/font-awesome.min.css') }}" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/custom.css') }}" /> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/custom.css') }}" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/fonts.css') }}" /> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/fonts.css') }}" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap-tagsinput.css') }}" /> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap-tagsinput.css') }}" />
{% endblock %} {% endblock %}
{% if title %} {% if title %}
<title>{{ title }} - {{ g.appname }}</title> <title>{{ title }} - {{ g.appname }}</title>
{% endif %} {% endif %}
</head> </head>
<body> <body>
<div class="container" style="height:50%"> <div class="container" style="height:50%">
<nav class="navbar navbar-default navbar-upper"> <nav class="navbar navbar-default navbar-upper">
<div class="navbar-header"> <div class="navbar-header">
<a class="navbar-brand navbar-brand-upper" href="">{{ g.appbrand }}</a> <a class="navbar-brand navbar-brand-upper" href="">{{ g.appbrand }}</a>
</div> </div>
</nav> </nav>
<nav class="navbar navbar-static-top navbar-lower"> <nav class="navbar navbar-static-top navbar-lower">
<ul class="nav navbar-nav"> <ul class="nav navbar-nav">
<li> <a href="/">Home</a> </li> <li> <a href="/">Home</a> </li>
<li> <a href="/latest">Latest</a> </li> <li> <a href="/latest">Latest</a> </li>
<li> <a href="/tags">Tags</a> </li> <li> <a href="/tags">Tags</a> </li>
<li> <a href="/add">Add new</a> </li> <li> <a href="/add">Add new</a> </li>
<li> <a href="/login">Log in</a> </li> <li> <a href="/login">Log in</a> </li>
{% if session.authorized %} {% if session.authorized %}
<li> <a href="/queue">Queue</a> </li> <li> <a href="/queue">Queue</a> </li>
{% endif %} {% endif %}
</ul> </ul>
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li> <li>
<form action="/search" method="post" class="navbar-form navbar-left" role="search"> <form action="/search" method="post" class="navbar-form navbar-left" role="search">
<div class="form-group"> <div class="form-group">
<input type="search" class="form-control" placeholder="Search"> <input type="search" class="form-control" placeholder="Search">
</div> </div>
</form> </form>
</li> </li>
<li> <a href="/tags"><i class="fa fa-search" aria-hidden="true"></i> <li> <a href="/tags"><i class="fa fa-search" aria-hidden="true"></i>
</a> </li> </a> </li>
</ul> </ul>
</nav> </nav>
<div class="content"> <div class="content">
{% block content %} {% block content %}
{% endblock %} {% endblock %}
<footer class="footer"> <footer class="footer">
<div class="footer-copyright"> <div class="footer-copyright">
Copyright © Lord Gumblert Productions 2016 Copyright © Lord Gumblert Productions 2016
</div> </div>
</footer> </footer>
</div> </div>
</div> </div>
<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script> <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='bootstrap/js/bootstrap.min.js') }}"></script> <script src="{{ url_for('static', filename='bootstrap/js/bootstrap.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap-tagsinput.min.js') }}"></script> <script src="{{ url_for('static', filename='js/bootstrap-tagsinput.min.js') }}"></script>
</body> </body>
</html> </html>

View file

@ -1,20 +1,20 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<table class="table"> <table class="table">
<tr> <tr>
<td> <td>
{{ welcometext|safe }} {{ welcometext|safe }}
</td> </td>
<td class="table-separator"> <td class="table-separator">
</td> </td>
<td> <td>
{{ newstext|safe }} {{ newstext|safe }}
</td> </td>
</tr> </tr>
</table> </table>
{{ msg|safe }} {{ msg|safe }}
{% endblock %} {% endblock %}

View file

@ -1,53 +1,53 @@
{% 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> <a class="quote-link" href="/quote/{{ quote.id }}">#{{ quote.id }}</a>
<a class="rate-positive">+</a> ({{quote.rating}}) <a class="rate-negative">-</a> <a class="rate-positive">+</a> ({{quote.rating}}) <a class="rate-negative">-</a>
<div class="pull-right quote-date">{{ quote.time }}</div> <div class="pull-right quote-date">{{ quote.time }}</div>
{% if session.authorized %} {% if session.authorized %}
<form class="mod-form" action="/moderate" name="moderate" method="post"> <form class="mod-form" action="/moderate" name="moderate" method="post">
<input type="hidden" name="quoteid" value={{quote.id}} /> <input type="hidden" name="quoteid" value={{quote.id}} />
<button type="submit" name="submit" class="btn btn-danger btn-sm btn-mod" value="Delete">Delete</button> <button type="submit" name="submit" class="btn btn-danger btn-sm btn-mod" value="Delete">Delete</button>
</form> </form>
{% endif %} {% endif %}
</div> </div>
<div class="quote"> <div class="quote">
<p>{{ quote.content|safe }}</p> <p>{{ quote.content|safe }}</p>
</div> </div>
<div class="tags"> <div class="tags">
Tags: Tags:
{% if quote.tags|length > 0 and quote.tags[0].name|length>0%} {% if quote.tags|length > 0 and quote.tags[0].name|length>0%}
{% for tag in quote.tags %} {% for tag in quote.tags %}
<a href="/tag/{{tag.name}}" class="badge"> {{tag.name}} </a> <a href="/tag/{{tag.name}}" class="badge"> {{tag.name}} </a>
{% endfor %} {% endfor %}
{% else %} {% else %}
<strong> No tags </strong> <strong> No tags </strong>
{% endif %} {% endif %}
</div> </div>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View file

@ -1,17 +1,17 @@
import datetime import datetime
import random import random
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):
@ -25,18 +25,18 @@ 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']
) )
#Show random quote on the homepage if any exist #Show random quote on the homepage if any exist
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()
@ -45,56 +45,56 @@ def index():
quote = random.choice(quotes) quote = random.choice(quotes)
news = str(Markup.escape(quote.content)).replace('\n', '<br />') news = str(Markup.escape(quote.content)).replace('\n', '<br />')
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 if allquotes%10 != 0 else allquotes//10, numpages=1 + allquotes//10 if allquotes%10 != 0 else 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),
@ -104,174 +104,174 @@ def latest_page(page):
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) return str(request.form)
else: else:
abort(501) abort(501)
elif request.method == 'GET': elif request.method == 'GET':
return render_template( return render_template(
"add.html", "add.html",
title="Add new" title="Add new"
) )