modrinth-dl 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ """
2
+ modrinth_dl
3
+ ===========
4
+ Python lib for downloading Minecraft add-ons, such as mods and datapacks,
5
+ from Modrinth.
6
+ """
7
+
8
+ from .downloader import Downloader
9
+ from .errors import ModrinthDlError
10
+
11
+ __all__ = ["Downloader", "ModrinthDlError"]
@@ -0,0 +1,53 @@
1
+ """Checksum helpers for verifying files downloaded from Modrinth."""
2
+
3
+ import hashlib
4
+ from typing import Any, Optional, Tuple
5
+
6
+ # Listed in order of preference. Modrinth publishes sha1 and sha512 for each
7
+ # file; sha1 is preferred because it is cheaper, and the check only guards
8
+ # against corrupt or truncated downloads (they already arrive over HTTPS).
9
+ SUPPORTED_ALGORITHMS = ("sha1", "sha512", "sha256")
10
+ CHUNK_SIZE = 8192
11
+
12
+
13
+ def get_expected_hash(file_info: Any) -> Tuple[Optional[str], Optional[str]]:
14
+ """Return the expected checksum of a Modrinth file.
15
+
16
+ :param file_info: Modrinth file metadata, with a ``hashes`` attribute.
17
+ The API client gives an object with one attribute per algorithm,
18
+ while raw Modrinth API JSON gives a dict, so both are accepted.
19
+ :return: Tuple of (algorithm, value), or (None, None) when Modrinth
20
+ publishes no supported checksum for the file.
21
+ """
22
+ hashes = getattr(file_info, "hashes", None)
23
+ if not hashes:
24
+ return None, None
25
+
26
+ if isinstance(hashes, dict):
27
+ hash_map = hashes
28
+ else:
29
+ hash_map = {
30
+ algorithm: getattr(hashes, algorithm, None)
31
+ for algorithm in SUPPORTED_ALGORITHMS
32
+ }
33
+
34
+ for algorithm in SUPPORTED_ALGORITHMS:
35
+ hash_value = hash_map.get(algorithm)
36
+ if hash_value:
37
+ return algorithm, hash_value
38
+
39
+ return None, None
40
+
41
+
42
+ def calculate_file_hash(file_path: str, algorithm: str) -> str:
43
+ """Calculate the checksum of a local file.
44
+
45
+ :param file_path: Path of the file to hash.
46
+ :param algorithm: Hash algorithm name, e.g. ``sha1``.
47
+ :return: Hex digest of the file content.
48
+ """
49
+ hasher = hashlib.new(algorithm)
50
+ with open(file_path, "rb") as file_handle:
51
+ for chunk in iter(lambda: file_handle.read(CHUNK_SIZE), b""):
52
+ hasher.update(chunk)
53
+ return hasher.hexdigest()
@@ -0,0 +1,271 @@
1
+ """Download Minecraft mods and datapacks from Modrinth.
2
+
3
+ For each project, the newest version matching the Minecraft version (and
4
+ loader, for mods) is resolved through the Modrinth API, then one file from
5
+ that version is downloaded and verified against its published checksum.
6
+ """
7
+
8
+ import hashlib
9
+ import os
10
+ import time
11
+ from typing import Callable, List, Optional
12
+
13
+ from modrinth_api_wrapper import Client
14
+ from modrinth_api_wrapper.models import File, Version
15
+ import requests
16
+
17
+ from .checksum import CHUNK_SIZE, calculate_file_hash, get_expected_hash
18
+ from .errors import ModrinthDlError
19
+ from .logger import init
20
+
21
+ # requests applies this to connecting and to each wait between received bytes,
22
+ # not to the whole download, so a large file on a slow link can take longer.
23
+ DOWNLOAD_TIMEOUT_IN_SECONDS = 60
24
+ DATAPACK_FILE_EXTENSION = ".zip"
25
+
26
+
27
+ class Downloader:
28
+ """Downloads the latest compatible files of Modrinth projects.
29
+
30
+ Download methods return whether anything was downloaded, so callers
31
+ such as Ansible modules can report ``changed``. Files from older
32
+ versions of a project already in the destination directory are left in
33
+ place; removing them is the caller's responsibility.
34
+ """
35
+
36
+ def __init__(self, client: Optional[Client] = None, delay_in_seconds: int = 0):
37
+ """Initialise downloader.
38
+
39
+ Args:
40
+ client: Modrinth API client, a new Client is created when omitted.
41
+ delay_in_seconds: Seconds to wait after each project when
42
+ downloading a list of projects, to go easy on Modrinth's API.
43
+ """
44
+ self.client = client if client is not None else Client()
45
+ self.delay_in_seconds = delay_in_seconds
46
+ self.logger = init()
47
+
48
+ def download_mods(
49
+ self, slugs: List[str], loader: str, game_version: str, dest_dir: str
50
+ ) -> bool:
51
+ """Download the latest compatible version of each mod.
52
+
53
+ :param slugs: Modrinth project slugs, e.g. ``lithium``.
54
+ :param loader: Mod loader, e.g. ``fabric``.
55
+ :param game_version: Minecraft version, e.g. ``1.21.4``.
56
+ :param dest_dir: Directory to save the mod files to.
57
+ :return: True if any mod was downloaded.
58
+ :raises ModrinthDlError: On the first mod that fails. Mods processed
59
+ before it stay downloaded and later mods are not attempted.
60
+ """
61
+ self.logger.info(
62
+ "%s mod(s) to download for Minecraft %s and loader %s",
63
+ len(slugs),
64
+ game_version,
65
+ loader,
66
+ )
67
+ return self._download_all(
68
+ slugs,
69
+ lambda slug: self.download_mod(slug, loader, game_version, dest_dir),
70
+ )
71
+
72
+ def download_datapacks(
73
+ self, slugs: List[str], game_version: str, dest_dir: str
74
+ ) -> bool:
75
+ """Download the latest compatible version of each datapack.
76
+
77
+ :param slugs: Modrinth project slugs, e.g. ``terralith``.
78
+ :param game_version: Minecraft version, e.g. ``1.21.4``.
79
+ :param dest_dir: Directory to save the datapack files to.
80
+ :return: True if any datapack was downloaded.
81
+ :raises ModrinthDlError: On the first datapack that fails. Datapacks
82
+ processed before it stay downloaded and later ones are not
83
+ attempted.
84
+ """
85
+ self.logger.info(
86
+ "%s datapack(s) to download for Minecraft %s",
87
+ len(slugs),
88
+ game_version,
89
+ )
90
+ return self._download_all(
91
+ slugs,
92
+ lambda slug: self.download_datapack(slug, game_version, dest_dir),
93
+ )
94
+
95
+ def download_mod(
96
+ self, slug: str, loader: str, game_version: str, dest_dir: str
97
+ ) -> bool:
98
+ """Download the latest version of a mod compatible with a loader.
99
+
100
+ :param slug: Modrinth project slug.
101
+ :param loader: Mod loader, e.g. ``fabric``.
102
+ :param game_version: Minecraft version.
103
+ :param dest_dir: Directory to save the mod file to.
104
+ :return: True if the mod was downloaded, False if already present.
105
+ :raises ModrinthDlError: If no compatible version or file exists.
106
+ """
107
+ # The API client models loaders and game_versions as optional, so a
108
+ # version without them is treated as incompatible rather than failing.
109
+ version = self._find_latest_version(
110
+ slug,
111
+ lambda version: loader in (version.loaders or [])
112
+ and game_version in (version.game_versions or []),
113
+ f"Minecraft {game_version} and loader {loader}",
114
+ )
115
+ # Any file type is accepted for mods; the primary file is preferred.
116
+ primary_file = _select_file(version.files, lambda file: True)
117
+ if primary_file is None:
118
+ raise ModrinthDlError(f"No downloadable file found for mod '{slug}'")
119
+ return self._download_file(slug, primary_file, dest_dir)
120
+
121
+ def download_datapack(self, slug: str, game_version: str, dest_dir: str) -> bool:
122
+ """Download the latest version of a datapack.
123
+
124
+ :param slug: Modrinth project slug.
125
+ :param game_version: Minecraft version.
126
+ :param dest_dir: Directory to save the datapack file to.
127
+ :return: True if the datapack was downloaded, False if already
128
+ present.
129
+ :raises ModrinthDlError: If no compatible version or zip file exists.
130
+ """
131
+ # Loaders are not checked: datapacks are loaded by Minecraft itself.
132
+ # Only the version that is newest overall is considered, so a project
133
+ # whose latest release is a mod build without a zip raises an error
134
+ # even when an older version has one.
135
+ version = self._find_latest_version(
136
+ slug,
137
+ lambda version: game_version in (version.game_versions or []),
138
+ f"Minecraft {game_version}",
139
+ )
140
+ # Datapack projects often also ship a mod build as a .jar, but only a
141
+ # .zip can be placed in a world's datapacks directory.
142
+ zip_file = _select_file(
143
+ version.files,
144
+ lambda file: file.filename.lower().endswith(DATAPACK_FILE_EXTENSION),
145
+ )
146
+ if zip_file is None:
147
+ raise ModrinthDlError(
148
+ f"No downloadable zip file found for datapack '{slug}'"
149
+ )
150
+ return self._download_file(slug, zip_file, dest_dir)
151
+
152
+ def _download_all(self, slugs: List[str], download: Callable) -> bool:
153
+ """Download each project in turn, pausing after each one.
154
+
155
+ The pause also follows skipped projects and the last project, which
156
+ keeps API request spacing predictable at the cost of a final wait.
157
+ """
158
+ changed = False
159
+ for slug in slugs:
160
+ if download(slug):
161
+ changed = True
162
+ time.sleep(self.delay_in_seconds)
163
+ return changed
164
+
165
+ def _find_latest_version(
166
+ self, slug: str, is_compatible: Callable, target: str
167
+ ) -> Version:
168
+ """Return the newest project version that passes a compatibility check.
169
+
170
+ Relies on Modrinth listing project versions newest first, so the
171
+ first match is the latest. Beta and alpha versions are not filtered
172
+ out and win if they are newest.
173
+ """
174
+ self.logger.debug("Fetching project versions for '%s'...", slug)
175
+ versions = self.client.list_project_versions(slug)
176
+ for version in versions:
177
+ if is_compatible(version):
178
+ return version
179
+ raise ModrinthDlError(f"No compatible version found for '{slug}' with {target}")
180
+
181
+ def _download_file(self, slug: str, file_info: File, dest_dir: str) -> bool:
182
+ """Download a Modrinth file unless a verified copy already exists.
183
+
184
+ An existing file with a matching checksum is kept, and one with a
185
+ different checksum is replaced. When Modrinth publishes no supported
186
+ checksum, an existing file is trusted by its name alone, and the
187
+ download is not verified.
188
+
189
+ :return: True if the file was downloaded, False if already present.
190
+ :raises ModrinthDlError: If the downloaded file fails checksum check.
191
+ """
192
+ os.makedirs(dest_dir, exist_ok=True)
193
+ dest_path = os.path.join(dest_dir, file_info.filename)
194
+ algorithm, expected_hash = get_expected_hash(file_info)
195
+
196
+ if os.path.exists(dest_path):
197
+ if not algorithm:
198
+ self.logger.info(
199
+ "'%s' already exists at '%s', skipping download",
200
+ file_info.filename,
201
+ dest_path,
202
+ )
203
+ return False
204
+ if calculate_file_hash(dest_path, algorithm) == expected_hash:
205
+ self.logger.info(
206
+ "'%s' already exists at '%s' with valid checksum, "
207
+ "skipping download",
208
+ file_info.filename,
209
+ dest_path,
210
+ )
211
+ return False
212
+ self.logger.warning(
213
+ "'%s' exists at '%s' but checksum mismatch, re-downloading",
214
+ file_info.filename,
215
+ dest_path,
216
+ )
217
+ os.remove(dest_path)
218
+
219
+ self.logger.info(
220
+ "Downloading '%s' from %s...", file_info.filename, file_info.url
221
+ )
222
+ downloaded_hash = _write_response(file_info.url, dest_path, algorithm)
223
+
224
+ if algorithm and downloaded_hash != expected_hash:
225
+ os.remove(dest_path)
226
+ raise ModrinthDlError(
227
+ f"Checksum mismatch for '{slug}' file '{file_info.filename}': "
228
+ f"expected {algorithm}={expected_hash}, got {downloaded_hash}"
229
+ )
230
+
231
+ self.logger.info(
232
+ "Successfully downloaded '%s' to '%s'", file_info.filename, dest_path
233
+ )
234
+ return True
235
+
236
+
237
+ def _select_file(files: List[File], is_wanted: Callable) -> Optional[File]:
238
+ """Return the primary file if wanted, otherwise the first wanted file."""
239
+ for file in files:
240
+ if file.primary and is_wanted(file):
241
+ return file
242
+ for file in files:
243
+ if is_wanted(file):
244
+ return file
245
+ return None
246
+
247
+
248
+ def _write_response(
249
+ url: str, dest_path: str, algorithm: Optional[str]
250
+ ) -> Optional[str]:
251
+ """Stream a URL to a file, hashing it on the way to avoid a second read.
252
+
253
+ Content is written straight to ``dest_path``, not via a temporary file,
254
+ so an interrupted download leaves a partial file behind. With a
255
+ published checksum, the next run detects and replaces it.
256
+
257
+ :return: Checksum of the content when an algorithm is set, else None.
258
+ """
259
+ response = requests.get(url, stream=True, timeout=DOWNLOAD_TIMEOUT_IN_SECONDS)
260
+ response.raise_for_status()
261
+
262
+ hasher = hashlib.new(algorithm) if algorithm else None
263
+ with open(dest_path, "wb") as file_handle:
264
+ for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
265
+ if not chunk: # keep-alive chunks carry no data
266
+ continue
267
+ file_handle.write(chunk)
268
+ if hasher:
269
+ hasher.update(chunk)
270
+
271
+ return hasher.hexdigest() if hasher else None
modrinth_dl/errors.py ADDED
@@ -0,0 +1,11 @@
1
+ """Errors raised by Modrinth Downloader."""
2
+
3
+
4
+ class ModrinthDlError(Exception):
5
+ """Raised when a Modrinth project cannot be resolved or downloaded.
6
+
7
+ Covers this library's own checks: no compatible version, no suitable
8
+ file, and checksum mismatch. Network, HTTP, and Modrinth API client
9
+ errors, e.g. an unknown project slug, are not wrapped and propagate
10
+ as-is.
11
+ """
modrinth_dl/logger.py ADDED
@@ -0,0 +1,24 @@
1
+ """Logger for Modrinth Downloader."""
2
+
3
+ from conflog import Conflog
4
+
5
+ LOGGER = None
6
+
7
+
8
+ def init():
9
+ """Initialize logger.
10
+
11
+ Logger is cached to prevent duplicate handlers
12
+ from being added on repeated calls.
13
+ """
14
+
15
+ global LOGGER # pylint: disable=global-statement
16
+ if LOGGER is not None:
17
+ return LOGGER
18
+
19
+ cfl = Conflog(
20
+ conf_dict={"level": "info", "format": "[modrinth-dl] %(levelname)s %(message)s"}
21
+ )
22
+
23
+ LOGGER = cfl.get_logger(__name__)
24
+ return LOGGER
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: modrinth-dl
3
+ Version: 1.0.0
4
+ Summary: Python lib for downloading Minecraft add-ons from Modrinth
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: modrinth-dl,modrinth,minecraft,mods,datapacks
8
+ Author: Little Godzilla Laboratory
9
+ Author-email: blah+lgl@cliffano.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3.15
20
+ Requires-Dist: conflog (>=2.1.0,<2.2.0)
21
+ Requires-Dist: modrinth-api-wrapper (>=1.0.0,<1.1.0)
22
+ Requires-Dist: requests (>=2.32.5,<2.33.0)
23
+ Project-URL: Documentation, https://github.com/littlegodzillalaboratory/modrinth-dl
24
+ Project-URL: Homepage, https://github.com/littlegodzillalaboratory/modrinth-dl
25
+ Project-URL: Repository, https://github.com/littlegodzillalaboratory/modrinth-dl
26
+ Description-Content-Type: text/markdown
27
+
28
+ <!-- BEGIN:AVATAR -->
29
+ ![Avatar](avatar.jpg)
30
+ <!-- END:AVATAR -->
31
+
32
+ <!-- BEGIN:BADGES -->
33
+ [![Build Status](https://github.com/littlegodzillalaboratory/modrinth-dl/workflows/CI/badge.svg)](https://github.com/littlegodzillalaboratory/modrinth-dl/actions?query=workflow%3ACI)
34
+ [![Code Scanning Status](https://github.com/littlegodzillalaboratory/modrinth-dl/workflows/CodeQL/badge.svg)](https://github.com/littlegodzillalaboratory/modrinth-dl/actions?query=workflow%3ACodeQL)
35
+ [![Dependencies Status](https://img.shields.io/librariesio/release/pypi/modrinth-dl)](https://libraries.io/npm/modrinth-dl)
36
+ [![Security Status](https://snyk.io/test/github/littlegodzillalaboratory/modrinth-dl/badge.svg)](https://snyk.io/test/github/littlegodzillalaboratory/modrinth-dl)
37
+ [![Published Version](https://img.shields.io/pypi/v/modrinth-dl.svg)](https://pypi.python.org/pypi/modrinth-dl)
38
+ <!-- END:BADGES -->
39
+
40
+ # Modrinth Downloader
41
+
42
+ Modrinth Downloader is a Python lib for downloading Minecraft add-ons, such as mods and datapacks, from [Modrinth](https://modrinth.com).
43
+
44
+ For each Modrinth project, it downloads the newest version that supports the given Minecraft version (and mod loader, for mods). Files that already exist with a matching checksum are skipped, and every download is verified against the checksum published by Modrinth.
45
+
46
+ ## Installation
47
+
48
+ ```shell
49
+ pip3 install modrinth-dl
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ Download mods for a Fabric server:
55
+
56
+ ```python
57
+ from modrinth_dl import Downloader
58
+
59
+ downloader = Downloader(delay_in_seconds=2)
60
+
61
+ changed = downloader.download_mods(
62
+ ["lithium", "ferrite-core"], "fabric", "1.21.4", "/opt/fabricmc/mods"
63
+ )
64
+ ```
65
+
66
+ Download datapacks into a world:
67
+
68
+ ```python
69
+ changed = downloader.download_datapacks(
70
+ ["terralith"], "1.21.4", "/opt/fabricmc/world/datapacks"
71
+ )
72
+ ```
73
+
74
+ Both return `True` when at least one file was downloaded, and `False` when every file was already present. A single project can also be downloaded with `download_mod` and `download_datapack`.
75
+
76
+ When a project has no version compatible with the given Minecraft version (or loader), or no suitable file, or a download fails its checksum check, a `modrinth_dl.ModrinthDlError` is raised.
77
+
78
+ ## Configuration
79
+
80
+ These are the `Downloader` constructor arguments:
81
+
82
+ | Argument | Type | Description | Default |
83
+ |----------|------|-------------|---------|
84
+ | `client` | `modrinth_api_wrapper.Client` | Modrinth API client | A new `Client()` |
85
+ | `delay_in_seconds` | int | Seconds to wait after each project when downloading a list of projects, to go easy on Modrinth's API | 0 |
86
+
87
+ ## Colophon
88
+
89
+ <!-- BEGIN:DEVELOPERS_GUIDE -->
90
+ [Developer's Guide](https://littlegodzillalaboratory.github.io/developers-guide-python.html)
91
+ <!-- END:DEVELOPERS_GUIDE -->
92
+
93
+ <!-- BEGIN:BUILD_REPORTS -->
94
+ Build reports:
95
+
96
+ * [Lint report](https://littlegodzillalaboratory.github.io/modrinth-dl/lint/pylint/index.html)
97
+ * [Code complexity report](https://littlegodzillalaboratory.github.io/modrinth-dl/complexity/radon/index.html)
98
+ * [Unit tests report](https://littlegodzillalaboratory.github.io/modrinth-dl/test/pytest/index.html)
99
+ * [Test coverage report](https://littlegodzillalaboratory.github.io/modrinth-dl/coverage/coverage/index.html)
100
+ * [Integration tests report](https://littlegodzillalaboratory.github.io/modrinth-dl/test-integration/pytest/index.html)
101
+ * [API Documentation](https://littlegodzillalaboratory.github.io/modrinth-dl/doc/sphinx/index.html)
102
+
103
+ <!-- END:BUILD_REPORTS -->
104
+
@@ -0,0 +1,9 @@
1
+ modrinth_dl/__init__.py,sha256=si03rLMyH0Cj0IuF_3tsJGFPA6trxXdF4Vb7KxnNysM,238
2
+ modrinth_dl/checksum.py,sha256=1fTOor5qoOX6t80UvLhwr4L7aO2i2Rzc0SFyr4sHYIQ,1879
3
+ modrinth_dl/downloader.py,sha256=0N08FOT-uOOxw5h8a-qdbG7HpxtoIBAOEtG2ysZwY1A,11082
4
+ modrinth_dl/errors.py,sha256=9TPbSlfBLMV8ZgieHv2E3RkDxZmbDCMtMQtfl5a2VQs,389
5
+ modrinth_dl/logger.py,sha256=-yXQO7nnoKMHDi4HXu10_ETQyIlNB2OrvDU3kjkpEA0,498
6
+ modrinth_dl-1.0.0.dist-info/METADATA,sha256=-meBZBylbvhBwehCX6_b-EBSCD3um9sjCW-XE1Wf0PM,4633
7
+ modrinth_dl-1.0.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
8
+ modrinth_dl-1.0.0.dist-info/licenses/LICENSE,sha256=gZ9kE1AroWPJ1swtDWhQder0BgUSl00ddKoHHT6KPjU,1072
9
+ modrinth_dl-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,19 @@
1
+ Copyright (C) 2026 by Little Godzilla Laboratory
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.