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, format_filename('%s-%s' % (doujinshi_obj.id,
51 file_list = os.listdir(doujinshi_dir)
54 for image in file_list:
55 if not os.path.splitext(image)[1] in ('.jpg', '.png'):
58 image_html += '<img src="{0}" class="image-item"/>\n'\
61 html = readfile('viewer/index.html')
62 css = readfile('viewer/styles.css')
63 js = readfile('viewer/scripts.js')
65 if doujinshi_obj is not None:
66 title = doujinshi_obj.name
67 if sys.version_info < (3, 0):
68 title = title.encode('utf-8')
70 title = 'nHentai HTML Viewer'
72 data = html.format(TITLE=title, IMAGES=image_html, SCRIPTS=js, STYLES=css)
74 if sys.version_info < (3, 0):
75 with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
78 with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
79 f.write(data.encode('utf-8'))
81 logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
82 except Exception as e:
83 logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
86 def generate_cbz(output_dir='.', doujinshi_obj=None):
87 if doujinshi_obj is not None:
88 doujinshi_dir = os.path.join(output_dir, format_filename('%s-%s' % (doujinshi_obj.id,
90 cbz_filename = os.path.join(output_dir, format_filename('%s-%s.cbz' % (doujinshi_obj.id,
93 cbz_filename = './doujinshi.cbz'
96 file_list = os.listdir(doujinshi_dir)
99 with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
100 for image in file_list:
101 image_path = os.path.join(doujinshi_dir, image)
102 cbz_pf.write(image_path, image)
104 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]