Merge main dans dev et résolution des conflits

This commit is contained in:
Mathis 2026-07-11 23:45:06 +02:00
commit f31a5d42fb
6 changed files with 289 additions and 291 deletions

View file

@ -14,12 +14,13 @@ app = Flask(__name__)
PROJECT_PATH = "/home/discord/Bot/Kuby"
WEBHOOK_SECRET = "Nois2"
PROCESS_NAME = "kuby"
# webhook de logs Discord
DISCORD_LOG_URL = "https://discord.com/api/webhooks/1482148910888652910/IA9CcOWtjGswbuxMaOu_6uaclv5zojZo4ttxtV6RYyZzJ9gW7BF7xp_Zv3oPIjYEuh8o"
# Chemin absolu vers le binaire PM2 (évite l'erreur 127 command not found)
# Chemin vers PM2
PM2_BINARY = "/home/discord/.nvm/versions/node/v24.15.0/bin/pm2"
# Bot Local Proxy
# Bot Local Proxy (Relai vers le Cog de ton bot)
BOT_LOCAL_URL = "http://127.0.0.1:5001/bot_event"
@ -43,7 +44,7 @@ def verify_signature(payload_brut, received_signature):
def send_discord_log(status, message, color, author=None, commit_msg=None):
embed = {
"title": f"🚀 Kuby V2 : {status}",
"title": f"🚀 Kuby V2 [Forgejo] : {status}",
"description": message,
"color": color,
"timestamp": datetime.now(timezone.utc).isoformat(),
@ -57,7 +58,7 @@ def send_discord_log(status, message, color, author=None, commit_msg=None):
payload = {"embeds": [embed]}
try:
requests.post(DISCORD_LOG_URL, json=payload, timeout=10) # ✅ Augmenté de 5s à 10s
requests.post(DISCORD_LOG_URL, json=payload, timeout=10)
except Exception as e:
print(f"[!] Erreur envoi Discord : {e}")
@ -79,29 +80,15 @@ def run_mep_logic(author, commit_msg, branch="main"):
os.chdir(target_path)
# 1. GIT
# 1. GIT (Va maintenant pull depuis ton Forgejo auto-hébergé)
subprocess.run(["git", "fetch", "origin"], check=True)
subprocess.run(["git", "reset", "--hard", f"origin/{branch}"], check=True)
# 2. RSYNC (si on utilise le fallback de dépôt)
# 2. RSYNC (Fallback)
if use_rsync:
subprocess.run(["rsync", "-a", "--exclude=.git", "--exclude=venv", "--exclude=.venv", "--exclude=__pycache__", f"{target_path}/", f"{PROJECT_PATH}/"], check=True)
# ⚡ Migration automatique GitLab tracking
send_discord_log("MIGRATION", "Migration GitLab tracking en cours...", 16776960, author, commit_msg)
try:
subprocess.run(
["python3", os.path.join(target_path, "scripts", "migrate_gitlab_tracking.py")],
cwd=target_path,
check=True,
capture_output=True,
text=True
)
send_discord_log("MIGRATION", "✅ Migration GitLab tracking terminée.", 3066993, author, commit_msg)
except subprocess.CalledProcessError as e:
send_discord_log("ERREUR MIGRATION", f"❌ Migration GitLab échouée: {e.stderr}", 15158332, author, commit_msg)
# 3. PM2 (Appelé directement via son chemin absolu pour corriger l'erreur 127)
# 3. PM2 Restart
subprocess.run(
[PM2_BINARY, "restart", PROCESS_NAME],
check=True,
@ -110,26 +97,35 @@ def run_mep_logic(author, commit_msg, branch="main"):
)
duration = (datetime.now() - start_time).total_seconds()
msg = f"✅ **Déploiement réussi en {duration:.2f}s**\nLe bot est à jour et redémarré."
msg = f"✅ **Déploiement réussi en {duration:.2f}s**\nLe bot est à jour sur Forgejo et redémarré."
send_discord_log("VALIDÉ", msg, 3066993, author, commit_msg)
except subprocess.CalledProcessError as e:
# Capture spécifique si une commande système (comme Git ou PM2) crash
error_stderr = e.stderr if e.stderr else "Pas de log d'erreur disponible (stderr vide)."
error_stderr = e.stderr if e.stderr else "Pas de log d'erreur disponible."
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)
except Exception as e:
# Capture globale pour le reste du script Python
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():
# Sécurité
if request.headers.get('X-Gitlab-Token') != WEBHOOK_SECRET:
# 1. Vérification de la signature HMAC
signature_recue = request.headers.get('X-Hub-Signature-256')
if not signature_recue:
abort(403)
# Extraction des infos GitLab
payload_brut = request.get_data()
signature_attendue = "sha256=" + hmac.new(
WEBHOOK_SECRET.encode('utf-8'),
payload_brut,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature_attendue, signature_recue):
abort(403)
# 2. Logique de déploiement si la signature est valide
data = request.json
author = "Inconnu"
commit_msg = "Pas de message"
@ -138,45 +134,54 @@ def deploy():
author = data['commits'][0].get('author', {}).get('name', 'Inconnu')
commit_msg = data['commits'][0].get('message', 'Pas de message')
# Extraction de la branche
ref = data.get('ref', 'refs/heads/main')
branch = ref.split('/')[-1] if ref else 'main'
# Threading pour répondre vite à GitLab
threading.Thread(target=run_mep_logic, args=(author, commit_msg, branch)).start()
return {"status": "accepted"}, 202
@app.route('/gitlab_webhook', methods=['POST'])
def gitlab_webhook():
received_token = request.headers.get('X-Gitlab-Token')
print(f"[DEBUG] Webhook GitLab reçu. Token reçu: '{received_token}'")
if received_token != WEBHOOK_SECRET:
abort(403)
payload = request.json
relay_payload_to_bot(payload)
return {"status": "received"}, 200
# 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():
# 1. On récupère la signature envoyée par Forgejo/Gitea
signature_recue = None
for header_name in ('X-Hub-Signature-256', 'X-Gitea-Signature', 'X-Gogs-Signature'):
signature_recue = request.headers.get(header_name)
if signature_recue:
break
# 2. On lit les données brutes envoyées par Forgejo
payload_brut = request.get_data()
received_signature = (
request.headers.get('X-Hub-Signature-256')
or request.headers.get('X-Gitea-Signature')
or request.headers.get('X-Gogs-Signature')
)
if received_signature and not verify_signature(payload_brut, received_signature):
print("[!] Signature Forgejo invalide", flush=True)
abort(403)
# 3. Vérification de signature (compatible GitHub/Gitea/Gogs)
if signature_recue:
signature_attendue = "sha256=" + hmac.new(
WEBHOOK_SECRET.encode('utf-8'),
payload_brut,
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(signature_attendue, signature_recue):
print("[!] Signature invalide ! Hacking intercepté 🛡️", flush=True)
abort(403)
else:
# Fallback pratique pour les environnements locaux / tests où Forgejo n'envoie pas d'en-tête de signature.
print("[WARN] Aucune signature détectée, relayage du webhook sans vérification de signature.", flush=True)
print("[DEBUG] Signature validée avec succès !", flush=True)
# 4. Si tout est bon, on transmet au bot sur le port 5001
payload = request.json
relay_payload_to_bot(payload)
try:
requests.post(BOT_LOCAL_URL, json=payload, timeout=5)
except Exception as e:
print(f"[!] Erreur de relais vers le bot Discord : {e}", flush=True)
return {"status": "received"}, 200
if __name__ == '__main__':
print(f"[*] Webhook opérationnel. En attente de push ou d'events...")
app.run(host='0.0.0.0', port=5000)
print(f"[*] Webhook Forgejo opérationnel sur le port 5000. Prêt pour les MEP !")
app.run(host='0.0.0.0', port=5000)