]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
Merge pull request #224 from RicterZ/pull/221
[nhentai.git] / nhentai / utils.py
1 # coding: utf-8
2
3 import sys
4 import re
5 import os
6 import zipfile
7 import shutil
8 import requests
9 import sqlite3
10
11 from nhentai import constant
12 from nhentai.logger import logger
13 from nhentai.serializer import serialize_json, serialize_comic_xml, set_js_database
14
15
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']
22     })
23
24     if not kwargs.get('proxies', None):
25         kwargs['proxies'] = constant.CONFIG['proxy']
26
27     return getattr(session, method)(url, verify=False, **kwargs)
28
29
30 def check_cookie():
31     response = request('get', constant.BASE_URL).text
32     username = re.findall('"/users/\d+/(.*?)"', response)
33     if not username:
34         logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
35     else:
36         logger.info('Login successfully! Your username: {}'.format(username[0]))
37
38
39 class _Singleton(type):
40     """ A metaclass that creates a Singleton base class when called. """
41     _instances = {}
42
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]
47
48
49 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
50     pass
51
52
53 def urlparse(url):
54     try:
55         from urlparse import urlparse
56     except ImportError:
57         from urllib.parse import urlparse
58
59     return urlparse(url)
60
61
62 def readfile(path):
63     loc = os.path.dirname(__file__)
64
65     with open(os.path.join(loc, path), 'r') as file:
66         return file.read()
67
68
69 def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
70     image_html = ''
71
72     if doujinshi_obj is not None:
73         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
74     else:
75         doujinshi_dir = '.'
76
77     if not os.path.exists(doujinshi_dir):
78         logger.warning('Path \'{0}\' does not exist, creating.'.format(doujinshi_dir))
79         try:
80             os.makedirs(doujinshi_dir)
81         except EnvironmentError as e:
82             logger.critical('{0}'.format(str(e)))
83
84     file_list = os.listdir(doujinshi_dir)
85     file_list.sort()
86
87     for image in file_list:
88         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
89             continue
90
91         image_html += '<img src="{0}" class="image-item"/>\n' \
92             .format(image)
93     html = readfile('viewer/{}/index.html'.format(template))
94     css = readfile('viewer/{}/styles.css'.format(template))
95     js = readfile('viewer/{}/scripts.js'.format(template))
96
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')
102     else:
103         name = {'title': 'nHentai HTML Viewer'}
104
105     data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
106     try:
107         if sys.version_info < (3, 0):
108             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
109                 f.write(data)
110         else:
111             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
112                 f.write(data.encode('utf-8'))
113
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)))
117
118
119 def generate_main_html(output_dir='./'):
120     """
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.
124     """
125
126     image_html = ''
127
128     main = readfile('viewer/main.html')
129     css = readfile('viewer/main.css')
130     js = readfile('viewer/main.js')
131
132     element = '\n\
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\
138                     </a>\n\
139                 </div>\n\
140             </div>\n'
141
142     os.chdir(output_dir)
143     doujinshi_dirs = next(os.walk('.'))[1]
144
145     for folder in doujinshi_dirs:
146         files = os.listdir(folder)
147         files.sort()
148
149         if 'index.html' in files:
150             logger.info('Add doujinshi \'{}\''.format(folder))
151         else:
152             continue
153
154         image = files[0]  # 001.jpg or 001.png
155         if folder is not None:
156             title = folder.replace('_', ' ')
157         else:
158             title = 'nHentai HTML Viewer'
159
160         image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
161     if image_html == '':
162         logger.warning('No index.html found, --gen-main paused.')
163         return
164     try:
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:
168                 f.write(data)
169         else:
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', './')
173         set_js_database()
174         logger.log(
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)))
178
179
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)
183         if write_comic_info:
184             serialize_comic_xml(doujinshi_obj, doujinshi_dir)
185         cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
186     else:
187         cbz_filename = './doujinshi.cbz'
188         doujinshi_dir = '.'
189
190     file_list = os.listdir(doujinshi_dir)
191     file_list.sort()
192
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)
198
199     if rm_origin_dir:
200         shutil.rmtree(doujinshi_dir, ignore_errors=True)
201
202     logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
203
204
205 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
206     try:
207         import img2pdf
208
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)
215             )
216         else:
217             pdf_filename = './doujinshi.pdf'
218             doujinshi_dir = '.'
219
220         file_list = os.listdir(doujinshi_dir)
221         file_list.sort()
222
223         logger.info('Writing PDF file to path: {}'.format(pdf_filename))
224         with open(pdf_filename, 'wb') as pdf_f:
225             full_path_list = (
226                 [os.path.join(doujinshi_dir, image) for image in file_list]
227             )
228             pdf_f.write(img2pdf.convert(full_path_list))
229
230         if rm_origin_dir:
231             shutil.rmtree(doujinshi_dir, ignore_errors=True)
232
233         logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
234
235     except ImportError:
236         logger.error("Please install img2pdf package by using pip.")
237
238
239 def unicode_truncate(s, length, encoding='utf-8'):
240     """https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
241     """
242     encoded = s.encode(encoding)[:length]
243     return encoded.decode(encoding, 'ignore')
244
245
246 def format_filename(s):
247     """
248     It used to be a whitelist approach allowed only alphabet and a part of symbols.
249     but most doujinshi's names include Japanese 2-byte characters and these was rejected.
250     so it is using blacklist approach now.
251     if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' '). 
252     """
253     # maybe you can use `--format` to select a suitable filename
254     ban_chars = '\\\'/:,;*?"<>|\t'
255     filename = s.translate(str.maketrans(ban_chars, ' ' * len(ban_chars))).strip()
256     filename = ' '.join(filename.split())
257
258     while filename.endswith('.'):
259         filename = filename[:-1]
260
261     if len(filename) > 100:
262         filename = filename[:100] + u'…'
263
264     # Remove [] from filename
265     filename = filename.replace('[]', '').strip()
266     return filename
267
268
269 def signal_handler(signal, frame):
270     logger.error('Ctrl-C signal received. Stopping...')
271     exit(1)
272
273
274 def paging(page_string):
275     # 1,3-5,14 -> [1, 3, 4, 5, 14]
276     if not page_string:
277         return []
278
279     page_list = []
280     for i in page_string.split(','):
281         if '-' in i:
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)))
286         else:
287             if not i.isdigit():
288                 raise Exception('Invalid page number')
289             page_list.append(int(i))
290
291     return page_list
292
293
294 def generate_metadata_file(output_dir, table, doujinshi_obj=None):
295     logger.info('Writing Metadata Info')
296
297     if doujinshi_obj is not None:
298         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
299     else:
300         doujinshi_dir = '.'
301
302     logger.info(doujinshi_dir)
303
304     f = open(os.path.join(doujinshi_dir, 'info.txt'), 'w', encoding='utf-8')
305
306     fields = ['TITLE', 'ORIGINAL TITLE', 'AUTHOR', 'ARTIST', 'CIRCLE', 'SCANLATOR',
307               'TRANSLATOR', 'PUBLISHER', 'DESCRIPTION', 'STATUS', 'CHAPTERS', 'PAGES',
308               'TAGS', 'TYPE', 'LANGUAGE', 'RELEASED', 'READING DIRECTION', 'CHARACTERS',
309               'SERIES', 'PARODY', 'URL']
310     special_fields = ['PARODY', 'TITLE', 'ORIGINAL TITLE', 'CHARACTERS', 'AUTHOR',
311                       'LANGUAGE', 'TAGS', 'URL', 'PAGES']
312
313     for i in range(len(fields)):
314         f.write('{}: '.format(fields[i]))
315         if fields[i] in special_fields:
316             f.write(str(table[special_fields.index(fields[i])][1]))
317         f.write('\n')
318
319     f.close()
320
321
322 class DB(object):
323     conn = None
324     cur = None
325
326     def __enter__(self):
327         self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
328         self.cur = self.conn.cursor()
329         self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
330         self.conn.commit()
331         return self
332
333     def __exit__(self, exc_type, exc_val, exc_tb):
334         self.conn.close()
335
336     def clean_all(self):
337         self.cur.execute('DELETE FROM download_history WHERE 1')
338         self.conn.commit()
339
340     def add_one(self, data):
341         self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
342         self.conn.commit()
343
344     def get_all(self):
345         data = self.cur.execute('SELECT id FROM download_history')
346         return [i[0] for i in data]