]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
28a1a7032c2fba61eed96bf4ee87a0e2a09c8fe3
[nhentai.git] / nhentai / utils.py
1 # coding: utf-8
2 from __future__ import unicode_literals, print_function
3
4 import os
5 import string
6 from nhentai.logger import logger
7 from nhentai.utils import format_filename
8
9
10 class _Singleton(type):
11     """ A metaclass that creates a Singleton base class when called. """
12     _instances = {}
13
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]
18
19
20 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
21     pass
22
23
24 def urlparse(url):
25     try:
26         from urlparse import urlparse
27     except ImportError:
28         from urllib.parse import urlparse
29
30     return urlparse(url)
31
32
33 def generate_html(output_dir='.', doujinshi_obj=None):
34     image_html = ''
35     previous = ''
36
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])))
40     else:
41         doujinshi_dir = '.'
42
43     file_list = os.listdir(doujinshi_dir)
44     file_list.sort()
45
46     for index, image in enumerate(file_list):
47         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
48             continue
49
50         try:
51             next_ = file_list[file_list.index(image) + 1]
52         except IndexError:
53             next_ = ''
54
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_)
57         previous = image
58
59     with open(os.path.join(os.path.dirname(__file__), 'doujinshi.html'), 'r') as template:
60         html = template.read()
61
62     if doujinshi_obj is not None:
63         title = doujinshi_obj.name
64     else:
65         title = 'nHentai HTML Viewer'
66
67     data = html.format(TITLE=title, IMAGES=image_html)
68     with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
69         f.write(data)
70
71     logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
72
73
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.
78
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
82 an invalid filename.
83
84 """
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.
88     return filename