bsshare/req-short.py
Holger Weber a3f5f4a5dc Load env variables and fix wrong text marker usage.
1. If environment variables are not set before by docker compose, program tries to get them from .env file.
2. Fix: If text marker was not found on bs page a wrong text marker was added.
2025-07-18 08:45:20 +02:00

97 lines
2.8 KiB
Python

from flask import Flask, request, jsonify, abort, send_from_directory, render_template_string
import os
from dotenv import load_dotenv
from datetime import datetime
from werkzeug.utils import secure_filename
import bsupdate as bu
app = Flask(__name__)
if "API_TOKEN" not in os.environ:
print("Environment variables not read. Try reading from file.")
load_dotenv()
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)
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)