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"(https?://[^<]+)", 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}")