]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
FIX: Use of img2lib even if it is not installed
[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_comicxml, 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     return getattr(session, method)(url, proxies=constant.CONFIG['proxy'], verify=False, **kwargs)
24
25
26 def check_cookie():
27     response = request('get', constant.BASE_URL).text
28     username = re.findall('"/users/\d+/(.*?)"', response)
29     if not username:
30         logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
31     else:
32         logger.info('Login successfully! Your username: {}'.format(username[0]))
33
34
35 class _Singleton(type):
36     """ A metaclass that creates a Singleton base class when called. """
37     _instances = {}
38
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]
43
44
45 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
46     pass
47
48
49 def urlparse(url):
50     try:
51         from urlparse import urlparse
52     except ImportError:
53         from urllib.parse import urlparse
54
55     return urlparse(url)
56
57
58 def readfile(path):
59     loc = os.path.dirname(__file__)
60
61     with open(os.path.join(loc, path), 'r') as file:
62         return file.read()
63
64
65 def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
66     image_html = ''
67
68     if doujinshi_obj is not None:
69         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
70     else:
71         doujinshi_dir = '.'
72
73     file_list = os.listdir(doujinshi_dir)
74     file_list.sort()
75
76     for image in file_list:
77         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
78             continue
79
80         image_html += '<img src="{0}" class="image-item"/>\n'\
81             .format(image)
82     html = readfile('viewer/{}/index.html'.format(template))
83     css = readfile('viewer/{}/styles.css'.format(template))
84     js = readfile('viewer/{}/scripts.js'.format(template))
85
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')
91     else:
92         name = {'title': 'nHentai HTML Viewer'}
93
94     data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
95     try:
96         if sys.version_info < (3, 0):
97             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
98                 f.write(data)
99         else:
100             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
101                 f.write(data.encode('utf-8'))
102
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)))
106
107
108 def generate_main_html(output_dir='./'):
109     """
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.
113     """
114
115     image_html = ''
116
117     main = readfile('viewer/main.html')
118     css = readfile('viewer/main.css')
119     js = readfile('viewer/main.js')
120
121     element = '\n\
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\
127                     </a>\n\
128                 </div>\n\
129             </div>\n'
130
131     os.chdir(output_dir)
132     doujinshi_dirs = next(os.walk('.'))[1]
133
134     for folder in doujinshi_dirs:
135         files = os.listdir(folder)
136         files.sort()
137
138         if 'index.html' in files:
139             logger.info('Add doujinshi \'{}\''.format(folder))
140         else:
141             continue
142
143         image = files[0]  # 001.jpg or 001.png
144         if folder is not None:
145             title = folder.replace('_', ' ')
146         else:
147             title = 'nHentai HTML Viewer'
148
149         image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
150     if image_html == '':
151         logger.warning('No index.html found, --gen-main paused.')
152         return
153     try:
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:
157                 f.write(data)
158         else:
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', './')
162         set_js_database()
163         logger.log(
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)))
167
168
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)
172         if write_comic_info:
173             serialize_comicxml(doujinshi_obj, doujinshi_dir)
174         cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
175     else:
176         cbz_filename = './doujinshi.cbz'
177         doujinshi_dir = '.'
178
179     file_list = os.listdir(doujinshi_dir)
180     file_list.sort()
181
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)
187
188     if rm_origin_dir:
189         shutil.rmtree(doujinshi_dir, ignore_errors=True)
190
191     logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
192
193
194 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
195     try:
196         import img2pdf
197         
198         """Write images to a PDF file using img2pdf."""
199         if doujinshi_obj is not None:
200             doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
201             pdf_filename = os.path.join(
202                 os.path.join(doujinshi_dir, '..'),
203                 '{}.pdf'.format(doujinshi_obj.filename)
204             )
205         else:
206             pdf_filename = './doujinshi.pdf'
207             doujinshi_dir = '.'
208
209         file_list = os.listdir(doujinshi_dir)
210         file_list.sort()
211
212         logger.info('Writing PDF file to path: {}'.format(pdf_filename))
213         with open(pdf_filename, 'wb') as pdf_f:
214             full_path_list = (
215                 [os.path.join(doujinshi_dir, image) for image in file_list]
216             )
217             pdf_f.write(img2pdf.convert(full_path_list))
218
219         if rm_origin_dir:
220             shutil.rmtree(doujinshi_dir, ignore_errors=True)
221
222         logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
223         
224     except ImportError:
225         logger.error("Please install img2pdf package by using pip.")
226
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
229     """
230     encoded = s.encode(encoding)[:length]
231     return encoded.decode(encoding, 'ignore')
232
233
234 def format_filename(s):
235     """
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(' '). 
240     """
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     filename = ' '.join(filename.split())
245     print(repr(filename))
246
247     while filename.endswith('.'):
248         filename = filename[:-1]
249
250     if len(filename) > 100:
251         filename = filename[:100] + u'…'
252
253     # Remove [] from filename
254     filename = filename.replace('[]', '').strip()
255     return filename
256
257
258 def signal_handler(signal, frame):
259     logger.error('Ctrl-C signal received. Stopping...')
260     exit(1)
261
262
263 def paging(page_string):
264     # 1,3-5,14 -> [1, 3, 4, 5, 14]
265     if not page_string:
266         return []
267
268     page_list = []
269     for i in page_string.split(','):
270         if '-' in i:
271             start, end = i.split('-')
272             if not (start.isdigit() and end.isdigit()):
273                 raise Exception('Invalid page number')
274             page_list.extend(list(range(int(start), int(end)+1)))
275         else:
276             if not i.isdigit():
277                 raise Exception('Invalid page number')
278             page_list.append(int(i))
279
280     return page_list
281
282
283 class DB(object):
284     conn = None
285     cur = None
286
287     def __enter__(self):
288         self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
289         self.cur = self.conn.cursor()
290         self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
291         self.conn.commit()
292         return self
293
294     def __exit__(self, exc_type, exc_val, exc_tb):
295         self.conn.close()
296
297     def clean_all(self):
298         self.cur.execute('DELETE FROM download_history WHERE 1')
299         self.conn.commit()
300
301     def add_one(self, data):
302         self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
303         self.conn.commit()
304
305     def get_all(self):
306         data = self.cur.execute('SELECT id FROM download_history')
307         return [i[0] for i in data]