]> git.lizzy.rs Git - nhentai.git/blob - nhentai/cmdline.py
fix #198 add notice
[nhentai.git] / nhentai / cmdline.py
1 # coding: utf-8
2
3 import os
4 import sys
5 import json
6 from optparse import OptionParser
7
8 try:
9     from itertools import ifilter as filter
10 except ImportError:
11     pass
12
13 import nhentai.constant as constant
14 from nhentai import __version__
15 from nhentai.utils import urlparse, generate_html, generate_main_html, DB
16 from nhentai.logger import logger
17
18
19 def banner():
20     logger.info(u'''nHentai ver %s: あなたも変態。 いいね?
21        _   _            _        _
22  _ __ | | | | ___ _ __ | |_ __ _(_)
23 | '_ \| |_| |/ _ \ '_ \| __/ _` | |
24 | | | |  _  |  __/ | | | || (_| | |
25 |_| |_|_| |_|\___|_| |_|\__\__,_|_|
26 ''' % __version__)
27
28
29 def load_config():
30     if not os.path.exists(constant.NHENTAI_CONFIG_FILE):
31         return
32
33     try:
34         with open(constant.NHENTAI_CONFIG_FILE, 'r') as f:
35             constant.CONFIG.update(json.load(f))
36     except json.JSONDecodeError:
37         logger.error('Failed to load config file.')
38         write_config()
39
40
41 def write_config():
42     if not os.path.exists(constant.NHENTAI_HOME):
43         os.mkdir(constant.NHENTAI_HOME)
44
45     with open(constant.NHENTAI_CONFIG_FILE, 'w') as f:
46         f.write(json.dumps(constant.CONFIG))
47
48
49 def cmd_parser():
50     load_config()
51
52     parser = OptionParser('\n  nhentai --search [keyword] --download'
53                           '\n  NHENTAI=http://h.loli.club nhentai --id [ID ...]'
54                           '\n  nhentai --file [filename]'
55                           '\n\nEnvironment Variable:\n'
56                           '  NHENTAI                 nhentai mirror url')
57     # operation options
58     parser.add_option('--download', '-D', dest='is_download', action='store_true',
59                       help='download doujinshi (for search results)')
60     parser.add_option('--show', '-S', dest='is_show', action='store_true', help='just show the doujinshi information')
61
62     # doujinshi options
63     parser.add_option('--id', type='string', dest='id', action='store', help='doujinshi ids set, e.g. 1,2,3')
64     parser.add_option('--search', '-s', type='string', dest='keyword', action='store',
65                       help='search doujinshi by keyword')
66     parser.add_option('--favorites', '-F', action='store_true', dest='favorites',
67                       help='list or download your favorites.')
68
69     # page options
70     parser.add_option('--page-all', dest='page_all', action='store_true', default=False,
71                       help='all search results')
72     parser.add_option('--page', '--page-range', type='string', dest='page', action='store', default='',
73                       help='page number of search results. e.g. 1,2-5,14')
74     parser.add_option('--sorting', dest='sorting', action='store', default='recent',
75                       help='sorting of doujinshi (recent / popular / popular-[today|week])',
76                       choices=['recent', 'popular', 'popular-today', 'popular-week'])
77
78     # download options
79     parser.add_option('--output', '-o', type='string', dest='output_dir', action='store', default='./',
80                       help='output dir')
81     parser.add_option('--threads', '-t', type='int', dest='threads', action='store', default=5,
82                       help='thread count for downloading doujinshi')
83     parser.add_option('--timeout', '-T', type='int', dest='timeout', action='store', default=30,
84                       help='timeout for downloading doujinshi')
85     parser.add_option('--delay', '-d', type='int', dest='delay', action='store', default=0,
86                       help='slow down between downloading every doujinshi')
87     parser.add_option('--proxy', type='string', dest='proxy', action='store', default='',
88                       help='store a proxy, for example: -p \'http://127.0.0.1:1080\'')
89     parser.add_option('--file',  '-f', type='string', dest='file', action='store', help='read gallery IDs from file.')
90     parser.add_option('--format', type='string', dest='name_format', action='store',
91                       help='format the saved folder name', default='[%i][%a][%t]')
92
93     # generate options
94     parser.add_option('--html', dest='html_viewer', action='store_true',
95                       help='generate a html viewer at current directory')
96     parser.add_option('--no-html', dest='is_nohtml', action='store_true',
97                       help='don\'t generate HTML after downloading')
98     parser.add_option('--gen-main', dest='main_viewer', action='store_true',
99                       help='generate a main viewer contain all the doujin in the folder')
100     parser.add_option('--cbz', '-C', dest='is_cbz', action='store_true',
101                       help='generate Comic Book CBZ File')
102     parser.add_option('--pdf', '-P', dest='is_pdf', action='store_true',
103                       help='generate PDF file')
104     parser.add_option('--rm-origin-dir', dest='rm_origin_dir', action='store_true', default=False,
105                       help='remove downloaded doujinshi dir when generated CBZ or PDF file.')
106
107     # nhentai options
108     parser.add_option('--cookie', type='str', dest='cookie', action='store',
109                       help='set cookie of nhentai to bypass Google recaptcha')
110     parser.add_option('--language', type='str', dest='language', action='store',
111                       help='set default language to parse doujinshis')
112     parser.add_option('--clean-language', dest='clean_language', action='store_true', default=False,
113                       help='set DEFAULT as language to parse doujinshis')
114     parser.add_option('--save-download-history', dest='is_save_download_history', action='store_true',
115                       default=False, help='save downloaded doujinshis, whose will be skipped if you re-download them')
116     parser.add_option('--clean-download-history', action='store_true', default=False, dest='clean_download_history',
117                       help='clean download history')
118     parser.add_option('--template', dest='viewer_template', action='store',
119                       help='set viewer template', default='')
120
121     try:
122         sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv]
123     except (NameError, TypeError):
124         pass
125     except UnicodeDecodeError:
126         exit(0)
127
128     args, _ = parser.parse_args(sys.argv[1:])
129
130     if args.html_viewer:
131         generate_html()
132         exit(0)
133
134     if args.main_viewer and not args.id and not args.keyword and not args.favorites:
135         generate_main_html()
136         exit(0)
137
138     if args.clean_download_history:
139         with DB() as db:
140             db.clean_all()
141
142         logger.info('Download history cleaned.')
143         exit(0)
144
145     # --- set config ---
146     if args.cookie is not None:
147         constant.CONFIG['cookie'] = args.cookie
148         logger.info('Cookie saved.')
149         write_config()
150         exit(0)
151
152     if args.language is not None:
153         constant.CONFIG['language'] = args.language
154         logger.info('Default language now set to \'{0}\''.format(args.language))
155         write_config()
156         exit(0)
157         # TODO: search without language
158
159     if args.proxy:
160         proxy_url = urlparse(args.proxy)
161         if not args.proxy == '' and proxy_url.scheme not in ('http', 'https'):
162             logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
163             exit(0)
164         else:
165             constant.CONFIG['proxy'] = {
166                 'http': args.proxy,
167                 'https': args.proxy,
168             }
169             logger.info('Proxy now set to \'{0}\'.'.format(args.proxy))
170             write_config()
171             exit(0)
172
173     if args.viewer_template:
174         if not args.viewer_template:
175             args.viewer_template = 'default'
176
177         if not os.path.exists(os.path.join(os.path.dirname(__file__),
178                                            'viewer/{}/index.html'.format(args.viewer_template))):
179             logger.error('Template \'{}\' does not exists'.format(args.viewer_template))
180             exit(1)
181         else:
182             constant.CONFIG['template'] = args.viewer_template
183             write_config()
184
185     # --- end set config ---
186
187     if args.favorites:
188         if not constant.CONFIG['cookie']:
189             logger.warning('Cookie has not been set, please use `nhentai --cookie \'COOKIE\'` to set it.')
190             exit(1)
191
192     if args.id:
193         _ = [i.strip() for i in args.id.split(',')]
194         args.id = set(int(i) for i in _ if i.isdigit())
195
196     if args.file:
197         with open(args.file, 'r') as f:
198             _ = [i.strip() for i in f.readlines()]
199             args.id = set(int(i) for i in _ if i.isdigit())
200
201     if (args.is_download or args.is_show) and not args.id and not args.keyword and not args.favorites:
202         logger.critical('Doujinshi id(s) are required for downloading')
203         parser.print_help()
204         exit(1)
205
206     if not args.keyword and not args.id and not  args.favorites:
207         parser.print_help()
208         exit(1)
209
210     if args.threads <= 0:
211         args.threads = 1
212
213     elif args.threads > 15:
214         logger.critical('Maximum number of used threads is 15')
215         exit(1)
216
217     return args