]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
618a6ad503b98d78537d1d895d94acf62392501d
[nhentai.git] / nhentai / utils.py
1 # coding: utf-8
2 from __future__ import unicode_literals, print_function
3
4 import sys
5 import os
6 import string
7 import zipfile
8 import shutil
9 from nhentai.logger import logger
10
11
12 class _Singleton(type):
13     """ A metaclass that creates a Singleton base class when called. """
14     _instances = {}
15
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]
20
21
22 class Singleton(_Singleton(str('SingletonMeta'), (object,), {})):
23     pass
24
25
26 def urlparse(url):
27     try:
28         from urlparse import urlparse
29     except ImportError:
30         from urllib.parse import urlparse
31
32     return urlparse(url)
33
34
35 def readfile(path):
36     loc = os.path.dirname(__file__)
37
38     with open(os.path.join(loc, path), 'r') as file:
39         return file.read()
40
41
42 def generate_html(output_dir='.', doujinshi_obj=None):
43     image_html = ''
44
45     if doujinshi_obj is not None:
46         doujinshi_dir = os.path.join(output_dir, format_filename('%s-%s' % (doujinshi_obj.id,
47                                                                             doujinshi_obj.name)))
48     else:
49         doujinshi_dir = '.'
50
51     file_list = os.listdir(doujinshi_dir)
52     file_list.sort()
53
54     for image in file_list:
55         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
56             continue
57
58         image_html += '<img src="{0}" class="image-item"/>\n'\
59             .format(image)
60
61     html = readfile('viewer/index.html')
62     css = readfile('viewer/styles.css')
63     js = readfile('viewer/scripts.js')
64
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')
69     else:
70         title = 'nHentai HTML Viewer'
71
72     data = html.format(TITLE=title, IMAGES=image_html, SCRIPTS=js, STYLES=css)
73     try:
74         if sys.version_info < (3, 0):
75             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
76                 f.write(data)
77         else:
78             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
79                 f.write(data.encode('utf-8'))
80
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)))
84
85
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,
89                                                                             doujinshi_obj.name)))
90         cbz_filename = os.path.join(output_dir, format_filename('%s-%s.cbz' % (doujinshi_obj.id,
91                                                                                doujinshi_obj.name)))
92     else:
93         cbz_filename = './doujinshi.cbz'
94         doujinshi_dir = '.'
95
96     file_list = os.listdir(doujinshi_dir)
97     file_list.sort()
98     
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)
103             
104     shutil.rmtree(doujinshi_dir, ignore_errors=True)
105     logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
106
107
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.
112
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
116 an invalid filename.
117
118 """
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]
124     return filename