2023-09-26 14:14:33 +02:00
|
|
|
from typing import Sequence, Union
|
2015-11-20 22:10:22 +01:00
|
|
|
import os
|
2023-09-26 14:14:33 +02:00
|
|
|
import sys
|
2015-11-20 22:10:22 +01:00
|
|
|
import urllib.request
|
|
|
|
|
2023-09-26 14:14:50 +02:00
|
|
|
from .verify import verify_file_digest
|
|
|
|
|
2023-09-26 14:14:33 +02:00
|
|
|
def __to_string_sequence(x: Union[str, Sequence[str]]) -> Sequence[str]:
|
|
|
|
if isinstance(x, str):
|
|
|
|
return (x,)
|
|
|
|
else:
|
|
|
|
return x
|
|
|
|
|
|
|
|
def __get_any(x: Union[str, Sequence[str]]) -> str:
|
|
|
|
if isinstance(x, str):
|
|
|
|
return x
|
|
|
|
else:
|
|
|
|
return x[0]
|
|
|
|
|
|
|
|
def __download_one(url: str, path: str) -> None:
|
|
|
|
print("download", url)
|
|
|
|
urllib.request.urlretrieve(url, path)
|
|
|
|
|
|
|
|
def __download(urls: Sequence[str], path: str) -> None:
|
|
|
|
for url in urls[:-1]:
|
|
|
|
try:
|
|
|
|
__download_one(url, path)
|
|
|
|
return
|
|
|
|
except:
|
|
|
|
print("download error:", sys.exc_info()[0])
|
|
|
|
__download_one(urls[-1], path)
|
|
|
|
|
|
|
|
def __download_and_verify_to(urls: Sequence[str], md5: str, path: str) -> None:
|
|
|
|
__download(urls, path)
|
|
|
|
if not verify_file_digest(path, md5):
|
|
|
|
raise RuntimeError("Digest mismatch")
|
|
|
|
|
|
|
|
def download_basename(urls: Union[str, Sequence[str]]) -> str:
|
|
|
|
return os.path.basename(__get_any(urls))
|
|
|
|
|
|
|
|
def download_and_verify(urls: Union[str, Sequence[str]], md5: str, parent_path: str) -> str:
|
2015-11-20 22:10:22 +01:00
|
|
|
"""Download a file, verify its MD5 checksum and return the local path."""
|
|
|
|
|
2023-09-26 14:14:33 +02:00
|
|
|
base = download_basename(urls)
|
|
|
|
|
2015-11-20 22:10:22 +01:00
|
|
|
os.makedirs(parent_path, exist_ok=True)
|
2023-09-26 14:14:33 +02:00
|
|
|
path = os.path.join(parent_path, base)
|
2015-11-20 22:10:22 +01:00
|
|
|
|
|
|
|
try:
|
2016-12-29 21:40:54 +01:00
|
|
|
if verify_file_digest(path, md5): return path
|
2015-11-20 22:10:22 +01:00
|
|
|
os.unlink(path)
|
|
|
|
except FileNotFoundError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
tmp_path = path + '.tmp'
|
|
|
|
|
2023-09-26 14:14:33 +02:00
|
|
|
__download_and_verify_to(__to_string_sequence(urls), md5, tmp_path)
|
2015-11-20 22:10:22 +01:00
|
|
|
os.rename(tmp_path, path)
|
|
|
|
return path
|