]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
store proxy config
[nhentai.git] / nhentai / utils.py
1 # coding: utf-8
2 from __future__ import unicode_literals, print_function
3
4 import sys
5 import os
6 import string
7 import zipfile
8 import shutil
9 from nhentai.logger import logger
10
11
12 class _Singleton(type):
13     """ A metaclass that creates a Singleton base class when called. """
14     _instances = {}
15
16     def __call__(cls, *args, **kwargs):
17         if cls not in cls._instances:
18             cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
19         return cls._instances[cls]
20
21
22 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
23     pass
24
25
26 def urlparse(url):
27     try:
28         from urlparse import urlparse
29     except ImportError:
30         from urllib.parse import urlparse
31
32     return urlparse(url)
33
34
35 def readfile(path):
36     loc = os.path.dirname(__file__)
37
38     with open(os.path.join(loc, path), 'r') as file:
39         return file.read()
40
41
42 def generate_html(output_dir='.', doujinshi_obj=None):
43     image_html = ''
44
45     if doujinshi_obj is not None:
46         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
47     else:
48         doujinshi_dir = '.'
49
50     file_list = os.listdir(doujinshi_dir)
51     file_list.sort()
52
53     for image in file_list:
54         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
55             continue
56
57         image_html += '<img src="{0}" class="image-item"/>\n'\
58             .format(image)
59
60     html = readfile('viewer/index.html')
61     css = readfile('viewer/styles.css')
62     js = readfile('viewer/scripts.js')
63
64     if doujinshi_obj is not None:
65         title = doujinshi_obj.name
66         if sys.version_info < (3, 0):
67             title = title.encode('utf-8')
68     else:
69         title = 'nHentai HTML Viewer'
70
71     data = html.format(TITLE=title, IMAGES=image_html, SCRIPTS=js, STYLES=css)
72     try:
73         if sys.version_info < (3, 0):
74             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
75                 f.write(data)
76         else:
77             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
78                 f.write(data.encode('utf-8'))
79
80         logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
81     except Exception as e:
82         logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
83
84 def generate_main_html(output_dir='.'):
85     """Generete a main html to show all the contain doujinshi.
86     With a link to thier `index.html`. 
87     Default output folder will be the CLI path."""
88     count = 0
89     image_html = ''
90     main = readfile('viewer/main.html')
91     css = readfile('viewer/main.css')
92     element = '\n\
93             <div class="gallery-favorite">\n\
94                 <div class="gallery">\n\
95                     <a href="./{FOLDER}/index.html" class="cover" style="padding:0 0 141.6% 0"><img\n\
96                             src="./{FOLDER}/{IMAGE}" />\n\
97                         <div class="caption">{TITLE}</div>\n\
98                     </a>\n\
99                 </div>\n\
100             </div>\n'
101
102     if output_dir == '':
103         os.chdir('.')
104     else:
105         os.chdir(output_dir)
106     # switch to given dir
107     doujinshi_dirs = next(os.walk('.'))[1]
108     # https://stackoverflow.com/questions/141291/how-to-list-only-top-level-directories-in-python
109
110     for folder in doujinshi_dirs:
111         if folder[0] is not '[':
112             continue
113         files = os.listdir(folder)
114         if 'index.html' in files:
115             count += 1
116         else:
117             logger.warning('{} folder does not have index.html (try use --html arg first).'
118                            .format(folder))
119             continue
120         image = files[0]  # 001.jpg or 001.png
121         if folder is not None:
122             title = folder.replace('_', ' ')
123             # if sys.version_info > (3, 0):
124             #     title = title.encode('utf-8')
125         else:
126             title = 'nHentai HTML Viewer'
127         image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
128
129     if image_html == '':
130         logger.warning('None index.html found, --gen-main paused.')
131         return
132     try:
133         data = main.format(STYLES=css, COUNT=count, PICTURE=image_html)
134         if sys.version_info < (3, 0):
135             with open('./main.html', 'w') as f:
136                 f.write(data)
137         else:
138             with open('./main.html', 'wb') as f:
139                 f.write(data.encode('utf-8'))
140         logger.log(
141             15, 'Main Viewer has been write to \'{0}/main.html\''.format(output_dir))
142     except Exception as e:
143         logger.warning('Writen Main Viewer failed ({})'.format(str(e)))
144
145 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
146     if doujinshi_obj is not None:
147         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
148         cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '%s.cbz' % doujinshi_obj.id)
149     else:
150         cbz_filename = './doujinshi.cbz'
151         doujinshi_dir = '.'
152
153     file_list = os.listdir(doujinshi_dir)
154     file_list.sort()
155
156     logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
157     with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
158         for image in file_list:
159             image_path = os.path.join(doujinshi_dir, image)
160             cbz_pf.write(image_path, image)
161
162     if rm_origin_dir:
163         shutil.rmtree(doujinshi_dir, ignore_errors=True)
164
165     logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
166
167
168 def format_filename(s):
169     """Take a string and return a valid filename constructed from the string.
170 Uses a whitelist approach: any characters not present in valid_chars are
171 removed. Also spaces are replaced with underscores.
172
173 Note: this method may produce invalid filenames such as ``, `.` or `..`
174 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
175 and append a file extension like '.txt', so I avoid the potential of using
176 an invalid filename.
177
178 """
179     valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
180     filename = ''.join(c for c in s if c in valid_chars)
181     filename = filename.replace(' ', '_')  # I don't like spaces in filenames.
182     if len(filename) > 100:
183         filename = filename[:100] + '...]'
184
185     # Remove [] from filename
186     filename = filename.replace('[]', '')
187     return filename