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
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)}
|
||||
Loading…
Add table
Add a link
Reference in a new issue