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 if not os.path.exists(doujinshi_dir):
78 logger.warning('Path \'{0}\' does not exist, creating.'.format(doujinshi_dir))
80 os.makedirs(doujinshi_dir)
81 except EnvironmentError as e:
82 logger.critical('{0}'.format(str(e)))
84 file_list = os.listdir(doujinshi_dir)
87 for image in file_list:
88 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
91 image_html += '<img src="{0}" class="image-item"/>\n'\
93 html = readfile('viewer/{}/index.html'.format(template))
94 css = readfile('viewer/{}/styles.css'.format(template))
95 js = readfile('viewer/{}/scripts.js'.format(template))
97 if doujinshi_obj is not None:
98 serialize_json(doujinshi_obj, doujinshi_dir)
99 name = doujinshi_obj.name
100 if sys.version_info < (3, 0):
101 name = doujinshi_obj.name.encode('utf-8')
103 name = {'title': 'nHentai HTML Viewer'}
105 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
107 if sys.version_info < (3, 0):
108 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
111 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
112 f.write(data.encode('utf-8'))
114 logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
115 except Exception as e:
116 logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
119 def generate_main_html(output_dir='./'):
121 Generate a main html to show all the contain doujinshi.
122 With a link to their `index.html`.
123 Default output folder will be the CLI path.
128 main = readfile('viewer/main.html')
129 css = readfile('viewer/main.css')
130 js = readfile('viewer/main.js')
133 <div class="gallery-favorite">\n\
134 <div class="gallery">\n\
135 <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
136 src="./{FOLDER}/{IMAGE}" />\n\
137 <div class="caption">{TITLE}</div>\n\
143 doujinshi_dirs = next(os.walk('.'))[1]
145 for folder in doujinshi_dirs:
146 files = os.listdir(folder)
149 if 'index.html' in files:
150 logger.info('Add doujinshi \'{}\''.format(folder))
154 image = files[0] # 001.jpg or 001.png
155 if folder is not None:
156 title = folder.replace('_', ' ')
158 title = 'nHentai HTML Viewer'
160 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
162 logger.warning('No index.html found, --gen-main paused.')
165 data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
166 if sys.version_info < (3, 0):
167 with open('./main.html', 'w') as f:
170 with open('./main.html', 'wb') as f:
171 f.write(data.encode('utf-8'))
172 shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
175 15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
176 except Exception as e:
177 logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
180 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=True):
181 if doujinshi_obj is not None:
182 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
184 serialize_comicxml(doujinshi_obj, doujinshi_dir)
185 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
187 cbz_filename = './doujinshi.cbz'
190 file_list = os.listdir(doujinshi_dir)
193 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
194 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
195 for image in file_list:
196 image_path = os.path.join(doujinshi_dir, image)
197 cbz_pf.write(image_path, image)
200 shutil.rmtree(doujinshi_dir, ignore_errors=True)
202 logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
205 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
209 """Write images to a PDF file using img2pdf."""
210 if doujinshi_obj is not None:
211 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
212 pdf_filename = os.path.join(
213 os.path.join(doujinshi_dir, '..'),
214 '{}.pdf'.format(doujinshi_obj.filename)
217 pdf_filename = './doujinshi.pdf'
220 file_list = os.listdir(doujinshi_dir)
223 logger.info('Writing PDF file to path: {}'.format(pdf_filename))
224 with open(pdf_filename, 'wb') as pdf_f:
226 [os.path.join(doujinshi_dir, image) for image in file_list]
228 pdf_f.write(img2pdf.convert(full_path_list))
231 shutil.rmtree(doujinshi_dir, ignore_errors=True)
233 logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
236 logger.error("Please install img2pdf package by using pip.")
238 def unicode_truncate(s, length, encoding='utf-8'):
239 """https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
241 encoded = s.encode(encoding)[:length]
242 return encoded.decode(encoding, 'ignore')
245 def format_filename(s):
247 It used to be a whitelist approach allowed only alphabet and a part of symbols.
248 but most doujinshi's names include Japanese 2-byte characters and these was rejected.
249 so it is using blacklist approach now.
250 if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' ').
252 # maybe you can use `--format` to select a suitable filename
253 ban_chars = '\\\'/:,;*?"<>|\t'
254 filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars))).strip()
255 filename = ' '.join(filename.split())
256 print(repr(filename))
258 while filename.endswith('.'):
259 filename = filename[:-1]
261 if len(filename) > 100:
262 filename = filename[:100] + u'…'
264 # Remove [] from filename
265 filename = filename.replace('[]', '').strip()
269 def signal_handler(signal, frame):
270 logger.error('Ctrl-C signal received. Stopping...')
274 def paging(page_string):
275 # 1,3-5,14 -> [1, 3, 4, 5, 14]
280 for i in page_string.split(','):
282 start, end = i.split('-')
283 if not (start.isdigit() and end.isdigit()):
284 raise Exception('Invalid page number')
285 page_list.extend(list(range(int(start), int(end)+1)))
288 raise Exception('Invalid page number')
289 page_list.append(int(i))
293 def generate_metadatafile(output_dir, table, doujinshi_obj=None):
294 logger.info("Writing Metadata Info")
297 if doujinshi_obj is not None:
298 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
302 logger.info(doujinshi_dir)
304 f = open(os.path.join(doujinshi_dir, 'info.txt'), "w", encoding="utf-8")
306 fields = ["TITLE", "ORIGINAL TITLE", "AUTHOR", "ARTIST", "CIRCLE", "SCANLATOR", "TRANSLATOR", "PUBLISHER", "DESCRIPTION", "STATUS", "CHAPTERS", "PAGES", "TAGS", "TYPE", "LANGUAGE", "RELEASED", "READING DIRECTION", "CHARACTERS", "SERIES", "PARODY", "URL"]
310 f.write("%s: " % fields[i])
313 f.write("%s" % table[0][1])
316 f.write("%s" % table[1][1])
319 f.write("%s" % table[2][1])
322 f.write("%s" % table[3][1])
325 f.write("%s" % table[4][1])
328 f.write("%s" % table[5][1])
331 f.write("%s" % table[6][1])
334 f.write("%s" % table[7][1])
337 f.write("%s" % table[8][1])
351 self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
352 self.cur = self.conn.cursor()
353 self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
357 def __exit__(self, exc_type, exc_val, exc_tb):
361 self.cur.execute('DELETE FROM download_history WHERE 1')
364 def add_one(self, data):
365 self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
369 data = self.cur.execute('SELECT id FROM download_history')
370 return [i[0] for i in data]