gettake.main

Main module for gettake.

  1"""Main module for gettake."""
  2
  3from __future__ import annotations
  4
  5import re
  6import sys
  7from argparse import (
  8    ArgumentDefaultsHelpFormatter,
  9    ArgumentParser,
 10    ArgumentTypeError,
 11    RawDescriptionHelpFormatter,
 12)
 13from pathlib import Path
 14from shutil import get_terminal_size
 15from typing import TYPE_CHECKING
 16from urllib.parse import urlparse
 17
 18from . import __version__
 19from .gettake import get_images
 20from .models import Option
 21
 22if TYPE_CHECKING:
 23    from urllib.parse import ParseResult
 24
 25VALID_HOSTS = ("webcomicgamma.takeshobo.co.jp",)
 26
 27
 28class CustomFormatter(ArgumentDefaultsHelpFormatter, RawDescriptionHelpFormatter):
 29    """Custom formatter for argparse."""
 30
 31
 32def available_list() -> str:
 33    """Return available urls.
 34
 35    Returns:
 36        str: available urls.
 37    """
 38    return "available urls:\n  - https://" + "\n  - https://".join(VALID_HOSTS)
 39
 40
 41def check_url(s: str) -> ParseResult:
 42    """Check if s is a valid url.
 43
 44    Args:
 45        s (str): url to check.
 46
 47    Raises:
 48        argparse.ArgumentTypeError: if s is invalid.
 49
 50    Returns:
 51        ParseResult: url object.
 52    """
 53    url = urlparse(s)
 54    if url.hostname in VALID_HOSTS and re.match("^/manga/[^/]+/?$", url.path):
 55        return url
 56    raise ArgumentTypeError(f"'{s}' is invalid.\n" + available_list())
 57
 58
 59def check_dir(s: str) -> Path:
 60    """Check if s is a valid directory.
 61
 62    Args:
 63        s (str): path to check.
 64
 65    Raises:
 66        argparse.ArgumentTypeError: if s is not a directory.
 67
 68    Returns:
 69        Path: path object.
 70    """
 71    if s == ".":
 72        return Path().cwd()
 73    path = Path(s)
 74    if not path.is_dir():
 75        msg = f"{s!r} is not dir."
 76        raise ArgumentTypeError(msg)
 77    return path
 78
 79
 80def parse_args(test: list[str] | None = None) -> Option:
 81    """Parse arguments.
 82
 83    Args:
 84        test (list[str] | None): test args. Defaults to None.
 85
 86    Returns:
 87            Option: cli options.
 88
 89    Raises:
 90            ArgumentTypeError: if url is invalid.
 91    """
 92    parser = ArgumentParser(
 93        formatter_class=(
 94            lambda prog: CustomFormatter(
 95                prog,
 96                width=get_terminal_size(fallback=(120, 50)).columns,
 97                max_help_position=25,
 98            )
 99        ),
100        description="Get and save images from webcomicgamma.",
101        epilog=available_list(),
102    )
103
104    parser.add_argument(
105        "url",
106        metavar="url",
107        type=check_url,
108        help="target url",
109    )
110    parser.add_argument(
111        "-d",
112        "--save-dir",
113        type=check_dir,
114        metavar="DIR",
115        default=".",
116        help="directory to save downloaded images",
117    )
118    parser.add_argument(
119        "-o",
120        "--overwrite",
121        action="store_true",
122        help="overwrite",
123    )
124    parser.add_argument(
125        "-q",
126        "--quiet",
127        action="store_true",
128        help="keep stdout quiet",
129    )
130    parser.add_argument("-V", "--version", action="version", version=__version__)
131
132    if test:
133        args = parser.parse_args(test)
134    if len(sys.argv) == 1:
135        parser.print_help()
136        sys.exit(0)
137    else:
138        args = parser.parse_args()
139    return Option(
140        url=args.url,
141        save_dir=args.save_dir,
142        overwrite=args.overwrite,
143        quiet=args.quiet,
144    )
145
146
147def _main(test: list[str] | None = None) -> None:
148    """Main function.
149
150    Args:
151        test (list[str] | None): test args. Defaults to None.
152    """
153    opt = parse_args(test)
154    if not opt.quiet:
155        print(f"[+] Target: {opt.url.geturl()}")
156        print(f"[+] Host:   {opt.url.hostname}")
157        print(f"[+] Slug:   {opt.get_slug()}")
158    get_images(opt)
159    if not opt.quiet:
160        print("[+] Done!")
161
162
163def main() -> None:
164    """Main function."""
165    try:
166        _main()
167    except KeyboardInterrupt:
168        sys.exit(1)
169
170
171if __name__ == "__main__":
172    main()
VALID_HOSTS = ('webcomicgamma.takeshobo.co.jp',)
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
29class CustomFormatter(ArgumentDefaultsHelpFormatter, RawDescriptionHelpFormatter):
30    """Custom formatter for argparse."""

Custom formatter for argparse.

def available_list() -> str:
33def available_list() -> str:
34    """Return available urls.
35
36    Returns:
37        str: available urls.
38    """
39    return "available urls:\n  - https://" + "\n  - https://".join(VALID_HOSTS)

Return available urls.

Returns:

str: available urls.

def check_url(s: str) -> urllib.parse.ParseResult:
42def check_url(s: str) -> ParseResult:
43    """Check if s is a valid url.
44
45    Args:
46        s (str): url to check.
47
48    Raises:
49        argparse.ArgumentTypeError: if s is invalid.
50
51    Returns:
52        ParseResult: url object.
53    """
54    url = urlparse(s)
55    if url.hostname in VALID_HOSTS and re.match("^/manga/[^/]+/?$", url.path):
56        return url
57    raise ArgumentTypeError(f"'{s}' is invalid.\n" + available_list())

Check if s is a valid url.

Arguments:
  • s (str): url to check.
Raises:
  • argparse.ArgumentTypeError: if s is invalid.
Returns:

ParseResult: url object.

def check_dir(s: str) -> pathlib.Path:
60def check_dir(s: str) -> Path:
61    """Check if s is a valid directory.
62
63    Args:
64        s (str): path to check.
65
66    Raises:
67        argparse.ArgumentTypeError: if s is not a directory.
68
69    Returns:
70        Path: path object.
71    """
72    if s == ".":
73        return Path().cwd()
74    path = Path(s)
75    if not path.is_dir():
76        msg = f"{s!r} is not dir."
77        raise ArgumentTypeError(msg)
78    return path

Check if s is a valid directory.

Arguments:
  • s (str): path to check.
Raises:
  • argparse.ArgumentTypeError: if s is not a directory.
Returns:

Path: path object.

def parse_args(test: list[str] | None = None) -> gettake.models.Option:
 81def parse_args(test: list[str] | None = None) -> Option:
 82    """Parse arguments.
 83
 84    Args:
 85        test (list[str] | None): test args. Defaults to None.
 86
 87    Returns:
 88            Option: cli options.
 89
 90    Raises:
 91            ArgumentTypeError: if url is invalid.
 92    """
 93    parser = ArgumentParser(
 94        formatter_class=(
 95            lambda prog: CustomFormatter(
 96                prog,
 97                width=get_terminal_size(fallback=(120, 50)).columns,
 98                max_help_position=25,
 99            )
100        ),
101        description="Get and save images from webcomicgamma.",
102        epilog=available_list(),
103    )
104
105    parser.add_argument(
106        "url",
107        metavar="url",
108        type=check_url,
109        help="target url",
110    )
111    parser.add_argument(
112        "-d",
113        "--save-dir",
114        type=check_dir,
115        metavar="DIR",
116        default=".",
117        help="directory to save downloaded images",
118    )
119    parser.add_argument(
120        "-o",
121        "--overwrite",
122        action="store_true",
123        help="overwrite",
124    )
125    parser.add_argument(
126        "-q",
127        "--quiet",
128        action="store_true",
129        help="keep stdout quiet",
130    )
131    parser.add_argument("-V", "--version", action="version", version=__version__)
132
133    if test:
134        args = parser.parse_args(test)
135    if len(sys.argv) == 1:
136        parser.print_help()
137        sys.exit(0)
138    else:
139        args = parser.parse_args()
140    return Option(
141        url=args.url,
142        save_dir=args.save_dir,
143        overwrite=args.overwrite,
144        quiet=args.quiet,
145    )

Parse arguments.

Arguments:
  • test (list[str] | None): test args. Defaults to None.
Returns:

Option: cli options.

Raises:
  • ArgumentTypeError: if url is invalid.
def main() -> None:
164def main() -> None:
165    """Main function."""
166    try:
167        _main()
168    except KeyboardInterrupt:
169        sys.exit(1)

Main function.