]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
fix #220 add pretty name of doujinshi format
[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     file_list = os.listdir(doujinshi_dir)
78     file_list.sort()
79
80     for image in file_list:
81         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
82             continue
83
84         image_html += '<img src="{0}" class="image-item"/>\n'\
85             .format(image)
86     html = readfile('viewer/{}/index.html'.format(template))
87     css = readfile('viewer/{}/styles.css'.format(template))
88     js = readfile('viewer/{}/scripts.js'.format(template))
89
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')
95     else:
96         name = {'title': 'nHentai HTML Viewer'}
97
98     data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
99     try:
100         if sys.version_info < (3, 0):
101             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
102                 f.write(data)
103         else:
104             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
105                 f.write(data.encode('utf-8'))
106
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)))
110
111
112 def generate_main_html(output_dir='./'):
113     """
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.
117     """
118
119     image_html = ''
120
121     main = readfile('viewer/main.html')
122     css = readfile('viewer/main.css')
123     js = readfile('viewer/main.js')
124
125     element = '\n\
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\
131                     </a>\n\
132                 </div>\n\
133             </div>\n'
134
135     os.chdir(output_dir)
136     doujinshi_dirs = next(os.walk('.'))[1]
137
138     for folder in doujinshi_dirs:
139         files = os.listdir(folder)
140         files.sort()
141
142         if 'index.html' in files:
143             logger.info('Add doujinshi \'{}\''.format(folder))
144         else:
145             continue
146
147         image = files[0]  # 001.jpg or 001.png
148         if folder is not None:
149             title = folder.replace('_', ' ')
150         else:
151             title = 'nHentai HTML Viewer'
152
153         image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
154     if image_html == '':
155         logger.warning('No index.html found, --gen-main paused.')
156         return
157     try:
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:
161                 f.write(data)
162         else:
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', './')
166         set_js_database()
167         logger.log(
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)))
171
172
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)
176         if write_comic_info:
177             serialize_comic_xml(doujinshi_obj, doujinshi_dir)
178         cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
179     else:
180         cbz_filename = './doujinshi.cbz'
181         doujinshi_dir = '.'
182
183     file_list = os.listdir(doujinshi_dir)
184     file_list.sort()
185
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)
191
192     if rm_origin_dir:
193         shutil.rmtree(doujinshi_dir, ignore_errors=True)
194
195     logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
196
197
198 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
199     try:
200         import img2pdf
201         
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)
208             )
209         else:
210             pdf_filename = './doujinshi.pdf'
211             doujinshi_dir = '.'
212
213         file_list = os.listdir(doujinshi_dir)
214         file_list.sort()
215
216         logger.info('Writing PDF file to path: {}'.format(pdf_filename))
217         with open(pdf_filename, 'wb') as pdf_f:
218             full_path_list = (
219                 [os.path.join(doujinshi_dir, image) for image in file_list]
220             )
221             pdf_f.write(img2pdf.convert(full_path_list))
222
223         if rm_origin_dir:
224             shutil.rmtree(doujinshi_dir, ignore_errors=True)
225
226         logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
227         
228     except ImportError:
229         logger.error("Please install img2pdf package by using pip.")
230
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
233     """
234     encoded = s.encode(encoding)[:length]
235     return encoded.decode(encoding, 'ignore')
236
237
238 def format_filename(s):
239     """
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(' '). 
244     """
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
250     while filename.endswith('.'):
251         filename = filename[:-1]
252
253     if len(filename) > 100:
254         filename = filename[:100] + u'…'
255
256     # Remove [] from filename
257     filename = filename.replace('[]', '').strip()
258     return filename
259
260
261 def signal_handler(signal, frame):
262     logger.error('Ctrl-C signal received. Stopping...')
263     exit(1)
264
265
266 def paging(page_string):
267     # 1,3-5,14 -> [1, 3, 4, 5, 14]
268     if not page_string:
269         return []
270
271     page_list = []
272     for i in page_string.split(','):
273         if '-' in i:
274             start, end = i.split('-')
275             if not (start.isdigit() and end.isdigit()):
276                 raise Exception('Invalid page number')
277             page_list.extend(list(range(int(start), int(end)+1)))
278         else:
279             if not i.isdigit():
280                 raise Exception('Invalid page number')
281             page_list.append(int(i))
282
283     return page_list
284
285
286 class DB(object):
287     conn = None
288     cur = None
289
290     def __enter__(self):
291         self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
292         self.cur = self.conn.cursor()
293         self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
294         self.conn.commit()
295         return self
296
297     def __exit__(self, exc_type, exc_val, exc_tb):
298         self.conn.close()
299
300     def clean_all(self):
301         self.cur.execute('DELETE FROM download_history WHERE 1')
302         self.conn.commit()
303
304     def add_one(self, data):
305         self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
306         self.conn.commit()
307
308     def get_all(self):
309         data = self.cur.execute('SELECT id FROM download_history')
310         return [i[0] for i in data]