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)))
85 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
86 if doujinshi_obj is not None:
87 doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
88 cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '%s.cbz' % doujinshi_obj.id)
90 cbz_filename = './doujinshi.cbz'
93 file_list = os.listdir(doujinshi_dir)
96 logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
97 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
98 for image in file_list:
99 image_path = os.path.join(doujinshi_dir, image)
100 cbz_pf.write(image_path, image)
103 shutil.rmtree(doujinshi_dir, ignore_errors=True)
105 logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
108 def format_filename(s):
109 """Take a string and return a valid filename constructed from the string.
110 Uses a whitelist approach: any characters not present in valid_chars are
111 removed. Also spaces are replaced with underscores.
113 Note: this method may produce invalid filenames such as ``, `.` or `..`
114 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
115 and append a file extension like '.txt', so I avoid the potential of using
119 valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
120 filename = ''.join(c for c in s if c in valid_chars)
121 filename = filename.replace(' ', '_') # I don't like spaces in filenames.
122 if len(filename) > 100:
123 filename = filename[:100] + '...]'
125 # Remove [] from filename
126 filename = filename.replace('[]', '')