|
5 | 5 | A module containing utility functions. |
6 | 6 | """ |
7 | 7 | import platform |
| 8 | +import math |
| 9 | +from pathlib import Path |
8 | 10 | import urllib.request |
9 | 11 | from typing import Optional |
10 | 12 | from urllib.error import HTTPError |
| 13 | +from http.client import HTTPResponse |
11 | 14 |
|
12 | 15 |
|
13 | 16 | def check_install_os() -> str: |
@@ -37,7 +40,26 @@ def download_file(url: str, file_name: str) -> Optional[str]: |
37 | 40 | :returns: The path to downloaded file if successful, otherwise `None`. |
38 | 41 | """ |
39 | 42 | try: |
40 | | - file, _ = urllib.request.urlretrieve(url, file_name) |
| 43 | + response: HTTPResponse = urllib.request.urlopen(url) |
41 | 44 | except (ValueError, HTTPError): |
42 | 45 | return None |
43 | | - return file |
| 46 | + |
| 47 | + if response.status != 200: |
| 48 | + return None |
| 49 | + length = response.length |
| 50 | + buffer = bytes() |
| 51 | + progress_bar = "=" if check_install_os() == "windows" else "█" |
| 52 | + while len(buffer) < length: |
| 53 | + block_size = int(length / 20) |
| 54 | + # show completed |
| 55 | + completed = len(buffer) / length |
| 56 | + print(" |" + progress_bar * int(completed * 20), end="") |
| 57 | + print(" " * math.ceil((1 - completed) * 20), end="|") |
| 58 | + print(f"{int(completed * 100)}% (of {length} bytes)", end="\r") |
| 59 | + remaining = length - len(buffer) |
| 60 | + buffer += response.read(block_size if remaining > block_size else remaining) |
| 61 | + response.close() |
| 62 | + print(" |" + (progress_bar * 20) + f"| 100% (of {length} bytes)") |
| 63 | + file = Path(file_name) |
| 64 | + file.write_bytes(buffer) |
| 65 | + return file.as_posix() |
0 commit comments