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']
24 if not kwargs.get('proxies', None):
25 kwargs['proxies'] = constant.CONFIG['proxy']
27 return getattr(session, method)(url, verify=False, **kwargs)
31 response = request('get', constant.BASE_URL).text
32 username = re.findall('"/users/\d+/(.*?)"', response)
34 logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
36 logger.info('Login successfully! Your username: {}'.format(username[0]))
39 class _Singleton(type):
40 """ A metaclass that creates a Singleton base class when called. """
43 def __call__(cls, *args, **kwargs):
44 if cls not in cls._instances:
45 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
46 return cls._instances[cls]
49 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
55 from urlparse import urlparse
57 from urllib.parse import urlparse
63 loc = os.path.dirname(__file__)
65 with open(os.path.join(loc, path), 'r') as file:
69 def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
72 if doujinshi_obj is not None:
73 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
77 file_list = os.listdir(doujinshi_dir)
80 for image in file_list:
81 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
84 image_html += '<img src="{0}" class="image-item"/>\n'\
86 html = readfile('viewer/{}/index.html'.format(template))
87 css = readfile('viewer/{}/styles.css'.format(template))
88 js = readfile('viewer/{}/scripts.js'.format(template))
90 if doujinshi_obj is not None:
91 serialize_json(doujinshi_obj, doujinshi_dir)
92 name = doujinshi_obj.name
93 if sys.version_info < (3, 0):
94 name = doujinshi_obj.name.encode('utf-8')
96 name = {'title': 'nHentai HTML Viewer'}
98 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
100 if sys.version_info < (3, 0):
101 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
104 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
105 f.write(data.encode('utf-8'))
107 logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
108 except Exception as e:
109 logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
112 def generate_main_html(output_dir='./'):
114 Generate a main html to show all the contain doujinshi.
115 With a link to their `index.html`.
116 Default output folder will be the CLI path.
121 main = readfile('viewer/main.html')
122 css = readfile('viewer/main.css')
123 js = readfile('viewer/main.js')
126 <div class="gallery-favorite">\n\
127 <div class="gallery">\n\
128 <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
129 src="./{FOLDER}/{IMAGE}" />\n\
130 <div class="caption">{TITLE}</div>\n\
136 doujinshi_dirs = next(os.walk('.'))[1]
138 for folder in doujinshi_dirs:
139 files = os.listdir(folder)
142 if 'index.html' in files:
143 logger.info('Add doujinshi \'{}\''.format(folder))
147 image = files[0] # 001.jpg or 001.png
148 if folder is not None:
149 title = folder.replace('_', ' ')
151 title = 'nHentai HTML Viewer'
153 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
155 logger.warning('No index.html found, --gen-main paused.')
158 data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
159 if sys.version_info < (3, 0):
160 with open('./main.html', 'w') as f:
163 with open('./main.html', 'wb') as f:
164 f.write(data.encode('utf-8'))
165 shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
168 15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
169 except Exception as e:
170 logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
173 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=True):
174 if doujinshi_obj is not None:
175 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
177 serialize_comicxml(doujinshi_obj, doujinshi_dir)
178 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
180 cbz_filename = './doujinshi.cbz'
183 file_list = os.listdir(doujinshi_dir)
186 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
187 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
188 for image in file_list:
189 image_path = os.path.join(doujinshi_dir, image)
190 cbz_pf.write(image_path, image)
193 shutil.rmtree(doujinshi_dir, ignore_errors=True)
195 logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
198 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
202 """Write images to a PDF file using img2pdf."""
203 if doujinshi_obj is not None:
204 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
205 pdf_filename = os.path.join(
206 os.path.join(doujinshi_dir, '..'),
207 '{}.pdf'.format(doujinshi_obj.filename)
210 pdf_filename = './doujinshi.pdf'
213 file_list = os.listdir(doujinshi_dir)
216 logger.info('Writing PDF file to path: {}'.format(pdf_filename))
217 with open(pdf_filename, 'wb') as pdf_f:
219 [os.path.join(doujinshi_dir, image) for image in file_list]
221 pdf_f.write(img2pdf.convert(full_path_list))
224 shutil.rmtree(doujinshi_dir, ignore_errors=True)
226 logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
229 logger.error("Please install img2pdf package by using pip.")
231 def unicode_truncate(s, length, encoding='utf-8'):
232 """https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
234 encoded = s.encode(encoding)[:length]
235 return encoded.decode(encoding, 'ignore')
238 def format_filename(s):
240 It used to be a whitelist approach allowed only alphabet and a part of symbols.
241 but most doujinshi's names include Japanese 2-byte characters and these was rejected.
242 so it is using blacklist approach now.
243 if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' ').
245 # maybe you can use `--format` to select a suitable filename
246 ban_chars = '\\\'/:,;*?"<>|\t'
247 filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars))).strip()
248 filename = ' '.join(filename.split())
249 print(repr(filename))
251 while filename.endswith('.'):
252 filename = filename[:-1]
254 if len(filename) > 100:
255 filename = filename[:100] + u'…'
257 # Remove [] from filename
258 filename = filename.replace('[]', '').strip()
262 def signal_handler(signal, frame):
263 logger.error('Ctrl-C signal received. Stopping...')
267 def paging(page_string):
268 # 1,3-5,14 -> [1, 3, 4, 5, 14]
273 for i in page_string.split(','):
275 start, end = i.split('-')
276 if not (start.isdigit() and end.isdigit()):
277 raise Exception('Invalid page number')
278 page_list.extend(list(range(int(start), int(end)+1)))
281 raise Exception('Invalid page number')
282 page_list.append(int(i))
292 self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
293 self.cur = self.conn.cursor()
294 self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
298 def __exit__(self, exc_type, exc_val, exc_tb):
302 self.cur.execute('DELETE FROM download_history WHERE 1')
305 def add_one(self, data):
306 self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
310 data = self.cur.execute('SELECT id FROM download_history')
311 return [i[0] for i in data]