wastetape/app.py

127 lines
4.8 KiB
Python
Raw Permalink 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
2024-09-09 17:32:01 +03:00
import shutil
2024-09-13 22:04:52 +03:00
from pathlib import Path
2024-09-09 08:14:11 +03:00
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
2024-09-13 22:04:52 +03:00
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", "webp", "webm"]
2024-09-09 08:14:11 +03:00
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)
2024-09-13 22:05:04 +03:00
sched.add_job(removal,'interval',seconds=1)
2024-09-09 08:14:11 +03:00
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()
2024-09-13 22:04:52 +03:00
@app.template_filter('totalfiles')
def totalfiles(value):
files = os.listdir("static/files")
return len(files)
@app.template_filter('totalfilesize')
def totalfilesize(value):
size = sum(p.stat().st_size for p in Path("static/files").rglob('*'))
print(size)
for unit in ("B", "K", "M", "G", "T"):
if size < 1024:
return f"{size:.1f}{unit}"
size /= 1024
2024-09-09 08:14:11 +03:00
@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'))
2024-09-13 22:04:52 +03:00
if filename.lower().split('.')[-1] not in allowedFormats:
2024-09-09 08:14:11 +03:00
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()
2024-09-09 17:30:34 +03:00
shutil.move(os.path.join('tmp', filename), os.path.join('static/files', slug + '.' + filename.split('.')[-1]))
2024-09-09 08:14:11 +03:00
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())