getjump

getjump 👉 getjmanga

PyPI version CI ghcr latest ghcr size

  • Retrieve and save images from manga distribution sites using GigaViewer

_Note: Redistribution of downloaded image data is prohibited. Please keep it to private use._

Screenshot

image

Valid URL Formats

Available Hosts

Deleted

Install

pip install getjump

CLI

Usage

$ jget -b https://kuragebunch.com/episode/10834108156628843815
get: https://kuragebunch.com/episode/10834108156628843815
  Downloading... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ( 18/18 pages ) remain: 0:00:00 spent: 0:00:02
  Saving...      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% ( 18/18 pages ) remain: 0:00:00 spent: 0:00:00
saved: 少女終末旅行/01 星空
next: https://kuragebunch.com/episode/10834108156628843819
...
saved: 少女終末旅行/42 終末
done.

Help

$ jget -h
usage: jget [-h] [-b] [-d DIR] [-f] [-o] [-m] [-u ID] [-p PW] [-q] [-V] url

Get images from jump web viewer

positional arguments:
  url                    target url

options:
  -h, --help             show this help message and exit
  -b, --bulk             download series in bulk (default: False)
  -d DIR, --savedir DIR  directory to save downloaded images (default: .)
  -f, --first            download only first page (default: False)
  -o, --overwrite        overwrite (default: False)
  -m, --metadata         save metadata as json (default: False)
  -u ID, --username ID   username if you want to login (default: None)
  -p PW, --password PW   password if you want to login (default: None)
  -q, --quiet            disable console print (default: False)
  -V, --version          show program's version number and exit

available urls:
  - https://comic-action.com
  - https://comic-days.com
  - https://comic-earthstar.com
  - https://comic-gardo.com
  - https://comic-ogyaaa.com
  - https://comic-seasons.com
  - https://comic-trail.com
  - https://comic-y-ours.com
  - https://comic-zenon.com
  - https://comicborder.com
  - https://feelweb.jp
  - https://ichicomi.com
  - https://kuragebunch.com
  - https://magcomi.com
  - https://mangatime-square.com
  - https://ourfeel.jp
  - https://shonenjumpplus.com
  - https://www.sunday-webry.com
  - https://tonarinoyj.jp

Library

Overview

from getjump import GetJump
g = GetJump()  # create session

g.get(
    url: str,
    save_path: str = ".",
    overwrite: bool = True,
    only_first: bool = False,
    username: str | None = None,
    password: str | None = None,
)
# >>> (next_uri: str | None, prev_title: str, saved: bool)

g.login(
    url: str,
    username: str | None = None,
    password: str | None = None,
    overwrite: bool = False,
)
# >>> logined_response: requests.Response | None

g.is_valid_uri(url: str)
# >>> is_valid_uri: bool

Download all series

To download all series at once:

from getjump import GetJump as g

G = g()
next_uri = "https://shonenjumpplus.com/episode/13932016480028799982.json"
while next_uri:
    next_uri, prev_title, saved = G.get(next_uri, overwrite=False)
    if saved:
        print("saved:", prev_title)
    print("next:", next_uri)

Login

To get purchased or login-required works:

from getjump import GetJump as g

G = g()
G.login("https://shonenjumpplus.com", username="***", password="***")
G.login("https://comic-days.com", username="***", password="***")
...
G.get(...)

License

MIT


Reference

 1""".. include:: ../README.md"""
 2
 3import importlib.metadata
 4
 5from .getjump import VALID_HOSTS, EpisodeJsonNotFoundError, GetJump, NeedPurchase
 6
 7try:
 8    __version__ = importlib.metadata.version(__name__)
 9except importlib.metadata.PackageNotFoundError:
10    __version__ = "0.0.0"
11
12__all__ = ("VALID_HOSTS", "EpisodeJsonNotFoundError", "GetJump", "NeedPurchase")
VALID_HOSTS = ('comic-action.com', 'comic-days.com', 'comic-earthstar.com', 'comic-gardo.com', 'comic-ogyaaa.com', 'comic-seasons.com', 'comic-trail.com', 'comic-y-ours.com', 'comic-zenon.com', 'comicborder.com', 'feelweb.jp', 'ichicomi.com', 'kuragebunch.com', 'magcomi.com', 'mangatime-square.com', 'ourfeel.jp', 'shonenjumpplus.com', 'www.sunday-webry.com', 'tonarinoyj.jp')
class EpisodeJsonNotFoundError(builtins.Exception):
95class EpisodeJsonNotFoundError(Exception):
96    def __init__(self, url: str) -> None:
97        super().__init__(
98            f"`script#episode-json` is not found in '{url}'. The site may be temporarily unavailable.",
99        )

Common base class for all non-exit exceptions.

EpisodeJsonNotFoundError(url: str)
96    def __init__(self, url: str) -> None:
97        super().__init__(
98            f"`script#episode-json` is not found in '{url}'. The site may be temporarily unavailable.",
99        )
class GetJump:
102class GetJump:
103    def __init__(self) -> None:
104        self._logged_in_hosts: list[str] = []
105
106        session = Session()
107        retry_adapter = HTTPAdapter(max_retries=Retry(total=10, backoff_factor=1))
108        session.mount("https://", retry_adapter)
109        session.mount("http://", retry_adapter)
110
111        self._session = session
112
113    def get(  # noqa: PLR0913
114        self,
115        url: str,
116        save_path: str | Path = ".",
117        *,
118        overwrite: bool = True,
119        only_first: bool = False,
120        username: str | None = None,
121        password: str | None = None,
122        save_metadata: bool = False,
123        print_log: bool = False,
124    ) -> tuple[str | None, Path, bool]:
125        self.__check_url(url)
126        self.__reject_feed_url(url)
127        self.login(url, username=username, password=password)
128
129        url = url.removesuffix(".json")
130
131        episode_json = self.__get_episode_json(url)
132        j = episode_json["readableProduct"]
133
134        nxt = j["nextReadableProductUri"]
135
136        if j["typeName"] == "magazine":
137            series_title = self.__get_series_title(url, j["title"])
138            title = j["title"].replace(series_title, "")
139        elif j["typeName"] in ("episode", "volume"):
140            series_title = j["series"]["title"].replace("/", "/")
141            title = j["title"].replace("/", "/")
142        else:
143            msg = f"Unknown typeName: {j['typeName']}"
144            raise ValueError(msg)
145
146        series_title = sanitize_filename(series_title)
147        title = sanitize_filename(title)
148
149        save_dir = Path(save_path) / series_title / title
150        if save_dir.exists() and not overwrite:
151            if print_log:
152                print(  # noqa: T201
153                    "already existed! (to overwrite, use `-o`)",
154                    file=sys.stderr,
155                )
156            return nxt, save_dir, False
157        save_dir.mkdir(exist_ok=True, parents=True)
158
159        if not j["isPublic"] and not j["hasPurchased"]:
160            warnings.warn(title, NeedPurchase, stacklevel=1)
161            return nxt, save_dir, False
162        pages: list[Page] = [p for p in j["pageStructure"]["pages"] if "src" in p]
163
164        if save_metadata:
165            (save_dir / "metadata.json").write_text(
166                json.dumps(episode_json, indent=4, ensure_ascii=False),
167                encoding="utf-8",
168            )
169        self.__save_images(pages, save_dir, only_first=only_first, print_log=print_log)
170
171        return nxt, save_dir, True
172
173    def get_episode_urls(self, url: str) -> list[str]:
174        """Expand `/rss/series/<id>` into every episode url in the feed.
175
176        Any other valid url is returned as-is.
177        """
178        self.__check_url(url)
179        if not self.__is_feed_url(url):
180            return [url]
181
182        res = self._session.get(url, headers=HEADERS)
183        # the feed is served by an already trusted host (see `VALID_HOSTS`)
184        feed = ET.fromstring(res.text)  # noqa: S314
185        links = [link.strip() for elem in feed.findall("./channel/item/link") if (link := elem.text)]
186        if not links:
187            msg = f"no episode is found in the feed: {url}"
188            raise ValueError(msg)
189        for link in links:
190            self.__check_url(link)
191        return links
192
193    @staticmethod
194    def is_valid_uri(url: str) -> bool:
195        o = urlparse(url)
196        return o.scheme == "https" and o.hostname in VALID_HOSTS and bool(re.match(_VALID_PATH_PATTERN, o.path))
197
198    def login(
199        self,
200        url: str,
201        *,
202        username: str | None = None,
203        password: str | None = None,
204        overwrite: bool = False,
205    ) -> Response | None:
206        if username is None and password is None:
207            return None  # needless to login
208        o = urlparse(url)
209        base_url = f"{o.scheme}://{o.netloc}"
210        login_url = f"{base_url}/user_account/login"
211        if base_url in self._logged_in_hosts and not overwrite:
212            return None  # skip if already being logged in
213        res = self._session.post(
214            login_url,
215            data={
216                "email_address": username,
217                "password": password,
218                "return_location_path": url,
219            },
220            headers={
221                "User-Agent": HEADERS["User-Agent"],
222                "x-requested-with": "XMLHttpRequest",
223            },
224        )
225        status_code = res.status_code
226        if res.ok:
227            self._logged_in_hosts.append(base_url)
228        else:
229            msg = f"Maybe login (to: {login_url}) is failed (code: {status_code}). Is given information correct?"
230            raise ValueError(msg)
231        return res
232
233    def __get_episode_json(self, url: str) -> dict[str, Any]:
234        for attempt in range(_EPISODE_JSON_RETRY):
235            res = self._session.get(url, headers=HEADERS)
236            self.__check_content_type(res.headers["content-type"])
237
238            script_tag = BeautifulSoup(res.content, "html.parser").find(
239                "script",
240                id="episode-json",
241            )
242            if isinstance(script_tag, Tag):
243                json_value = script_tag.attrs.get("data-value", None)
244                if json_value is None:
245                    msg = f"json data is missing in '{url}'."
246                    raise ValueError(msg)
247                return dict(json.loads(str(json_value)))
248
249            if attempt + 1 < _EPISODE_JSON_RETRY:
250                time.sleep(_EPISODE_JSON_RETRY_INTERVAL * (attempt + 1))
251
252        raise EpisodeJsonNotFoundError(url)
253
254    def __check_url(self, url: str) -> None:
255        if not self.is_valid_uri(url):
256            msg = f"'{url}' is not valid url."
257            raise ValueError(msg)
258
259    @staticmethod
260    def __is_feed_url(url: str) -> bool:
261        return bool(re.match(_RSS_PATH_PATTERN, urlparse(url).path))
262
263    @classmethod
264    def __reject_feed_url(cls, url: str) -> None:
265        if cls.__is_feed_url(url):
266            msg = f"'{url}' is a feed. Expand it with `get_episode_urls()` first."
267            raise ValueError(msg)
268
269    @staticmethod
270    def __check_content_type(type_: str) -> None:
271        if "text/html" not in type_:
272            msg = f"got '{type_}', expect 'text/html'. Is given URL correct?"
273            raise TypeError(msg)
274
275    def __save_images(
276        self,
277        pages: list[Page],
278        save_dir: Path,
279        *,
280        only_first: bool = False,
281        print_log: bool = False,
282    ) -> None:
283        progress = Progress(
284            SpinnerColumn(),
285            TextColumn("{task.description}"),
286            BarColumn(),
287            TaskProgressColumn(),
288            TextColumn("("),
289            MofNCompleteColumn(),
290            TextColumn("pages"),
291            TextColumn(")"),
292            TextColumn("remain:"),
293            TimeRemainingColumn(),
294            TextColumn("spent:"),
295            TimeElapsedColumn(),
296            disable=not print_log,
297        )
298        with progress:
299            imgs: list[Image.Image] = []
300            task_dl = progress.add_task(
301                "[red]Downloading...",
302                total=1 if only_first else len(pages),
303            )
304            for page in pages:
305                img = self.__get_image(page["src"])
306                imgs.append(img)
307                progress.update(task_dl, advance=1)
308                if only_first:
309                    break
310
311            len_page_digit = len(str(len(imgs)))
312            task_save = progress.add_task("[green]Saving...", total=len(imgs))
313            for idx, img in enumerate(imgs):
314                save_img_name = f"%0{len_page_digit}d" % idx
315                save_img_path = save_dir / save_img_name
316                img.save(save_img_path.with_suffix(".jpg"))
317                progress.update(task_save, advance=1)
318
319    def __get_image(self, image_src: str, div: int = 4, mul: int = 8) -> Image.Image:
320        img = Image.open(BytesIO(self._session.get(image_src, timeout=10).content))
321        img_width, img_height = img.size
322        fixed_width = int(float(img_width) / (div * mul)) * mul
323        fixed_height = int(float(img_height) / (div * mul)) * mul
324        buff: list[list[Image.Image]] = []
325        for x in range(div):
326            inbuff: list[Image.Image] = []
327            for y in range(div):
328                cropped = img.crop(
329                    box=(
330                        fixed_width * x,
331                        fixed_height * y,
332                        fixed_width * (x + 1),
333                        fixed_height * (y + 1),
334                    ),
335                )
336                inbuff.append(cropped)
337            buff.append(inbuff)
338
339        for y, inbuff in enumerate(buff):
340            for x, cropped in enumerate(inbuff):
341                img.paste(cropped, box=(fixed_width * x, fixed_height * y))
342        return img
343
344    def __get_series_title(self, url: str, title: str) -> str:
345        res = self._session.get(url.replace(".json", ""), headers=HEADERS)
346        title_tag = BeautifulSoup(res.content, "html.parser").find(
347            "h1",
348            class_="series-header-title",
349        )
350        if title_tag is None:
351            return re.sub(r"\s*" + _MAGAZINE_TITLE_PATTERN, "", title)
352
353        return title_tag.text
def get( self, url: str, save_path: str | pathlib.Path = '.', *, overwrite: bool = True, only_first: bool = False, username: str | None = None, password: str | None = None, save_metadata: bool = False, print_log: bool = False) -> tuple[str | None, pathlib.Path, bool]:
113    def get(  # noqa: PLR0913
114        self,
115        url: str,
116        save_path: str | Path = ".",
117        *,
118        overwrite: bool = True,
119        only_first: bool = False,
120        username: str | None = None,
121        password: str | None = None,
122        save_metadata: bool = False,
123        print_log: bool = False,
124    ) -> tuple[str | None, Path, bool]:
125        self.__check_url(url)
126        self.__reject_feed_url(url)
127        self.login(url, username=username, password=password)
128
129        url = url.removesuffix(".json")
130
131        episode_json = self.__get_episode_json(url)
132        j = episode_json["readableProduct"]
133
134        nxt = j["nextReadableProductUri"]
135
136        if j["typeName"] == "magazine":
137            series_title = self.__get_series_title(url, j["title"])
138            title = j["title"].replace(series_title, "")
139        elif j["typeName"] in ("episode", "volume"):
140            series_title = j["series"]["title"].replace("/", "/")
141            title = j["title"].replace("/", "/")
142        else:
143            msg = f"Unknown typeName: {j['typeName']}"
144            raise ValueError(msg)
145
146        series_title = sanitize_filename(series_title)
147        title = sanitize_filename(title)
148
149        save_dir = Path(save_path) / series_title / title
150        if save_dir.exists() and not overwrite:
151            if print_log:
152                print(  # noqa: T201
153                    "already existed! (to overwrite, use `-o`)",
154                    file=sys.stderr,
155                )
156            return nxt, save_dir, False
157        save_dir.mkdir(exist_ok=True, parents=True)
158
159        if not j["isPublic"] and not j["hasPurchased"]:
160            warnings.warn(title, NeedPurchase, stacklevel=1)
161            return nxt, save_dir, False
162        pages: list[Page] = [p for p in j["pageStructure"]["pages"] if "src" in p]
163
164        if save_metadata:
165            (save_dir / "metadata.json").write_text(
166                json.dumps(episode_json, indent=4, ensure_ascii=False),
167                encoding="utf-8",
168            )
169        self.__save_images(pages, save_dir, only_first=only_first, print_log=print_log)
170
171        return nxt, save_dir, True
def get_episode_urls(self, url: str) -> list[str]:
173    def get_episode_urls(self, url: str) -> list[str]:
174        """Expand `/rss/series/<id>` into every episode url in the feed.
175
176        Any other valid url is returned as-is.
177        """
178        self.__check_url(url)
179        if not self.__is_feed_url(url):
180            return [url]
181
182        res = self._session.get(url, headers=HEADERS)
183        # the feed is served by an already trusted host (see `VALID_HOSTS`)
184        feed = ET.fromstring(res.text)  # noqa: S314
185        links = [link.strip() for elem in feed.findall("./channel/item/link") if (link := elem.text)]
186        if not links:
187            msg = f"no episode is found in the feed: {url}"
188            raise ValueError(msg)
189        for link in links:
190            self.__check_url(link)
191        return links

Expand /rss/series/<id> into every episode url in the feed.

Any other valid url is returned as-is.

@staticmethod
def is_valid_uri(url: str) -> bool:
193    @staticmethod
194    def is_valid_uri(url: str) -> bool:
195        o = urlparse(url)
196        return o.scheme == "https" and o.hostname in VALID_HOSTS and bool(re.match(_VALID_PATH_PATTERN, o.path))
def login( self, url: str, *, username: str | None = None, password: str | None = None, overwrite: bool = False) -> requests.models.Response | None:
198    def login(
199        self,
200        url: str,
201        *,
202        username: str | None = None,
203        password: str | None = None,
204        overwrite: bool = False,
205    ) -> Response | None:
206        if username is None and password is None:
207            return None  # needless to login
208        o = urlparse(url)
209        base_url = f"{o.scheme}://{o.netloc}"
210        login_url = f"{base_url}/user_account/login"
211        if base_url in self._logged_in_hosts and not overwrite:
212            return None  # skip if already being logged in
213        res = self._session.post(
214            login_url,
215            data={
216                "email_address": username,
217                "password": password,
218                "return_location_path": url,
219            },
220            headers={
221                "User-Agent": HEADERS["User-Agent"],
222                "x-requested-with": "XMLHttpRequest",
223            },
224        )
225        status_code = res.status_code
226        if res.ok:
227            self._logged_in_hosts.append(base_url)
228        else:
229            msg = f"Maybe login (to: {login_url}) is failed (code: {status_code}). Is given information correct?"
230            raise ValueError(msg)
231        return res
class NeedPurchase(builtins.Warning):
91class NeedPurchase(Warning):
92    pass

Base class for warning categories.