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