2026-03-14 17:05:20 +01:00
|
|
|
import os, subprocess, threading, requests
|
2026-06-03 16:10:36 +02:00
|
|
|
# Nettoyer les variables de certificats SSL corrompues ou obsolètes pour éviter les crashs TLS
|
|
|
|
|
os.environ.pop("REQUESTS_CA_BUNDLE", None)
|
|
|
|
|
os.environ.pop("SSL_CERT_FILE", None)
|
|
|
|
|
|
2026-03-14 17:05:20 +01:00
|
|
|
from flask import Flask, request, abort
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
# --- CONFIGURATION ---
|
2026-06-03 16:10:36 +02:00
|
|
|
PROJECT_PATH = "/home/discord/Bot/Kuby"
|
2026-03-14 18:35:18 +01:00
|
|
|
WEBHOOK_SECRET = "Nois2"
|
2026-05-16 18:58:29 +02:00
|
|
|
PROCESS_NAME = "kuby"
|
2026-07-11 19:49:40 +02:00
|
|
|
# Ton webhook de logs Discord
|
2026-03-14 17:05:20 +01:00
|
|
|
DISCORD_LOG_URL = "https://discord.com/api/webhooks/1482148910888652910/IA9CcOWtjGswbuxMaOu_6uaclv5zojZo4ttxtV6RYyZzJ9gW7BF7xp_Zv3oPIjYEuh8o"
|
|
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# Chemin vers PM2
|
2026-06-07 16:40:46 +02:00
|
|
|
PM2_BINARY = "/home/discord/.nvm/versions/node/v24.15.0/bin/pm2"
|
|
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# Bot Local Proxy (Relai vers le Cog de ton bot)
|
2026-03-14 17:05:20 +01:00
|
|
|
BOT_LOCAL_URL = "http://127.0.0.1:5001/bot_event"
|
|
|
|
|
|
|
|
|
|
def send_discord_log(status, message, color, author=None, commit_msg=None):
|
|
|
|
|
embed = {
|
2026-07-11 19:49:40 +02:00
|
|
|
"title": f"🚀 Kuby V2 [Forgejo] : {status}",
|
2026-03-14 17:05:20 +01:00
|
|
|
"description": message,
|
|
|
|
|
"color": color,
|
|
|
|
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
|
|
|
"fields": []
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if author:
|
|
|
|
|
embed["fields"].append({"name": "👤 Auteur", "value": author, "inline": True})
|
|
|
|
|
if commit_msg:
|
|
|
|
|
embed["fields"].append({"name": "📝 Commit", "value": commit_msg, "inline": True})
|
|
|
|
|
|
|
|
|
|
payload = {"embeds": [embed]}
|
|
|
|
|
try:
|
2026-07-11 19:49:40 +02:00
|
|
|
requests.post(DISCORD_LOG_URL, json=payload, timeout=10)
|
2026-03-14 17:05:20 +01:00
|
|
|
except Exception as e:
|
|
|
|
|
print(f"[!] Erreur envoi Discord : {e}")
|
|
|
|
|
|
2026-03-15 12:04:18 +01:00
|
|
|
def run_mep_logic(author, commit_msg, branch="main"):
|
2026-03-14 17:05:20 +01:00
|
|
|
start_time = datetime.now()
|
2026-03-15 12:04:18 +01:00
|
|
|
send_discord_log("EN COURS", f"Déploiement branch **{branch}** lancé sur la machine de guerre...", 3447003, author, commit_msg)
|
2026-03-14 17:05:20 +01:00
|
|
|
|
|
|
|
|
try:
|
2026-06-03 16:10:36 +02:00
|
|
|
target_path = PROJECT_PATH
|
|
|
|
|
use_rsync = False
|
|
|
|
|
if not os.path.exists(os.path.join(target_path, ".git")):
|
|
|
|
|
alt_path = "/home/discord/Bot/Kuby"
|
|
|
|
|
if os.path.exists(os.path.join(alt_path, ".git")):
|
|
|
|
|
print(f"[!] {target_path} n'est pas un dépôt Git. Utilisation du dépôt {alt_path} et rsync.")
|
|
|
|
|
target_path = alt_path
|
|
|
|
|
use_rsync = True
|
|
|
|
|
else:
|
|
|
|
|
raise RuntimeError(f"Aucun dépôt Git trouvé dans {target_path} ou {alt_path}")
|
|
|
|
|
|
|
|
|
|
os.chdir(target_path)
|
2026-03-14 17:05:20 +01:00
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# 1. GIT (Va maintenant pull depuis ton Forgejo auto-hébergé)
|
2026-03-14 17:05:20 +01:00
|
|
|
subprocess.run(["git", "fetch", "origin"], check=True)
|
2026-03-15 12:04:18 +01:00
|
|
|
subprocess.run(["git", "reset", "--hard", f"origin/{branch}"], check=True)
|
2026-03-14 17:05:20 +01:00
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# 2. RSYNC (Fallback)
|
2026-06-03 16:10:36 +02:00
|
|
|
if use_rsync:
|
|
|
|
|
subprocess.run(["rsync", "-a", "--exclude=.git", "--exclude=venv", "--exclude=.venv", "--exclude=__pycache__", f"{target_path}/", f"{PROJECT_PATH}/"], check=True)
|
|
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# 3. PM2 Restart
|
2026-06-05 17:59:37 +02:00
|
|
|
subprocess.run(
|
2026-06-07 16:40:46 +02:00
|
|
|
[PM2_BINARY, "restart", PROCESS_NAME],
|
|
|
|
|
check=True,
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True
|
2026-06-05 17:59:37 +02:00
|
|
|
)
|
2026-03-14 17:05:20 +01:00
|
|
|
|
2026-06-07 16:22:17 +02:00
|
|
|
duration = (datetime.now() - start_time).total_seconds()
|
2026-07-11 19:49:40 +02:00
|
|
|
msg = f"✅ **Déploiement réussi en {duration:.2f}s**\nLe bot est à jour sur Forgejo et redémarré."
|
2026-06-07 16:22:17 +02:00
|
|
|
send_discord_log("VALIDÉ", msg, 3066993, author, commit_msg)
|
|
|
|
|
|
2026-06-07 16:40:46 +02:00
|
|
|
except subprocess.CalledProcessError as e:
|
2026-07-11 19:49:40 +02:00
|
|
|
error_stderr = e.stderr if e.stderr else "Pas de log d'erreur disponible."
|
2026-06-07 16:40:46 +02:00
|
|
|
error_msg = f"❌ **ERREUR de commande (Status {e.returncode})**\nCommande : `{ ' '.join(e.cmd) }`\n\n**Détails :**\n```\n{error_stderr}\n```"
|
|
|
|
|
send_discord_log("ÉCHEC", error_msg, 15158332, author, commit_msg)
|
2026-03-14 17:05:20 +01:00
|
|
|
except Exception as e:
|
|
|
|
|
error_msg = f"❌ **ERREUR de déploiement**\n```python\n{str(e)}\n```"
|
|
|
|
|
send_discord_log("ÉCHEC", error_msg, 15158332, author, commit_msg)
|
|
|
|
|
|
|
|
|
|
@app.route('/deploy', methods=['POST'])
|
|
|
|
|
def deploy():
|
2026-07-11 19:49:40 +02:00
|
|
|
# ⚡ MODIFICATION : Forgejo envoie son token secret dans 'X-Gitea-Token'
|
|
|
|
|
if request.headers.get('X-Gitea-Token') != WEBHOOK_SECRET:
|
2026-03-14 17:05:20 +01:00
|
|
|
abort(403)
|
|
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# Extraction des infos (La structure des commits est identique à GitLab)
|
2026-03-14 17:05:20 +01:00
|
|
|
data = request.json
|
|
|
|
|
author = "Inconnu"
|
|
|
|
|
commit_msg = "Pas de message"
|
|
|
|
|
|
|
|
|
|
if data and 'commits' in data and len(data['commits']) > 0:
|
|
|
|
|
author = data['commits'][0].get('author', {}).get('name', 'Inconnu')
|
|
|
|
|
commit_msg = data['commits'][0].get('message', 'Pas de message')
|
|
|
|
|
|
2026-03-15 12:04:18 +01:00
|
|
|
# Extraction de la branche
|
|
|
|
|
ref = data.get('ref', 'refs/heads/main')
|
|
|
|
|
branch = ref.split('/')[-1] if ref else 'main'
|
|
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# Threading inchangé pour répondre instantanément à Forgejo
|
2026-03-15 12:04:18 +01:00
|
|
|
threading.Thread(target=run_mep_logic, args=(author, commit_msg, branch)).start()
|
2026-03-14 17:05:20 +01:00
|
|
|
|
|
|
|
|
return {"status": "accepted"}, 202
|
|
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# Nouvelle route renommée pour la clarté, accepte aussi l'ancienne au cas où
|
|
|
|
|
@app.route('/forgejo_webhook', methods=['POST'])
|
|
|
|
|
@app.route('/gitlab_webhook', methods=['POST'])
|
|
|
|
|
def forgejo_webhook():
|
|
|
|
|
# ⚡ MODIFICATION : Sécurité via l'en-tête Forgejo
|
|
|
|
|
received_token = request.headers.get('X-Gitea-Token')
|
2026-03-14 18:35:18 +01:00
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
print(f"[DEBUG] Webhook d'événements reçu. Token reçu: '{received_token}'")
|
2026-03-14 18:35:18 +01:00
|
|
|
|
|
|
|
|
if received_token != WEBHOOK_SECRET:
|
2026-07-11 19:49:40 +02:00
|
|
|
abort(403)
|
2026-03-14 17:05:20 +01:00
|
|
|
|
2026-07-11 19:49:40 +02:00
|
|
|
# Relai direct de la payload de l'événement (tickets, commentaires) vers ton bot local au port 5001
|
2026-03-14 17:05:20 +01:00
|
|
|
payload = request.json
|
|
|
|
|
try:
|
2026-05-01 16:16:33 +02:00
|
|
|
requests.post(BOT_LOCAL_URL, json=payload, timeout=5)
|
|
|
|
|
except Exception as e:
|
2026-03-14 17:05:20 +01:00
|
|
|
print(f"[!] Erreur de relais vers le bot Discord : {e}")
|
|
|
|
|
|
|
|
|
|
return {"status": "received"}, 200
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2026-07-11 19:49:40 +02:00
|
|
|
print(f"[*] Webhook Forgejo opérationnel sur le port 5000. Prêt pour les MEP !")
|
2026-06-07 16:40:46 +02:00
|
|
|
app.run(host='0.0.0.0', port=5000)
|