Compare commits

...

19 Commits

Author SHA1 Message Date
8b8b5f193e 0.4.11 2021-01-11 11:15:21 +08:00
fc99d91ac1 fix #193 2021-01-11 11:14:35 +08:00
ba141efba7 remove repeated spaces 2021-01-11 11:04:29 +08:00
f78d8750f3 remove __future__ 2021-01-11 11:03:45 +08:00
af379c825c Merge branch 'master' into dev 2021-01-10 14:40:09 +08:00
2f9386f22c fix #188 2021-01-10 11:44:04 +08:00
3667bc34b7 0.4.10 2021-01-10 11:41:38 +08:00
84749c56bd fix #191 2021-01-10 11:40:46 +08:00
24f79e0945 Merge pull request #190 from RicterZ/dev
fix bugs
2021-01-07 20:42:26 +08:00
edc46a9531 Merge pull request #189 from mobrine1/mobrine1-patch-1
Fixing loop when id not found, issue #188
2021-01-07 20:39:44 +08:00
72035a14e6 Fixing loop when id not found, issue #188 2021-01-07 07:32:29 -05:00
472528e464 Merge pull request #187 from atsushi-hirako/patch-1
fix issue #186
2021-01-02 02:16:50 +08:00
3f5915fd2a fix issue #186
change to blacklist approach (allow 2-bytes character)
2021-01-01 20:11:09 +09:00
0cd2576dab 0.4.9 2020-12-02 07:45:31 +08:00
445a8c052e Merge pull request #180 from RicterZ/dev
0.4.8
2020-12-01 21:01:00 +08:00
7a75afef0a 0.4.8 2020-12-01 20:58:28 +08:00
a5813e19b1 fix bug on first start 2020-12-01 20:56:27 +08:00
8462d2f2aa use dict.update to update config values 2020-11-26 17:52:10 +08:00
51074ee948 support multi viewers 2020-11-26 17:22:23 +08:00
12 changed files with 71 additions and 55 deletions

View File

@ -1,9 +1,4 @@
include README.md include README.md
include requirements.txt include requirements.txt
include nhentai/viewer/index.html include nhentai/viewer/*
include nhentai/viewer/styles.css include nhentai/viewer/default/*
include nhentai/viewer/scripts.js
include nhentai/viewer/main.html
include nhentai/viewer/main.css
include nhentai/viewer/main.js
include nhentai/viewer/logo.png

View File

@ -1,3 +1,3 @@
__version__ = '0.4.6' __version__ = '0.4.11'
__author__ = 'RicterZ' __author__ = 'RicterZ'
__email__ = 'ricterzheng@gmail.com' __email__ = 'ricterzheng@gmail.com'

View File

@ -1,5 +1,5 @@
# coding: utf-8 # coding: utf-8
from __future__ import print_function
import os import os
import sys import sys
import json import json
@ -15,17 +15,6 @@ from nhentai import __version__
from nhentai.utils import urlparse, generate_html, generate_main_html, DB from nhentai.utils import urlparse, generate_html, generate_main_html, DB
from nhentai.logger import logger from nhentai.logger import logger
try:
if sys.version_info < (3, 0, 0):
import codecs
import locale
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
sys.stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr)
except NameError:
# python3
pass
def banner(): def banner():
logger.info(u'''nHentai ver %s: あなたも変態。 いいね? logger.info(u'''nHentai ver %s: あなたも変態。 いいね?
@ -43,7 +32,7 @@ def load_config():
try: try:
with open(constant.NHENTAI_CONFIG_FILE, 'r') as f: with open(constant.NHENTAI_CONFIG_FILE, 'r') as f:
constant.CONFIG = json.load(f) constant.CONFIG.update(json.load(f))
except json.JSONDecodeError: except json.JSONDecodeError:
logger.error('Failed to load config file.') logger.error('Failed to load config file.')
write_config() write_config()
@ -126,6 +115,8 @@ def cmd_parser():
default=False, help='save downloaded doujinshis, whose will be skipped if you re-download them') default=False, help='save downloaded doujinshis, whose will be skipped if you re-download them')
parser.add_option('--clean-download-history', action='store_true', default=False, dest='clean_download_history', parser.add_option('--clean-download-history', action='store_true', default=False, dest='clean_download_history',
help='clean download history') help='clean download history')
parser.add_option('--template', dest='viewer_template', action='store',
help='set viewer template', default='')
try: try:
sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv] sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv]
@ -179,6 +170,19 @@ def cmd_parser():
logger.info('Proxy now set to \'{0}\'.'.format(args.proxy)) logger.info('Proxy now set to \'{0}\'.'.format(args.proxy))
write_config() write_config()
exit(0) exit(0)
if args.viewer_template:
if not args.viewer_template:
args.viewer_template = 'default'
if not os.path.exists(os.path.join(os.path.dirname(__file__),
'viewer/{}/index.html'.format(args.viewer_template))):
logger.error('Template \'{}\' does not exists'.format(args.viewer_template))
exit(1)
else:
constant.CONFIG['template'] = args.viewer_template
write_config()
# --- end set config --- # --- end set config ---
if args.favorites: if args.favorites:

View File

@ -1,8 +1,7 @@
#!/usr/bin/env python2.7 #!/usr/bin/env python2.7
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals, print_function
import json import sys
import os
import signal import signal
import platform import platform
import time import time
@ -13,7 +12,7 @@ from nhentai.parser import doujinshi_parser, search_parser, print_doujinshi, fav
from nhentai.doujinshi import Doujinshi from nhentai.doujinshi import Doujinshi
from nhentai.downloader import Downloader from nhentai.downloader import Downloader
from nhentai.logger import logger from nhentai.logger import logger
from nhentai.constant import NHENTAI_CONFIG_FILE, BASE_URL from nhentai.constant import BASE_URL
from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, \ from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, \
paging, check_cookie, signal_handler, DB paging, check_cookie, signal_handler, DB
@ -24,8 +23,13 @@ def main():
logger.info('Using mirror: {0}'.format(BASE_URL)) logger.info('Using mirror: {0}'.format(BASE_URL))
# CONFIG['proxy'] will be changed after cmd_parser() # CONFIG['proxy'] will be changed after cmd_parser()
if constant.CONFIG['proxy']: if constant.CONFIG['proxy']['http']:
logger.info('Using proxy: {0}'.format(constant.CONFIG['proxy'])) logger.info('Using proxy: {0}'.format(constant.CONFIG['proxy']['http']))
if not constant.CONFIG['template']:
constant.CONFIG['template'] = 'default'
logger.info('Using viewer template "{}"'.format(constant.CONFIG['template']))
# check your cookie # check your cookie
check_cookie() check_cookie()
@ -88,7 +92,7 @@ def main():
db.add_one(doujinshi.id) db.add_one(doujinshi.id)
if not options.is_nohtml and not options.is_cbz and not options.is_pdf: if not options.is_nohtml and not options.is_cbz and not options.is_pdf:
generate_html(options.output_dir, doujinshi) generate_html(options.output_dir, doujinshi, template=constant.CONFIG['template'])
elif options.is_cbz: elif options.is_cbz:
generate_cbz(options.output_dir, doujinshi, options.rm_origin_dir) generate_cbz(options.output_dir, doujinshi, options.rm_origin_dir)
elif options.is_pdf: elif options.is_pdf:
@ -108,5 +112,10 @@ def main():
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
if __name__ == '__main__': if __name__ == '__main__':
if sys.version_info < (3, 0, 0):
logger.error('nhentai now only support Python 3.x')
exit(1)
main() main()

View File

@ -1,5 +1,5 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals, print_function
import os import os
import tempfile import tempfile
@ -29,9 +29,10 @@ NHENTAI_HOME = os.path.join(os.getenv('HOME', tempfile.gettempdir()), '.nhentai'
NHENTAI_HISTORY = os.path.join(NHENTAI_HOME, 'history.sqlite3') NHENTAI_HISTORY = os.path.join(NHENTAI_HOME, 'history.sqlite3')
NHENTAI_CONFIG_FILE = os.path.join(NHENTAI_HOME, 'config.json') NHENTAI_CONFIG_FILE = os.path.join(NHENTAI_HOME, 'config.json')
CONFIG = { CONFIG = {
'proxy': {}, 'proxy': {'http': '', 'https': ''},
'cookie': '', 'cookie': '',
'language': '', 'language': '',
'template': '',
} }

View File

@ -1,7 +1,6 @@
# coding: utf-8 # coding: utf-8
from __future__ import print_function, unicode_literals
from tabulate import tabulate from tabulate import tabulate
from future.builtins import range
from nhentai.constant import DETAIL_URL, IMAGE_URL from nhentai.constant import DETAIL_URL, IMAGE_URL
from nhentai.logger import logger from nhentai.logger import logger

View File

@ -1,5 +1,4 @@
# coding: utf- # coding: utf-
from __future__ import unicode_literals, print_function
import multiprocessing import multiprocessing
import signal import signal

View File

@ -1,5 +1,4 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals, print_function
import os import os
import re import re
@ -116,8 +115,11 @@ def doujinshi_parser(id_):
try: try:
response = request('get', url) response = request('get', url)
if response.status_code in (200,): if response.status_code in (200, ):
response = response.content response = response.content
elif response.status_code in (404,):
logger.error("Doujinshi with id {0} cannot be found".format(id_))
return []
else: else:
logger.debug('Slow down and retry ({}) ...'.format(id_)) logger.debug('Slow down and retry ({}) ...'.format(id_))
time.sleep(1) time.sleep(1)

View File

@ -1,10 +1,8 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals, print_function
import sys import sys
import re import re
import os import os
import string
import zipfile import zipfile
import shutil import shutil
import requests import requests
@ -64,7 +62,7 @@ def readfile(path):
return file.read() return file.read()
def generate_html(output_dir='.', doujinshi_obj=None): def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
image_html = '' image_html = ''
if doujinshi_obj is not None: if doujinshi_obj is not None:
@ -81,9 +79,9 @@ def generate_html(output_dir='.', doujinshi_obj=None):
image_html += '<img src="{0}" class="image-item"/>\n'\ image_html += '<img src="{0}" class="image-item"/>\n'\
.format(image) .format(image)
html = readfile('viewer/index.html') html = readfile('viewer/{}/index.html'.format(template))
css = readfile('viewer/styles.css') css = readfile('viewer/{}/styles.css'.format(template))
js = readfile('viewer/scripts.js') js = readfile('viewer/{}/scripts.js'.format(template))
if doujinshi_obj is not None: if doujinshi_obj is not None:
serialize_json(doujinshi_obj, doujinshi_dir) serialize_json(doujinshi_obj, doujinshi_dir)
@ -226,22 +224,31 @@ def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir)) logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
def unicode_truncate(s, length, encoding='utf-8'):
"""https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
"""
encoded = s.encode(encoding)[:length]
return encoded.decode(encoding, 'ignore')
def format_filename(s): def format_filename(s):
"""Take a string and return a valid filename constructed from the string. """
Uses a whitelist approach: any characters not present in valid_chars are It used to be a whitelist approach allowed only alphabet and a part of symbols.
removed. Also spaces are replaced with underscores. but most doujinshi's names include Japanese 2-byte characters and these was rejected.
so it is using blacklist approach now.
Note: this method may produce invalid filenames such as ``, `.` or `..` if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' ').
When I use this method I prepend a date string like '2009_01_15_19_46_32_' """
and append a file extension like '.txt', so I avoid the potential of using
an invalid filename.
"""
# maybe you can use `--format` to select a suitable filename # maybe you can use `--format` to select a suitable filename
valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits) ban_chars = '\\\'/:,;*?"<>|\t'
filename = ''.join(c for c in s if c in valid_chars) filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars))).strip()
filename = ' '.join(filename.split())
print(repr(filename))
while filename.endswith('.'):
filename = filename[:-1]
if len(filename) > 100: if len(filename) > 100:
filename = filename[:100] + '...]' filename = filename[:100] + u''
# Remove [] from filename # Remove [] from filename
filename = filename.replace('[]', '').strip() filename = filename.replace('[]', '').strip()