mirror of
https://github.com/RicterZ/nhentai.git
synced 2025-07-01 16:09:28 +02:00
Compare commits
74 Commits
Author | SHA1 | Date | |
---|---|---|---|
74197f8f90 | |||
6d91a39533 | |||
e181e0b9dd | |||
6fed1f94cb | |||
9cfb23c8ec | |||
fc347cdadf | |||
1cdebaab61 | |||
9513141ccf | |||
bdc9fa113e | |||
36946111db | |||
ce8ae54536 | |||
7aedb905d6 | |||
8b8b5f193e | |||
fc99d91ac1 | |||
ba141efba7 | |||
f78d8750f3 | |||
08bb8ffda4 | |||
af379c825c | |||
2f9386f22c | |||
3667bc34b7 | |||
84749c56bd | |||
24f79e0945 | |||
edc46a9531 | |||
72035a14e6 | |||
472528e464 | |||
3f5915fd2a | |||
0cd2576dab | |||
445a8c052e | |||
7a75afef0a | |||
a5813e19b1 | |||
8462d2f2aa | |||
51074ee948 | |||
9c7354be32 | |||
7f48b3edd1 | |||
d84b827241 | |||
4ac161a38c | |||
648b6f87bf | |||
2ec1283ba8 | |||
a9bd46b426 | |||
c52bc271fc | |||
f2d22f8e7d | |||
ea6089ff31 | |||
670d14c3f3 | |||
b46106a5bc | |||
f04359e486 | |||
6861cbcbc1 | |||
e0938c5a0e | |||
641f8e4c51 | |||
b2fae226f9 | |||
4aa34c668a | |||
f157ac3246 | |||
139e01d3ca | |||
4d870e36a1 | |||
74b0df26a9 | |||
1746e731ec | |||
8ad60d9838 | |||
be05b9c0eb | |||
9054b98934 | |||
b82201ff27 | |||
532c74e075 | |||
5a50a5b1ba | |||
b5fe48746e | |||
94d8da655a | |||
6ff2816d95 | |||
4d89b80e67 | |||
0a94ef9cf1 | |||
4cc4f35a0d | |||
ad86c49de9 | |||
5a538fe82f | |||
eb35ba9848 | |||
b0902c2d58 | |||
320f36c264 | |||
1dae63be39 | |||
8ed1b89277 |
@ -4,13 +4,14 @@ os:
|
||||
language: python
|
||||
python:
|
||||
- 3.7
|
||||
- 3.8
|
||||
|
||||
install:
|
||||
- python setup.py install
|
||||
|
||||
script:
|
||||
- echo 268642 > /tmp/test.txt
|
||||
- nhentai --cookie "_ga=GA1.2.2000087053.1558179358; __cfduid=d8930f7b43d04e1b2117719e28386b2e31593148489; csrftoken=3914GQGSmmqQyfQTBswNgfXuhFiefu8sAgOnsfZWiiqS4PJpKivuTp34p2USV6xu; sessionid=be0w2lwlprlmld3ahg9i592ipsuaw840"
|
||||
- nhentai --cookie "_ga=GA1.2.1651446371.1545407218; __cfduid=d0ed34dfb81167d2a51a1d6392c1768a81601380350; csrftoken=KRN0GR1ft86m3HTefpQA99pp6R1Bo7hUs5QxNGOAIuwB5g4EcJj04fwMB8QKgLaB; sessionid=7hzoowox78c90wi5ud5ibphm4axcck7c"
|
||||
- nhentai --search umaru
|
||||
- nhentai --id=152503,146134 -t 10 --output=/tmp/ --cbz
|
||||
- nhentai -F
|
||||
|
@ -1,8 +1,4 @@
|
||||
include README.md
|
||||
include requirements.txt
|
||||
include nhentai/viewer/index.html
|
||||
include nhentai/viewer/styles.css
|
||||
include nhentai/viewer/scripts.js
|
||||
include nhentai/viewer/main.html
|
||||
include nhentai/viewer/main.css
|
||||
include nhentai/viewer/main.js
|
||||
include nhentai/viewer/*
|
||||
include nhentai/viewer/default/*
|
@ -1,3 +1,3 @@
|
||||
__version__ = '0.4.1'
|
||||
__version__ = '0.4.14'
|
||||
__author__ = 'RicterZ'
|
||||
__email__ = 'ricterzheng@gmail.com'
|
||||
|
@ -1,8 +1,10 @@
|
||||
# coding: utf-8
|
||||
from __future__ import print_function
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
from optparse import OptionParser
|
||||
|
||||
try:
|
||||
from itertools import ifilter as filter
|
||||
except ImportError:
|
||||
@ -13,17 +15,6 @@ from nhentai import __version__
|
||||
from nhentai.utils import urlparse, generate_html, generate_main_html, DB
|
||||
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():
|
||||
logger.info(u'''nHentai ver %s: あなたも変態。 いいね?
|
||||
@ -35,7 +26,29 @@ def banner():
|
||||
''' % __version__)
|
||||
|
||||
|
||||
def load_config():
|
||||
if not os.path.exists(constant.NHENTAI_CONFIG_FILE):
|
||||
return
|
||||
|
||||
try:
|
||||
with open(constant.NHENTAI_CONFIG_FILE, 'r') as f:
|
||||
constant.CONFIG.update(json.load(f))
|
||||
except json.JSONDecodeError:
|
||||
logger.error('Failed to load config file.')
|
||||
write_config()
|
||||
|
||||
|
||||
def write_config():
|
||||
if not os.path.exists(constant.NHENTAI_HOME):
|
||||
os.mkdir(constant.NHENTAI_HOME)
|
||||
|
||||
with open(constant.NHENTAI_CONFIG_FILE, 'w') as f:
|
||||
f.write(json.dumps(constant.CONFIG))
|
||||
|
||||
|
||||
def cmd_parser():
|
||||
load_config()
|
||||
|
||||
parser = OptionParser('\n nhentai --search [keyword] --download'
|
||||
'\n NHENTAI=http://h.loli.club nhentai --id [ID ...]'
|
||||
'\n nhentai --file [filename]'
|
||||
@ -54,16 +67,16 @@ def cmd_parser():
|
||||
help='list or download your favorites.')
|
||||
|
||||
# page options
|
||||
parser.add_option('--page', type='int', dest='page', action='store', default=1,
|
||||
help='page number of search results')
|
||||
parser.add_option('--page-range', type='string', dest='page_range', action='store',
|
||||
help='page range of favorites. e.g. 1,2-5,14')
|
||||
parser.add_option('--page-all', dest='page_all', action='store_true', default=False,
|
||||
help='all search results')
|
||||
parser.add_option('--page', '--page-range', type='string', dest='page', action='store', default='',
|
||||
help='page number of search results. e.g. 1,2-5,14')
|
||||
parser.add_option('--sorting', dest='sorting', action='store', default='recent',
|
||||
help='sorting of doujinshi (recent / popular / popular-[today|week])',
|
||||
choices=['recent', 'popular', 'popular-today', 'popular-week'])
|
||||
|
||||
# download options
|
||||
parser.add_option('--output', '-o', type='string', dest='output_dir', action='store', default='',
|
||||
parser.add_option('--output', '-o', type='string', dest='output_dir', action='store', default='./',
|
||||
help='output dir')
|
||||
parser.add_option('--threads', '-t', type='int', dest='threads', action='store', default=5,
|
||||
help='thread count for downloading doujinshi')
|
||||
@ -71,7 +84,7 @@ def cmd_parser():
|
||||
help='timeout for downloading doujinshi')
|
||||
parser.add_option('--delay', '-d', type='int', dest='delay', action='store', default=0,
|
||||
help='slow down between downloading every doujinshi')
|
||||
parser.add_option('--proxy', '-p', type='string', dest='proxy', action='store', default='',
|
||||
parser.add_option('--proxy', type='string', dest='proxy', action='store',
|
||||
help='store a proxy, for example: -p \'http://127.0.0.1:1080\'')
|
||||
parser.add_option('--file', '-f', type='string', dest='file', action='store', help='read gallery IDs from file.')
|
||||
parser.add_option('--format', type='string', dest='name_format', action='store',
|
||||
@ -96,14 +109,17 @@ def cmd_parser():
|
||||
help='set cookie of nhentai to bypass Google recaptcha')
|
||||
parser.add_option('--language', type='str', dest='language', action='store',
|
||||
help='set default language to parse doujinshis')
|
||||
parser.add_option('--clean-language', dest='clean_language', action='store_true', default=False,
|
||||
help='set DEFAULT as language to parse doujinshis')
|
||||
parser.add_option('--save-download-history', dest='is_save_download_history', action='store_true',
|
||||
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',
|
||||
help='clean download history')
|
||||
parser.add_option('--template', dest='viewer_template', action='store',
|
||||
help='set viewer template', default='')
|
||||
|
||||
try:
|
||||
sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv]
|
||||
print()
|
||||
except (NameError, TypeError):
|
||||
pass
|
||||
except UnicodeDecodeError:
|
||||
@ -126,69 +142,50 @@ def cmd_parser():
|
||||
logger.info('Download history cleaned.')
|
||||
exit(0)
|
||||
|
||||
if os.path.exists(constant.NHENTAI_COOKIE):
|
||||
with open(constant.NHENTAI_COOKIE, 'r') as f:
|
||||
constant.COOKIE = f.read()
|
||||
|
||||
if args.cookie:
|
||||
try:
|
||||
if not os.path.exists(constant.NHENTAI_HOME):
|
||||
os.mkdir(constant.NHENTAI_HOME)
|
||||
|
||||
with open(constant.NHENTAI_COOKIE, 'w') as f:
|
||||
f.write(args.cookie)
|
||||
except Exception as e:
|
||||
logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
|
||||
exit(1)
|
||||
|
||||
# --- set config ---
|
||||
if args.cookie is not None:
|
||||
constant.CONFIG['cookie'] = args.cookie
|
||||
logger.info('Cookie saved.')
|
||||
write_config()
|
||||
exit(0)
|
||||
|
||||
if os.path.exists(constant.NHENTAI_LANGUAGE) and not args.language:
|
||||
with open(constant.NHENTAI_LANGUAGE, 'r') as f:
|
||||
constant.LANGUAGE = f.read()
|
||||
args.language = f.read()
|
||||
|
||||
if args.language:
|
||||
try:
|
||||
if not os.path.exists(constant.NHENTAI_HOME):
|
||||
os.mkdir(constant.NHENTAI_HOME)
|
||||
|
||||
with open(constant.NHENTAI_LANGUAGE, 'w') as f:
|
||||
f.write(args.language)
|
||||
except Exception as e:
|
||||
logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
|
||||
exit(1)
|
||||
|
||||
logger.info('Default language now is {}.'.format(args.language))
|
||||
if args.language is not None:
|
||||
constant.CONFIG['language'] = args.language
|
||||
logger.info('Default language now set to \'{0}\''.format(args.language))
|
||||
write_config()
|
||||
exit(0)
|
||||
# TODO: search without language
|
||||
|
||||
if os.path.exists(constant.NHENTAI_PROXY):
|
||||
with open(constant.NHENTAI_PROXY, 'r') as f:
|
||||
link = f.read()
|
||||
constant.PROXY = {'http': link, 'https': link}
|
||||
|
||||
if args.proxy:
|
||||
try:
|
||||
if not os.path.exists(constant.NHENTAI_HOME):
|
||||
os.mkdir(constant.NHENTAI_HOME)
|
||||
|
||||
if args.proxy is not None:
|
||||
proxy_url = urlparse(args.proxy)
|
||||
if proxy_url.scheme not in ('http', 'https'):
|
||||
if not args.proxy == '' and proxy_url.scheme not in ('http', 'https'):
|
||||
logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
|
||||
else:
|
||||
with open(constant.NHENTAI_PROXY, 'w') as f:
|
||||
f.write(args.proxy)
|
||||
|
||||
except Exception as e:
|
||||
logger.error('Cannot create NHENTAI_HOME: {}'.format(str(e)))
|
||||
exit(1)
|
||||
|
||||
logger.info('Proxy \'{0}\' saved.'.format(args.proxy))
|
||||
exit(0)
|
||||
else:
|
||||
constant.CONFIG['proxy'] = {
|
||||
'http': args.proxy,
|
||||
'https': args.proxy,
|
||||
}
|
||||
logger.info('Proxy now set to \'{0}\'.'.format(args.proxy))
|
||||
write_config()
|
||||
exit(0)
|
||||
|
||||
if args.viewer_template is not None:
|
||||
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 ---
|
||||
|
||||
if args.favorites:
|
||||
if not constant.COOKIE:
|
||||
if not constant.CONFIG['cookie']:
|
||||
logger.warning('Cookie has not been set, please use `nhentai --cookie \'COOKIE\'` to set it.')
|
||||
exit(1)
|
||||
|
||||
|
@ -1,28 +1,40 @@
|
||||
#!/usr/bin/env python2.7
|
||||
# coding: utf-8
|
||||
from __future__ import unicode_literals, print_function
|
||||
|
||||
import sys
|
||||
import signal
|
||||
import platform
|
||||
import time
|
||||
|
||||
from nhentai import constant
|
||||
from nhentai.cmdline import cmd_parser, banner
|
||||
from nhentai.parser import doujinshi_parser, search_parser, print_doujinshi, favorites_parser
|
||||
from nhentai.doujinshi import Doujinshi
|
||||
from nhentai.downloader import Downloader
|
||||
from nhentai.logger import logger
|
||||
from nhentai.constant import BASE_URL
|
||||
from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, check_cookie, signal_handler, DB
|
||||
from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, \
|
||||
paging, check_cookie, signal_handler, DB
|
||||
|
||||
|
||||
def main():
|
||||
banner()
|
||||
|
||||
if sys.version_info < (3, 0, 0):
|
||||
logger.error('nhentai now only support Python 3.x')
|
||||
exit(1)
|
||||
|
||||
options = cmd_parser()
|
||||
logger.info('Using mirror: {0}'.format(BASE_URL))
|
||||
|
||||
from nhentai.constant import PROXY
|
||||
# constant.PROXY will be changed after cmd_parser()
|
||||
if PROXY:
|
||||
logger.info('Using proxy: {0}'.format(PROXY))
|
||||
# CONFIG['proxy'] will be changed after cmd_parser()
|
||||
if constant.CONFIG['proxy']['http']:
|
||||
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_cookie()
|
||||
@ -31,18 +43,20 @@ def main():
|
||||
doujinshi_ids = []
|
||||
doujinshi_list = []
|
||||
|
||||
page_list = paging(options.page)
|
||||
|
||||
if options.favorites:
|
||||
if not options.is_download:
|
||||
logger.warning('You do not specify --download option')
|
||||
|
||||
doujinshis = favorites_parser(options.page_range)
|
||||
doujinshis = favorites_parser(page=page_list)
|
||||
|
||||
elif options.keyword:
|
||||
from nhentai.constant import LANGUAGE
|
||||
if LANGUAGE:
|
||||
logger.info('Using deafult language: {0}'.format(LANGUAGE))
|
||||
options.keyword += ', language:{}'.format(LANGUAGE)
|
||||
doujinshis = search_parser(options.keyword, sorting=options.sorting, page=options.page)
|
||||
if constant.CONFIG['language']:
|
||||
logger.info('Using default language: {0}'.format(constant.CONFIG['language']))
|
||||
options.keyword += ' language:{}'.format(constant.CONFIG['language'])
|
||||
doujinshis = search_parser(options.keyword, sorting=options.sorting, page=page_list,
|
||||
is_page_all=options.page_all)
|
||||
|
||||
elif not doujinshi_ids:
|
||||
doujinshi_ids = options.id
|
||||
@ -53,9 +67,9 @@ def main():
|
||||
|
||||
if options.is_save_download_history:
|
||||
with DB() as db:
|
||||
data = set(db.get_all())
|
||||
data = map(int, db.get_all())
|
||||
|
||||
doujinshi_ids = list(set(doujinshi_ids) - data)
|
||||
doujinshi_ids = list(set(doujinshi_ids) - set(data))
|
||||
|
||||
if doujinshi_ids:
|
||||
for i, id_ in enumerate(doujinshi_ids):
|
||||
@ -83,7 +97,7 @@ def main():
|
||||
db.add_one(doujinshi.id)
|
||||
|
||||
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:
|
||||
generate_cbz(options.output_dir, doujinshi, options.rm_origin_dir)
|
||||
elif options.is_pdf:
|
||||
@ -103,5 +117,6 @@ def main():
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
@ -1,5 +1,5 @@
|
||||
# coding: utf-8
|
||||
from __future__ import unicode_literals, print_function
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
@ -26,12 +26,13 @@ u = urlparse(BASE_URL)
|
||||
IMAGE_URL = '%s://i.%s/galleries' % (u.scheme, u.hostname)
|
||||
|
||||
NHENTAI_HOME = os.path.join(os.getenv('HOME', tempfile.gettempdir()), '.nhentai')
|
||||
NHENTAI_PROXY = os.path.join(NHENTAI_HOME, 'proxy')
|
||||
NHENTAI_COOKIE = os.path.join(NHENTAI_HOME, 'cookie')
|
||||
NHENTAI_LANGUAGE = os.path.join(NHENTAI_HOME, 'language')
|
||||
NHENTAI_HISTORY = os.path.join(NHENTAI_HOME, 'history.sqlite3')
|
||||
NHENTAI_CONFIG_FILE = os.path.join(NHENTAI_HOME, 'config.json')
|
||||
|
||||
PROXY = {}
|
||||
|
||||
COOKIE = ''
|
||||
LANGUAGE = ''
|
||||
CONFIG = {
|
||||
'proxy': {'http': '', 'https': ''},
|
||||
'cookie': '',
|
||||
'language': '',
|
||||
'template': '',
|
||||
}
|
||||
|
@ -1,7 +1,6 @@
|
||||
# coding: utf-8
|
||||
from __future__ import print_function, unicode_literals
|
||||
|
||||
from tabulate import tabulate
|
||||
from future.builtins import range
|
||||
|
||||
from nhentai.constant import DETAIL_URL, IMAGE_URL
|
||||
from nhentai.logger import logger
|
||||
@ -48,6 +47,7 @@ class Doujinshi(object):
|
||||
|
||||
def show(self):
|
||||
table = [
|
||||
["Parodies", self.info.parodies],
|
||||
["Doujinshi", self.name],
|
||||
["Subtitle", self.info.subtitle],
|
||||
["Characters", self.info.characters],
|
||||
|
@ -1,5 +1,4 @@
|
||||
# coding: utf-
|
||||
from __future__ import unicode_literals, print_function
|
||||
|
||||
import multiprocessing
|
||||
import signal
|
||||
@ -120,14 +119,14 @@ class Downloader(Singleton):
|
||||
folder = os.path.join(self.path, folder)
|
||||
|
||||
if not os.path.exists(folder):
|
||||
logger.warn('Path \'{0}\' does not exist, creating.'.format(folder))
|
||||
logger.warning('Path \'{0}\' does not exist, creating.'.format(folder))
|
||||
try:
|
||||
os.makedirs(folder)
|
||||
except EnvironmentError as e:
|
||||
logger.critical('{0}'.format(str(e)))
|
||||
|
||||
else:
|
||||
logger.warn('Path \'{0}\' already exist.'.format(folder))
|
||||
logger.warning('Path \'{0}\' already exist.'.format(folder))
|
||||
|
||||
queue = [(self, url, folder) for url in queue]
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
#
|
||||
# Copyright (C) 2010-2012 Vinay Sajip. All rights reserved. Licensed under the new BSD license.
|
||||
#
|
||||
from __future__ import print_function, unicode_literals
|
||||
import logging
|
||||
import re
|
||||
import platform
|
||||
@ -174,7 +173,7 @@ logger.setLevel(logging.DEBUG)
|
||||
if __name__ == '__main__':
|
||||
logger.log(15, 'nhentai')
|
||||
logger.info('info')
|
||||
logger.warn('warn')
|
||||
logger.warning('warning')
|
||||
logger.debug('debug')
|
||||
logger.error('error')
|
||||
logger.critical('critical')
|
||||
|
@ -1,7 +1,5 @@
|
||||
# coding: utf-8
|
||||
from __future__ import unicode_literals, print_function
|
||||
|
||||
import sys
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
@ -64,7 +62,7 @@ def _get_title_and_id(response):
|
||||
return result
|
||||
|
||||
|
||||
def favorites_parser(page_range=''):
|
||||
def favorites_parser(page=None):
|
||||
result = []
|
||||
html = BeautifulSoup(request('get', constant.FAV_URL).content, 'html.parser')
|
||||
count = html.find('span', attrs={'class': 'count'})
|
||||
@ -78,6 +76,9 @@ def favorites_parser(page_range=''):
|
||||
return []
|
||||
pages = int(count / 25)
|
||||
|
||||
if page:
|
||||
page_range_list = page
|
||||
else:
|
||||
if pages:
|
||||
pages += 1 if count % (25 * pages) else 0
|
||||
else:
|
||||
@ -89,9 +90,6 @@ def favorites_parser(page_range=''):
|
||||
pages = 1
|
||||
|
||||
page_range_list = range(1, pages + 1)
|
||||
if page_range:
|
||||
logger.info('page range is {0}'.format(page_range))
|
||||
page_range_list = page_range_parser(page_range, pages)
|
||||
|
||||
for page in page_range_list:
|
||||
try:
|
||||
@ -105,32 +103,6 @@ def favorites_parser(page_range=''):
|
||||
return result
|
||||
|
||||
|
||||
def page_range_parser(page_range, max_page_num):
|
||||
pages = set()
|
||||
ranges = str.split(page_range, ',')
|
||||
for range_str in ranges:
|
||||
idx = range_str.find('-')
|
||||
if idx == -1:
|
||||
try:
|
||||
page = int(range_str)
|
||||
if page <= max_page_num:
|
||||
pages.add(page)
|
||||
except ValueError:
|
||||
logger.error('page range({0}) is not valid'.format(page_range))
|
||||
else:
|
||||
try:
|
||||
left = int(range_str[:idx])
|
||||
right = int(range_str[idx + 1:])
|
||||
if right > max_page_num:
|
||||
right = max_page_num
|
||||
for page in range(left, right + 1):
|
||||
pages.add(page)
|
||||
except ValueError:
|
||||
logger.error('page range({0}) is not valid'.format(page_range))
|
||||
|
||||
return list(pages)
|
||||
|
||||
|
||||
def doujinshi_parser(id_):
|
||||
if not isinstance(id_, (int,)) and (isinstance(id_, (str,)) and not id_.isdigit()):
|
||||
raise Exception('Doujinshi id({0}) is not valid'.format(id_))
|
||||
@ -145,13 +117,16 @@ def doujinshi_parser(id_):
|
||||
response = request('get', url)
|
||||
if response.status_code in (200, ):
|
||||
response = response.content
|
||||
elif response.status_code in (404,):
|
||||
logger.error("Doujinshi with id {0} cannot be found".format(id_))
|
||||
return []
|
||||
else:
|
||||
logger.debug('Slow down and retry ({}) ...'.format(id_))
|
||||
time.sleep(1)
|
||||
return doujinshi_parser(str(id_))
|
||||
|
||||
except Exception as e:
|
||||
logger.warn('Error: {}, ignored'.format(str(e)))
|
||||
logger.warning('Error: {}, ignored'.format(str(e)))
|
||||
return None
|
||||
|
||||
html = BeautifulSoup(response, 'html.parser')
|
||||
@ -205,7 +180,7 @@ def old_search_parser(keyword, sorting='date', page=1):
|
||||
|
||||
result = _get_title_and_id(response)
|
||||
if not result:
|
||||
logger.warn('Not found anything of keyword {}'.format(keyword))
|
||||
logger.warning('Not found anything of keyword {}'.format(keyword))
|
||||
|
||||
return result
|
||||
|
||||
@ -215,30 +190,39 @@ def print_doujinshi(doujinshi_list):
|
||||
return
|
||||
doujinshi_list = [(i['id'], i['title']) for i in doujinshi_list]
|
||||
headers = ['id', 'doujinshi']
|
||||
logger.info('Search Result\n' +
|
||||
logger.info('Search Result || Found %i doujinshis \n' % doujinshi_list.__len__() +
|
||||
tabulate(tabular_data=doujinshi_list, headers=headers, tablefmt='rst'))
|
||||
|
||||
|
||||
def search_parser(keyword, sorting, page):
|
||||
logger.debug('Searching doujinshis using keywords {0}'.format(keyword))
|
||||
keyword = '+'.join([i.strip().replace(' ', '-').lower() for i in keyword.split(',')])
|
||||
def search_parser(keyword, sorting, page, is_page_all=False):
|
||||
# keyword = '+'.join([i.strip().replace(' ', '-').lower() for i in keyword.split(',')])
|
||||
result = []
|
||||
if not page:
|
||||
page = [1]
|
||||
|
||||
if is_page_all:
|
||||
url = request('get', url=constant.SEARCH_URL, params={'query': keyword}).url
|
||||
init_response = request('get', url.replace('%2B', '+')).json()
|
||||
page = range(1, init_response['num_pages']+1)
|
||||
|
||||
total = '/{0}'.format(page[-1]) if is_page_all else ''
|
||||
for p in page:
|
||||
i = 0
|
||||
while i < 5:
|
||||
|
||||
logger.info('Searching doujinshis using keywords "{0}" on page {1}{2}'.format(keyword, p, total))
|
||||
while i < 3:
|
||||
try:
|
||||
url = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page, 'sort': sorting}).url
|
||||
url = request('get', url=constant.SEARCH_URL, params={'query': keyword,
|
||||
'page': p, 'sort': sorting}).url
|
||||
response = request('get', url.replace('%2B', '+')).json()
|
||||
except Exception as e:
|
||||
i += 1
|
||||
if not i < 5:
|
||||
logger.critical(str(e))
|
||||
logger.warn('If you are in China, please configure the proxy to fu*k GFW.')
|
||||
exit(1)
|
||||
continue
|
||||
|
||||
break
|
||||
|
||||
if 'result' not in response:
|
||||
raise Exception('No result in response')
|
||||
logger.warning('No result in response in page {}'.format(p))
|
||||
break
|
||||
|
||||
for row in response['result']:
|
||||
title = row['title']['english']
|
||||
@ -246,7 +230,7 @@ def search_parser(keyword, sorting, page):
|
||||
result.append({'id': row['id'], 'title': title})
|
||||
|
||||
if not result:
|
||||
logger.warn('No results for keywords {}'.format(keyword))
|
||||
logger.warning('No results for keywords {}'.format(keyword))
|
||||
|
||||
return result
|
||||
|
||||
|
@ -1,10 +1,8 @@
|
||||
# coding: utf-8
|
||||
from __future__ import unicode_literals, print_function
|
||||
|
||||
import sys
|
||||
import re
|
||||
import os
|
||||
import string
|
||||
import zipfile
|
||||
import shutil
|
||||
import requests
|
||||
@ -20,9 +18,9 @@ def request(method, url, **kwargs):
|
||||
session.headers.update({
|
||||
'Referer': constant.LOGIN_URL,
|
||||
'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
|
||||
'Cookie': constant.COOKIE
|
||||
'Cookie': constant.CONFIG['cookie']
|
||||
})
|
||||
return getattr(session, method)(url, proxies=constant.PROXY, verify=False, **kwargs)
|
||||
return getattr(session, method)(url, proxies=constant.CONFIG['proxy'], verify=False, **kwargs)
|
||||
|
||||
|
||||
def check_cookie():
|
||||
@ -64,7 +62,7 @@ def readfile(path):
|
||||
return file.read()
|
||||
|
||||
|
||||
def generate_html(output_dir='.', doujinshi_obj=None):
|
||||
def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
|
||||
image_html = ''
|
||||
|
||||
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'\
|
||||
.format(image)
|
||||
html = readfile('viewer/index.html')
|
||||
css = readfile('viewer/styles.css')
|
||||
js = readfile('viewer/scripts.js')
|
||||
html = readfile('viewer/{}/index.html'.format(template))
|
||||
css = readfile('viewer/{}/styles.css'.format(template))
|
||||
js = readfile('viewer/{}/scripts.js'.format(template))
|
||||
|
||||
if doujinshi_obj is not None:
|
||||
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))
|
||||
|
||||
|
||||
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):
|
||||
"""Take a string and return a valid filename constructed from the string.
|
||||
Uses a whitelist approach: any characters not present in valid_chars are
|
||||
removed. Also spaces are replaced with underscores.
|
||||
|
||||
Note: this method may produce invalid filenames such as ``, `.` or `..`
|
||||
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.
|
||||
|
||||
"""
|
||||
It used to be a whitelist approach allowed only alphabet and a part of symbols.
|
||||
but most doujinshi's names include Japanese 2-byte characters and these was rejected.
|
||||
so it is using blacklist approach now.
|
||||
if filename include forbidden characters (\'/:,;*?"<>|) ,it replace space character(' ').
|
||||
"""
|
||||
# maybe you can use `--format` to select a suitable filename
|
||||
valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
|
||||
filename = ''.join(c for c in s if c in valid_chars)
|
||||
ban_chars = '\\\'/:,;*?"<>|\t'
|
||||
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:
|
||||
filename = filename[:100] + '...]'
|
||||
filename = filename[:100] + u'…'
|
||||
|
||||
# Remove [] from filename
|
||||
filename = filename.replace('[]', '').strip()
|
||||
@ -253,6 +260,26 @@ def signal_handler(signal, frame):
|
||||
exit(1)
|
||||
|
||||
|
||||
def paging(page_string):
|
||||
# 1,3-5,14 -> [1, 3, 4, 5, 14]
|
||||
if not page_string:
|
||||
return []
|
||||
|
||||
page_list = []
|
||||
for i in page_string.split(','):
|
||||
if '-' in i:
|
||||
start, end = i.split('-')
|
||||
if not (start.isdigit() and end.isdigit()):
|
||||
raise Exception('Invalid page number')
|
||||
page_list.extend(list(range(int(start), int(end)+1)))
|
||||
else:
|
||||
if not i.isdigit():
|
||||
raise Exception('Invalid page number')
|
||||
page_list.append(int(i))
|
||||
|
||||
return page_list
|
||||
|
||||
|
||||
class DB(object):
|
||||
conn = None
|
||||
cur = None
|
||||
|
Reference in New Issue
Block a user