wastetape/app.py

111 lines
4.4 KiB
Python
Raw Normal View History

2024-09-09 08:14:11 +03:00
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
import os, sys, time, hashlib
from apscheduler.schedulers.background import BackgroundScheduler
import markdown
app = Flask(__name__)
db = sqlite3.connect('wastetape.db', check_same_thread=False)
cs = db.cursor()
app.secret_key = hashlib.md5(os.urandom(32)).hexdigest()
maxFileSize = 1024 * 1024 * 128
maxExpiry = 60 * 60 * 24 * 7
allowedFormats = ["png", "jpg", "jpeg", "gif", "pdf", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "mp4", "mpg", "wmv", "mov", "avi", "swf", "zip", "tar.gz", "tar", "rar", "7z", "mp3", "txt", "py", "php", "htm", "html", "css", "js", "ts", "cr", "c", "cpp", "rs", "rst", "md"]
def removal():
cs.execute("SELECT * FROM files WHERE deletion < ?;", (int(time.time()),))
files = cs.fetchall()
for file in files:
id = file[0]
slug = file[1]
for realfile in os.listdir('./static/files'):
if realfile.startswith(slug):
path = os.path.join('./static/files', realfile)
if os.path.exists(path):
os.remove(path)
cs.execute('DELETE FROM files WHERE id = ?;', (id,))
db.commit()
print(f"[{int(time.time())}]: DELETED #{id}")
sched = BackgroundScheduler(daemon=True)
sched.add_job(removal,'interval',seconds=5)
sched.start()
@app.template_filter('expirein')
def expirein(value):
if value == 2147483647:
return 'Never'
else:
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(value))
@app.template_filter('markdown')
def mrkdwn(value):
return markdown.markdown(str(value))
@app.template_filter('gettxt')
def gettxt(value):
with open(os.path.join('static/files', value), 'r') as f:
return f.read()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
expiry = request.form['expiry']
if file.filename == '':
flash('No selected file')
return redirect(url_for('index'))
if expiry == '':
flash('No expiry date selected')
return redirect(url_for('index'))
if int(expiry) > maxExpiry and expiry != '2147483647':
flash('We had encountered an error while processing your request. This incident has been reported.')
return redirect(url_for('index'))
if file:
filename = file.filename
originalName = filename
file.save(os.path.join('tmp', filename))
hash = hashlib.md5(open(os.path.join('tmp', filename), 'rb').read()).hexdigest()
print(hash)
slug = str(hash) + str(int(time.time()))
print(slug)
slug = hashlib.md5(str(slug).encode('utf-8')).hexdigest()[:6]
expiry = int(time.time()) + int(expiry)
if os.path.getsize(os.path.join('tmp', filename)) > maxFileSize:
os.remove(os.path.join('tmp', filename))
flash('File too large')
return redirect(url_for('index'))
elif expiry == '2147483647' and os.path.getsize(os.path.join('tmp', filename)) > maxFileSize / 4:
os.remove(os.path.join('tmp', filename))
flash('File too large')
return redirect(url_for('index'))
if filename.split('.')[-1] not in allowedFormats:
os.remove(os.path.join('tmp', filename))
flash('File format not allowed')
return redirect(url_for('index'))
cs.execute('INSERT INTO files (slug, originalName, md5, date, deletion, ip) VALUES (?, ?, ?, ?, ?, ?)', (slug, originalName, hash, int(time.time()), expiry, request.remote_addr))
db.commit()
os.rename(os.path.join('tmp', filename), os.path.join('static/files', slug + '.' + filename.split('.')[-1]))
return redirect("/file/" + slug)
@app.route('/file/<slug>')
def file(slug):
cs.execute('SELECT * FROM files WHERE slug=?', (slug,))
file = cs.fetchone()
if file is None:
return render_template('404.html')
else:
return render_template('file.html', file=file)
@app.route('/about')
def about():
with open(os.path.join('templates/about.md'), 'r') as f:
return render_template('markdown.html', file=f.read())