]> git.lizzy.rs Git - nhentai.git/blob - nhentai/utils.py
Update README.md
[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, doujinshi_obj.filename)
47     else:
48         doujinshi_dir = '.'
49
50     file_list = os.listdir(doujinshi_dir)
51     file_list.sort()
52
53     for image in file_list:
54         if not os.path.splitext(image)[1] in ('.jpg', '.png'):
55             continue
56
57         image_html += '<img src="{0}" class="image-item"/>\n'\
58             .format(image)
59
60     html = readfile('viewer/index.html')
61     css = readfile('viewer/styles.css')
62     js = readfile('viewer/scripts.js')
63
64     if doujinshi_obj is not None:
65         title = doujinshi_obj.name
66         if sys.version_info < (3, 0):
67             title = title.encode('utf-8')
68     else:
69         title = 'nHentai HTML Viewer'
70
71     data = html.format(TITLE=title, IMAGES=image_html, SCRIPTS=js, STYLES=css)
72     try:
73         if sys.version_info < (3, 0):
74             with open(os.path.join(doujinshi_dir, 'index.html'), 'w') as f:
75                 f.write(data)
76         else:
77             with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
78                 f.write(data.encode('utf-8'))
79
80         logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
81     except Exception as e:
82         logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
83
84
85 def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
86     if doujinshi_obj is not None:
87         doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
88         cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '%s.cbz' % doujinshi_obj.id)
89     else:
90         cbz_filename = './doujinshi.cbz'
91         doujinshi_dir = '.'
92
93     file_list = os.listdir(doujinshi_dir)
94     file_list.sort()
95
96     logger.info('Writing CBZ file to path: {}'.format(cbz_filename))
97     with zipfile.ZipFile(cbz_filename, 'w') as cbz_pf:
98         for image in file_list:
99             image_path = os.path.join(doujinshi_dir, image)
100             cbz_pf.write(image_path, image)
101
102     if rm_origin_dir:
103         shutil.rmtree(doujinshi_dir, ignore_errors=True)
104
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
125     # Remove [] from filename
126     filename = filename.replace('[]', '')
127     return filename