94 lines
2.8 KiB
Python
94 lines
2.8 KiB
Python
from flask import Flask, request, jsonify, abort, send_from_directory, render_template_string
|
|
import os
|
|
from datetime import datetime
|
|
from werkzeug.utils import secure_filename
|
|
import bsupdate as bu
|
|
|
|
app = Flask(__name__)
|
|
|
|
UPLOAD_FOLDER = "UPLOAD_FOLDER"
|
|
API_TOKEN = os.getenv("API_TOKEN", "my-secret-token")
|
|
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "webp"}
|
|
|
|
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
|
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
|
|
|
|
# Authentifizierung
|
|
def check_auth():
|
|
token = request.headers.get("X-API-Token")
|
|
if token != API_TOKEN:
|
|
abort(401, description="Unauthorized")
|
|
|
|
# Dateiendung prüfen
|
|
def allowed_file(filename):
|
|
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
|
|
|
# Upload-Endpunkt
|
|
@app.route("/upload", methods=["POST"])
|
|
def upload():
|
|
check_auth()
|
|
|
|
text = request.form.get("text")
|
|
uploaded_file = request.files.get("file")
|
|
|
|
if uploaded_file and uploaded_file.filename != "":
|
|
filename = secure_filename(uploaded_file.filename)
|
|
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
full_filename = f"{timestamp}_{filename}"
|
|
path = os.path.join(app.config["UPLOAD_FOLDER"], full_filename)
|
|
uploaded_file.save(path)
|
|
print(f"Gespeichert: {path}")
|
|
else:
|
|
print("Keine Datei erhalten.")
|
|
|
|
if text:
|
|
bu.add_link_or_text(text)
|
|
# with open(os.path.join(app.config["UPLOAD_FOLDER"], "log.txt"), "a") as f:
|
|
# f.write(f"{datetime.now()}: {text}\n")
|
|
print(f"Text erhalten: {text}")
|
|
|
|
return jsonify({"status": "OK"}), 200
|
|
|
|
# Galerie anzeigen
|
|
@app.route("/")
|
|
def gallery():
|
|
files = os.listdir(app.config["UPLOAD_FOLDER"])
|
|
image_files = [
|
|
f for f in sorted(files, reverse=True)
|
|
if allowed_file(f)
|
|
]
|
|
html = render_template_string("""
|
|
<!doctype html>
|
|
<html lang="de">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>Bilder-Galerie</title>
|
|
<style>
|
|
body { font-family: sans-serif; padding: 2em; }
|
|
img { max-width: 300px; margin: 1em; }
|
|
.grid { display: flex; flex-wrap: wrap; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h1>Hochgeladene Bilder</h1>
|
|
<div class="grid">
|
|
{% for filename in images %}
|
|
<div>
|
|
<img src="/uploads/{{ filename }}" alt="{{ filename }}">
|
|
<p>{{ filename }}</p>
|
|
</div>
|
|
{% endfor %}
|
|
</div>
|
|
</body>
|
|
</html>
|
|
""", images=image_files)
|
|
return html
|
|
|
|
# Bilder statisch servieren
|
|
@app.route("/uploads/<path:filename>")
|
|
def uploaded_file(filename):
|
|
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=8050)
|