manga-dlp/mangadlp/downloader.py

53 lines
1.6 KiB
Python
Raw Normal View History

2021-12-19 17:20:34 +01:00
from pathlib import Path
from time import sleep
2022-05-16 16:09:17 +02:00
import shutil
import requests
2022-05-16 16:09:17 +02:00
import mangadlp.utils as utils
2021-12-19 17:20:34 +01:00
2022-05-16 16:09:17 +02:00
# download images
def download_chapter(
2022-05-20 19:32:36 +02:00
image_urls: list, chapter_path: str or Path, download_wait: float, verbose: bool
) -> None:
total_img = len(image_urls)
2022-05-16 16:09:17 +02:00
for img_num, img in enumerate(image_urls, 1):
2022-05-04 19:17:12 +02:00
# set image path
image_path = Path(f"{chapter_path}/{img_num:03d}")
# show progress bar if verbose logging is not active
if verbose:
print(f"INFO: Downloading image {img_num}/{total_img}")
else:
utils.progress_bar(img_num, total_img)
2022-05-16 16:09:17 +02:00
counter = 1
while counter <= 3:
try:
r = requests.get(img, stream=True)
if r.status_code != 200:
print(f"ERR: Request for image {img} failed, retrying")
raise ConnectionError
2022-05-16 16:09:17 +02:00
except KeyboardInterrupt:
print("ERR: Stopping")
exit(1)
except:
if counter >= 3:
print("ERR: Maybe the MangaDex Servers are down?")
raise ConnectionError
sleep(download_wait)
counter += 1
else:
break
2021-12-19 17:20:34 +01:00
2022-05-16 16:09:17 +02:00
# write image
try:
2022-05-04 19:17:12 +02:00
with image_path.open("wb") as file:
2022-05-16 16:09:17 +02:00
r.raw.decode_content = True
2022-05-13 22:34:25 +02:00
shutil.copyfileobj(r.raw, file)
2022-05-16 16:09:17 +02:00
except:
print("ERR: Can't write file")
raise IOError
2021-12-19 17:20:34 +01:00
2022-05-16 16:09:17 +02:00
img_num += 1
sleep(download_wait)