2 from __future__ import unicode_literals, print_function
13 from nhentai import constant
14 from nhentai.logger import logger
15 from nhentai.serializer import serialize, set_js_database
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.COOKIE
25 return getattr(session, method)(url, proxies=constant.PROXY, verify=False, **kwargs)
29 response = request('get', constant.BASE_URL).text
30 username = re.findall('"/users/\d+/(.*?)"', response)
32 logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
34 logger.info('Login successfully! Your username: {}'.format(username[0]))
37 class _Singleton(type):
38 """ A metaclass that creates a Singleton base class when called. """
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]
47 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
53 from urlparse import urlparse
55 from urllib.parse import urlparse
61 loc = os.path.dirname(__file__)
63 with open(os.path.join(loc, path), 'r') as file:
67 def generate_html(output_dir='.', doujinshi_obj=None):
70 if doujinshi_obj is not None:
71 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
75 file_list = os.listdir(doujinshi_dir)
78 for image in file_list:
79 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
82 image_html += '<img src="{0}" class="image-item"/>\n'\
84 html = readfile('viewer/index.html')
85 css = readfile('viewer/styles.css')
86 js = readfile('viewer/scripts.js')
88 if doujinshi_obj is not None:
89 serialize(doujinshi_obj, doujinshi_dir)
90 name = doujinshi_obj.name
91 if sys.version_info < (3, 0):
92 name = doujinshi_obj.name.encode('utf-8')
94 name = {'title': 'nHentai HTML Viewer'}
96 data = html.format(TITLE=name, IMAGES=image_html, SCRIPTS=js, STYLES=css)
98 if sys.version_info < (3, 0):
99 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
102 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
103 f.write(data.encode('utf-8'))
105 logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
106 except Exception as e:
107 logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
110 def generate_main_html(output_dir='./'):
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.
119 main = readfile('viewer/main.html')
120 css = readfile('viewer/main.css')
121 js = readfile('viewer/main.js')
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\
134 doujinshi_dirs = next(os.walk('.'))[1]
136 for folder in doujinshi_dirs:
137 files = os.listdir(folder)
140 if 'index.html' in files:
141 logger.info('Add doujinshi \'{}\''.format(folder))
145 image = files[0] # 001.jpg or 001.png
146 if folder is not None:
147 title = folder.replace('_', ' ')
149 title = 'nHentai HTML Viewer'
151 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
153 logger.warning('None index.html found, --gen-main paused.')
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:
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', './')
166 15, 'Main Viewer has been write to \'{0}main.html\''.format(output_dir))
167 except Exception as e:
168 logger.warning('Writen Main Viewer failed ({})'.format(str(e)))
171 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
172 if doujinshi_obj is not None:
173 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
174 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
176 cbz_filename = './doujinshi.cbz'
179 file_list = os.listdir(doujinshi_dir)
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)
189 shutil.rmtree(doujinshi_dir, ignore_errors=True)
191 logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
194 def format_filename(s):
195 """Take a string and return a valid filename constructed from the string.
196 Uses a whitelist approach: any characters not present in valid_chars are
197 removed. Also spaces are replaced with underscores.
199 Note: this method may produce invalid filenames such as ``, `.` or `..`
200 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
201 and append a file extension like '.txt', so I avoid the potential of using
205 valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
206 filename = ''.join(c for c in s if c in valid_chars)
207 if len(filename) > 100:
208 filename = filename[:100] + '...]'
210 # Remove [] from filename
211 filename = filename.replace('[]', '').strip()
215 def signal_handler(signal, frame):
216 logger.error('Ctrl-C signal received. Stopping...')
225 self.conn = sqlite3.connect(constant.NHENTAI_HISTORY)
226 self.cur = self.conn.cursor()
227 self.cur.execute('CREATE TABLE IF NOT EXISTS download_history (id text)')
231 def __exit__(self, exc_type, exc_val, exc_tb):
235 self.cur.execute('DELETE FROM download_history WHERE 1')
238 def add_one(self, data):
239 self.cur.execute('INSERT INTO download_history VALUES (?)', [data])
243 data = self.cur.execute('SELECT id FROM download_history')
244 return [i[0] for i in data]