fork/nix-minecraft

git clone https://git.julia.blue/fork/nix-minecraft

Infinidogerefactor(minecraft-servers): remove jq from update.py031fbcb

feat/abduco
2.8 KiB109 linesraw
1#!/usr/bin/env nix-shell
2#!nix-shell -i python3 -p python3Packages.requests
3
4import json
5import requests
6from pathlib import Path
7from typing import Union, Dict
8
9
10# These versions don't have servers
11BLACKLIST = [
12    "1.2.4",
13    "1.2.3",
14    "1.2.2",
15    "1.2.1",
16    "1.1",
17    "1.0",
18]
19
20
21def parse_manifest() -> Dict[str, str]:
22    """
23    Fetches the version manifest from Mojang and processes it
24    Returns its output as a dict of {id: url}
25    """
26
27    print("Fetching manifest")
28    response = requests.get(
29        "https://launchermeta.mojang.com/mc/game/version_manifest.json"
30    )
31    response.raise_for_status()
32
33    return dict(
34        map(
35            lambda elem: (elem["id"], elem["url"]),
36            filter(
37                lambda elem: elem["type"] in ("release", "snapshot"),
38                response.json()["versions"],
39            ),
40        )
41    )
42
43
44def parse_version(url) -> Union[Dict[str, Union[str, int]], None]:
45    """
46    Fetches the version JSON at the URl and processes it
47    Returns a dict in the form:
48    {
49        "url": string,
50        "sha1": string,
51        "version": string,
52        "javaVersion": int,
53        "manifestUrl": string
54    }
55    """
56
57    print(f"Fetching {url}")
58    response = requests.get(url)
59    response.raise_for_status()
60
61    data = response.json()
62    if "server" in data["downloads"]:
63        return {
64            "url": data["downloads"]["server"]["url"],
65            "sha1": data["downloads"]["server"]["sha1"],
66            "version": data["id"],
67            "javaVersion": data.get("javaVersion", {"majorVersion": 8})["majorVersion"],
68            "manifestUrl": url,
69        }
70
71
72def main(versions, lock_file):
73    """
74    Takes in a dict of the existing version lock, and the output file
75    Fetches the version manifest and fetches any missing/changed versions
76    Writes the new version lock to the output file
77    """
78
79    manifest = parse_manifest()
80
81    try:
82        for version, url in manifest.items():
83            if (
84                not (v := versions.get(version, None))
85                or v.get("manifestUrl", None) != url
86            ):  # Fetch if version isn't locked or if manifest url changes
87                if version in BLACKLIST:
88                    continue
89                elif (parsed := parse_version(url)) is not None:
90                    versions[version] = parsed
91                else:
92                    print(f"{version} has no server, add to blacklist")
93    except KeyboardInterrupt:
94        print("Cancelled fetching. Writing and exiting")
95
96    json.dump(versions, lock_file, indent=2)
97    lock_file.write("\n")
98
99
100if __name__ == "__main__":
101    lock_path = Path(__file__).parent / "versions.json"
102    lock_path.touch()
103
104    versions = (
105        {} if lock_path.stat().st_size == 0 else json.loads(lock_path.read_text())
106    )
107
108    with lock_path.open("w") as lock_file:
109        main(versions, lock_file)