Mise à jour : Passage des issues et du client vers Forgejo
This commit is contained in:
parent
d5167448df
commit
0e6a14dd10
3 changed files with 175 additions and 184 deletions
|
|
@ -12,17 +12,18 @@ app = Flask(__name__)
|
|||
PROJECT_PATH = "/home/discord/Bot/Kuby"
|
||||
WEBHOOK_SECRET = "Nois2"
|
||||
PROCESS_NAME = "kuby"
|
||||
# Ton 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"
|
||||
|
||||
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(),
|
||||
|
|
@ -36,7 +37,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}")
|
||||
|
||||
|
|
@ -58,29 +59,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,
|
||||
|
|
@ -89,26 +76,24 @@ 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:
|
||||
# ⚡ MODIFICATION : Forgejo envoie son token secret dans 'X-Gitea-Token'
|
||||
if request.headers.get('X-Gitea-Token') != WEBHOOK_SECRET:
|
||||
abort(403)
|
||||
|
||||
# Extraction des infos GitLab
|
||||
# Extraction des infos (La structure des commits est identique à GitLab)
|
||||
data = request.json
|
||||
author = "Inconnu"
|
||||
commit_msg = "Pas de message"
|
||||
|
|
@ -121,34 +106,32 @@ def deploy():
|
|||
ref = data.get('ref', 'refs/heads/main')
|
||||
branch = ref.split('/')[-1] if ref else 'main'
|
||||
|
||||
# Threading pour répondre vite à GitLab
|
||||
# Threading inchangé pour répondre instantanément à Forgejo
|
||||
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():
|
||||
# Protection par Token uniquement (anti-crawler géré par le secret)
|
||||
received_token = request.headers.get('X-Gitlab-Token')
|
||||
# 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')
|
||||
|
||||
# Log de debug pour voir ce que GitLab envoie vs ce qu'on attend
|
||||
print(f"[DEBUG] Webhook reçu. Token attendu: '{WEBHOOK_SECRET}', Token reçu: '{received_token}'")
|
||||
print(f"[DEBUG] Webhook d'événements reçu. Token reçu: '{received_token}'")
|
||||
|
||||
if received_token != WEBHOOK_SECRET:
|
||||
abort(403) # Changé en 403 pour différencier une route non trouvée d'un accès refusé
|
||||
abort(403)
|
||||
|
||||
# Transférer la payload au bot Discord localement sur le port 5001
|
||||
# Relai direct de la payload de l'événement (tickets, commentaires) vers ton bot local au port 5001
|
||||
payload = request.json
|
||||
try:
|
||||
# On tente de relayer au bot discord. Timeout légèrement augmenté pour plus de stabilité.
|
||||
# On ne passe plus de token interne pour simplifier comme demandé.
|
||||
requests.post(BOT_LOCAL_URL, json=payload, timeout=5)
|
||||
except Exception as e:
|
||||
print(f"[!] Erreur de relais vers le bot Discord : {e}")
|
||||
# On renvoie 200 à GitLab quand même car GitLab n'a pas à savoir l'état interne
|
||||
|
||||
return {"status": "received"}, 200
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(f"[*] Webhook opérationnel. En attente de push ou d'events...")
|
||||
print(f"[*] Webhook Forgejo opérationnel sur le port 5000. Prêt pour les MEP !")
|
||||
app.run(host='0.0.0.0', port=5000)
|
||||
Loading…
Add table
Add a link
Reference in a new issue