2 from __future__ import unicode_literals, print_function
5 from nhentai.logger import logger
8 class _Singleton(type):
9 """ A metaclass that creates a Singleton base class when called. """
12 def __call__(cls, *args, **kwargs):
13 if cls not in cls._instances:
14 cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
15 return cls._instances[cls]
18 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
24 from urlparse import urlparse
26 from urllib.parse import urlparse
31 def generate_html(output_dir='.', doujinshi_obj=None):
35 if doujinshi_obj is not None:
36 doujinshi_dir = os.path.join(output_dir, str(doujinshi_obj.id))
40 file_list = os.listdir(doujinshi_dir)
43 for index, image in enumerate(file_list):
44 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
48 next_ = file_list[file_list.index(image) + 1]
52 image_html += '<img src="{0}" class="image-item {1}" attr-prev="{2}" attr-next="{3}">\n'\
53 .format(image, 'current' if index == 0 else '', previous, next_)
56 with open(os.path.join(os.path.dirname(__file__), 'doujinshi.html'), 'r') as template:
57 html = template.read()
59 if doujinshi_obj is not None:
60 title = doujinshi_obj.name
62 title = 'nHentai HTML Viewer'
64 data = html.format(TITLE=title, IMAGES=image_html)
65 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
68 logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
71 def format_filename(s):
72 """Take a string and return a valid filename constructed from the string.
73 Uses a whitelist approach: any characters not present in valid_chars are
74 removed. Also spaces are replaced with underscores.
76 Note: this method may produce invalid filenames such as ``, `.` or `..`
77 When I use this method I prepend a date string like '2009_01_15_19_46_32_'
78 and append a file extension like '.txt', so I avoid the potential of using
82 valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
83 filename = ''.join(c for c in s if c in valid_chars)
84 filename = filename.replace(' ', '_') # I don't like spaces in filenames.