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 file_list = os.listdir(doujinshi_dir)
76 for image in file_list:
77 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
80 image_html += '<img src="{0}" class="image-item"/>\n'\
82 html = readfile('viewer/{}/index.html'.format(template))
83 css = readfile('viewer/{}/styles.css'.format(template))
84 js = readfile('viewer/{}/scripts.js'.format(template))
86 if doujinshi_obj is not None:
87 serialize_json(doujinshi_obj, doujinshi_dir)
88 name = doujinshi_obj.name
89 if sys.version_info < (3, 0):
90 name = doujinshi_obj.name.encode('utf-8')
92 name = {'title': 'nHentai HTML Viewer'}
94 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
96 if sys.version_info < (3, 0):
97 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
100 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
101 f.write(data.encode('utf-8'))
103 logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
104 except Exception as e:
105 logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
108 def generate_main_html(output_dir='./'):
110 Generate a main html to show all the contain doujinshi.
111 With a link to their `index.html`.
112 Default output folder will be the CLI path.
117 main = readfile('viewer/main.html')
118 css = readfile('viewer/main.css')
119 js = readfile('viewer/main.js')
122 <div class="gallery-favorite">\n\
123 <div class="gallery">\n\
124 <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
125 src="./{FOLDER}/{IMAGE}" />\n\
126 <div class="caption">{TITLE}</div>\n\
132 doujinshi_dirs = next(os.walk('.'))[1]
134 for folder in doujinshi_dirs:
135 files = os.listdir(folder)
138 if 'index.html' in files:
139 logger.info('Add doujinshi \'{}\''.format(folder))
143 image = files[0] # 001.jpg or 001.png
144 if folder is not None:
145 title = folder.replace('_', ' ')
147 title = 'nHentai HTML Viewer'
149 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
151 logger.warning('No index.html found, --gen-main paused.')
154 data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
155 if sys.version_info < (3, 0):
156 with open('./main.html', 'w') as f:
159 with open('./main.html', 'wb') as f:
160 f.write(data.encode('utf-8'))
161 shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
164 15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
165 except Exception as e:
166 logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
169 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=False):
170 if doujinshi_obj is not None:
171 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
173 serialize_comicxml(doujinshi_obj, doujinshi_dir)
174 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
176 cbz_filename = './doujinshi.cbz'
179 file_list = os.listdir(doujinshi_dir)
182 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
183 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
184 for image in file_list:
185 image_path = os.path.join(doujinshi_dir, image)
186 cbz_pf.write(image_path, image)
189 shutil.rmtree(doujinshi_dir, ignore_errors=True)
191 logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
194 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
198 logger.error("Please install img2pdf package by using pip.")
200 """Write images to a PDF file using img2pdf."""
201 if doujinshi_obj is not None:
202 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
203 pdf_filename = os.path.join(
204 os.path.join(doujinshi_dir, '..'),
205 '{}.pdf'.format(doujinshi_obj.filename)
208 pdf_filename = './doujinshi.pdf'
211 file_list = os.listdir(doujinshi_dir)
214 logger.info('Writing PDF file to path: {}'.format(pdf_filename))
215 with open(pdf_filename, 'wb') as pdf_f:
217 [os.path.join(doujinshi_dir, image) for image in file_list]
219 pdf_f.write(img2pdf.convert(full_path_list))
222 shutil.rmtree(doujinshi_dir, ignore_errors=True)
224 logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
227 def unicode_truncate(s, length, encoding='utf-8'):
228 """https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
230 encoded = s.encode(encoding)[:length]
231 return encoded.decode(encoding, 'ignore')
234 def format_filename(s):
236 It used to be a whitelist approach allowed only alphabet and a part of symbols.
237 but most doujinshi's names include Japanese 2-byte characters and these was rejected.
238 so it is using blacklist approach now.
239 if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' ').
241 # maybe you can use `--format` to select a suitable filename
242 ban_chars = '\\\'/:,;*?"<>|\t'
243 filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars))).strip()
244 while filename.endswith('.'):
245 filename = filename[:-1]
247 if len(filename) > 100:
248 filename = filename[:100] + u'…'
250 # Remove [] from filename
251 filename = filename.replace('[]', '').strip()
255 def signal_handler(signal, frame):
256 logger.error('Ctrl-C signal received. Stopping...')
260 def paging(page_string):
261 # 1,3-5,14 -> [1, 3, 4, 5, 14]
266 for i in page_string.split(','):
268 start, end = i.split('-')
269 if not (start.isdigit() and end.isdigit()):
270 raise Exception('Invalid page number')
271 page_list.extend(list(range(int(start), int(end)+1)))
274 raise Exception('Invalid page number')
275 page_list.append(int(i))
285 self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
286 self.cur = self.conn.cursor()
287 self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
291 def __exit__(self, exc_type, exc_val, exc_tb):
295 self.cur.execute('DELETE FROM download_history WHERE 1')
298 def add_one(self, data):
299 self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
303 data = self.cur.execute('SELECT id FROM download_history')
304 return [i[0] for i in data]