235 lines
7.8 KiB
Python
235 lines
7.8 KiB
Python
from flask import Flask, render_template, redirect, url_for, request, session, jsonify, send_file, flash
|
|
from requests_oauthlib import OAuth2Session
|
|
import os
|
|
import subprocess
|
|
import mysql.connector
|
|
from datetime import datetime
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = os.getenv("FLASK_SECRET_KEY")
|
|
|
|
LOG_FILE_PATH = os.path.join("logs", f"{datetime.now().strftime('%Y-%m-%d')}.log")
|
|
|
|
# Verwende Umgebungsvariablen aus Coolify für die Datenbankverbindung
|
|
DB_HOST = os.getenv("DB_HOST")
|
|
DB_PORT = os.getenv("DB_PORT")
|
|
DB_USER = os.getenv("DB_USER")
|
|
DB_PASS = os.getenv("DB_PASSWORD")
|
|
DB_NAME = os.getenv("DB_DATABASE")
|
|
|
|
DISCORD_CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
|
|
DISCORD_CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
|
|
DISCORD_REDIRECT_URI = os.getenv("DISCORD_REDIRECT_URI")
|
|
DISCORD_OAUTH2_URL = "https://discord.com/api/oauth2/authorize"
|
|
DISCORD_TOKEN_URL = "https://discord.com/api/oauth2/token"
|
|
DISCORD_API_URL = "https://discord.com/api/users/@me"
|
|
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
|
|
|
|
bot_process = None
|
|
|
|
def bot_status():
|
|
"""Überprüft, ob der Bot läuft."""
|
|
global bot_process
|
|
if bot_process is None:
|
|
return False
|
|
return bot_process.poll() is None # None bedeutet, dass der Prozess noch läuft
|
|
|
|
def start_bot():
|
|
"""Startet den Bot."""
|
|
global bot_process
|
|
if not bot_status():
|
|
bot_process = subprocess.Popen(["python", "bot.py"], cwd=os.path.dirname(os.path.abspath(__file__)))
|
|
else:
|
|
print("Bot läuft bereits.")
|
|
|
|
def stop_bot():
|
|
"""Stoppt den Bot."""
|
|
global bot_process
|
|
if bot_process and bot_status():
|
|
bot_process.terminate()
|
|
bot_process.wait()
|
|
bot_process = None
|
|
else:
|
|
print("Bot läuft nicht.")
|
|
|
|
def get_db_connection():
|
|
"""Stellt eine Verbindung zur MySQL-Datenbank her."""
|
|
return mysql.connector.connect(
|
|
host=DB_HOST,
|
|
port=DB_PORT,
|
|
user=DB_USER,
|
|
password=DB_PASS,
|
|
database=DB_NAME
|
|
)
|
|
|
|
def make_discord_session(token=None, state=None):
|
|
return OAuth2Session(
|
|
DISCORD_CLIENT_ID,
|
|
token=token,
|
|
state=state,
|
|
redirect_uri=DISCORD_REDIRECT_URI,
|
|
scope=["identify"]
|
|
)
|
|
|
|
def is_global_admin():
|
|
"""Überprüft, ob der Benutzer globale Admin-Rechte hat."""
|
|
if "discord_user" in session:
|
|
user_info = session["discord_user"]
|
|
user_id = user_info["id"]
|
|
|
|
connection = get_db_connection()
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT global_permission FROM bot_data WHERE user_id = %s", (user_id,))
|
|
bot_data = cursor.fetchone()
|
|
cursor.close()
|
|
connection.close()
|
|
|
|
if bot_data and bot_data["global_permission"] >= 8:
|
|
return True
|
|
return False
|
|
|
|
def is_server_admin(guild_id):
|
|
"""Überprüft, ob der Benutzer Admin-Rechte auf einem bestimmten Server hat."""
|
|
if "discord_user" in session:
|
|
user_info = session["discord_user"]
|
|
user_id = user_info["id"]
|
|
|
|
connection = get_db_connection()
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT permission FROM user_data WHERE user_id = %s AND guild_id = %s", (user_id, guild_id))
|
|
user_data = cursor.fetchone()
|
|
cursor.close()
|
|
connection.close()
|
|
|
|
if user_data and user_data["permission"] >= 8:
|
|
return True
|
|
return False
|
|
|
|
@app.route("/")
|
|
def landing_page():
|
|
"""Ungeschützte Landing Page"""
|
|
return render_template("landing.html")
|
|
|
|
@app.route("/login")
|
|
def login():
|
|
"""Startet den Discord-OAuth2-Flow."""
|
|
discord = make_discord_session()
|
|
authorization_url, state = discord.authorization_url(DISCORD_OAUTH2_URL)
|
|
|
|
session['oauth_state'] = state
|
|
return redirect(authorization_url)
|
|
|
|
@app.route("/callback")
|
|
def callback():
|
|
"""Verarbeitet den OAuth2-Rückruf von Discord."""
|
|
discord = make_discord_session(state=session.get("oauth_state"))
|
|
token = discord.fetch_token(
|
|
DISCORD_TOKEN_URL,
|
|
client_secret=DISCORD_CLIENT_SECRET,
|
|
authorization_response=request.url,
|
|
)
|
|
|
|
session['oauth_token'] = token
|
|
|
|
user_info = discord.get(DISCORD_API_URL).json()
|
|
session['discord_user'] = user_info
|
|
|
|
connection = get_db_connection()
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT global_permission FROM bot_data WHERE user_id = %s", (user_info["id"],))
|
|
bot_data = cursor.fetchone()
|
|
cursor.close()
|
|
connection.close()
|
|
|
|
if bot_data and bot_data["global_permission"] >= 8:
|
|
return redirect(url_for("global_admin_dashboard"))
|
|
else:
|
|
return redirect(url_for("select_guild"))
|
|
|
|
@app.route("/select_guild")
|
|
def select_guild():
|
|
"""Lässt den Benutzer den Server auswählen, auf dem er aktiv sein möchte."""
|
|
if "discord_user" in session:
|
|
user_info = session["discord_user"]
|
|
user_id = user_info["id"]
|
|
|
|
connection = get_db_connection()
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT guild_id FROM user_data WHERE user_id = %s", (user_id,))
|
|
guilds = cursor.fetchall()
|
|
cursor.close()
|
|
connection.close()
|
|
|
|
if guilds:
|
|
return render_template("select_guild.html", guilds=guilds)
|
|
else:
|
|
return "No server found for this user.", 404
|
|
return redirect(url_for("landing_page"))
|
|
|
|
@app.route("/set_guild/<int:guild_id>")
|
|
def set_guild(guild_id):
|
|
"""Setzt den aktuellen Server (guild_id) für den Benutzer."""
|
|
session["guild_id"] = guild_id
|
|
return redirect(url_for("server_dashboard", guild_id=guild_id))
|
|
|
|
@app.route("/global_admin_dashboard")
|
|
def global_admin_dashboard():
|
|
"""Globales Admin-Dashboard für globale Administratoren."""
|
|
if is_global_admin():
|
|
user_info = session["discord_user"]
|
|
return render_template("global_admin_dashboard.html", user_info=user_info, bot_running=bot_status())
|
|
return redirect(url_for("landing_page"))
|
|
|
|
@app.route("/server_dashboard/<int:guild_id>")
|
|
def server_dashboard(guild_id):
|
|
"""Server-spezifisches Dashboard für den aktuellen Server (guild_id)."""
|
|
if is_server_admin(guild_id):
|
|
user_info = session["discord_user"]
|
|
return render_template("server_dashboard.html", user_info=user_info, guild_id=guild_id, bot_running=bot_status())
|
|
return redirect(url_for("landing_page"))
|
|
|
|
@app.route("/start_bot")
|
|
def start():
|
|
if is_global_admin():
|
|
start_bot()
|
|
return redirect(url_for("global_admin_dashboard"))
|
|
return redirect(url_for("landing_page"))
|
|
|
|
@app.route("/stop_bot")
|
|
def stop():
|
|
if is_global_admin():
|
|
stop_bot()
|
|
return redirect(url_for("global_admin_dashboard"))
|
|
return redirect(url_for("landing_page"))
|
|
|
|
@app.route("/server_admin/giveaways/<int:guild_id>")
|
|
def server_admin_giveaways(guild_id):
|
|
"""Zeigt eine Liste der Giveaways für einen bestimmten Server an."""
|
|
if is_server_admin(guild_id):
|
|
connection = get_db_connection()
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT * FROM giveaway_data WHERE guild_id = %s", (guild_id,))
|
|
giveaways = cursor.fetchall()
|
|
cursor.close()
|
|
connection.close()
|
|
return render_template("server_admin_giveaways.html", giveaways=giveaways, guild_id=guild_id)
|
|
return redirect(url_for("landing_page"))
|
|
|
|
@app.route("/users")
|
|
def users():
|
|
"""Zeigt die Liste der Benutzer an."""
|
|
if is_global_admin():
|
|
connection = get_db_connection()
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT user_id, permission, points, ban FROM user_data")
|
|
users = cursor.fetchall()
|
|
cursor.close()
|
|
connection.close()
|
|
return render_template("users.html", users=users)
|
|
return redirect(url_for("landing_page"))
|
|
|
|
# Weitere Routen für Server-spezifische Funktionen, Punkteverwaltung, Giveaways etc.
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=5000, debug=True)
|