]> git.lizzy.rs Git - nhentai.git/blobdiff - nhentai/utils.py
fix #74
[nhentai.git] / nhentai / utils.py
index fe1270924aae1f73cd36fda332298d8f76f14f96..6a0d00bb848f620c8ce8ed686ba1b90c08274964 100644 (file)
@@ -2,13 +2,36 @@
 from __future__ import unicode_literals, print_function
 
 import sys
+import re
 import os
 import string
 import zipfile
 import shutil
+import requests
+
+from nhentai import constant
 from nhentai.logger import logger
 
 
+def request(method, url, **kwargs):
+    session = requests.Session()
+    session.headers.update({
+        'Referer': constant.LOGIN_URL,
+        'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
+        'Cookie': constant.COOKIE
+    })
+    return getattr(session, method)(url, proxies=constant.PROXY, verify=False, **kwargs)
+
+
+def check_cookie():
+    response = request('get', constant.BASE_URL).text
+    username = re.findall('"/users/\d+/(.*?)"', response)
+    if not username:
+        logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
+    else:
+        logger.info('Login successfully! Your username: {}'.format(username[0]))
+
+
 class _Singleton(type):
     """ A metaclass that creates a Singleton base class when called. """
     _instances = {}
@@ -81,11 +104,14 @@ def generate_html(output_dir='.', doujinshi_obj=None):
     except Exception as e:
         logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
 
-def generate_main_html(output_dir='.'):
-    """Generete a main html to show all the contain doujinshi.
-    With a link to thier `index.html`. 
+
+def generate_main_html(output_dir='./'):
+    """
+    Generate a main html to show all the contain doujinshi.
+    With a link to their `index.html`.
     Default output folder will be the CLI path.
     """
+
     count = 0
     image_html = ''
     main = readfile('viewer/main.html')
@@ -99,32 +125,32 @@ def generate_main_html(output_dir='.'):
                     </a>\n\
                 </div>\n\
             </div>\n'
-    
-    if output_dir == '':
-        os.chdir('.')
-    else:
-        os.chdir(output_dir) 
-    # switch to given dir
-    doujinshi_dirs = next(os.walk('.'))[1] 
-    # https://stackoverflow.com/questions/141291/how-to-list-only-top-level-directories-in-python
+
+    os.chdir(output_dir)
+    doujinshi_dirs = next(os.walk('.'))[1]
 
     for folder in doujinshi_dirs:
+
         files = os.listdir(folder)
+        files.sort()
+
         if 'index.html' in files:
             count += 1
+            logger.info('Add doujinshi \'{}\''.format(folder))
         else:
-            logger.warning('{} folder does not have index.html, try use --html arg first.'\
-            .format(folder))
             continue
-        image = files[0] # 001.jpg or 001.png
+
+        image = files[0]  # 001.jpg or 001.png
         if folder is not None:
             title = folder.replace('_', ' ')
-            # if sys.version_info > (3, 0):
-            #     title = title.encode('utf-8')
         else:
             title = 'nHentai HTML Viewer'
+
         image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
 
+    if image_html == '':
+        logger.warning('None index.html found, --gen-main paused.')
+        return
     try:
         data = main.format(STYLES=css, COUNT=count, PICTURE=image_html)
         if sys.version_info < (3, 0):
@@ -133,15 +159,16 @@ def generate_main_html(output_dir='.'):
         else:
             with open('./main.html', 'wb') as f:
                 f.write(data.encode('utf-8'))
-        logger.log(15, 'Main Viewer has been write to \'{0}\''.format('./main.html'))
+        logger.log(
+            15, 'Main Viewer has been write to \'{0}main.html\''.format(output_dir))
     except Exception as e:
         logger.warning('Writen Main Viewer failed ({})'.format(str(e)))
-    logger.info('==>Process finished.')
+
 
 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
     if doujinshi_obj is not None:
         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
-        cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '%s.cbz' % doujinshi_obj.id)
+        cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
     else:
         cbz_filename = './doujinshi.cbz'
         doujinshi_dir = '.'
@@ -174,7 +201,6 @@ an invalid filename.
 """
     valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
     filename = ''.join(c for c in s if c in valid_chars)
-    filename = filename.replace(' ', '_')  # I don't like spaces in filenames.
     if len(filename) > 100:
         filename = filename[:100] + '...]'