reddit/app/app.py

88 lines
3.2 KiB
Python
Executable File

from flask import Flask, send_file, render_template, request
from urllib.parse import urlparse
import config
import json
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('/', methods=['GET', 'POST'])
def index():
connection = sqlite3.connect(config.db_file)
cursor = connection.cursor()
select = "SELECT subreddit, count(*) count FROM post WHERE hidden = ? GROUP BY subreddit ORDER BY count desc LIMIT 1"
binds = [False]
row = cursor.execute(select, binds).fetchone()
connection.close()
return get_subreddit(row[0])
@app.route('/r/<path:subreddit>')
def get_subreddit(subreddit):
title = f"/r/{subreddit}"
connection = sqlite3.connect(config.db_file)
cursor = connection.cursor()
select = "SELECT subreddit, count FROM (SELECT subreddit, count(*) count FROM post WHERE hidden = ? GROUP BY subreddit ORDER BY count desc) t WHERE count > 0"
binds = [False]
results = cursor.execute(select, binds).fetchall()
subreddits = [f"/r/{sub[0]}" for sub in results]
count = results[subreddits.index(title)][1]
select = "SELECT post FROM post WHERE subreddit = ? and hidden = ? ORDER BY score desc LIMIT ?"
binds = [subreddit, False, config.posts_per_page_load]
results = cursor.execute(select, binds).fetchall()
posts = [json.loads(post[0]) for post in results]
add_media_html_to_posts(posts)
connection.close()
return render_template('index.html', title=title, count=count, posts=posts, subreddits=subreddits)
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 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"])
#subprocess.run(["python3", "scrape_posts.py"])
app.run(host='0.0.0.0', port=8000)