Files
E3FI2_Kamil_Filehosting/main.py
2025-03-22 13:58:12 +01:00

63 lines
2.1 KiB
Python

from flask import send_file, Flask, request
#from werkzeug.middleware.proxy_fix import ProxyFix # Für Einsatz in Produktion
import sqlite3, hashlib, random, os, pathlib
app = Flask(__name__)
#app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1) # Für Einsatz in Produktion
db = sqlite3.connect("_map.db", check_same_thread=False)
dbCursor = db.cursor()
dbCursor.execute("CREATE TABLE IF NOT EXISTS _idToFile (id TEXT PRIMARY KEY, destination TEXT, uploadTime DATETIME, fileName TEXT, usesLeft INT);")
if pathlib.Path("./data").is_dir() == False:
os.mkdir("data")
@app.route("/")
def mainpage():
return send_file("index.html")
@app.route("/upload", methods = ["POST"])
def uploader():
file = request.files['file'] #
name = file.filename.rsplit(".", 1)
idValue = ""
idIsUnique = False
while idIsUnique == False:
if idValue != "":
idValue = ""
for _ in range(14):
vArray = [""] * 3
vArray[0] = chr(random.randint(48, 57)) # 0 - 9
vArray[1] = chr(random.randint(65, 90)) # A - Z
vArray[2] = chr(random.randint(97, 122)) # a - z
selector = random.randint(0,2)
idValue += vArray[selector]
dbCursor.execute("SELECT * FROM _idToFile WHERE id=?;", (idValue,))
if dbCursor.fetchone() == None:
idIsUnique = True
if (len(name) > 1): # Dateinamen die ein Suffix besitzen
path = f"./data/{hashlib.sha256((name[0] + idValue).encode()).hexdigest()}.{name[1]}"
else: # Dateinamen die kein Suffix besitzen
path = f"./data/{hashlib.sha256((name[0] + idValue).encode()).hexdigest()}"
file.save(path)
dbCursor.execute("INSERT INTO _idToFile VALUES (?, ?, datetime('now'), ?, ?);", (idValue, path, file.filename, 10))
db.commit()
return "sank you"
@app.route("/download/<string:identifier>")
def downloader(identifier):
dbCursor.execute("SELECT destination FROM _idToFile WHERE id=?;", (identifier,))
path = dbCursor.fetchone()
if path != None:
return send_file(path[0])
else:
return "no file, now fuck off"