summaryrefslogtreecommitdiff
path: root/app.py
blob: cf0b0d4b52d89e44ac2f0733cb945fff49c4dcda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/python3
import markdown
from flask import (
    Flask,
    render_template,
    Markup,
    request,
    g,
    send_from_directory,
    redirect
)
import sqlite3


class dbProxy(object):
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.conn.row_factory = self.dict_factory
        self.c = self.conn.cursor()

    def create(self):
        self.c.execute("CREATE TABLE IF NOT EXISTS jokes(id INTEGER PRIMARY KEY NOT NULL, text TEXT, upvotes INTEGER, downvotes INTEGER, reports INTEGER)")

    def close(self):
        self.conn.close()

    def dict_factory(self, cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d

    def sort(self, joke):
        interactions = joke["reports"]*5 + joke["upvotes"] + joke["downvotes"] + 1
        score = 1/interactions * (joke["upvotes"]+1)/interactions
        return score

    def getJokes(self):
        jokes = self.c.execute("SELECT * FROM jokes").fetchall()
        jokes = sorted(jokes, key=self.sort, reverse=True)
        return jokes

    def addJoke(self, text):
        self.c.execute("INSERT INTO jokes(text, upvotes, downvotes, reports) VALUES (?, 0, 0, 0)", (text, ))
        self.conn.commit()

    def voteJoke(self, objectId, down):
        if down:
            self.c.execute("UPDATE jokes SET downvotes=downvotes+1 WHERE id=?", (objectId))
        else:
            self.c.execute("UPDATE jokes SET upvotes=upvotes+1 WHERE id=?", (objectId))
        self.conn.commit()

    def reportJoke(self, objectId):
        self.c.execute("UPDATE jokes SET reports=reports+1 WHERE id=?", (objectId))
        self.conn.commit()


def db():
    db = getattr(g, "_database", None)
    if db is None:
        db = g._database = dbProxy("votes.db")
        db.create()
    return db

app = Flask(__name__)


@app.teardown_appcontext
def close_db(exception):
    db = getattr(g, "_database", None)
    if db is not None:
        db.close()

@app.route('/')
def root():
    jokes = db().getJokes()
    for joke in jokes:
        joke['text'] = Markup(markdown.markdown(joke['text'], extensions=['markdown.extensions.nl2br'], output_format="html5", safe_mode="remove"))  # TODO cache TODO safe_mode deprecated
    return render_template('index.html', jokes=jokes)

@app.route('/submit', methods=['POST'])
def submit():
    text = request.form['text']
    db().addJoke(text)  # TODO auth
    return redirect('/')

@app.route('/vote', methods=['POST'])
def vote():
    objectId = request.form['id']
    db().voteJoke(objectId, request.form['vote'] == 'downvote')
    return redirect('/')

@app.route('/report', methods=['POST'])
def report():
    objectId = request.form['id']
    db().reportJoke(objectId)
    return redirect('/')

@app.route('/static/<path:path>')
def get_static(path):
    return send_from_directory('static', path)

if __name__ == '__main__':
    app.run(debug=True)