scripts/downloaders/mangadex.py

42 lines
1.2 KiB
Python
Executable File

#!/usr/bin/env python3
from tqdm import tqdm
import requests
import shutil
import simplejson.errors
import sys
import os
if len(sys.argv) < 2:
raise Exception("sys.argv[1]")
def parse_chapter_api(data):
if not data["server"].startswith("http"):
data["server"] = "https://mangadex.org/data/"
base_url = data["server"] + data["hash"] + "/"
return list(map(lambda page: base_url + page, data["page_array"]))
for chapter in tqdm(sys.argv[1:]):
chapter_api_response = requests.get(
f"https://mangadex.org/api/?id={chapter}&type=chapter"
)
chapter_number = chapter_api_response.json()["chapter"]
os.makedirs(chapter_number, exist_ok=True)
try:
for image in tqdm(parse_chapter_api(chapter_api_response.json())):
r = requests.get(image, stream=True)
with open(chapter_number + "/" + image.split("/")[-1], "wb") as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
except simplejson.errors.JSONDecodeError as e:
if chapter_api_response.status_code != 200:
raise Exception(
f"API request failed with HTTP status code {chapter_api_response.status_code}"
) from None
else:
raise e