]> git.lizzy.rs Git - nhentai.git/blob - nhentai/cmdline.py
Update README.rst
[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', dest='is_download', action='store_true',
46                       help='download doujinshi (for search results)')
47     parser.add_option('--show', 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', 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', 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', type='int', dest='timeout', action='store', default=30,
68                       help='timeout for downloading doujinshi')
69     parser.add_option('--proxy', type='string', dest='proxy', action='store', default='',
70                       help='uses a proxy, for example: http://127.0.0.1:1080')
71     parser.add_option('--file',  '-f', type='string', dest='file', action='store', help='read gallery IDs from file.')
72
73     # generate options
74     parser.add_option('--html', dest='html_viewer', action='store_true',
75                       help='generate a html viewer at current directory')
76     parser.add_option('--nohtml', dest='is_nohtml', action='store_true',
77                       help='don\'t generate HTML')
78     parser.add_option('--cbz', dest='is_cbz', action='store_true',
79                       help='generate Comic Book CBZ File')
80     parser.add_option('--rm-origin-dir', dest='rm_origin_dir', action='store_true', default=False,
81                       help='remove downloaded doujinshi dir when generated CBZ file.')
82
83     # nhentai options
84     parser.add_option('--cookie', type='str', dest='cookie', action='store',
85                       help='set cookie of nhentai to bypass Google recaptcha')
86
87     try:
88         sys.argv = list(map(lambda x: unicode(x.decode(sys.stdin.encoding)), sys.argv))
89     except (NameError, TypeError):
90         pass
91     except UnicodeDecodeError:
92         exit(0)
93
94     args, _ = parser.parse_args(sys.argv[1:])
95
96     if args.html_viewer:
97         generate_html()
98         exit(0)
99
100     if os.path.exists(os.path.join(constant.NHENTAI_HOME, 'cookie')):
101         with open(os.path.join(constant.NHENTAI_HOME, 'cookie'), 'r') as f:
102             constant.COOKIE = f.read()
103
104     if args.cookie:
105         try:
106             if not os.path.exists(constant.NHENTAI_HOME):
107                 os.mkdir(constant.NHENTAI_HOME)
108
109             with open(os.path.join(constant.NHENTAI_HOME, 'cookie'), 'w') as f:
110                 f.write(args.cookie)
111         except Exception as e:
112             logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
113             exit(1)
114
115         logger.info('Cookie saved.')
116         exit(0)
117
118     '''
119     if args.login:
120         try:
121             _, _ = args.login.split(':', 1)
122         except ValueError:
123             logger.error('Invalid `username:password` pair.')
124             exit(1)
125
126         if not args.is_download:
127             logger.warning('YOU DO NOT SPECIFY `--download` OPTION !!!')
128     '''
129
130     if args.favorites:
131         if not constant.COOKIE:
132             logger.warning('Cookie has not been set, please use `nhentai --cookie \'COOKIE\'` to set it.')
133             exit(1)
134
135     if args.id:
136         _ = map(lambda id_: id_.strip(), args.id.split(','))
137         args.id = set(map(int, filter(lambda id_: id_.isdigit(), _)))
138
139     if args.file:
140         with open(args.file, 'r') as f:
141             _ = map(lambda id: id.strip(), f.readlines())
142             args.id = set(map(int, filter(lambda id_: id_.isdigit(), _)))
143
144     if (args.is_download or args.is_show) and not args.id and not args.keyword and \
145             not args.tag and not args.favorites:
146         logger.critical('Doujinshi id(s) are required for downloading')
147         parser.print_help()
148         exit(1)
149
150     if not args.keyword and not args.id and not args.tag and not args.favorites:
151         parser.print_help()
152         exit(1)
153
154     if args.threads <= 0:
155         args.threads = 1
156
157     elif args.threads > 15:
158         logger.critical('Maximum number of used threads is 15')
159         exit(1)
160
161     if args.proxy:
162         proxy_url = urlparse(args.proxy)
163         if proxy_url.scheme not in ('http', 'https'):
164             logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
165         else:
166             constant.PROXY = {'http': args.proxy, 'https': args.proxy}
167
168     return args