reddit/app/app.py

198 lines
4.6 KiB
Python
Executable File

from flask import Flask, send_file, render_template, request
from urllib.parse import urlparse
import config
import json
import re
import sqlite3
import subprocess
app = Flask(__name__)
@app.route('/file/<path:filename>')
def serve_file(filename):
try:
return send_file('{0}/{1}'.format(config.media_dir, filename), as_attachment=False)
except FileNotFoundError:
return "File not found", 404
@app.route('/hide/<path:permalink>')
def hide_post(permalink):
if permalink[0] != "/":
permalink = "/" + permalink
connection = sqlite3.connect(config.db_file)
cursor = connection.cursor()
update = """
UPDATE
post
SET
hidden = ?
WHERE
permalink = ?
"""
binds = [True, permalink]
print(update)
print(binds)
cursor.execute(update,binds)
connection.commit()
connection.close()
return ""
@app.route('/')
def index():
return front_page()
@app.route('/r/all')
def front_page():
title = "/r/all"
connection = sqlite3.connect(config.db_file)
cursor = connection.cursor()
subreddits = get_subreddits(cursor)
select = """
SELECT
post
FROM
post
WHERE
hidden = ?
ORDER BY
score desc
LIMIT ?
"""
binds = [False, config.posts_per_page_load]
posts = get_posts_from_select(cursor, select, binds)
add_subreddits_to_posts(posts)
connection.close()
return render_template('index.html', title=title, posts=posts, subreddits=subreddits)
@app.route('/r/other')
def other_page():
title = "/r/other"
connection = sqlite3.connect(config.db_file)
cursor = connection.cursor()
subreddits = get_subreddits(cursor)
select = """
SELECT
post
FROM
post
WHERE
hidden = ? AND
subreddit IN
(
SELECT
subreddit
FROM
(
SELECT
subreddit,
count(*) count
FROM
post
WHERE
hidden = ?
GROUP BY
subreddit
) t
WHERE
count <= ?
)
ORDER BY
score desc
LIMIT ?
"""
binds = [False, False, config.other_posts_cutoff, config.posts_per_page_load]
posts = get_posts_from_select(cursor, select, binds)
add_subreddits_to_posts(posts)
connection.close()
return render_template('index.html', title=title, posts=posts, subreddits=subreddits)
@app.route('/r/<path:subreddit>')
def get_subreddit(subreddit):
title = f"/r/{subreddit}"
connection = sqlite3.connect(config.db_file)
cursor = connection.cursor()
subreddits = get_subreddits(cursor)
select = """
SELECT
post
FROM
post
WHERE
subreddit = ? AND
hidden = ?
ORDER BY
score desc
LIMIT ?
"""
binds = [subreddit, False, config.posts_per_page_load]
posts = get_posts_from_select(cursor, select, binds)
connection.close()
return render_template('index.html', title=title, posts=posts, subreddits=subreddits)
def get_subreddits(cursor):
select = """
SELECT
subreddit
FROM
(
SELECT
subreddit,
count(*) count
FROM
post
WHERE
hidden = ?
GROUP BY
subreddit
ORDER BY
count desc
) t
WHERE
count > ?
"""
binds = [False, config.other_posts_cutoff]
results = cursor.execute(select, binds).fetchall()
subreddits = [f"/r/{sub[0]}" for sub in results]
subreddits.insert(0, "/r/all")
subreddits.append("/r/other")
return subreddits
def get_posts_from_select(cursor, select, binds):
results = cursor.execute(select, binds).fetchall()
posts = [json.loads(post[0]) for post in results]
add_media_html_to_posts(posts)
return posts
def add_media_html_to_posts(posts):
for post_index, post in enumerate(posts):
media_html = []
for media_index, media in enumerate(post["media_urls"]):
filename = urlparse(media).path
if filename[0]=='/':
filename = filename[1:]
html = get_media_html(filename, True if (post_index < 3 and media_index == 0) else False)
media_html.append(html)
post["media_html"] = media_html
def add_subreddits_to_posts(posts):
for post in posts:
m = re.search(r"\/r\/([a-zA-Z0-9_]+)\/.*", post["permalink"])
post["subreddit"] = f"/r/{m.group(1)}"
def get_media_html(file, priority=False):
if file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.png') or file.endswith('.gif'):
return '<img class="invertible" src="/file/{0}" {1}>'.format(file, 'fetchpriority="high" loading="eager"' if priority else '')
if file.find("_AUDIO_")>0:
return '<audio src="/file/{0}" hidden></audio>'.format(file)
if file.endswith('.mp4'):
return '<video src="/file/{0}" type="video/mp4" onplay="playAudio(this)" onpause="pauseAudio(this)" onseeked="seekAudio(this)" controls></video>'.format(file)
if file.endswith('.webm'):
return '<video src="/file/{0}" type="video/webm" controls></video>'.format(file)
return file
if __name__ == '__main__':
subprocess.run(["python3", "make_db.py"])
app.run(host='0.0.0.0', port=8000)