2 from __future__ import unicode_literals, print_function
12 from nhentai import constant
13 from nhentai.logger import logger
14 from nhentai.serializer import serialize, set_js_database
17 def request(method, url, **kwargs):
18 session = requests.Session()
19 session.headers.update({
20 'Referer': constant.LOGIN_URL,
21 'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
22 'Cookie': constant.COOKIE
24 return getattr(session, method)(url, proxies=constant.PROXY, verify=False, **kwargs)
28 response = request('get', constant.BASE_URL).text
29 username = re.findall('"/users/\d+/(.*?)"', response)
31 logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
33 logger.info('Login successfully! Your username: {}'.format(username[0]))
36 class _Singleton(type):
37 """ A metaclass that creates a Singleton base class when called. """
40 def __call__(cls, *args, **kwargs):
41 if cls not in cls._instances:
42 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
43 return cls._instances[cls]
46 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
52 from urlparse import urlparse
54 from urllib.parse import urlparse
60 loc = os.path.dirname(__file__)
62 with open(os.path.join(loc, path), 'r') as file:
66 def generate_html(output_dir='.', doujinshi_obj=None):
69 if doujinshi_obj is not None:
70 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
74 file_list = os.listdir(doujinshi_dir)
77 for image in file_list:
78 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
81 image_html += '<img src="{0}" class="image-item"/>\n'\
83 html = readfile('viewer/index.html')
84 css = readfile('viewer/styles.css')
85 js = readfile('viewer/scripts.js')
87 if doujinshi_obj is not None:
88 serialize(doujinshi_obj, doujinshi_dir)
89 name = doujinshi_obj.name
90 if sys.version_info < (3, 0):
91 name = doujinshi_obj.name.encode('utf-8')
93 name = {'title': 'nHentai HTML Viewer'}
95 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
97 if sys.version_info < (3, 0):
98 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
101 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
102 f.write(data.encode('utf-8'))
104 logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
105 except Exception as e:
106 logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
109 def generate_main_html(output_dir='./'):
111 Generate a main html to show all the contain doujinshi.
112 With a link to their `index.html`.
113 Default output folder will be the CLI path.
118 main = readfile('viewer/main.html')
119 css = readfile('viewer/main.css')
120 js = readfile('viewer/main.js')
123 <div class="gallery-favorite">\n\
124 <div class="gallery">\n\
125 <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
126 src="./{FOLDER}/{IMAGE}" />\n\
127 <div class="caption">{TITLE}</div>\n\
133 doujinshi_dirs = next(os.walk('.'))[1]
135 for folder in doujinshi_dirs:
136 files = os.listdir(folder)
139 if 'index.html' in files:
140 logger.info('Add doujinshi \'{}\''.format(folder))
144 image = files[0] # 001.jpg or 001.png
145 if folder is not None:
146 title = folder.replace('_', ' ')
148 title = 'nHentai HTML Viewer'
150 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
152 logger.warning('None index.html found, --gen-main paused.')
155 data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
156 if sys.version_info < (3, 0):
157 with open('./main.html', 'w') as f:
160 with open('./main.html', 'wb') as f:
161 f.write(data.encode('utf-8'))
162 shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
165 15, 'Main Viewer has been write to \'{0}main.html\''.format(output_dir))
166 except Exception as e:
167 logger.warning('Writen Main Viewer failed ({})'.format(str(e)))
170 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
171 if doujinshi_obj is not None:
172 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
173 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
175 cbz_filename = './doujinshi.cbz'
178 file_list = os.listdir(doujinshi_dir)
181 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
182 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
183 for image in file_list:
184 image_path = os.path.join(doujinshi_dir, image)
185 cbz_pf.write(image_path, image)
188 shutil.rmtree(doujinshi_dir, ignore_errors=True)
190 logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
193 def format_filename(s):
194 """Take a string and return a valid filename constructed from the string.
195 Uses a whitelist approach: any characters not present in valid_chars are
196 removed. Also spaces are replaced with underscores.
198 Note: this method may produce invalid filenames such as ``, `.` or `..`
199 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
200 and append a file extension like '.txt', so I avoid the potential of using
204 valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
205 filename = ''.join(c for c in s if c in valid_chars)
206 if len(filename) > 100:
207 filename = filename[:100] + '...]'
209 # Remove [] from filename
210 filename = filename.replace('[]', '')
214 def signal_handler(signal, frame):
215 logger.error('Ctrl-C signal received. Stopping...')