11 from nhentai import constant
12 from nhentai.logger import logger
13 from nhentai.serializer import serialize_json, serialize_comicxml, set_js_database
16 def request(method, url, **kwargs):
17 session = requests.Session()
18 session.headers.update({
19 'Referer': constant.LOGIN_URL,
20 'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
21 'Cookie': constant.CONFIG['cookie']
23 return getattr(session, method)(url, proxies=constant.CONFIG['proxy'], verify=False, **kwargs)
27 response = request('get', constant.BASE_URL).text
28 username = re.findall('"/users/\d+/(.*?)"', response)
30 logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
32 logger.info('Login successfully! Your username: {}'.format(username[0]))
35 class _Singleton(type):
36 """ A metaclass that creates a Singleton base class when called. """
39 def __call__(cls, *args, **kwargs):
40 if cls not in cls._instances:
41 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
42 return cls._instances[cls]
45 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
51 from urlparse import urlparse
53 from urllib.parse import urlparse
59 loc = os.path.dirname(__file__)
61 with open(os.path.join(loc, path), 'r') as file:
65 def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
68 if doujinshi_obj is not None:
69 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
73 if not os.path.exists(doujinshi_dir):
74 logger.warning('Path \'{0}\' does not exist, creating.'.format(doujinshi_dir))
76 os.makedirs(doujinshi_dir)
77 except EnvironmentError as e:
78 logger.critical('{0}'.format(str(e)))
80 file_list = os.listdir(doujinshi_dir)
83 for image in file_list:
84 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
87 image_html += '<img src="{0}" class="image-item"/>\n'\
89 html = readfile('viewer/{}/index.html'.format(template))
90 css = readfile('viewer/{}/styles.css'.format(template))
91 js = readfile('viewer/{}/scripts.js'.format(template))
93 if doujinshi_obj is not None:
94 serialize_json(doujinshi_obj, doujinshi_dir)
95 name = doujinshi_obj.name
96 if sys.version_info < (3, 0):
97 name = doujinshi_obj.name.encode('utf-8')
99 name = {'title': 'nHentai HTML Viewer'}
101 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
103 if sys.version_info < (3, 0):
104 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
107 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
108 f.write(data.encode('utf-8'))
110 logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
111 except Exception as e:
112 logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
115 def generate_main_html(output_dir='./'):
117 Generate a main html to show all the contain doujinshi.
118 With a link to their `index.html`.
119 Default output folder will be the CLI path.
124 main = readfile('viewer/main.html')
125 css = readfile('viewer/main.css')
126 js = readfile('viewer/main.js')
129 <div class="gallery-favorite">\n\
130 <div class="gallery">\n\
131 <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
132 src="./{FOLDER}/{IMAGE}" />\n\
133 <div class="caption">{TITLE}</div>\n\
139 doujinshi_dirs = next(os.walk('.'))[1]
141 for folder in doujinshi_dirs:
142 files = os.listdir(folder)
145 if 'index.html' in files:
146 logger.info('Add doujinshi \'{}\''.format(folder))
150 image = files[0] # 001.jpg or 001.png
151 if folder is not None:
152 title = folder.replace('_', ' ')
154 title = 'nHentai HTML Viewer'
156 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
158 logger.warning('No index.html found, --gen-main paused.')
161 data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
162 if sys.version_info < (3, 0):
163 with open('./main.html', 'w') as f:
166 with open('./main.html', 'wb') as f:
167 f.write(data.encode('utf-8'))
168 shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
171 15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
172 except Exception as e:
173 logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
176 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=True):
177 if doujinshi_obj is not None:
178 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
180 serialize_comicxml(doujinshi_obj, doujinshi_dir)
181 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
183 cbz_filename = './doujinshi.cbz'
186 file_list = os.listdir(doujinshi_dir)
189 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
190 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
191 for image in file_list:
192 image_path = os.path.join(doujinshi_dir, image)
193 cbz_pf.write(image_path, image)
196 shutil.rmtree(doujinshi_dir, ignore_errors=True)
198 logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
201 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
205 """Write images to a PDF file using img2pdf."""
206 if doujinshi_obj is not None:
207 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
208 pdf_filename = os.path.join(
209 os.path.join(doujinshi_dir, '..'),
210 '{}.pdf'.format(doujinshi_obj.filename)
213 pdf_filename = './doujinshi.pdf'
216 file_list = os.listdir(doujinshi_dir)
219 logger.info('Writing PDF file to path: {}'.format(pdf_filename))
220 with open(pdf_filename, 'wb') as pdf_f:
222 [os.path.join(doujinshi_dir, image) for image in file_list]
224 pdf_f.write(img2pdf.convert(full_path_list))
227 shutil.rmtree(doujinshi_dir, ignore_errors=True)
229 logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
232 logger.error("Please install img2pdf package by using pip.")
234 def unicode_truncate(s, length, encoding='utf-8'):
235 """https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
237 encoded = s.encode(encoding)[:length]
238 return encoded.decode(encoding, 'ignore')
241 def format_filename(s):
243 It used to be a whitelist approach allowed only alphabet and a part of symbols.
244 but most doujinshi's names include Japanese 2-byte characters and these was rejected.
245 so it is using blacklist approach now.
246 if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' ').
248 # maybe you can use `--format` to select a suitable filename
249 ban_chars = '\\\'/:,;*?"<>|\t'
250 filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars))).strip()
251 filename = ' '.join(filename.split())
252 print(repr(filename))
254 while filename.endswith('.'):
255 filename = filename[:-1]
257 if len(filename) > 100:
258 filename = filename[:100] + u'…'
260 # Remove [] from filename
261 filename = filename.replace('[]', '').strip()
265 def signal_handler(signal, frame):
266 logger.error('Ctrl-C signal received. Stopping...')
270 def paging(page_string):
271 # 1,3-5,14 -> [1, 3, 4, 5, 14]
276 for i in page_string.split(','):
278 start, end = i.split('-')
279 if not (start.isdigit() and end.isdigit()):
280 raise Exception('Invalid page number')
281 page_list.extend(list(range(int(start), int(end)+1)))
284 raise Exception('Invalid page number')
285 page_list.append(int(i))
295 self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
296 self.cur = self.conn.cursor()
297 self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
301 def __exit__(self, exc_type, exc_val, exc_tb):
305 self.cur.execute('DELETE FROM download_history WHERE 1')
308 def add_one(self, data):
309 self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
313 data = self.cur.execute('SELECT id FROM download_history')
314 return [i[0] for i in data]