2 from __future__ import unicode_literals, print_function
14 from nhentai import constant
15 from nhentai.logger import logger
16 from nhentai.serializer import serialize_json, serialize_comicxml, set_js_database
19 def request(method, url, **kwargs):
20 session = requests.Session()
21 session.headers.update({
22 'Referer': constant.LOGIN_URL,
23 'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
24 'Cookie': constant.COOKIE
26 return getattr(session, method)(url, proxies=constant.PROXY, verify=False, **kwargs)
30 response = request('get', constant.BASE_URL).text
31 username = re.findall('"/users/\d+/(.*?)"', response)
33 logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
35 logger.info('Login successfully! Your username: {}'.format(username[0]))
38 class _Singleton(type):
39 """ A metaclass that creates a Singleton base class when called. """
42 def __call__(cls, *args, **kwargs):
43 if cls not in cls._instances:
44 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
45 return cls._instances[cls]
48 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
54 from urlparse import urlparse
56 from urllib.parse import urlparse
62 loc = os.path.dirname(__file__)
64 with open(os.path.join(loc, path), 'r') as file:
68 def generate_html(output_dir='.', doujinshi_obj=None):
71 if doujinshi_obj is not None:
72 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
76 file_list = os.listdir(doujinshi_dir)
79 for image in file_list:
80 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
83 image_html += '<img src="{0}" class="image-item"/>\n'\
85 html = readfile('viewer/index.html')
86 css = readfile('viewer/styles.css')
87 js = readfile('viewer/scripts.js')
89 if doujinshi_obj is not None:
90 serialize_json(doujinshi_obj, doujinshi_dir)
91 name = doujinshi_obj.name
92 if sys.version_info < (3, 0):
93 name = doujinshi_obj.name.encode('utf-8')
95 name = {'title': 'nHentai HTML Viewer'}
97 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
99 if sys.version_info < (3, 0):
100 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
103 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
104 f.write(data.encode('utf-8'))
106 logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
107 except Exception as e:
108 logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
111 def generate_main_html(output_dir='./'):
113 Generate a main html to show all the contain doujinshi.
114 With a link to their `index.html`.
115 Default output folder will be the CLI path.
120 main = readfile('viewer/main.html')
121 css = readfile('viewer/main.css')
122 js = readfile('viewer/main.js')
125 <div class="gallery-favorite">\n\
126 <div class="gallery">\n\
127 <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
128 src="./{FOLDER}/{IMAGE}" />\n\
129 <div class="caption">{TITLE}</div>\n\
135 doujinshi_dirs = next(os.walk('.'))[1]
137 for folder in doujinshi_dirs:
138 files = os.listdir(folder)
141 if 'index.html' in files:
142 logger.info('Add doujinshi \'{}\''.format(folder))
146 image = files[0] # 001.jpg or 001.png
147 if folder is not None:
148 title = folder.replace('_', ' ')
150 title = 'nHentai HTML Viewer'
152 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
154 logger.warning('No index.html found, --gen-main paused.')
157 data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
158 if sys.version_info < (3, 0):
159 with open('./main.html', 'w') as f:
162 with open('./main.html', 'wb') as f:
163 f.write(data.encode('utf-8'))
164 shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
167 15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
168 except Exception as e:
169 logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
172 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=False):
173 if doujinshi_obj is not None:
174 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
176 serialize_comicxml(doujinshi_obj, doujinshi_dir)
177 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
179 cbz_filename = './doujinshi.cbz'
182 file_list = os.listdir(doujinshi_dir)
185 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
186 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
187 for image in file_list:
188 image_path = os.path.join(doujinshi_dir, image)
189 cbz_pf.write(image_path, image)
192 shutil.rmtree(doujinshi_dir, ignore_errors=True)
194 logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
197 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
198 """Write images to a PDF file using img2pdf."""
199 if doujinshi_obj is not None:
200 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
201 pdf_filename = os.path.join(
202 os.path.join(doujinshi_dir, '..'),
203 '{}.pdf'.format(doujinshi_obj.filename)
206 pdf_filename = './doujinshi.pdf'
209 file_list = os.listdir(doujinshi_dir)
212 logger.info('Writing PDF file to path: {}'.format(pdf_filename))
213 with open(pdf_filename, 'wb') as pdf_f:
215 [os.path.join(doujinshi_dir, image) for image in file_list]
217 pdf_f.write(img2pdf.convert(full_path_list))
220 shutil.rmtree(doujinshi_dir, ignore_errors=True)
222 logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
225 def format_filename(s):
226 """Take a string and return a valid filename constructed from the string.
227 Uses a whitelist approach: any characters not present in valid_chars are
228 removed. Also spaces are replaced with underscores.
230 Note: this method may produce invalid filenames such as ``, `.` or `..`
231 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
232 and append a file extension like '.txt', so I avoid the potential of using
236 if sys.platform.startswith('win32'):
237 invalid_chars = '\/:*?"<>|.'
238 for char in invalid_chars:
239 s = s.replace(char, '_')
242 # maybe you can use `--format` to select a suitable filename
243 valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
244 filename = ''.join(c for c in s if c in valid_chars)
245 if len(filename) > 100:
246 filename = filename[:100] + '...]'
248 # Remove [] from filename
249 filename = filename.replace('[]', '').strip()
253 def signal_handler(signal, frame):
254 logger.error('Ctrl-C signal received. Stopping...')
263 self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
264 self.cur = self.conn.cursor()
265 self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
269 def __exit__(self, exc_type, exc_val, exc_tb):
273 self.cur.execute('DELETE FROM download_history WHERE 1')
276 def add_one(self, data):
277 self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
281 data = self.cur.execute('SELECT id FROM download_history')
282 return [i[0] for i in data]