manga-dlp/mangadlp/downloader.py

60 lines
1.7 KiB
Python
Raw Normal View History

2022-07-06 22:19:40 +02:00
import logging
import shutil
import sys
2021-12-19 17:20:34 +01:00
from pathlib import Path
from time import sleep
2022-06-20 17:46:04 +02:00
from typing import Union
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-06-20 17:46:04 +02:00
image_urls: list,
chapter_path: Union[str, Path],
download_wait: float,
) -> None:
total_img = len(image_urls)
for image_num, image in enumerate(image_urls, 1):
# get image suffix
image_suffix = str(Path(image).suffix) or ".png"
2022-05-04 19:17:12 +02:00
# set image path
image_path = Path(f"{chapter_path}/{image_num:03d}{image_suffix}")
2022-07-06 22:19:40 +02:00
# show progress bar for default log level
if logging.root.level == logging.INFO:
utils.progress_bar(image_num, total_img)
2022-07-06 22:19:40 +02:00
logging.verbose(f"Downloading image {image_num}/{total_img}") # type: ignore
2022-05-16 16:09:17 +02:00
counter = 1
while counter <= 3:
try:
r = requests.get(image, stream=True)
if r.status_code != 200:
2022-07-06 22:19:40 +02:00
logging.error(f"Request for image {image} failed, retrying")
raise ConnectionError
2022-05-16 16:09:17 +02:00
except KeyboardInterrupt:
2022-07-06 22:19:40 +02:00
logging.critical("Stopping")
sys.exit(1)
2022-05-16 16:09:17 +02:00
except:
if counter >= 3:
2022-07-06 22:19:40 +02:00
logging.error("Maybe the MangaDex Servers are down?")
2022-05-16 16:09:17 +02:00
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:
2022-07-06 22:19:40 +02:00
logging.error("Can't write file")
2022-05-16 16:09:17 +02:00
raise IOError
2021-12-19 17:20:34 +01:00
image_num += 1
2022-05-16 16:09:17 +02:00
sleep(download_wait)