]> git.lizzy.rs Git - nhentai.git/blob - nhentai/cmdline.py
add some shortcut options
[nhentai.git] / nhentai / cmdline.py
1 # coding: utf-8
2 from __future__ import print_function
3 import os
4 import sys
5 from optparse import OptionParser
6 try:
7     from itertools import ifilter as filter
8 except ImportError:
9     pass
10
11 import nhentai.constant as constant
12 from nhentai import __version__
13 from nhentai.utils import urlparse, generate_html
14 from nhentai.logger import logger
15
16 try:
17     if sys.version_info < (3, 0, 0):
18         import codecs
19         import locale
20         sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
21         sys.stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr)
22
23 except NameError:
24     # python3
25     pass
26
27
28 def banner():
29     logger.info(u'''nHentai ver %s: あなたも変態。 いいね?
30        _   _            _        _
31  _ __ | | | | ___ _ __ | |_ __ _(_)
32 | '_ \| |_| |/ _ \ '_ \| __/ _` | |
33 | | | |  _  |  __/ | | | || (_| | |
34 |_| |_|_| |_|\___|_| |_|\__\__,_|_|
35 ''' % __version__)
36
37
38 def cmd_parser():
39     parser = OptionParser('\n  nhentai --search [keyword] --download'
40                           '\n  NHENTAI=http://h.loli.club nhentai --id [ID ...]'
41                           '\n  nhentai --file [filename]'    
42                           '\n\nEnvironment Variable:\n'
43                           '  NHENTAI                 nhentai mirror url')
44     # operation options
45     parser.add_option('--download', '-D', dest='is_download', action='store_true',
46                       help='download doujinshi (for search results)')
47     parser.add_option('--show', '-S', dest='is_show', action='store_true', help='just show the doujinshi information')
48
49     # doujinshi options
50     parser.add_option('--id', type='string', dest='id', action='store', help='doujinshi ids set, e.g. 1,2,3')
51     parser.add_option('--search', '-s', type='string', dest='keyword', action='store', help='search doujinshi by keyword')
52     parser.add_option('--tag', type='string', dest='tag', action='store', help='download doujinshi by tag')
53     parser.add_option('--favorites', '-F', action='store_true', dest='favorites',
54                       help='list or download your favorites.')
55
56     # page options
57     parser.add_option('--page', type='int', dest='page', action='store', default=1,
58                       help='page number of search results')
59     parser.add_option('--max-page', type='int', dest='max_page', action='store', default=1,
60                       help='The max page when recursive download tagged doujinshi')
61
62     # download options
63     parser.add_option('--output', '-o', type='string', dest='output_dir', action='store', default='',
64                       help='output dir')
65     parser.add_option('--threads', '-t', type='int', dest='threads', action='store', default=5,
66                       help='thread count for downloading doujinshi')
67     parser.add_option('--timeout', '-T', type='int', dest='timeout', action='store', default=30,
68                       help='timeout for downloading doujinshi')
69     parser.add_option('--delay', '-d', type='int', dest='delay', action='store', default=0,
70                       help='slow down between downloading every doujinshi')
71     parser.add_option('--proxy', '-p', type='string', dest='proxy', action='store', default='',
72                       help='uses a proxy, for example: http://127.0.0.1:1080')
73     parser.add_option('--file',  '-f', type='string', dest='file', action='store', help='read gallery IDs from file.')
74     parser.add_option('--format', type='string', dest='name_format', action='store',
75                       help='format the saved folder name', default='[%i][%n]')
76
77     # generate options
78     parser.add_option('--html', dest='html_viewer', action='store_true',
79                       help='generate a html viewer at current directory')
80     parser.add_option('--no-html', dest='is_nohtml', action='store_true',
81                       help='don\'t generate HTML after downloading')
82     parser.add_option('--cbz', '-C', dest='is_cbz', action='store_true',
83                       help='generate Comic Book CBZ File')
84     parser.add_option('--rm-origin-dir', dest='rm_origin_dir', action='store_true', default=False,
85                       help='remove downloaded doujinshi dir when generated CBZ file.')
86
87     # nhentai options
88     parser.add_option('--cookie', type='str', dest='cookie', action='store',
89                       help='set cookie of nhentai to bypass Google recaptcha')
90
91     try:
92         sys.argv = list(map(lambda x: unicode(x.decode(sys.stdin.encoding)), sys.argv))
93     except (NameError, TypeError):
94         pass
95     except UnicodeDecodeError:
96         exit(0)
97
98     args, _ = parser.parse_args(sys.argv[1:])
99
100     if args.html_viewer:
101         generate_html()
102         exit(0)
103
104     if os.path.exists(os.path.join(constant.NHENTAI_HOME, 'cookie')):
105         with open(os.path.join(constant.NHENTAI_HOME, 'cookie'), 'r') as f:
106             constant.COOKIE = f.read()
107
108     if args.cookie:
109         try:
110             if not os.path.exists(constant.NHENTAI_HOME):
111                 os.mkdir(constant.NHENTAI_HOME)
112
113             with open(os.path.join(constant.NHENTAI_HOME, 'cookie'), 'w') as f:
114                 f.write(args.cookie)
115         except Exception as e:
116             logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
117             exit(1)
118
119         logger.info('Cookie saved.')
120         exit(0)
121
122     '''
123     if args.login:
124         try:
125             _, _ = args.login.split(':', 1)
126         except ValueError:
127             logger.error('Invalid `username:password` pair.')
128             exit(1)
129
130         if not args.is_download:
131             logger.warning('YOU DO NOT SPECIFY `--download` OPTION !!!')
132     '''
133
134     if args.favorites:
135         if not constant.COOKIE:
136             logger.warning('Cookie has not been set, please use `nhentai --cookie \'COOKIE\'` to set it.')
137             exit(1)
138
139     if args.id:
140         _ = map(lambda id_: id_.strip(), args.id.split(','))
141         args.id = set(map(int, filter(lambda id_: id_.isdigit(), _)))
142
143     if args.file:
144         with open(args.file, 'r') as f:
145             _ = map(lambda id: id.strip(), f.readlines())
146             args.id = set(map(int, filter(lambda id_: id_.isdigit(), _)))
147
148     if (args.is_download or args.is_show) and not args.id and not args.keyword and \
149             not args.tag and not args.favorites:
150         logger.critical('Doujinshi id(s) are required for downloading')
151         parser.print_help()
152         exit(1)
153
154     if not args.keyword and not args.id and not args.tag and not args.favorites:
155         parser.print_help()
156         exit(1)
157
158     if args.threads <= 0:
159         args.threads = 1
160
161     elif args.threads > 15:
162         logger.critical('Maximum number of used threads is 15')
163         exit(1)
164
165     if args.proxy:
166         proxy_url = urlparse(args.proxy)
167         if proxy_url.scheme not in ('http', 'https'):
168             logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
169         else:
170             constant.PROXY = {'http': args.proxy, 'https': args.proxy}
171
172     return args