2 from __future__ import unicode_literals, print_function
9 from nhentai.logger import logger
12 class _Singleton(type):
13 """ A metaclass that creates a Singleton base class when called. """
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]
22 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
28 from urlparse import urlparse
30 from urllib.parse import urlparse
36 loc = os.path.dirname(__file__)
38 with open(os.path.join(loc, path), 'r') as file:
42 def generate_html(output_dir='.', doujinshi_obj=None):
45 if doujinshi_obj is not None:
46 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
50 file_list = os.listdir(doujinshi_dir)
53 for image in file_list:
54 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
57 image_html += '<img src="{0}" class="image-item"/>\n'\
60 html = readfile('viewer/index.html')
61 css = readfile('viewer/styles.css')
62 js = readfile('viewer/scripts.js')
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')
69 title = 'nHentai HTML Viewer'
71 data = html.format(TITLE=title, IMAGES=image_html, SCRIPTS=js, STYLES=css)
73 if sys.version_info < (3, 0):
74 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
77 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
78 f.write(data.encode('utf-8'))
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)))
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."""
90 main = readfile('viewer/main.html')
91 css = readfile('viewer/main.css')
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\
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
110 for folder in doujinshi_dirs:
111 if folder[0] is not '[':
113 files = os.listdir(folder)
114 if 'index.html' in files:
117 logger.warning('{} folder does not have index.html (try use --html arg first).'
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')
126 title = 'nHentai HTML Viewer'
127 image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
130 logger.warning('None index.html found, --gen-main paused.')
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:
138 with open('./main.html', 'wb') as f:
139 f.write(data.encode('utf-8'))
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)))
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)
150 cbz_filename = './doujinshi.cbz'
153 file_list = os.listdir(doujinshi_dir)
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)
163 shutil.rmtree(doujinshi_dir, ignore_errors=True)
165 logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
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.
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
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] + '...]'
185 # Remove [] from filename
186 filename = filename.replace('[]', '')