diff --git a/mc-get.py b/mc-get.py index d1eeff0..a2a56f6 100755 --- a/mc-get.py +++ b/mc-get.py @@ -7,11 +7,15 @@ import mcgetdb from colorama import Fore, Style +class HashError(ValueError): + """Incorrect hash""" + + def validate(): raise NotImplementedError -def download_cache(url: str, filename: str, size: int): +def download_cache(url: str, filename: str, size: int, hash: str): cache_file_path = os.path.join(mcfs.cache_dir, filename) if not mcfs.is_path_exist(mcfs.cache_dir): os.mkdir(mcfs.cache_dir) @@ -19,7 +23,9 @@ def download_cache(url: str, filename: str, size: int): api.download(url, size, cache_file_path) else: print(f"{filename} is in cache.") - return filename + if mcfs.check_file_hash(cache_file_path, hash): + os.remove(cache_file_path) + raise HashError(f"Incorrect hash for {filename}") def modpack_install(filename: str): @@ -29,7 +35,7 @@ def modpack_install(filename: str): path = file["path"].split("/") downloads = file["downloads"] print(file["path"]) - download_cache(downloads[0], path[1], file["fileSize"]) + download_cache(downloads[0], path[1], file["fileSize"], file["hashes"]["sha512"]) mcfs.install(path[1], path[0]) print(f"{Fore.YELLOW}Overriding...{Style.RESET_ALL}") mcfs.install_modpacks_override(filename) @@ -111,10 +117,18 @@ def install(projects: list, version, loader): print("Canceled.") return + failed_to_install = [] + for project, version in all_to_install: file = type("mc_file", (object,), version.files[0]) filename = file.filename - download_cache(file.url, filename, file.size) + try: + download_cache(file.url, filename, file.size, file.hashes["sha512"]) + except HashError: + print(f"Failed to install {project.title} ({project.slug}) [{version.version_number}] due to an incorrect " + f"hash") + failed_to_install.append((project, version)) + continue match project.project_type: case "resourcepack": subdir = "resourcepacks" @@ -129,6 +143,9 @@ def install(projects: list, version, loader): raise NotImplementedError mcfs.install(filename, subdir) + if failed_to_install: + print("Failed to install:", + *[project.title + " " + version.version_number for project, version in failed_to_install], sep="\n\t") def search(query: list): diff --git a/mcfs.py b/mcfs.py index c852838..7eb3833 100644 --- a/mcfs.py +++ b/mcfs.py @@ -3,7 +3,7 @@ from sys import platform import shutil import zipfile import json - +from hashlib import sha512 class MCVersion: def __init__(self, version_number, is_modified=False, modloader=None): @@ -118,3 +118,14 @@ def get_installed_mc_versions(): pass versions.append(mc_ver) return sorted(versions, reverse=True) + + +def check_file_hash(path, ref_hash): + buffer_size = 65536 + hash = sha512() + with open(path, 'rb') as f: + data = True + while data: + data = f.read(buffer_size) + hash.update(data) + return hash.hexdigest() == ref_hash