]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
fix issue #186
[nhentai.git] / nhentai / utils.py
1 # coding: utf-8
2 from __future__ import unicode_literals, print_function
3
4 import sys
5 import re
6 import os
7 import string
8 import zipfile
9 import shutil
10 import requests
11 import sqlite3
12
13 from nhentai import constant
14 from nhentai.logger import logger
15 from nhentai.serializer import serialize_json, serialize_comicxml, set_js_database
16
17
18 def request(method, url, **kwargs):
19     session = requests.Session()
20     session.headers.update({
21         'Referer': constant.LOGIN_URL,
22         'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
23         'Cookie': constant.CONFIG['cookie']
24     })
25     return getattr(session, method)(url, proxies=constant.CONFIG['proxy'], verify=False, **kwargs)
26
27
28 def check_cookie():
29     response = request('get', constant.BASE_URL).text
30     username = re.findall('"/users/\d+/(.*?)"', response)
31     if not username:
32         logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
33     else:
34         logger.info('Login successfully! Your username: {}'.format(username[0]))
35
36
37 class _Singleton(type):
38     """ A metaclass that creates a Singleton base class when called. """
39     _instances = {}
40
41     def __call__(cls, *args, **kwargs):
42         if cls not in cls._instances:
43             cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
44         return cls._instances[cls]
45
46
47 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
48     pass
49
50
51 def urlparse(url):
52     try:
53         from urlparse import urlparse
54     except ImportError:
55         from urllib.parse import urlparse
56
57     return urlparse(url)
58
59
60 def readfile(path):
61     loc = os.path.dirname(__file__)
62
63     with open(os.path.join(loc, path), 'r') as file:
64         return file.read()
65
66
67 def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
68     image_html = ''
69
70     if doujinshi_obj is not None:
71         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
72     else:
73         doujinshi_dir = '.'
74
75     file_list = os.listdir(doujinshi_dir)
76     file_list.sort()
77
78     for image in file_list:
79         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
80             continue
81
82         image_html += '<img src="{0}" class="image-item"/>\n'\
83             .format(image)
84     html = readfile('viewer/{}/index.html'.format(template))
85     css = readfile('viewer/{}/styles.css'.format(template))
86     js = readfile('viewer/{}/scripts.js'.format(template))
87
88     if doujinshi_obj is not None:
89         serialize_json(doujinshi_obj, doujinshi_dir)
90         name = doujinshi_obj.name
91         if sys.version_info < (3, 0):
92             name = doujinshi_obj.name.encode('utf-8')
93     else:
94         name = {'title': 'nHentai HTML Viewer'}
95
96     data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
97     try:
98         if sys.version_info < (3, 0):
99             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
100                 f.write(data)
101         else:
102             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
103                 f.write(data.encode('utf-8'))
104
105         logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
106     except Exception as e:
107         logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
108
109
110 def generate_main_html(output_dir='./'):
111     """
112     Generate a main html to show all the contain doujinshi.
113     With a link to their `index.html`.
114     Default output folder will be the CLI path.
115     """
116
117     image_html = ''
118
119     main = readfile('viewer/main.html')
120     css = readfile('viewer/main.css')
121     js = readfile('viewer/main.js')
122
123     element = '\n\
124             <div class="gallery-favorite">\n\
125                 <div class="gallery">\n\
126                     <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
127                             src="./{FOLDER}/{IMAGE}" />\n\
128                         <div class="caption">{TITLE}</div>\n\
129                     </a>\n\
130                 </div>\n\
131             </div>\n'
132
133     os.chdir(output_dir)
134     doujinshi_dirs = next(os.walk('.'))[1]
135
136     for folder in doujinshi_dirs:
137         files = os.listdir(folder)
138         files.sort()
139
140         if 'index.html' in files:
141             logger.info('Add doujinshi \'{}\''.format(folder))
142         else:
143             continue
144
145         image = files[0]  # 001.jpg or 001.png
146         if folder is not None:
147             title = folder.replace('_', ' ')
148         else:
149             title = 'nHentai HTML Viewer'
150
151         image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
152     if image_html == '':
153         logger.warning('No index.html found, --gen-main paused.')
154         return
155     try:
156         data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
157         if sys.version_info < (3, 0):
158             with open('./main.html', 'w') as f:
159                 f.write(data)
160         else:
161             with open('./main.html', 'wb') as f:
162                 f.write(data.encode('utf-8'))
163         shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
164         set_js_database()
165         logger.log(
166             15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
167     except Exception as e:
168         logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
169
170
171 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=False):
172     if doujinshi_obj is not None:
173         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
174         if write_comic_info:
175             serialize_comicxml(doujinshi_obj, doujinshi_dir)
176         cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
177     else:
178         cbz_filename = './doujinshi.cbz'
179         doujinshi_dir = '.'
180
181     file_list = os.listdir(doujinshi_dir)
182     file_list.sort()
183
184     logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
185     with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
186         for image in file_list:
187             image_path = os.path.join(doujinshi_dir, image)
188             cbz_pf.write(image_path, image)
189
190     if rm_origin_dir:
191         shutil.rmtree(doujinshi_dir, ignore_errors=True)
192
193     logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
194
195
196 def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
197     try:
198         import img2pdf
199     except ImportError:
200         logger.error("Please install img2pdf package by using pip.")
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
229 def format_filename(s):
230     """
231     It used to be a whitelist approach allowed only alphabet and a part of symbols.
232     but most doujinshi's names include Japanese 2-byte characters and these was rejected.
233     so it is using blacklist approach now.
234     if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' '). 
235     """
236     # maybe you can use `--format` to select a suitable filename
237     ban_chars = '\\\'/:,;*?"<>|'
238     filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars)))
239     if len(filename) > 100:
240         filename = filename[:100] + '...]'
241
242     # Remove [] from filename
243     filename = filename.replace('[]', '').strip()
244     return filename
245
246
247 def signal_handler(signal, frame):
248     logger.error('Ctrl-C signal received. Stopping...')
249     exit(1)
250
251
252 def paging(page_string):
253     # 1,3-5,14 -> [1, 3, 4, 5, 14]
254     if not page_string:
255         return []
256
257     page_list = []
258     for i in page_string.split(','):
259         if '-' in i:
260             start, end = i.split('-')
261             if not (start.isdigit() and end.isdigit()):
262                 raise Exception('Invalid page number')
263             page_list.extend(list(range(int(start), int(end)+1)))
264         else:
265             if not i.isdigit():
266                 raise Exception('Invalid page number')
267             page_list.append(int(i))
268
269     return page_list
270
271
272 class DB(object):
273     conn = None
274     cur = None
275
276     def __enter__(self):
277         self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
278         self.cur = self.conn.cursor()
279         self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
280         self.conn.commit()
281         return self
282
283     def __exit__(self, exc_type, exc_val, exc_tb):
284         self.conn.close()
285
286     def clean_all(self):
287         self.cur.execute('DELETE FROM download_history WHERE 1')
288         self.conn.commit()
289
290     def add_one(self, data):
291         self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
292         self.conn.commit()
293
294     def get_all(self):
295         data = self.cur.execute('SELECT id FROM download_history')
296         return [i[0] for i in data]