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