]> git.lizzy.rs Git - nhentai.git/blobdiff - nhentai/cmdline.py
remove __future__
[nhentai.git] / nhentai / cmdline.py
index 76d2168068182460e1ffceb223b3b599d7e3bb8e..ffc8a3e0a456e88f3869d959aa248fdd74bb6252 100644 (file)
@@ -1,8 +1,10 @@
 # coding: utf-8
-from __future__ import print_function
+
 import os
 import sys
+import json
 from optparse import OptionParser
+
 try:
     from itertools import ifilter as filter
 except ImportError:
@@ -13,17 +15,6 @@ from nhentai import __version__
 from nhentai.utils import urlparse, generate_html, generate_main_html, DB
 from nhentai.logger import logger
 
-try:
-    if sys.version_info < (3, 0, 0):
-        import codecs
-        import locale
-        sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
-        sys.stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr)
-
-except NameError:
-    # python3
-    pass
-
 
 def banner():
     logger.info(u'''nHentai ver %s: あなたも変態。 いいね?
@@ -35,7 +26,29 @@ def banner():
 ''' % __version__)
 
 
+def load_config():
+    if not os.path.exists(constant.NHENTAI_CONFIG_FILE):
+        return
+
+    try:
+        with open(constant.NHENTAI_CONFIG_FILE, 'r') as f:
+            constant.CONFIG.update(json.load(f))
+    except json.JSONDecodeError:
+        logger.error('Failed to load config file.')
+        write_config()
+
+
+def write_config():
+    if not os.path.exists(constant.NHENTAI_HOME):
+        os.mkdir(constant.NHENTAI_HOME)
+
+    with open(constant.NHENTAI_CONFIG_FILE, 'w') as f:
+        f.write(json.dumps(constant.CONFIG))
+
+
 def cmd_parser():
+    load_config()
+
     parser = OptionParser('\n  nhentai --search [keyword] --download'
                           '\n  NHENTAI=http://h.loli.club nhentai --id [ID ...]'
                           '\n  nhentai --file [filename]'
@@ -56,16 +69,14 @@ def cmd_parser():
     # page options
     parser.add_option('--page-all', dest='page_all', action='store_true', default=False,
                       help='all search results')
-    parser.add_option('--page', type='int', dest='page', action='store', default=1,
-                      help='page number of search results')
-    parser.add_option('--page-range', type='string', dest='page_range', action='store',
-                      help='page range of favorites.  e.g. 1,2-5,14')
+    parser.add_option('--page', '--page-range', type='string', dest='page', action='store', default='',
+                      help='page number of search results. e.g. 1,2-5,14')
     parser.add_option('--sorting', dest='sorting', action='store', default='recent',
                       help='sorting of doujinshi (recent / popular / popular-[today|week])',
                       choices=['recent', 'popular', 'popular-today', 'popular-week'])
 
     # download options
-    parser.add_option('--output', '-o', type='string', dest='output_dir', action='store', default='',
+    parser.add_option('--output', '-o', type='string', dest='output_dir', action='store', default='./',
                       help='output dir')
     parser.add_option('--threads', '-t', type='int', dest='threads', action='store', default=5,
                       help='thread count for downloading doujinshi')
@@ -73,7 +84,7 @@ def cmd_parser():
                       help='timeout for downloading doujinshi')
     parser.add_option('--delay', '-d', type='int', dest='delay', action='store', default=0,
                       help='slow down between downloading every doujinshi')
-    parser.add_option('--proxy', '-p', type='string', dest='proxy', action='store', default='',
+    parser.add_option('--proxy', type='string', dest='proxy', action='store', default='',
                       help='store a proxy, for example: -p \'http://127.0.0.1:1080\'')
     parser.add_option('--file',  '-f', type='string', dest='file', action='store', help='read gallery IDs from file.')
     parser.add_option('--format', type='string', dest='name_format', action='store',
@@ -104,6 +115,8 @@ def cmd_parser():
                       default=False, help='save downloaded doujinshis, whose will be skipped if you re-download them')
     parser.add_option('--clean-download-history', action='store_true', default=False, dest='clean_download_history',
                       help='clean download history')
+    parser.add_option('--template', dest='viewer_template', action='store',
+                      help='set viewer template', default='')
 
     try:
         sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv]
@@ -130,83 +143,50 @@ def cmd_parser():
         logger.info('Download history cleaned.')
         exit(0)
 
-    if os.path.exists(constant.NHENTAI_COOKIE):
-        with open(constant.NHENTAI_COOKIE, 'r') as f:
-            constant.COOKIE = f.read()
-
-    if args.cookie:
-        try:
-            if not os.path.exists(constant.NHENTAI_HOME):
-                os.mkdir(constant.NHENTAI_HOME)
-
-            with open(constant.NHENTAI_COOKIE, 'w') as f:
-                f.write(args.cookie)
-        except Exception as e:
-            logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
-            exit(1)
-
+    # --- set config ---
+    if args.cookie is not None:
+        constant.CONFIG['cookie'] = args.cookie
         logger.info('Cookie saved.')
+        write_config()
         exit(0)
 
-    if os.path.exists(constant.NHENTAI_LANGUAGE) and not args.language:
-        with open(constant.NHENTAI_LANGUAGE, 'r') as f:
-            constant.LANGUAGE = f.read()
-            args.language = f.read()
-
-    if args.language:
-        try:
-            if not os.path.exists(constant.NHENTAI_HOME):
-                os.mkdir(constant.NHENTAI_HOME)
-
-            with open(constant.NHENTAI_LANGUAGE, 'w') as f:
-                f.write(args.language)
-        except Exception as e:
-            logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
-            exit(1)
-
-        logger.info('Default language now is {}.'.format(args.language))
-        exit(0)
-
-    if args.clean_language:
-        try:
-            if not os.path.exists(constant.NHENTAI_HOME):
-                os.mkdir(constant.NHENTAI_HOME)
-
-            with open(constant.NHENTAI_LANGUAGE, 'w') as f:
-                f.close()
-        except Exception as e:
-            logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
-            exit(1)
-
-        logger.info('Language now is DEFAULT')
+    if args.language is not None:
+        constant.CONFIG['language'] = args.language
+        logger.info('Default language now set to \'{0}\''.format(args.language))
+        write_config()
         exit(0)
-
-    if os.path.exists(constant.NHENTAI_PROXY):
-        with open(constant.NHENTAI_PROXY, 'r') as f:
-            link = f.read()
-            constant.PROXY = {'http': link, 'https': link}
+        # TODO: search without language
 
     if args.proxy:
-        try:
-            if not os.path.exists(constant.NHENTAI_HOME):
-                os.mkdir(constant.NHENTAI_HOME)
-
-            proxy_url = urlparse(args.proxy)
-            if proxy_url.scheme not in ('http', 'https'):
-                logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
-            else:
-                with open(constant.NHENTAI_PROXY, 'w') as f:
-                    f.write(args.proxy)
-
-        except Exception as e:
-            logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
+        proxy_url = urlparse(args.proxy)
+        if not args.proxy == '' and proxy_url.scheme not in ('http', 'https'):
+            logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
+            exit(0)
+        else:
+            constant.CONFIG['proxy'] = {
+                'http': args.proxy,
+                'https': args.proxy,
+            }
+            logger.info('Proxy now set to \'{0}\'.'.format(args.proxy))
+            write_config()
+            exit(0)
+
+    if args.viewer_template:
+        if not args.viewer_template:
+            args.viewer_template = 'default'
+
+        if not os.path.exists(os.path.join(os.path.dirname(__file__),
+                                           'viewer/{}/index.html'.format(args.viewer_template))):
+            logger.error('Template \'{}\' does not exists'.format(args.viewer_template))
             exit(1)
+        else:
+            constant.CONFIG['template'] = args.viewer_template
+            write_config()
 
-        logger.info('Proxy \'{0}\' saved.'.format(args.proxy))
-        exit(0)
+    # --- end set config ---
 
     if args.favorites:
-        if not constant.COOKIE:
+        if not constant.CONFIG['cookie']:
             logger.warning('Cookie has not been set, please use `nhentai --cookie \'COOKIE\'` to set it.')
             exit(1)