Initial commit: FlexiCraft Web Portal + Discord SSO + Quartz/Iron engines
This commit is contained in:
commit
f488ff57c5
19 changed files with 3256 additions and 0 deletions
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
venv/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
data/package_backups/
|
||||
*.tmp
|
||||
74
app.py
Normal file
74
app.py
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import os, json, secrets
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
from core.server_live import get_live_status, get_citizens_count
|
||||
from core.auth_tiers import compute_user_tier, filter_tools_for_tier
|
||||
from core.discord_oauth import get_authorize_url, exchange_code_and_fetch_member
|
||||
|
||||
BASE = "/var/www/flexicraft-site"
|
||||
app = FastAPI(title="FlexiCraft Portal")
|
||||
app.add_middleware(SessionMiddleware, secret_key=os.environ.get("WEB_SECRET_KEY", "flexicraft_super_secret_2026"))
|
||||
app.mount("/static", StaticFiles(directory=f"{BASE}/static"), name="static")
|
||||
templates = Jinja2Templates(directory=f"{BASE}/templates")
|
||||
|
||||
def load_json(rel):
|
||||
with open(f"{BASE}/{rel}", "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def get_ctx(request: Request):
|
||||
cfg = load_json("config/site_config.json")
|
||||
content = load_json("config/content.json")
|
||||
user = request.session.get("user")
|
||||
tier = compute_user_tier(user.get("roles", []), cfg["role_tiers"]) if user else "visitor"
|
||||
return {
|
||||
"request": request,
|
||||
"cfg": cfg,
|
||||
"content": content,
|
||||
"user": user,
|
||||
"tier": tier,
|
||||
"sso_enabled": bool(os.environ.get("DISCORD_CLIENT_ID"))
|
||||
}
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def home(request: Request):
|
||||
ctx = get_ctx(request)
|
||||
ctx["status"] = get_live_status(ctx["cfg"]["mc_host"], ctx["cfg"]["mc_port"])
|
||||
ctx["citizens_count"] = get_citizens_count()
|
||||
return templates.TemplateResponse(request=request, name="index.html", context=ctx)
|
||||
|
||||
@app.get("/tools", response_class=HTMLResponse)
|
||||
async def tools_page(request: Request):
|
||||
ctx = get_ctx(request)
|
||||
ctx["tools"] = filter_tools_for_tier(ctx["content"]["tools"], ctx["tier"])
|
||||
return templates.TemplateResponse(request=request, name="tools.html", context=ctx)
|
||||
|
||||
@app.get("/auth/discord")
|
||||
async def auth_discord(request: Request):
|
||||
state = secrets.token_urlsafe(16)
|
||||
request.session["oauth_state"] = state
|
||||
return RedirectResponse(get_authorize_url(state))
|
||||
|
||||
@app.get("/auth/discord/callback")
|
||||
async def auth_discord_callback(request: Request, code: str = None, state: str = None):
|
||||
if not code or state != request.session.get("oauth_state"):
|
||||
return RedirectResponse("/?auth_error=invalid_state")
|
||||
try:
|
||||
user_info = await exchange_code_and_fetch_member(code)
|
||||
request.session["user"] = user_info
|
||||
except Exception as e:
|
||||
print(f"[SSO] Erreur callback Discord : {e}")
|
||||
return RedirectResponse("/?auth_error=oauth_failed")
|
||||
return RedirectResponse("/tools")
|
||||
|
||||
@app.get("/auth/logout")
|
||||
async def auth_logout(request: Request):
|
||||
request.session.clear()
|
||||
return RedirectResponse("/")
|
||||
|
||||
@app.get("/api/status")
|
||||
async def api_status():
|
||||
cfg = load_json("config/site_config.json")
|
||||
return JSONResponse(get_live_status(cfg["mc_host"], cfg["mc_port"]))
|
||||
71
config/content.json
Normal file
71
config/content.json
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
{
|
||||
"hero_title": "FlexiCraft — Musée Vivant & Démocratie depuis 2019",
|
||||
"hero_subtitle": "Serveur Survie Semi-Vanilla Crossplay (Java 1.9 → 1.21.11+ & Bedrock). Une société organisée par ses citoyens, ses ministères et ses lois.",
|
||||
"pillars": [
|
||||
{
|
||||
"icon": "🏛️",
|
||||
"title": "Démocratie & Lois",
|
||||
"text": "Une constitution et des codes ministériels votés et appliqués en toute transparence."
|
||||
},
|
||||
{
|
||||
"icon": "🌍",
|
||||
"title": "Crossplay Universel",
|
||||
"text": "Jouez ensemble depuis Java (1.9 à 1.21.11+) et Bedrock (Switch, Mobile, Console) avec synchronisation de profil."
|
||||
},
|
||||
{
|
||||
"icon": "🧱",
|
||||
"title": "Musée Vivant (Depuis 2019)",
|
||||
"text": "Aucune réinitialisation destructive : chaque construction, gare et monument fait partie de l'histoire du serveur."
|
||||
}
|
||||
],
|
||||
"tools": [
|
||||
{
|
||||
"id": "pl3xmap",
|
||||
"title": "🗺️ Carte Interactive 2D (Pl3xMap)",
|
||||
"desc": "Explorez le monde en temps réel, les régions et les constructions.",
|
||||
"url": "https://map.flexicraft.eu",
|
||||
"min_tier": "visitor",
|
||||
"badge": "Public"
|
||||
},
|
||||
{
|
||||
"id": "discord",
|
||||
"title": "💬 Communauté & Citoyenneté Discord",
|
||||
"desc": "Liez votre compte Minecraft, acceptez les Codes et participez aux assemblées.",
|
||||
"url": "https://discord.flexicraft.eu",
|
||||
"min_tier": "visitor",
|
||||
"badge": "Public"
|
||||
},
|
||||
{
|
||||
"id": "forgejo",
|
||||
"title": "🦊 Forgejo — Dépôts Git, Plugins & Datapacks",
|
||||
"desc": "Code source, configurations publiques, datapacks et suivi des mises à jour.",
|
||||
"url": "https://forge.flexicraft.eu",
|
||||
"min_tier": "citizen",
|
||||
"badge": "Citoyen+"
|
||||
},
|
||||
{
|
||||
"id": "audit_hub",
|
||||
"title": "🕵️ Portail Contre-Pouvoir & Audits",
|
||||
"desc": "Consultation des journaux d'actions et transparence des ministères.",
|
||||
"url": "https://audit.flexicraft.eu",
|
||||
"min_tier": "charcoal",
|
||||
"badge": "Charcoal / Guardian"
|
||||
},
|
||||
{
|
||||
"id": "updater",
|
||||
"title": "🔄 Gestionnaire Auto-Update Plugins & Datapacks",
|
||||
"desc": "Déclenchement et suivi des mises à jour automatisées du serveur.",
|
||||
"url": "/tools/updater",
|
||||
"min_tier": "admin",
|
||||
"badge": "Admin / Diamond"
|
||||
},
|
||||
{
|
||||
"id": "pterodactyl",
|
||||
"title": "🖥️ Console & Orchestrateur Pterodactyl",
|
||||
"desc": "Accès technique au panel serveur et aux dossiers ministériels.",
|
||||
"url": "https://admin.flexicraft.eu",
|
||||
"min_tier": "guardian",
|
||||
"badge": "Guardians"
|
||||
}
|
||||
]
|
||||
}
|
||||
2119
config/packages_registry.json
Normal file
2119
config/packages_registry.json
Normal file
File diff suppressed because it is too large
Load diff
28
config/site_config.json
Normal file
28
config/site_config.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"site_name": "FlexiCraft",
|
||||
"guild_id": "645626003594412061",
|
||||
"mc_host": "151.247.192.82",
|
||||
"mc_port": 25565,
|
||||
"public_links": {
|
||||
"java_ip": "mc.flexicraft.eu",
|
||||
"bedrock_ip": "mc.flexicraft.eu",
|
||||
"bedrock_port": 19132,
|
||||
"map_url": "https://map.flexicraft.eu",
|
||||
"discord_url": "https://discord.flexicraft.eu",
|
||||
"forgejo_url": "https://forge.flexicraft.eu",
|
||||
"audit_url": "https://audit.flexicraft.eu",
|
||||
"panel_url": "https://admin.flexicraft.eu"
|
||||
},
|
||||
"role_tiers": {
|
||||
"citizen": ["645629375060115466"],
|
||||
"moderation": ["1572688957362409482", "1572687861407555745", "1572684174895218818"],
|
||||
"guardian": [
|
||||
"1572681141528301588", "1572682446665949344", "1572683109999190128",
|
||||
"1572683357815316500", "1572686122721480734", "1572685733733601321",
|
||||
"1572684601111879730", "1572686978980388894", "1572685344153796749",
|
||||
"1572686623743672363", "1572687298682687538", "1572684174895218818"
|
||||
],
|
||||
"charcoal": ["1572680750321369420"],
|
||||
"admin": ["1572681141528301588", "683346841265373195"]
|
||||
}
|
||||
}
|
||||
32
core/auth_tiers.py
Normal file
32
core/auth_tiers.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
TIER_LEVELS = {
|
||||
"visitor": 0,
|
||||
"citizen": 1,
|
||||
"moderation": 2,
|
||||
"charcoal": 3,
|
||||
"guardian": 4,
|
||||
"admin": 5
|
||||
}
|
||||
|
||||
def compute_user_tier(role_ids: list, role_tiers_cfg: dict) -> str:
|
||||
rset = {str(r) for r in role_ids}
|
||||
if rset & set(role_tiers_cfg.get("admin", [])):
|
||||
return "admin"
|
||||
if rset & set(role_tiers_cfg.get("guardian", [])):
|
||||
return "guardian"
|
||||
if rset & set(role_tiers_cfg.get("charcoal", [])):
|
||||
return "charcoal"
|
||||
if rset & set(role_tiers_cfg.get("moderation", [])):
|
||||
return "moderation"
|
||||
if rset & set(role_tiers_cfg.get("citizen", [])):
|
||||
return "citizen"
|
||||
return "visitor"
|
||||
|
||||
def filter_tools_for_tier(tools: list, user_tier: str) -> list:
|
||||
user_lvl = TIER_LEVELS.get(user_tier, 0)
|
||||
enriched = []
|
||||
for t in tools:
|
||||
req_lvl = TIER_LEVELS.get(t.get("min_tier", "visitor"), 0)
|
||||
item = dict(t)
|
||||
item["unlocked"] = user_lvl >= req_lvl
|
||||
enriched.append(item)
|
||||
return enriched
|
||||
64
core/discord_oauth.py
Normal file
64
core/discord_oauth.py
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import os, urllib.parse, httpx
|
||||
|
||||
GUILD_ID = "645626003594412061"
|
||||
DISCORD_API = "https://discord.com" + "/api/v10"
|
||||
DISCORD_AUTH = "https://discord.com" + "/oauth2/authorize"
|
||||
REDIRECT_URI = "https://flexicraft.eu" + "/auth/discord/callback"
|
||||
|
||||
def get_authorize_url(state: str) -> str:
|
||||
client_id = os.environ.get("DISCORD_CLIENT_ID", "")
|
||||
params = {
|
||||
"client_id": client_id,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"response_type": "code",
|
||||
"scope": "identify guilds.members.read",
|
||||
"state": state
|
||||
}
|
||||
return DISCORD_AUTH + "?" + urllib.parse.urlencode(params)
|
||||
|
||||
async def exchange_code_and_fetch_member(code: str) -> dict:
|
||||
client_id = os.environ.get("DISCORD_CLIENT_ID", "")
|
||||
client_secret = os.environ.get("DISCORD_CLIENT_SECRET", "")
|
||||
bot_token = os.environ.get("DISCORD_BOT_TOKEN", "")
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
token_resp = await client.post(
|
||||
DISCORD_API + "/oauth2/token",
|
||||
data={
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
"redirect_uri": REDIRECT_URI
|
||||
},
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"}
|
||||
)
|
||||
token_resp.raise_for_status()
|
||||
access_token = token_resp.json()["access_token"]
|
||||
|
||||
user_resp = await client.get(
|
||||
DISCORD_API + "/users/@me",
|
||||
headers={"Authorization": f"Bearer {access_token}"}
|
||||
)
|
||||
user_resp.raise_for_status()
|
||||
u = user_resp.json()
|
||||
|
||||
roles = []
|
||||
nick = u.get("global_name") or u.get("username")
|
||||
if bot_token:
|
||||
mem_resp = await client.get(
|
||||
f"{DISCORD_API}/guilds/{GUILD_ID}/members/{u['id']}",
|
||||
headers={"Authorization": f"Bot {bot_token}"}
|
||||
)
|
||||
if mem_resp.status_code == 200:
|
||||
mdata = mem_resp.json()
|
||||
roles = mdata.get("roles", [])
|
||||
if mdata.get("nick"):
|
||||
nick = mdata["nick"]
|
||||
|
||||
return {
|
||||
"id": u["id"],
|
||||
"username": nick,
|
||||
"avatar": u.get("avatar"),
|
||||
"roles": roles
|
||||
}
|
||||
81
core/forgejo_bridge.py
Normal file
81
core/forgejo_bridge.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import os, time, shutil, zipfile, subprocess
|
||||
from datetime import datetime
|
||||
from core.package_updater import (
|
||||
PLUGINS_DIR, DATAPACKS_DIR, BACKUP_DIR,
|
||||
load_registry, save_registry, _verify_archive
|
||||
)
|
||||
|
||||
def deploy_from_forgejo_release(payload: dict) -> dict:
|
||||
"""
|
||||
Declenche lorsqu'un Guardian publie une Release sur Forgejo.
|
||||
Verifie que le paquet est bien route sur la voie 'forgejo' par le Ministre du Lapis.
|
||||
"""
|
||||
action = payload.get("action")
|
||||
if action != "published":
|
||||
return {"ok": True, "ignored": f"Action release '{action}' ignoree"}
|
||||
|
||||
repo_full = payload.get("repository", {}).get("full_name", "")
|
||||
rel = payload.get("release", {})
|
||||
tag = str(rel.get("tag_name", "")).lstrip("v")
|
||||
assets = rel.get("assets", [])
|
||||
zipball_url = rel.get("zipball_url", "")
|
||||
|
||||
reg = load_registry()
|
||||
pkg = next((p for p in reg.get("packages", []) if p.get("forgejo", {}).get("repo", "").lower() == repo_full.lower()), None)
|
||||
if not pkg:
|
||||
return {"ok": False, "error": f"Aucun paquet associe au depot {repo_full}"}
|
||||
|
||||
if pkg.get("track") != "forgejo":
|
||||
return {"ok": False, "error": f"Refuse : {pkg['name']} est actuellement route sur la voie Externe (Quartz) par Lapis"}
|
||||
|
||||
ptype = pkg.get("type", "plugin")
|
||||
target_dir = PLUGINS_DIR if ptype == "plugin" else DATAPACKS_DIR
|
||||
ext_wanted = ".jar" if ptype == "plugin" else ".zip"
|
||||
|
||||
chosen_asset = next((a for a in assets if a.get("name", "").endswith(ext_wanted)), None)
|
||||
dl_url = chosen_asset.get("browser_download_url") if chosen_asset else (zipball_url if ptype == "datapack" else "")
|
||||
new_fn = chosen_asset.get("name") if chosen_asset else f"{pkg['id']}-{tag}.zip"
|
||||
|
||||
if not dl_url:
|
||||
return {"ok": False, "error": f"Aucun fichier {ext_wanted} attache a la release {tag}"}
|
||||
|
||||
tmp_path = f"/tmp/fc_forge_{int(time.time())}_{new_fn}"
|
||||
try:
|
||||
res = subprocess.run(["curl", "-4", "-fL", "--connect-timeout", "15", dl_url, "-o", tmp_path])
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"Echec telechargement release Forgejo (curl {res.returncode})")
|
||||
|
||||
# Si datapack telecharge depuis zipball GitHub/Forgejo (dossier racine imbrique), re-empaqueter proprement
|
||||
if not chosen_asset and ptype == "datapack":
|
||||
clean_zip = f"/tmp/fc_dp_clean_{int(time.time())}_{new_fn}"
|
||||
with zipfile.ZipFile(tmp_path, "r") as zin:
|
||||
mcmeta = next((n for n in zin.namelist() if n.endswith("pack.mcmeta")), None)
|
||||
if not mcmeta:
|
||||
raise RuntimeError("pack.mcmeta introuvable dans la release du datapack")
|
||||
prefix = mcmeta[:-len("pack.mcmeta")]
|
||||
with zipfile.ZipFile(clean_zip, "w", zipfile.ZIP_DEFLATED) as zout:
|
||||
for item in zin.infolist():
|
||||
if item.filename.startswith(prefix) and len(item.filename) > len(prefix):
|
||||
zout.writestr(item.filename[len(prefix):], zin.read(item.filename))
|
||||
os.remove(tmp_path)
|
||||
tmp_path = clean_zip
|
||||
|
||||
_verify_archive(tmp_path, ptype)
|
||||
|
||||
old_path = os.path.join(target_dir, pkg.get("filename", ""))
|
||||
if os.path.exists(old_path):
|
||||
shutil.copy2(old_path, os.path.join(BACKUP_DIR, f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{pkg['filename']}"))
|
||||
if pkg["filename"] != new_fn:
|
||||
os.remove(old_path)
|
||||
|
||||
final_p = os.path.join(target_dir, new_fn)
|
||||
shutil.move(tmp_path, final_p)
|
||||
shutil.chown(final_p, user="pterodactyl", group="pterodactyl")
|
||||
|
||||
pkg.update({"filename": new_fn, "version": tag})
|
||||
save_registry(reg)
|
||||
return {"ok": True, "msg": f"Release Forgejo {tag} deployee pour {pkg['name']} ({new_fn})"}
|
||||
except Exception as e:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
return {"ok": False, "error": str(e)}
|
||||
146
core/package_updater.py
Normal file
146
core/package_updater.py
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import os, re, json, time, shutil, zipfile, subprocess
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlunsplit, urlparse
|
||||
|
||||
MC_BASE = "/var/lib/pterodactyl/volumes/bd102f43-4033-4c60-9922-53c436330f21"
|
||||
PLUGINS_DIR = f"{MC_BASE}/plugins"
|
||||
DATAPACKS_DIR = f"{MC_BASE}/world/datapacks"
|
||||
REG_FILE = "/var/www/flexicraft-site/config/packages_registry.json"
|
||||
BACKUP_DIR = "/var/www/flexicraft-site/data/package_backups"
|
||||
os.makedirs(BACKUP_DIR, exist_ok=True)
|
||||
|
||||
def _build_url(host_parts, path_str):
|
||||
return urlunsplit(("https", ".".join(host_parts), path_str, "", ""))
|
||||
|
||||
def load_registry():
|
||||
if not os.path.exists(REG_FILE):
|
||||
return {"packages": []}
|
||||
with open(REG_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def save_registry(data):
|
||||
tmp = REG_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
os.replace(tmp, REG_FILE)
|
||||
|
||||
def _curl_json(url):
|
||||
cmd = ["curl", "-4", "-fsSL", "--connect-timeout", "10", "-A", "FlexiCraft-Quartz/1.0", url]
|
||||
res = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"Erreur reseau API (code {res.returncode})")
|
||||
return json.loads(res.stdout)
|
||||
|
||||
def _norm_ver(v):
|
||||
clean = re.sub(r"^v", "", str(v or "").strip().lower())
|
||||
clean, _, _ = clean.partition("+")
|
||||
clean, _, _ = clean.partition("-snapshot")
|
||||
return clean
|
||||
|
||||
def resolve_latest_release(pkg: dict) -> dict:
|
||||
ext = pkg.get("external", {})
|
||||
provider = ext.get("provider", "manual")
|
||||
slug = str(ext.get("slug", "")).strip()
|
||||
af = str(ext.get("asset_filter", "")).strip().lower()
|
||||
ptype = pkg.get("type", "plugin")
|
||||
|
||||
if provider in ("manual", "vanillatweaks", "") or (provider != "direct_url" and not slug):
|
||||
return None
|
||||
if provider == "modrinth":
|
||||
versions = _curl_json(_build_url(("api", "modrinth", "com"), f"/v2/project/{slug}/version"))
|
||||
stable = next((v for v in versions if v.get("version_type") == "release"), None)
|
||||
if not stable:
|
||||
raise RuntimeError("Aucune release stable sur Modrinth")
|
||||
files = stable.get("files", [])
|
||||
chosen = next((f for f in files if af in f.get("filename", "").lower()), None) if af else next((f for f in files if f.get("primary")), next(iter(files), None))
|
||||
if not chosen:
|
||||
raise RuntimeError("Fichier introuvable sur Modrinth")
|
||||
return {"version": str(stable.get("version_number")), "download_url": chosen.get("url"), "filename": chosen.get("filename")}
|
||||
if provider == "hangar":
|
||||
oslug = slug if "/" in slug else f"PaperMC/{slug}"
|
||||
res = subprocess.run(["curl", "-4", "-fsSL", "--connect-timeout", "10", "-A", "FlexiCraft-Quartz/1.0", _build_url(("hangar", "papermc", "io"), f"/api/v1/projects/{oslug}/latestrelease")], capture_output=True, text=True)
|
||||
ver = res.stdout.strip().strip('"')
|
||||
if res.returncode != 0 or not ver:
|
||||
raise RuntimeError("Erreur Hangar API")
|
||||
return {"version": ver, "download_url": _build_url(("hangar", "papermc", "io"), f"/api/v1/projects/{oslug}/versions/{ver}/PAPER/download"), "filename": f"{pkg.get('name', slug)}-{ver}.jar"}
|
||||
if provider == "github":
|
||||
rel = _curl_json(_build_url(("api", "github", "com"), f"/repos/{slug}/releases/latest"))
|
||||
ext_w = ".jar" if ptype == "plugin" else ".zip"
|
||||
cands = [a for a in rel.get("assets", []) if a.get("name", "").endswith(ext_w)]
|
||||
chosen = next((a for a in cands if af in a.get("name", "").lower()), next(iter(cands), None))
|
||||
if not chosen:
|
||||
raise RuntimeError(f"Asset {ext_w} introuvable sur GitHub")
|
||||
return {"version": str(rel.get("tag_name", "")).lstrip("v"), "download_url": chosen.get("browser_download_url"), "filename": chosen.get("name")}
|
||||
if provider == "direct_url":
|
||||
raw_u = ext.get("url", "").strip()
|
||||
return {"version": "direct", "download_url": raw_u, "filename": os.path.basename(urlparse(raw_u).path) or pkg.get("filename")}
|
||||
raise RuntimeError(f"Provider inconnu : {provider}")
|
||||
|
||||
def _verify_archive(tmp_path: str, ptype: str):
|
||||
if not os.path.exists(tmp_path) or os.path.getsize(tmp_path) == 0 or not zipfile.is_zipfile(tmp_path):
|
||||
raise RuntimeError("Archive corrompue ou page HTML")
|
||||
with zipfile.ZipFile(tmp_path, "r") as z:
|
||||
names = z.namelist()
|
||||
if ptype == "plugin" and not any(n in names for n in ("plugin.yml", "paper-plugin.yml")):
|
||||
raise RuntimeError("JAR valide mais plugin.yml absent")
|
||||
if ptype == "datapack" and "pack.mcmeta" not in names:
|
||||
raise RuntimeError("ZIP valide mais pack.mcmeta absent")
|
||||
|
||||
def scan_external_updates() -> list:
|
||||
reg = load_registry()
|
||||
report = []
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
for pkg in reg.get("packages", []):
|
||||
if pkg.get("track") != "external" or not pkg.get("enabled", True):
|
||||
continue
|
||||
ext = pkg.get("external", {})
|
||||
try:
|
||||
lat = resolve_latest_release(pkg)
|
||||
if not lat:
|
||||
report.append({"id": pkg["id"], "status": "skipped", "msg": "Source manuelle"})
|
||||
continue
|
||||
cur_v, lat_v = pkg.get("version", ""), lat["version"]
|
||||
if _norm_ver(lat_v) != _norm_ver(cur_v) and _norm_ver(cur_v) not in _norm_ver(lat_v):
|
||||
if ext.get("pending_version") != lat_v:
|
||||
ext.update({"pending_version": lat_v, "pending_url": lat["download_url"], "pending_filename": lat["filename"], "detected_at": now_iso})
|
||||
ext["last_error"] = None
|
||||
report.append({"id": pkg["id"], "status": "update_pending", "msg": f"v{cur_v} -> v{lat_v} (quarantaine {ext.get('quarantine_days', 3)}j)"})
|
||||
else:
|
||||
ext.update({"pending_version": None, "pending_url": None, "detected_at": None, "last_error": None})
|
||||
report.append({"id": pkg["id"], "status": "up_to_date", "msg": f"A jour (v{cur_v})"})
|
||||
except Exception as e:
|
||||
ext["last_error"] = str(e)
|
||||
report.append({"id": pkg["id"], "status": "error", "msg": str(e)})
|
||||
save_registry(reg)
|
||||
return report
|
||||
|
||||
def apply_package_update(pkg_id: str) -> dict:
|
||||
reg = load_registry()
|
||||
pkg = next((p for p in reg.get("packages", []) if p.get("id") == pkg_id), None)
|
||||
if not pkg or not pkg.get("external", {}).get("pending_url"):
|
||||
return {"ok": False, "error": "Aucune mise a jour en attente"}
|
||||
ext = pkg["external"]
|
||||
ptype = pkg.get("type", "plugin")
|
||||
target_dir = PLUGINS_DIR if ptype == "plugin" else DATAPACKS_DIR
|
||||
tmp_path = f"/tmp/fc_upd_{int(time.time())}_{ext['pending_filename']}"
|
||||
try:
|
||||
res = subprocess.run(["curl", "-4", "-fL", "--connect-timeout", "15", "-A", "FlexiCraft-Quartz/1.0", ext["pending_url"], "-o", tmp_path])
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"Echec curl ({res.returncode})")
|
||||
_verify_archive(tmp_path, ptype)
|
||||
old_path = os.path.join(target_dir, pkg.get("filename", ""))
|
||||
if os.path.exists(old_path):
|
||||
shutil.copy2(old_path, os.path.join(BACKUP_DIR, f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{pkg['filename']}"))
|
||||
if pkg["filename"] != ext["pending_filename"]:
|
||||
os.remove(old_path)
|
||||
final_p = os.path.join(target_dir, ext["pending_filename"])
|
||||
shutil.move(tmp_path, final_p)
|
||||
shutil.chown(final_p, user="pterodactyl", group="pterodactyl")
|
||||
pkg.update({"filename": ext["pending_filename"], "version": ext["pending_version"]})
|
||||
ext.update({"pending_version": None, "pending_url": None, "pending_filename": None, "detected_at": None, "last_error": None})
|
||||
save_registry(reg)
|
||||
return {"ok": True, "msg": f"{pkg['name']} mis a jour vers v{pkg['version']}"}
|
||||
except Exception as e:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
return {"ok": False, "error": str(e)}
|
||||
34
core/server_live.py
Normal file
34
core/server_live.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import os, json
|
||||
from mcstatus import JavaServer
|
||||
|
||||
LINKS_DB = "/root/flexicraft-discord-setup/data/crossplay_links.json"
|
||||
|
||||
def get_live_status(host="151.247.192.82", port=25565):
|
||||
try:
|
||||
srv = JavaServer.lookup(f"{host}:{port}")
|
||||
st = srv.status()
|
||||
players = [p.name for p in st.players.sample] if st.players.sample else []
|
||||
return {
|
||||
"online": True,
|
||||
"players_online": st.players.online,
|
||||
"players_max": st.players.max,
|
||||
"players_list": players,
|
||||
"version": "Paper 1.21.11 (1.9 → 1.21.11+)"
|
||||
}
|
||||
except Exception:
|
||||
return {
|
||||
"online": False,
|
||||
"players_online": 0,
|
||||
"players_max": 25,
|
||||
"players_list": [],
|
||||
"version": "Paper 1.21.11"
|
||||
}
|
||||
|
||||
def get_citizens_count():
|
||||
if os.path.exists(LINKS_DB):
|
||||
try:
|
||||
with open(LINKS_DB, "r", encoding="utf-8") as f:
|
||||
return len(json.load(f))
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
1
index.html
Normal file
1
index.html
Normal file
|
|
@ -0,0 +1 @@
|
|||
<h1>Bienvenue sur FlexiCraft</h1><p>Site en cours de construction. Rejoignez-nous sur <b>mc.flexicraft.eu</b> !</p>
|
||||
39
static/style.css
Normal file
39
static/style.css
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
:root {
|
||||
--bg: #0e1117;
|
||||
--surface: #161b24;
|
||||
--surface-hover: #1e2532;
|
||||
--border: #283142;
|
||||
--text: #e6edf3;
|
||||
--muted: #8b949e;
|
||||
--accent: #a371f7;
|
||||
--diamond: #58a6ff;
|
||||
--emerald: #3fb950;
|
||||
--gold: #d29922;
|
||||
--danger: #f85149;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: 'Segoe UI', system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); line-height: 1.6; }
|
||||
a { color: inherit; text-decoration: none; }
|
||||
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 1rem 5%; background: var(--surface); border-bottom: 1px solid var(--border); position: sticky; top: 0; z-index: 10; }
|
||||
.brand { font-size: 1.35rem; font-weight: 800; background: linear-gradient(90deg, var(--diamond), var(--accent)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
||||
.nav-links { display: flex; gap: 1.5rem; align-items: center; }
|
||||
.nav-links a:hover { color: var(--diamond); }
|
||||
.btn { display: inline-flex; align-items: center; gap: .5rem; padding: .55rem 1.1rem; border-radius: 8px; font-weight: 600; border: 1px solid var(--border); background: var(--surface-hover); cursor: pointer; transition: .2s; }
|
||||
.btn-primary { background: #5865F2; border-color: #5865F2; color: #fff; }
|
||||
.btn-primary:hover { background: #4752C4; }
|
||||
.btn-emerald { background: var(--emerald); border-color: var(--emerald); color: #09130b; }
|
||||
.container { max-width: 1120px; margin: 0 auto; padding: 2.5rem 1.5rem; }
|
||||
.hero { text-align: center; padding: 3.5rem 1.5rem; background: radial-gradient(circle at top, #1d2236 0%, var(--bg) 70%); border-bottom: 1px solid var(--border); }
|
||||
.hero h1 { font-size: 2.4rem; margin-bottom: 1rem; }
|
||||
.hero p { color: var(--muted); max-width: 680px; margin: 0 auto 2rem; font-size: 1.1rem; }
|
||||
.status-bar { display: inline-flex; flex-wrap: wrap; gap: 1rem; justify-content: center; background: var(--surface); padding: .85rem 1.4rem; border-radius: 12px; border: 1px solid var(--border); }
|
||||
.pill { display: inline-flex; align-items: center; gap: .4rem; font-size: .92rem; padding: .25rem .7rem; border-radius: 999px; background: var(--bg); border: 1px solid var(--border); }
|
||||
.dot-on { width: 9px; height: 9px; border-radius: 50%; background: var(--emerald); box-shadow: 0 0 8px var(--emerald); }
|
||||
.dot-off { width: 9px; height: 9px; border-radius: 50%; background: var(--danger); }
|
||||
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.4rem; margin-top: 1.5rem; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 1.5rem; display: flex; flex-direction: column; justify-content: space-between; transition: .2s; }
|
||||
.card:hover { border-color: var(--diamond); transform: translateY(-2px); }
|
||||
.card.locked { opacity: .65; border-style: dashed; }
|
||||
.badge { font-size: .75rem; font-weight: 700; padding: .2rem .6rem; border-radius: 6px; background: var(--bg); color: var(--diamond); border: 1px solid var(--border); }
|
||||
.copy-box { font-family: monospace; background: var(--bg); padding: .5rem .9rem; border-radius: 8px; border: 1px solid var(--border); color: var(--diamond); cursor: pointer; }
|
||||
footer { text-align: center; padding: 2rem; color: var(--muted); border-top: 1px solid var(--border); margin-top: 4rem; font-size: .9rem; }
|
||||
32
templates/base.html
Normal file
32
templates/base.html
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{ cfg.site_name }} — Musée Vivant & Démocratie</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navbar">
|
||||
<a href="/" class="brand">🪨 {{ cfg.site_name }}</a>
|
||||
<div class="nav-links">
|
||||
<a href="/">Accueil</a>
|
||||
<a href="/tools">Outils & Écosystème</a>
|
||||
<a href="{{ cfg.public_links.map_url }}" target="_blank">Carte 2D</a>
|
||||
<a href="{{ cfg.public_links.forgejo_url }}" target="_blank">Forgejo</a>
|
||||
{% if user %}
|
||||
<span class="pill">👤 {{ user.username }} ({{ tier|upper }})</span>
|
||||
<a href="/auth/logout" class="btn">Déconnexion</a>
|
||||
{% elif sso_enabled %}
|
||||
<a href="/auth/discord" class="btn btn-primary">Connexion Discord</a>
|
||||
{% else %}
|
||||
<a href="{{ cfg.public_links.discord_url }}" target="_blank" class="btn btn-primary">Rejoindre Discord</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</nav>
|
||||
{% block content %}{% endblock %}
|
||||
<footer>
|
||||
FlexiCraft (2019 — 2026) • Java 1.9 → 1.21.11+ & Bedrock Crossplay • Mode actif : <strong>{{ tier|upper }}</strong>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
42
templates/index.html
Normal file
42
templates/index.html
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<section class="hero">
|
||||
<h1>{{ content.hero_title }}</h1>
|
||||
<p>{{ content.hero_subtitle }}</p>
|
||||
<div class="status-bar">
|
||||
<span class="pill">
|
||||
<span class="{{ 'dot-on' if status.online else 'dot-off' }}"></span>
|
||||
{{ 'EN LIGNE' if status.online else 'HORS LIGNE' }} ({{ status.players_online }}/{{ status.players_max }})
|
||||
</span>
|
||||
<span class="copy-box" onclick="navigator.clipboard.writeText('{{ cfg.public_links.java_ip }}')" title="Cliquer pour copier">
|
||||
☕ Java : {{ cfg.public_links.java_ip }}
|
||||
</span>
|
||||
<span class="copy-box" onclick="navigator.clipboard.writeText('{{ cfg.public_links.bedrock_ip }}:{{ cfg.public_links.bedrock_port }}')" title="Cliquer pour copier">
|
||||
📱 Bedrock : {{ cfg.public_links.bedrock_ip }} ({{ cfg.public_links.bedrock_port }})
|
||||
</span>
|
||||
<span class="pill">🪪 {{ citizens_count }} Citoyen(s) lié(s)</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="container">
|
||||
<h2>Les 3 piliers de FlexiCraft</h2>
|
||||
<div class="grid">
|
||||
{% for p in content.pillars %}
|
||||
<div class="card">
|
||||
<div>
|
||||
<h3>{{ p.icon }} {{ p.title }}</h3>
|
||||
<p style="color:var(--muted);margin-top:.6rem">{{ p.text }}</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div style="margin-top:3rem;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem">
|
||||
<div>
|
||||
<h2>Accès rapide à l'écosystème</h2>
|
||||
<p style="color:var(--muted)">Explorez la carte interactive, rejoignez le Discord ou accédez aux outils selon votre rôle.</p>
|
||||
</div>
|
||||
<a href="/tools" class="btn btn-emerald">Voir tous les outils →</a>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
31
templates/tools.html
Normal file
31
templates/tools.html
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem">
|
||||
<div>
|
||||
<h1>🧰 Portail des Outils FlexiCraft</h1>
|
||||
<p style="color:var(--muted)">Niveau d'accès actuel : <strong>{{ tier|upper }}</strong> {% if tier == 'visitor' %}(Mode visiteur public — connectez-vous via Discord pour débloquer les outils citoyens et ministériels){% endif %}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
{% for t in tools %}
|
||||
<div class="card {{ '' if t.unlocked else 'locked' }}">
|
||||
<div>
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.8rem">
|
||||
<span class="badge">{{ t.badge }}</span>
|
||||
<span>{{ '🔓 Débloqué' if t.unlocked else '🔒 Verrouillé' }}</span>
|
||||
</div>
|
||||
<h3>{{ t.title }}</h3>
|
||||
<p style="color:var(--muted);margin:.6rem 0 1.2rem">{{ t.desc }}</p>
|
||||
</div>
|
||||
{% if t.unlocked %}
|
||||
<a href="{{ t.url }}" class="btn btn-primary" target="{{ '_blank' if t.url.startswith('http') else '_self' }}">Ouvrir l'outil →</a>
|
||||
{% else %}
|
||||
<span class="btn" style="cursor:not-allowed">Requiert le rang {{ t.badge }}</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
115
tools/check_updates_status.py
Normal file
115
tools/check_updates_status.py
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import os, re, json, subprocess
|
||||
|
||||
MC_LOG = "/var/lib/pterodactyl/volumes/bd102f43-4033-4c60-9922-53c436330f21/logs/latest.log"
|
||||
REG_FILE = "/var/www/flexicraft-site/config/packages_registry.json"
|
||||
|
||||
API_OVERRIDES = {
|
||||
"essentials": ("modrinth", "essentialsx"),
|
||||
"essentialschat": ("modrinth", "essentialsx"),
|
||||
"essentialsspawn": ("modrinth", "essentialsx"),
|
||||
"coreprotect": ("modrinth", "coreprotect"),
|
||||
"geyser-spigot": ("hangar", "GeyserMC/Geyser"),
|
||||
"floodgate": ("hangar", "GeyserMC/Floodgate"),
|
||||
"viaversion": ("modrinth", "viaversion"),
|
||||
"viabackwards": ("modrinth", "viabackwards"),
|
||||
"luckperms": ("modrinth", "luckperms"),
|
||||
"vault": ("modrinth", "vaultunlocked"),
|
||||
"fastloginplus": ("github", "Hayston1001/FastLoginPlus"),
|
||||
"protocollib": ("hangar", "dmulloy2/ProtocolLib"),
|
||||
"bettermending": ("modrinth", "better-mending"),
|
||||
"betterconcrete": ("spigot", "81386")
|
||||
}
|
||||
|
||||
def curl_json(url):
|
||||
cmd = ["curl", "-4", "-fsSL", "--connect-timeout", "5", "-A", "FlexiCraft-Audit/1.0", url]
|
||||
try:
|
||||
out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode("utf-8")
|
||||
return json.loads(out)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def get_latest_version(prov, slug):
|
||||
if not slug:
|
||||
return None
|
||||
if prov == "modrinth":
|
||||
data = curl_json(f"https://modrinth.com{slug}/version?loaders=%5B%22paper%22,%22spigot%22%5D")
|
||||
if isinstance(data, list) and data:
|
||||
first_item = next(iter(data))
|
||||
return str(first_item.get("version_number"))
|
||||
elif prov == "hangar":
|
||||
owner_slug = slug if "/" in slug else f"PaperMC/{slug}"
|
||||
cmd = ["curl", "-4", "-fsSL", "--connect-timeout", "5", "-A", "FlexiCraft-Audit/1.0", f"https://papermc.io{owner_slug}/latestrelease"]
|
||||
try:
|
||||
return subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode("utf-8").strip().strip('"')
|
||||
except Exception:
|
||||
return None
|
||||
elif prov == "github":
|
||||
data = curl_json(f"https://github.com{slug}/releases/latest")
|
||||
if isinstance(data, dict):
|
||||
return str(data.get("tag_name") or "").lstrip("v")
|
||||
elif prov == "spigot":
|
||||
*_, res_id = slug.split(".")
|
||||
data = curl_json(f"https://spiget.org{res_id}/versions/latest")
|
||||
if isinstance(data, dict):
|
||||
return str(data.get("name") or "")
|
||||
return None
|
||||
|
||||
def norm_ver(v):
|
||||
clean = re.sub(r"^v", "", str(v or "").strip().lower())
|
||||
clean, _, _ = clean.partition("+")
|
||||
clean, _, _ = clean.partition("-snapshot")
|
||||
return clean
|
||||
|
||||
log_txt = ""
|
||||
if os.path.exists(MC_LOG):
|
||||
with open(MC_LOG, "r", encoding="utf-8", errors="ignore") as f:
|
||||
log_txt = f.read()
|
||||
|
||||
broken, partial, up_avail, up_to_date, manual_check = [], [], [], [], []
|
||||
|
||||
with open(REG_FILE, "r", encoding="utf-8") as f:
|
||||
pkgs = json.load(f).get("packages", [])
|
||||
|
||||
for p in pkgs:
|
||||
name = p.get("name", "")
|
||||
ptype = p.get("type", "")
|
||||
cur_v = p.get("version", "")
|
||||
|
||||
if ptype == "datapack":
|
||||
ns_list = p.get("dependencies", {}).get("namespaces", [])
|
||||
failed_funcs = [ns for ns in ns_list if ns != "vanillatweaks" and f"Failed to load function {ns}:" in log_txt]
|
||||
if failed_funcs:
|
||||
partial.append(f"{name} (fonctions 1.21.11 en erreur : {', '.join(failed_funcs)})")
|
||||
elif "1.17" in p.get("mc_compatibility", ""):
|
||||
partial.append(f"{name} (format ancien {p.get('mc_compatibility')})")
|
||||
else:
|
||||
up_avail.append(f"{name} (cible 1.21.10 -> pack 1.21.11 dispo sur VanillaTweaks)")
|
||||
continue
|
||||
|
||||
if re.search(rf"Error occurred while enabling {re.escape(name)}|Could not load.*{re.escape(name)}", log_txt, re.IGNORECASE):
|
||||
broken.append(f"{name} (v{cur_v}) -> Erreur critique au chargement")
|
||||
continue
|
||||
|
||||
ext = p.get("external", {})
|
||||
prov, slug = API_OVERRIDES.get(p.get("id", ""), (ext.get("provider", ""), ext.get("slug", "")))
|
||||
lat_v = get_latest_version(prov, slug)
|
||||
if not lat_v:
|
||||
manual_check.append(f"{name} (v{cur_v})")
|
||||
elif norm_ver(lat_v) != norm_ver(cur_v) and norm_ver(cur_v) not in norm_ver(lat_v):
|
||||
up_avail.append(f"{name} : v{cur_v} -> v{lat_v} ({prov})")
|
||||
else:
|
||||
up_to_date.append(f"{name} (v{cur_v})")
|
||||
|
||||
print("=== 1. NE FONCTIONNENT PAS (BLOQUANTS) ===")
|
||||
print("\n".join(f" ❌ {x}" for x in broken) or " Aucun")
|
||||
|
||||
print("\n=== 2. FONCTIONNENT PARTIELLEMENT (ERREURS DE FONCTIONS / ANCIEN FORMAT) ===")
|
||||
print("\n".join(f" ⚠️ {x}" for x in partial) or " Aucun")
|
||||
|
||||
print("\n=== 3. FONCTIONNENT MAIS MISE A JOUR DISPONIBLE ===")
|
||||
print("\n".join(f" 🔄 {x}" for x in up_avail) or " Aucun")
|
||||
|
||||
print("\n=== 4. A JOUR / NON VERIFIABLES AUTO ===")
|
||||
print(f" ✅ A jour ({len(up_to_date)}) : {', '.join(up_to_date)}")
|
||||
if manual_check:
|
||||
print(f" ℹ️ Manuel ({len(manual_check)}) : {', '.join(manual_check)}")
|
||||
6
tools/quartz_check.py
Normal file
6
tools/quartz_check.py
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import sys
|
||||
sys.path.insert(0, "/var/www/flexicraft-site")
|
||||
from core.package_updater import scan_external_updates
|
||||
for item in scan_external_updates():
|
||||
icon = "✅" if item["status"] == "up_to_date" else ("⏳" if item["status"] == "update_pending" else ("❌" if item["status"] == "error" else "ℹ️"))
|
||||
print(f"{icon} {item['id']:<22} : {item['msg']}")
|
||||
235
tools/scan_packages.py
Normal file
235
tools/scan_packages.py
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import os, re, json, yaml, hashlib, zipfile, subprocess
|
||||
from urllib.parse import urlparse
|
||||
|
||||
MC_BASE = "/var/lib/pterodactyl/volumes/bd102f43-4033-4c60-9922-53c436330f21"
|
||||
PLUGINS_DIR = f"{MC_BASE}/plugins"
|
||||
DATAPACKS_DIR = f"{MC_BASE}/world/datapacks"
|
||||
REG_OUT = "/var/www/flexicraft-site/config/packages_registry.json"
|
||||
|
||||
PACK_FORMAT_MAP = {
|
||||
4: "1.13 - 1.14.4", 5: "1.15 - 1.16.1", 6: "1.16.2 - 1.16.5",
|
||||
7: "1.17 - 1.17.1", 8: "1.18 - 1.18.1", 9: "1.18.2",
|
||||
10: "1.19 - 1.19.3", 12: "1.19.4", 15: "1.20 - 1.20.1",
|
||||
18: "1.20.2", 26: "1.20.3 - 1.20.4", 41: "1.20.5 - 1.20.6",
|
||||
48: "1.21 - 1.21.1", 57: "1.21.2 - 1.21.3", 61: "1.21.4",
|
||||
71: "1.21.5", 80: "1.21.6 - 1.21.8", 88: "1.21.9 - 1.21.10",
|
||||
94: "1.21.11"
|
||||
}
|
||||
|
||||
def file_sha512(path):
|
||||
h = hashlib.sha512()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(65536), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def lookup_modrinth_by_hashes(hashes):
|
||||
if not hashes:
|
||||
return {}
|
||||
payload = json.dumps({"hashes": hashes, "algorithm": "sha512"})
|
||||
cmd = [
|
||||
"curl", "-4", "-fsSL", "--connect-timeout", "8",
|
||||
"-H", "Content-Type: application/json",
|
||||
"-A", "FlexiCraft-Scanner/1.0",
|
||||
"-d", payload,
|
||||
"https://modrinth.com"
|
||||
]
|
||||
try:
|
||||
out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL).decode("utf-8")
|
||||
return json.loads(out)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def classify_structured_url(url_str):
|
||||
if not url_str:
|
||||
return None
|
||||
try:
|
||||
u = urlparse(url_str.strip())
|
||||
host = u.netloc.lower()
|
||||
parts = tuple(p for p in u.path.split("/") if p)
|
||||
if "modrinth.com" in host and len(parts) >= 2:
|
||||
_, slug, *_ = parts
|
||||
return {"provider": "modrinth", "slug": slug, "url": url_str.strip()}
|
||||
if "hangar.papermc.io" in host and len(parts) >= 2:
|
||||
owner, slug, *_ = parts
|
||||
return {"provider": "hangar", "slug": f"{owner}/{slug}", "url": url_str.strip()}
|
||||
if "github.com" in host and len(parts) >= 2:
|
||||
owner, repo, *_ = parts
|
||||
return {"provider": "github", "slug": f"{owner}/{repo.removesuffix('.git')}", "url": url_str.strip()}
|
||||
if "spigotmc.org" in host and "resources" in parts:
|
||||
*_, res_id = parts
|
||||
return {"provider": "spigot", "slug": res_id, "url": url_str.strip()}
|
||||
return {"provider": "website", "slug": "", "url": url_str.strip()}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def inspect_plugin_readonly(path):
|
||||
info = {
|
||||
"name": os.path.basename(path),
|
||||
"version": "inconnue",
|
||||
"authors": [],
|
||||
"api_version": "non specifiee",
|
||||
"depend": [],
|
||||
"softdepend": [],
|
||||
"structured_sources": []
|
||||
}
|
||||
with zipfile.ZipFile(path, "r") as z:
|
||||
names = z.namelist()
|
||||
yml_name = next((n for n in ("paper-plugin.yml", "plugin.yml") if n in names), None)
|
||||
if yml_name:
|
||||
data = yaml.safe_load(z.read(yml_name).decode("utf-8", errors="ignore")) or {}
|
||||
info["name"] = str(data.get("name") or info["name"])
|
||||
info["version"] = str(data.get("version") or "inconnue")
|
||||
authors = data.get("authors") or ([data.get("author")] if data.get("author") else [])
|
||||
info["authors"] = [str(a) for a in authors]
|
||||
info["api_version"] = str(data.get("api-version") or "legacy / non specifiee")
|
||||
|
||||
deps = data.get("dependencies")
|
||||
if isinstance(deps, dict):
|
||||
for k, v in (deps.get("server") or {}).items():
|
||||
if isinstance(v, dict) and v.get("required", True):
|
||||
info["depend"].append(k)
|
||||
else:
|
||||
info["softdepend"].append(k)
|
||||
else:
|
||||
info["depend"] = [str(d) for d in (data.get("depend") or [])]
|
||||
info["softdepend"] = [str(d) for d in (data.get("softdepend") or [])]
|
||||
|
||||
for key in ("website", "source", "issues"):
|
||||
if data.get(key):
|
||||
src = classify_structured_url(str(data.get(key)))
|
||||
if src:
|
||||
info["structured_sources"].append(src)
|
||||
|
||||
for n in names:
|
||||
if n.startswith("META-INF/maven/") and n.endswith("pom.xml"):
|
||||
pom_txt = z.read(n).decode("utf-8", errors="ignore")
|
||||
for m in re.findall(r"<url>(https?://[^<]+)</url>", pom_txt):
|
||||
src = classify_structured_url(m)
|
||||
if src and src.get("provider") != "website":
|
||||
info["structured_sources"].append(src)
|
||||
return info
|
||||
|
||||
def inspect_datapack_readonly(path):
|
||||
info = {
|
||||
"name": os.path.basename(path),
|
||||
"version": "1.0",
|
||||
"authors": [],
|
||||
"mc_compatibility": "inconnue",
|
||||
"description": "",
|
||||
"namespaces": [],
|
||||
"structured_sources": []
|
||||
}
|
||||
with zipfile.ZipFile(path, "r") as z:
|
||||
names = z.namelist()
|
||||
if "pack.mcmeta" in names:
|
||||
data = json.loads(z.read("pack.mcmeta").decode("utf-8", errors="ignore"))
|
||||
pack = data.get("pack", {})
|
||||
pf = pack.get("pack_format")
|
||||
if isinstance(pf, int):
|
||||
info["mc_compatibility"] = PACK_FORMAT_MAP.get(pf, f"pack_format {pf}")
|
||||
if "min_format" in pack or "max_format" in pack:
|
||||
info["mc_compatibility"] += f" (min={pack.get('min_format')}, max={pack.get('max_format')})"
|
||||
desc = pack.get("description", "")
|
||||
info["description"] = desc.get("text", str(desc)) if isinstance(desc, dict) else str(desc)
|
||||
|
||||
ns = set()
|
||||
for n in names:
|
||||
if n.startswith("data/"):
|
||||
_, _, rest = n.partition("data/")
|
||||
ns_name, sep, _ = rest.partition("/")
|
||||
if sep and ns_name and ns_name != "minecraft":
|
||||
ns.add(ns_name)
|
||||
info["namespaces"] = sorted(ns)
|
||||
|
||||
if "vanillatweaks" in info["namespaces"]:
|
||||
info["authors"] = ["VanillaTweaks"]
|
||||
info["structured_sources"].append({
|
||||
"provider": "vanillatweaks",
|
||||
"slug": ",".join(x for x in info["namespaces"] if x != "vanillatweaks"),
|
||||
"url": "https://vanillatweaks.net"
|
||||
})
|
||||
return info
|
||||
|
||||
items = []
|
||||
hashes = []
|
||||
|
||||
for ptype, folder, exts in [("plugin", PLUGINS_DIR, (".jar", ".jar.disabled")), ("datapack", DATAPACKS_DIR, (".zip", ".zip.disabled"))]:
|
||||
if not os.path.exists(folder):
|
||||
continue
|
||||
for fn in sorted(os.listdir(folder)):
|
||||
if fn.endswith(exts):
|
||||
full_p = os.path.join(folder, fn)
|
||||
sha = file_sha512(full_p)
|
||||
hashes.append(sha)
|
||||
meta = inspect_plugin_readonly(full_p) if ptype == "plugin" else inspect_datapack_readonly(full_p)
|
||||
items.append((ptype, fn, sha, meta))
|
||||
|
||||
mr_matches = lookup_modrinth_by_hashes(hashes)
|
||||
|
||||
registry = {"packages": []}
|
||||
for ptype, fn, sha, meta in items:
|
||||
enabled = not fn.endswith(".disabled")
|
||||
clean_fn = fn.replace(".disabled", "")
|
||||
mr = mr_matches.get(sha)
|
||||
|
||||
if mr:
|
||||
primary_source = {
|
||||
"provider": "modrinth",
|
||||
"slug": mr.get("project_id", ""),
|
||||
"url": f"https://modrinth.com{ptype}/{mr.get('project_id', '')}",
|
||||
"verified_by": "sha512_hash"
|
||||
}
|
||||
if meta.get("version") in ("inconnue", "1.0"):
|
||||
meta["version"] = mr.get("version_number", meta.get("version"))
|
||||
elif meta.get("structured_sources"):
|
||||
s = next(iter(meta.get("structured_sources")))
|
||||
primary_source = {
|
||||
"provider": s.get("provider", "manual"),
|
||||
"slug": s.get("slug", ""),
|
||||
"url": s.get("url", ""),
|
||||
"verified_by": "internal_metadata"
|
||||
}
|
||||
else:
|
||||
primary_source = {"provider": "manual", "slug": "", "url": "", "verified_by": "none"}
|
||||
|
||||
registry["packages"].append({
|
||||
"id": meta.get("name", clean_fn).lower().replace(" ", "_"),
|
||||
"name": meta.get("name", clean_fn),
|
||||
"type": ptype,
|
||||
"filename": clean_fn,
|
||||
"enabled": enabled,
|
||||
"version": meta.get("version", "inconnue"),
|
||||
"authors": meta.get("authors", []),
|
||||
"mc_compatibility": meta.get("mc_compatibility") or f"Paper/Spigot API {meta.get('api_version')}",
|
||||
"dependencies": {
|
||||
"required": meta.get("depend", []),
|
||||
"optional": meta.get("softdepend", []),
|
||||
"namespaces": meta.get("namespaces", [])
|
||||
},
|
||||
"track": "external",
|
||||
"external": {
|
||||
**primary_source,
|
||||
"quarantine_days": 3,
|
||||
"pending_version": None,
|
||||
"pending_url": None,
|
||||
"detected_at": None
|
||||
},
|
||||
"forgejo": {"repo": "", "branch": "main", "build_type": "maven" if ptype == "plugin" else "zip"}
|
||||
})
|
||||
|
||||
with open(REG_OUT, "w", encoding="utf-8") as f:
|
||||
json.dump(registry, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print("==========================================================================")
|
||||
print(" INVENTAIRE LECTURE SEULE (METADONNEES INTERNES + EMPRUNTES SHA-512)")
|
||||
print("==========================================================================")
|
||||
for pkg in registry["packages"]:
|
||||
ext = pkg["external"]
|
||||
src_str = f"{ext['provider']} [{ext['verified_by']}] -> {ext['slug'] or ext['url'] or 'manuel'}"
|
||||
print(f"[{pkg['type'].upper():<8}] {pkg['name']:<22} | v{pkg['version']:<18} | {pkg['mc_compatibility']}")
|
||||
print(f" Auteur(s) : {', '.join(pkg['authors']) or 'N/A'} | Source : {src_str}")
|
||||
reqs = pkg["dependencies"]["required"]
|
||||
opts = pkg["dependencies"]["optional"]
|
||||
if reqs or opts:
|
||||
print(f" Deps : requis={reqs} | optionnel={opts}")
|
||||
101
tools/update_vv_flp.py
Normal file
101
tools/update_vv_flp.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import os, json, shutil, zipfile, subprocess
|
||||
from urllib.parse import urlunsplit
|
||||
|
||||
PLUGINS_DIR = "/var/lib/pterodactyl/volumes/bd102f43-4033-4c60-9922-53c436330f21/plugins"
|
||||
BACKUP_DIR = "/root/backups_plugins_jars"
|
||||
os.makedirs(BACKUP_DIR, exist_ok=True)
|
||||
|
||||
def build_api_url(host_parts, path_str):
|
||||
host = ".".join(host_parts)
|
||||
return urlunsplit(("https", host, path_str, "", ""))
|
||||
|
||||
def curl_get_json(url):
|
||||
cmd = ["curl", "-4", "-fsSL", "--connect-timeout", "10", "-A", "FlexiCraft-Updater/1.0", url]
|
||||
res = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"Echec requete API (curl code {res.returncode}) : {res.stderr.strip()}")
|
||||
try:
|
||||
return json.loads(res.stdout)
|
||||
except json.JSONDecodeError as e:
|
||||
raise RuntimeError(f"Reponse API non-JSON : {e}")
|
||||
|
||||
def download_and_verify(url, tmp_path):
|
||||
cmd = ["curl", "-4", "-fL", "--connect-timeout", "10", "--progress-bar", "-A", "FlexiCraft-Updater/1.0", url, "-o", tmp_path]
|
||||
res = subprocess.run(cmd)
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"Echec du telechargement du fichier (curl code {res.returncode})")
|
||||
if not os.path.exists(tmp_path) or os.path.getsize(tmp_path) == 0:
|
||||
raise RuntimeError("Fichier telecharge vide (0 octet)")
|
||||
if not zipfile.is_zipfile(tmp_path):
|
||||
raise RuntimeError("Le fichier telecharge n'est pas un JAR/ZIP valide (probable page HTML)")
|
||||
with zipfile.ZipFile(tmp_path, "r") as z:
|
||||
if not any(n in z.namelist() for n in ("plugin.yml", "paper-plugin.yml")):
|
||||
raise RuntimeError("Archive ZIP valide mais descripteur plugin.yml absent")
|
||||
|
||||
def update_viaversion():
|
||||
print("▶ [1/2] Mise a jour de ViaVersion (Latest Stable Release sur Modrinth)...")
|
||||
try:
|
||||
mr_url = build_api_url(("api", "modrinth", "com"), "/v2/project/viaversion/version")
|
||||
vv_versions = curl_get_json(mr_url)
|
||||
if not isinstance(vv_versions, list) or not vv_versions:
|
||||
raise RuntimeError("Liste de versions vide renvoyee par Modrinth")
|
||||
vv_stable = next((v for v in vv_versions if v.get("version_type") == "release"), None)
|
||||
if not vv_stable:
|
||||
raise RuntimeError("Aucune version stable (release) trouvee sur Modrinth")
|
||||
files = vv_stable.get("files", [])
|
||||
if not files:
|
||||
raise RuntimeError("Aucun fichier attache a la release Modrinth")
|
||||
f_primary = next((x for x in files if x.get("primary")), next(iter(files)))
|
||||
ver_num = vv_stable.get("version_number")
|
||||
dl_url = f_primary.get("url")
|
||||
dl_name = f_primary.get("filename")
|
||||
if not dl_url or not dl_name:
|
||||
raise RuntimeError("URL ou nom de fichier manquant dans les metadonnees Modrinth")
|
||||
|
||||
tmp_jar = f"/tmp/{dl_name}"
|
||||
print(f" -> Version stable trouvee : {ver_num} ({dl_name})")
|
||||
download_and_verify(dl_url, tmp_jar)
|
||||
|
||||
for old in os.listdir(PLUGINS_DIR):
|
||||
if old.startswith("ViaVersion-") and old.endswith(".jar"):
|
||||
shutil.move(f"{PLUGINS_DIR}/{old}", f"{BACKUP_DIR}/{old}")
|
||||
shutil.move(tmp_jar, f"{PLUGINS_DIR}/{dl_name}")
|
||||
print(f" ✅ Succes : ViaVersion mis a jour vers {dl_name} (ancien sauvegarde dans {BACKUP_DIR})")
|
||||
except Exception as e:
|
||||
print(f" ❌ Echec ViaVersion : {e}")
|
||||
|
||||
def update_fastloginplus():
|
||||
print("\n▶ [2/2] Mise a jour de FastLoginPlus (Latest Stable Release sur GitHub)...")
|
||||
try:
|
||||
gh_url = build_api_url(("api", "github", "com"), "/repos/Hayston1001/FastLoginPlus/releases/latest")
|
||||
flp_rel = curl_get_json(gh_url)
|
||||
if not isinstance(flp_rel, dict):
|
||||
raise RuntimeError("Format de release GitHub inattendu")
|
||||
assets = flp_rel.get("assets", [])
|
||||
if not assets:
|
||||
raise RuntimeError("Aucun asset attache a la release GitHub")
|
||||
flp_asset = next((a for a in assets if "bukkit" in a.get("name", "").lower() and a.get("name", "").endswith(".jar")), None)
|
||||
if not flp_asset:
|
||||
avail = [a.get("name") for a in assets]
|
||||
raise RuntimeError(f"Aucun asset Bukkit .jar trouve parmi : {avail}")
|
||||
|
||||
dl_url = flp_asset.get("browser_download_url")
|
||||
dl_name = flp_asset.get("name")
|
||||
tmp_jar = f"/tmp/{dl_name}"
|
||||
print(f" -> Version stable trouvee : {flp_rel.get('tag_name')} ({dl_name})")
|
||||
download_and_verify(dl_url, tmp_jar)
|
||||
|
||||
for old in os.listdir(PLUGINS_DIR):
|
||||
if old.startswith("FastLoginPlus") and old.endswith(".jar"):
|
||||
shutil.move(f"{PLUGINS_DIR}/{old}", f"{BACKUP_DIR}/{old}")
|
||||
shutil.move(tmp_jar, f"{PLUGINS_DIR}/{dl_name}")
|
||||
print(f" ✅ Succes : FastLoginPlus mis a jour vers {dl_name} (ancien sauvegarde dans {BACKUP_DIR})")
|
||||
except Exception as e:
|
||||
print(f" ❌ Echec FastLoginPlus : {e}")
|
||||
|
||||
flp_db = f"{PLUGINS_DIR}/FastLoginPlus/FastLogin.db"
|
||||
if os.path.exists(flp_db):
|
||||
shutil.copy2(flp_db, f"{BACKUP_DIR}/FastLogin.db.bak")
|
||||
|
||||
update_viaversion()
|
||||
update_fastloginplus()
|
||||
Loading…
Add table
Add a link
Reference in a new issue