2 from __future__ import unicode_literals, print_function
6 from nhentai.logger import logger
7 from nhentai.utils import format_filename
10 class _Singleton(type):
11 """ A metaclass that creates a Singleton base class when called. """
14 def __call__(cls, *args, **kwargs):
15 if cls not in cls._instances:
16 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
17 return cls._instances[cls]
20 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
26 from urlparse import urlparse
28 from urllib.parse import urlparse
33 def generate_html(output_dir='.', doujinshi_obj=None):
37 if doujinshi_obj is not None:
38 doujinshi_dir = os.path.join(output_dir, format_filename('%s-%s' % (doujinshi_obj.id,
39 doujinshi_obj.name[:200])))
43 file_list = os.listdir(doujinshi_dir)
46 for index, image in enumerate(file_list):
47 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
51 next_ = file_list[file_list.index(image) + 1]
55 image_html += '<img src="{0}" class="image-item {1}" attr-prev="{2}" attr-next="{3}">\n'\
56 .format(image, 'current' if index == 0 else '', previous, next_)
59 with open(os.path.join(os.path.dirname(__file__), 'doujinshi.html'), 'r') as template:
60 html = template.read()
62 if doujinshi_obj is not None:
63 title = doujinshi_obj.name
65 title = 'nHentai HTML Viewer'
67 data = html.format(TITLE=title, IMAGES=image_html)
68 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
71 logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
74 def format_filename(s):
75 """Take a string and return a valid filename constructed from the string.
76 Uses a whitelist approach: any characters not present in valid_chars are
77 removed. Also spaces are replaced with underscores.
79 Note: this method may produce invalid filenames such as ``, `.` or `..`
80 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
81 and append a file extension like '.txt', so I avoid the potential of using
85 valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
86 filename = ''.join(c for c in s if c in valid_chars)
87 filename = filename.replace(' ', '_') # I don't like spaces in filenames.