mirror of
https://github.com/RicterZ/nhentai.git
synced 2025-07-01 16:09:28 +02:00
Compare commits
156 Commits
Author | SHA1 | Date | |
---|---|---|---|
31b95fe2dd | |||
be8c97f8d4 | |||
348e51676e | |||
ea356a1ca2 | |||
5a4dfb8a76 | |||
4b15744ceb | |||
b05fa16286 | |||
0879486881 | |||
c66ba730d3 | |||
606c5e0ffd | |||
ba04f81a6f | |||
6519e6f221 | |||
7594625d72 | |||
4948c8f0c5 | |||
e22a99fa8c | |||
19a1d5c404 | |||
ad1e876611 | |||
1de7e1f998 | |||
b97e707817 | |||
6ef2189bfe | |||
24be2d37d4 | |||
d9d2a6fb91 | |||
bd38294bb7 | |||
2cf4e6718e | |||
8cd4b948e7 | |||
f884384eb3 | |||
87afab46c4 | |||
c7b1d7e6a8 | |||
ad02371158 | |||
7c9d55e0ee | |||
00aad774ae | |||
373086b459 | |||
3a83f99771 | |||
00627ab36a | |||
592e163891 | |||
84523475b0 | |||
5f5461c902 | |||
05e6ceb3cd | |||
db59426503 | |||
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 | |||
14a53a0953 | |||
c5e4b5ffa8 | |||
b3f25875d0 | |||
91053b98af | |||
7570b6ae7d | |||
d2e68c6c45 | |||
b0902c2d58 | |||
320f36c264 | |||
1dae63be39 | |||
78429423d9 | |||
38ff69d99d | |||
2ce36204fe | |||
8ed1b89277 | |||
e9864d158f | |||
43013badd4 | |||
7508a2010d | |||
946761477d | |||
db80408024 | |||
4c85cebb78 | |||
e982a8170c | |||
0b62f0ebd9 | |||
37b4ee7d00 | |||
84cad0d475 | |||
bf03881ed6 | |||
f97b814b45 | |||
7323eae99b | |||
6e07f0426b | |||
44c424a321 | |||
3db77e0ce3 | |||
22dbb4dd0d | |||
2be4bd71ce | |||
fc39aeb49e | |||
be2ec3f452 | |||
0c23f64356 | |||
7e4dff8fec | |||
e2a1d79b1b | |||
8183f3a7a9 | |||
80713d2e00 | |||
a2cd025027 | |||
2f7bb59e58 | |||
e94685d9c5 | |||
07d804b047 | |||
5552d39337 | |||
d35190f9d0 | |||
c8bca4240a | |||
130386054f | |||
c18cd2aaa5 |
2
.gitignore
vendored
2
.gitignore
vendored
@ -6,3 +6,5 @@ dist/
|
||||
.python-version
|
||||
.DS_Store
|
||||
output/
|
||||
venv/
|
||||
.vscode/
|
||||
|
@ -3,18 +3,17 @@ os:
|
||||
|
||||
language: python
|
||||
python:
|
||||
- 2.7
|
||||
- 3.7
|
||||
- 3.8
|
||||
|
||||
install:
|
||||
- python setup.py install
|
||||
|
||||
script:
|
||||
- echo 268642 > /tmp/test.txt
|
||||
- nhentai --cookie "csrftoken=xIh7s9d4NB8qSLN7eJZG9064zsV84aHEYFoAU49Ib9anqmoT0pZRw6TIdayLzQuT; sessionid=un101zfgpglsyffdnsm72le4euuisp7t"
|
||||
- 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 --tag lolicon --sorting popular
|
||||
- nhentai -F
|
||||
- nhentai --file /tmp/test.txt
|
||||
- nhentai --id=152503,146134 --gen-main --output=/tmp/
|
||||
|
@ -1,8 +1,5 @@
|
||||
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/*
|
||||
include nhentai/viewer/minimal/*
|
101
README.rst
101
README.rst
@ -19,15 +19,30 @@ nhentai
|
||||
|
||||
nHentai is a CLI tool for downloading doujinshi from <http://nhentai.net>
|
||||
|
||||
============
|
||||
Installation
|
||||
============
|
||||
===================
|
||||
Manual Installation
|
||||
===================
|
||||
.. code-block::
|
||||
|
||||
git clone https://github.com/RicterZ/nhentai
|
||||
cd nhentai
|
||||
python setup.py install
|
||||
|
||||
|
||||
==================
|
||||
Installation (pip)
|
||||
==================
|
||||
Alternatively, install from PyPI with pip:
|
||||
|
||||
.. code-block::
|
||||
|
||||
pip install nhentai
|
||||
|
||||
For a self-contained installation, use `Pipx <https://github.com/pipxproject/pipx/>`_:
|
||||
|
||||
.. code-block::
|
||||
|
||||
pipx install nhentai
|
||||
|
||||
=====================
|
||||
Installation (Gentoo)
|
||||
=====================
|
||||
@ -35,7 +50,14 @@ Installation (Gentoo)
|
||||
|
||||
layman -fa glicOne
|
||||
sudo emerge net-misc/nhentai
|
||||
|
||||
=====================
|
||||
Installation (NixOs)
|
||||
=====================
|
||||
.. code-block::
|
||||
|
||||
nix-env -iA nixos.nhentai
|
||||
|
||||
=====
|
||||
Usage
|
||||
=====
|
||||
@ -50,6 +72,20 @@ Set your nhentai cookie against captcha:
|
||||
|
||||
nhentai --cookie "YOUR COOKIE FROM nhentai.net"
|
||||
|
||||
**NOTE**
|
||||
|
||||
- The format of the cookie is `"csrftoken=TOKEN; sessionid=ID; cf_clearance=CLOUDFLARE"`
|
||||
- `cf_clearance` cookie and useragent must be set if you encounter "blocked by cloudflare captcha" error. Make sure you use the same IP and useragent as when you got it
|
||||
|
||||
| To get csrftoken and sessionid, first login to your nhentai account in web browser, then:
|
||||
| (Chrome) |ve| |ld| More tools |ld| Developer tools |ld| Application |ld| Storage |ld| Cookies |ld| https://nhentai.net
|
||||
| (Firefox) |hv| |ld| Web Developer |ld| Web Developer Tools |ld| Storage |ld| Cookies |ld| https://nhentai.net
|
||||
|
|
||||
|
||||
.. |hv| unicode:: U+2630 .. https://www.compart.com/en/unicode/U+2630
|
||||
.. |ve| unicode:: U+22EE .. https://www.compart.com/en/unicode/U+22EE
|
||||
.. |ld| unicode:: U+2014 .. https://www.compart.com/en/unicode/U+2014
|
||||
|
||||
Download specified doujinshi:
|
||||
|
||||
.. code-block:: bash
|
||||
@ -62,53 +98,20 @@ Download doujinshi with ids specified in a file (doujinshi ids split by line):
|
||||
|
||||
nhentai --file=doujinshi.txt
|
||||
|
||||
Set search default language
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --language=english
|
||||
|
||||
Search a keyword and download the first page:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --search="tomori" --page=1 --download
|
||||
|
||||
Download by tag name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --tag lolicon --download --page=2
|
||||
|
||||
Download by language:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --language english --download --page=2
|
||||
|
||||
Download by artist name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --artist henreader --download
|
||||
|
||||
Download by character name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --character "kuro von einsbern" --download
|
||||
|
||||
Download by parody name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --parody "the idolmaster" --download
|
||||
|
||||
Download by group name:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --group clesta --download
|
||||
|
||||
Download using multiple tags (--tag, --character, --paordy and --group supported):
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
nhentai --tag "lolicon, teasing" --artist "tamano kedama, atte nanakusa"
|
||||
# you also can download by tags and multiple keywords
|
||||
nhentai --search="tag:lolicon, artist:henreader, tag:full color"
|
||||
nhentai --search="lolicon, henreader, full color"
|
||||
|
||||
Download your favorites with delay:
|
||||
|
||||
@ -128,6 +131,7 @@ Supported doujinshi folder formatter:
|
||||
- %t: Doujinshi name
|
||||
- %s: Doujinshi subtitle (translated name)
|
||||
- %a: Doujinshi authors' name
|
||||
- %p: Doujinshi pretty name
|
||||
|
||||
|
||||
Other options:
|
||||
@ -170,8 +174,9 @@ Other options:
|
||||
--no-html don't generate HTML after downloading
|
||||
--gen-main generate a main viewer contain all the doujin in the folder
|
||||
-C, --cbz generate Comic Book CBZ File
|
||||
-P --pdf generate PDF file
|
||||
--rm-origin-dir remove downloaded doujinshi dir when generated CBZ
|
||||
file.
|
||||
or PDF file.
|
||||
|
||||
# nHentai options
|
||||
--cookie=COOKIE set cookie of nhentai to bypass Google recaptcha
|
||||
@ -183,7 +188,7 @@ nHentai Mirror
|
||||
If you want to use a mirror, you should set up a reverse proxy of `nhentai.net` and `i.nhentai.net`.
|
||||
For example:
|
||||
|
||||
.. code-block::
|
||||
.. code-block::
|
||||
|
||||
i.h.loli.club -> i.nhentai.net
|
||||
h.loli.club -> nhentai.net
|
||||
|
@ -1,3 +1,3 @@
|
||||
__version__ = '0.3.8'
|
||||
__version__ = '0.4.17'
|
||||
__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,10 +26,32 @@ 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]'
|
||||
'\n nhentai --file [filename]'
|
||||
'\n\nEnvironment Variable:\n'
|
||||
' NHENTAI nhentai mirror url')
|
||||
# operation options
|
||||
@ -50,29 +63,20 @@ def cmd_parser():
|
||||
parser.add_option('--id', type='string', dest='id', action='store', help='doujinshi ids set, e.g. 1,2,3')
|
||||
parser.add_option('--search', '-s', type='string', dest='keyword', action='store',
|
||||
help='search doujinshi by keyword')
|
||||
parser.add_option('--tag', type='string', dest='tag', action='store', help='download doujinshi by tag')
|
||||
parser.add_option('--artist', type='string', dest='artist', action='store', help='download doujinshi by artist')
|
||||
parser.add_option('--character', type='string', dest='character', action='store',
|
||||
help='download doujinshi by character')
|
||||
parser.add_option('--parody', type='string', dest='parody', action='store', help='download doujinshi by parody')
|
||||
parser.add_option('--group', type='string', dest='group', action='store', help='download doujinshi by group')
|
||||
parser.add_option('--language', type='string', dest='language', action='store',
|
||||
help='download doujinshi by language')
|
||||
parser.add_option('--favorites', '-F', action='store_true', dest='favorites',
|
||||
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('--max-page', type='int', dest='max_page', action='store', default=1,
|
||||
help='The max page when recursive download tagged doujinshi')
|
||||
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('--sorting', dest='sorting', action='store', default='date',
|
||||
help='sorting of doujinshi (date / popular)', choices=['date', 'popular'])
|
||||
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')
|
||||
@ -80,11 +84,12 @@ 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('--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',
|
||||
help='format the saved folder name', default='[%i][%a][%t]')
|
||||
parser.add_option('--dry-run', '-r', action='store_true', dest='dryrun', help='Dry run, skip file download.')
|
||||
|
||||
# generate options
|
||||
parser.add_option('--html', dest='html_viewer', action='store_true',
|
||||
@ -95,20 +100,31 @@ def cmd_parser():
|
||||
help='generate a main viewer contain all the doujin in the folder')
|
||||
parser.add_option('--cbz', '-C', dest='is_cbz', action='store_true',
|
||||
help='generate Comic Book CBZ File')
|
||||
parser.add_option('--pdf', '-P', dest='is_pdf', action='store_true',
|
||||
help='generate PDF file')
|
||||
parser.add_option('--rm-origin-dir', dest='rm_origin_dir', action='store_true', default=False,
|
||||
help='remove downloaded doujinshi dir when generated CBZ file.')
|
||||
help='remove downloaded doujinshi dir when generated CBZ or PDF file.')
|
||||
parser.add_option('--meta', dest='generate_metadata', action='store_true',
|
||||
help='generate a metadata file in doujinshi format')
|
||||
|
||||
# nhentai options
|
||||
parser.add_option('--cookie', type='str', dest='cookie', action='store',
|
||||
help='set cookie of nhentai to bypass Google recaptcha')
|
||||
help='set cookie of nhentai to bypass Cloudflare captcha')
|
||||
parser.add_option('--useragent', type='str', dest='useragent', action='store',
|
||||
help='set useragent to bypass Cloudflare captcha')
|
||||
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:
|
||||
@ -117,12 +133,10 @@ def cmd_parser():
|
||||
args, _ = parser.parse_args(sys.argv[1:])
|
||||
|
||||
if args.html_viewer:
|
||||
generate_html()
|
||||
generate_html(template=constant.CONFIG['template'])
|
||||
exit(0)
|
||||
|
||||
if args.main_viewer and not args.id and not args.keyword and \
|
||||
not args.tag and not args.artist and not args.character and \
|
||||
not args.parody and not args.group and not args.language and not args.favorites:
|
||||
if args.main_viewer and not args.id and not args.keyword and not args.favorites:
|
||||
generate_main_html()
|
||||
exit(0)
|
||||
|
||||
@ -133,50 +147,54 @@ 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
|
||||
write_config()
|
||||
logger.info('Cookie saved.')
|
||||
exit(0)
|
||||
|
||||
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)
|
||||
|
||||
proxy_url = urlparse(args.proxy)
|
||||
if 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))
|
||||
elif args.useragent is not None:
|
||||
constant.CONFIG['useragent'] = args.useragent
|
||||
write_config()
|
||||
logger.info('Useragent saved.')
|
||||
exit(0)
|
||||
elif args.language is not None:
|
||||
constant.CONFIG['language'] = args.language
|
||||
write_config()
|
||||
logger.info('Default language now set to \'{0}\''.format(args.language))
|
||||
exit(0)
|
||||
# TODO: search without language
|
||||
|
||||
if args.proxy is not None:
|
||||
proxy_url = urlparse(args.proxy)
|
||||
if not args.proxy == '' and proxy_url.scheme not in ('http', 'https', 'socks5', 'socks5h', 'socks4', 'socks4a'):
|
||||
logger.error('Invalid protocol \'{0}\' of proxy, ignored'.format(proxy_url.scheme))
|
||||
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)
|
||||
|
||||
@ -189,15 +207,12 @@ def cmd_parser():
|
||||
_ = [i.strip() for i in f.readlines()]
|
||||
args.id = set(int(i) for i in _ if i.isdigit())
|
||||
|
||||
if (args.is_download or args.is_show) and not args.id and not args.keyword and \
|
||||
not args.tag and not args.artist and not args.character and \
|
||||
not args.parody and not args.group and not args.language and not args.favorites:
|
||||
if (args.is_download or args.is_show) and not args.id and not args.keyword and not args.favorites:
|
||||
logger.critical('Doujinshi id(s) are required for downloading')
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
|
||||
if not args.keyword and not args.id and not args.tag and not args.artist and \
|
||||
not args.character and not args.parody and not args.group and not args.language and not args.favorites:
|
||||
if not args.keyword and not args.id and not args.favorites:
|
||||
parser.print_help()
|
||||
exit(1)
|
||||
|
||||
@ -208,4 +223,8 @@ def cmd_parser():
|
||||
logger.critical('Maximum number of used threads is 15')
|
||||
exit(1)
|
||||
|
||||
if args.dryrun and (args.is_cbz or args.is_pdf):
|
||||
logger.critical('Cannot generate PDF or CBZ during dry-run')
|
||||
exit(1)
|
||||
|
||||
return args
|
||||
|
@ -1,79 +1,75 @@
|
||||
#!/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, tag_parser
|
||||
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, check_cookie, signal_handler, DB
|
||||
from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, generate_metadata_file, \
|
||||
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()
|
||||
|
||||
index = 0
|
||||
doujinshis = []
|
||||
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)
|
||||
|
||||
elif options.tag:
|
||||
doujinshis = tag_parser(options.tag, sorting=options.sorting, max_page=options.max_page)
|
||||
|
||||
elif options.artist:
|
||||
index = 1
|
||||
|
||||
elif options.character:
|
||||
index = 2
|
||||
|
||||
elif options.parody:
|
||||
index = 3
|
||||
|
||||
elif options.group:
|
||||
index = 4
|
||||
|
||||
elif options.language:
|
||||
index = 5
|
||||
doujinshis = favorites_parser(page=page_list)
|
||||
|
||||
elif options.keyword:
|
||||
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
|
||||
|
||||
if index:
|
||||
doujinshis = tag_parser(options.language, max_page=options.max_page, index=index)
|
||||
|
||||
print_doujinshi(doujinshis)
|
||||
if options.is_download and doujinshis:
|
||||
doujinshi_ids = [i['id'] for i in doujinshis]
|
||||
|
||||
if options.is_save_download_history:
|
||||
with DB() as db:
|
||||
data = set(db.get_all())
|
||||
if options.is_save_download_history:
|
||||
with DB() as db:
|
||||
data = map(int, db.get_all())
|
||||
|
||||
doujinshi_ids = list(set(doujinshi_ids) - data)
|
||||
doujinshi_ids = list(set(map(int, doujinshi_ids)) - set(data))
|
||||
|
||||
if doujinshi_ids:
|
||||
for i, id_ in enumerate(doujinshi_ids):
|
||||
@ -93,17 +89,24 @@ def main():
|
||||
timeout=options.timeout, delay=options.delay)
|
||||
|
||||
for doujinshi in doujinshi_list:
|
||||
if not options.dryrun:
|
||||
doujinshi.downloader = downloader
|
||||
doujinshi.download()
|
||||
|
||||
if options.generate_metadata:
|
||||
table = doujinshi.table
|
||||
generate_metadata_file(options.output_dir, table, doujinshi)
|
||||
|
||||
doujinshi.downloader = downloader
|
||||
doujinshi.download()
|
||||
if options.is_save_download_history:
|
||||
with DB() as db:
|
||||
db.add_one(doujinshi.id)
|
||||
|
||||
if not options.is_nohtml and not options.is_cbz:
|
||||
generate_html(options.output_dir, doujinshi)
|
||||
if not options.is_nohtml and not options.is_cbz and not options.is_pdf:
|
||||
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:
|
||||
generate_pdf(options.output_dir, doujinshi, options.rm_origin_dir)
|
||||
|
||||
if options.main_viewer:
|
||||
generate_main_html(options.output_dir)
|
||||
@ -119,6 +122,5 @@ 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
|
||||
|
||||
@ -12,17 +12,10 @@ except ImportError:
|
||||
BASE_URL = os.getenv('NHENTAI', 'https://nhentai.net')
|
||||
|
||||
__api_suspended_DETAIL_URL = '%s/api/gallery' % BASE_URL
|
||||
__api_suspended_SEARCH_URL = '%s/api/galleries/search' % BASE_URL
|
||||
|
||||
DETAIL_URL = '%s/g' % BASE_URL
|
||||
SEARCH_URL = '%s/search/' % BASE_URL
|
||||
SEARCH_URL = '%s/api/galleries/search' % BASE_URL
|
||||
|
||||
TAG_URL = ['%s/tag' % BASE_URL,
|
||||
'%s/artist' % BASE_URL,
|
||||
'%s/character' % BASE_URL,
|
||||
'%s/parody' % BASE_URL,
|
||||
'%s/group' % BASE_URL,
|
||||
'%s/language' % BASE_URL]
|
||||
|
||||
TAG_API_URL = '%s/api/galleries/tagged' % BASE_URL
|
||||
LOGIN_URL = '%s/login/' % BASE_URL
|
||||
@ -33,10 +26,20 @@ 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_HISTORY = os.path.join(NHENTAI_HOME, 'history.sqlite3')
|
||||
NHENTAI_CONFIG_FILE = os.path.join(NHENTAI_HOME, 'config.json')
|
||||
|
||||
PROXY = {}
|
||||
CONFIG = {
|
||||
'proxy': {'http': '', 'https': ''},
|
||||
'cookie': '',
|
||||
'language': '',
|
||||
'template': '',
|
||||
'useragent': 'nhentai command line client (https://github.com/RicterZ/nhentai)'
|
||||
}
|
||||
|
||||
COOKIE = ''
|
||||
LANGUAGEISO ={
|
||||
'english' : 'en',
|
||||
'chinese' : 'zh',
|
||||
'japanese' : 'ja',
|
||||
'translated' : 'translated'
|
||||
}
|
||||
|
@ -1,13 +1,11 @@
|
||||
# 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
|
||||
from nhentai.utils import format_filename
|
||||
|
||||
|
||||
EXT_MAP = {
|
||||
'j': 'jpg',
|
||||
'p': 'png',
|
||||
@ -27,8 +25,10 @@ class DoujinshiInfo(dict):
|
||||
|
||||
|
||||
class Doujinshi(object):
|
||||
def __init__(self, name=None, id=None, img_id=None, ext='', pages=0, name_format='[%i][%a][%t]', **kwargs):
|
||||
def __init__(self, name=None, pretty_name=None, id=None, img_id=None,
|
||||
ext='', pages=0, name_format='[%i][%a][%t]', **kwargs):
|
||||
self.name = name
|
||||
self.pretty_name = pretty_name
|
||||
self.id = id
|
||||
self.img_id = img_id
|
||||
self.ext = ext
|
||||
@ -40,14 +40,12 @@ class Doujinshi(object):
|
||||
name_format = name_format.replace('%i', str(self.id))
|
||||
name_format = name_format.replace('%a', self.info.artists)
|
||||
name_format = name_format.replace('%t', self.name)
|
||||
name_format = name_format.replace('%p', self.pretty_name)
|
||||
name_format = name_format.replace('%s', self.info.subtitle)
|
||||
self.filename = format_filename(name_format)
|
||||
|
||||
def __repr__(self):
|
||||
return '<Doujinshi: {0}>'.format(self.name)
|
||||
|
||||
def show(self):
|
||||
table = [
|
||||
self.table = [
|
||||
["Parodies", self.info.parodies],
|
||||
["Doujinshi", self.name],
|
||||
["Subtitle", self.info.subtitle],
|
||||
["Characters", self.info.characters],
|
||||
@ -57,26 +55,25 @@ class Doujinshi(object):
|
||||
["URL", self.url],
|
||||
["Pages", self.pages],
|
||||
]
|
||||
logger.info(u'Print doujinshi information of {0}\n{1}'.format(self.id, tabulate(table)))
|
||||
|
||||
def __repr__(self):
|
||||
return '<Doujinshi: {0}>'.format(self.name)
|
||||
|
||||
def show(self):
|
||||
|
||||
logger.info(u'Print doujinshi information of {0}\n{1}'.format(self.id, tabulate(self.table)))
|
||||
|
||||
def download(self):
|
||||
logger.info('Starting to download doujinshi: %s' % self.name)
|
||||
if self.downloader:
|
||||
download_queue = []
|
||||
|
||||
if len(self.ext) != self.pages:
|
||||
logger.warning('Page count and ext count do not equal')
|
||||
|
||||
for i in range(1, min(self.pages, len(self.ext)) + 1):
|
||||
download_queue.append('%s/%d/%d.%s' % (IMAGE_URL, int(self.img_id), i, self.ext[i-1]))
|
||||
download_queue.append('%s/%d/%d.%s' % (IMAGE_URL, int(self.img_id), i, self.ext[i - 1]))
|
||||
|
||||
self.downloader.download(download_queue, self.filename)
|
||||
|
||||
'''
|
||||
for i in range(len(self.ext)):
|
||||
download_queue.append('%s/%d/%d.%s' % (IMAGE_URL, int(self.img_id), i+1, EXT_MAP[self.ext[i]]))
|
||||
'''
|
||||
|
||||
else:
|
||||
logger.critical('Downloader has not been loaded')
|
||||
|
||||
|
@ -1,27 +1,26 @@
|
||||
# coding: utf-
|
||||
from __future__ import unicode_literals, print_function
|
||||
|
||||
import multiprocessing
|
||||
import signal
|
||||
|
||||
from future.builtins import str as text
|
||||
import sys
|
||||
import os
|
||||
import requests
|
||||
import threadpool
|
||||
import time
|
||||
import multiprocessing as mp
|
||||
|
||||
try:
|
||||
from urllib.parse import urlparse
|
||||
except ImportError:
|
||||
from urlparse import urlparse
|
||||
|
||||
from nhentai import constant
|
||||
from nhentai.logger import logger
|
||||
from nhentai.parser import request
|
||||
from nhentai.utils import Singleton, signal_handler
|
||||
from nhentai.utils import Singleton
|
||||
|
||||
requests.packages.urllib3.disable_warnings()
|
||||
semaphore = mp.Semaphore()
|
||||
semaphore = multiprocessing.Semaphore(1)
|
||||
|
||||
|
||||
class NHentaiImageNotExistException(Exception):
|
||||
@ -36,7 +35,7 @@ class Downloader(Singleton):
|
||||
self.timeout = timeout
|
||||
self.delay = delay
|
||||
|
||||
def download_(self, url, folder='', filename='', retried=0):
|
||||
def download_(self, url, folder='', filename='', retried=0, proxy=None):
|
||||
if self.delay:
|
||||
time.sleep(self.delay)
|
||||
logger.info('Starting to download {0} ...'.format(url))
|
||||
@ -53,7 +52,7 @@ class Downloader(Singleton):
|
||||
i = 0
|
||||
while i < 10:
|
||||
try:
|
||||
response = request('get', url, stream=True, timeout=self.timeout)
|
||||
response = request('get', url, stream=True, timeout=self.timeout, proxies=proxy)
|
||||
if response.status_code != 200:
|
||||
raise NHentaiImageNotExistException
|
||||
|
||||
@ -79,7 +78,8 @@ class Downloader(Singleton):
|
||||
except (requests.HTTPError, requests.Timeout) as e:
|
||||
if retried < 3:
|
||||
logger.warning('Warning: {0}, retrying({1}) ...'.format(str(e), retried))
|
||||
return 0, self.download_(url=url, folder=folder, filename=filename, retried=retried+1)
|
||||
return 0, self.download_(url=url, folder=folder, filename=filename,
|
||||
retried=retried+1, proxy=proxy)
|
||||
else:
|
||||
return 0, None
|
||||
|
||||
@ -121,29 +121,27 @@ 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]
|
||||
queue = [(self, url, folder, constant.CONFIG['proxy']) for url in queue]
|
||||
|
||||
pool = multiprocessing.Pool(self.size, init_worker)
|
||||
|
||||
for item in queue:
|
||||
pool.apply_async(download_wrapper, args=item, callback=self._download_callback)
|
||||
[pool.apply_async(download_wrapper, args=item) for item in queue]
|
||||
|
||||
pool.close()
|
||||
pool.join()
|
||||
|
||||
|
||||
def download_wrapper(obj, url, folder=''):
|
||||
if semaphore.get_value():
|
||||
return Downloader.download_(obj, url=url, folder=folder)
|
||||
def download_wrapper(obj, url, folder='', proxy=None):
|
||||
if sys.platform == 'darwin' or semaphore.get_value():
|
||||
return Downloader.download_(obj, url=url, folder=folder, proxy=proxy)
|
||||
else:
|
||||
return -3, None
|
||||
|
||||
|
@ -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,20 +76,20 @@ def favorites_parser(page_range=''):
|
||||
return []
|
||||
pages = int(count / 25)
|
||||
|
||||
if pages:
|
||||
pages += 1 if count % (25 * pages) else 0
|
||||
if page:
|
||||
page_range_list = page
|
||||
else:
|
||||
pages = 1
|
||||
if pages:
|
||||
pages += 1 if count % (25 * pages) else 0
|
||||
else:
|
||||
pages = 1
|
||||
|
||||
logger.info('You have %d favorites in %d pages.' % (count, pages))
|
||||
logger.info('You have %d favorites in %d pages.' % (count, pages))
|
||||
|
||||
if os.getenv('DEBUG'):
|
||||
pages = 1
|
||||
if os.getenv('DEBUG'):
|
||||
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)
|
||||
page_range_list = range(1, pages + 1)
|
||||
|
||||
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,26 +117,32 @@ 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')
|
||||
doujinshi_info = html.find('div', attrs={'id': 'info'})
|
||||
|
||||
title = doujinshi_info.find('h1').text
|
||||
pretty_name = doujinshi_info.find('h1').find('span', attrs={'class': 'pretty'}).text
|
||||
subtitle = doujinshi_info.find('h2')
|
||||
|
||||
doujinshi['name'] = title
|
||||
doujinshi['pretty_name'] = pretty_name
|
||||
doujinshi['subtitle'] = subtitle.text if subtitle else ''
|
||||
|
||||
doujinshi_cover = html.find('div', attrs={'id': 'cover'})
|
||||
img_id = re.search('/galleries/([\d]+)/cover\.(jpg|png|gif)$', doujinshi_cover.a.img.attrs['data-src'])
|
||||
img_id = re.search('/galleries/([0-9]+)/cover.(jpg|png|gif)$',
|
||||
doujinshi_cover.a.img.attrs['data-src'])
|
||||
|
||||
ext = []
|
||||
for i in html.find_all('div', attrs={'class': 'thumb-container'}):
|
||||
@ -178,12 +156,9 @@ def doujinshi_parser(id_):
|
||||
doujinshi['img_id'] = img_id.group(1)
|
||||
doujinshi['ext'] = ext
|
||||
|
||||
pages = 0
|
||||
for _ in doujinshi_info.find_all('div', class_=''):
|
||||
pages = re.search('([\d]+) pages', _.text)
|
||||
if pages:
|
||||
pages = pages.group(1)
|
||||
break
|
||||
for _ in doujinshi_info.find_all('div', class_='tag-container field-name'):
|
||||
if re.search('Pages:', _.text):
|
||||
pages = _.find('span', class_='name').string
|
||||
doujinshi['pages'] = int(pages)
|
||||
|
||||
# gain information of the doujinshi
|
||||
@ -192,7 +167,7 @@ def doujinshi_parser(id_):
|
||||
for field in information_fields:
|
||||
field_name = field.contents[0].strip().strip(':')
|
||||
if field_name in needed_fields:
|
||||
data = [sub_field.contents[0].strip() for sub_field in
|
||||
data = [sub_field.find('span', attrs={'class': 'name'}).contents[0].strip() for sub_field in
|
||||
field.find_all('a', attrs={'class': 'tag'})]
|
||||
doujinshi[field_name.lower()] = ', '.join(data)
|
||||
|
||||
@ -202,13 +177,13 @@ def doujinshi_parser(id_):
|
||||
return doujinshi
|
||||
|
||||
|
||||
def search_parser(keyword, sorting='date', page=1):
|
||||
def old_search_parser(keyword, sorting='date', page=1):
|
||||
logger.debug('Searching doujinshis of keyword {0}'.format(keyword))
|
||||
response = request('get', url=constant.SEARCH_URL, params={'q': keyword, 'page': page, 'sort': sorting}).content
|
||||
|
||||
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
|
||||
|
||||
@ -218,96 +193,47 @@ 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 tag_parser(tag_name, sorting='date', max_page=1, index=0):
|
||||
def search_parser(keyword, sorting, page, is_page_all=False):
|
||||
# keyword = '+'.join([i.strip().replace(' ', '-').lower() for i in keyword.split(',')])
|
||||
result = []
|
||||
tag_name = tag_name.lower()
|
||||
if ',' in tag_name:
|
||||
tag_name = [i.strip().replace(' ', '-') for i in tag_name.split(',')]
|
||||
else:
|
||||
tag_name = tag_name.strip().replace(' ', '-')
|
||||
if sorting == 'date':
|
||||
sorting = ''
|
||||
if not page:
|
||||
page = [1]
|
||||
|
||||
for p in range(1, max_page + 1):
|
||||
if sys.version_info >= (3, 0, 0):
|
||||
unicode_ = str
|
||||
else:
|
||||
unicode_ = unicode
|
||||
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)
|
||||
|
||||
if isinstance(tag_name, (str, unicode_)):
|
||||
logger.debug('Fetching page {0} for doujinshi with tag \'{1}\''.format(p, tag_name))
|
||||
response = request('get', url='%s/%s/%s?page=%d' % (constant.TAG_URL[index], tag_name, sorting, p)).content
|
||||
result += _get_title_and_id(response)
|
||||
else:
|
||||
for i in tag_name:
|
||||
logger.debug('Fetching page {0} for doujinshi with tag \'{1}\''.format(p, i))
|
||||
response = request('get',
|
||||
url='%s/%s/%s?page=%d' % (constant.TAG_URL[index], i, sorting, p)).content
|
||||
result += _get_title_and_id(response)
|
||||
total = '/{0}'.format(page[-1]) if is_page_all else ''
|
||||
for p in page:
|
||||
i = 0
|
||||
|
||||
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': p, 'sort': sorting}).url
|
||||
response = request('get', url.replace('%2B', '+')).json()
|
||||
except Exception as e:
|
||||
logger.critical(str(e))
|
||||
|
||||
break
|
||||
|
||||
if 'result' not in response:
|
||||
logger.warning('No result in response in page {}'.format(p))
|
||||
break
|
||||
|
||||
for row in response['result']:
|
||||
title = row['title']['english']
|
||||
title = title[:85] + '..' if len(title) > 85 else title
|
||||
result.append({'id': row['id'], 'title': title})
|
||||
|
||||
if not result:
|
||||
logger.error('Cannot find doujinshi id of tag \'{0}\''.format(tag_name))
|
||||
return
|
||||
|
||||
if not result:
|
||||
logger.warn('No results for tag \'{}\''.format(tag_name))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def __api_suspended_search_parser(keyword, sorting, page):
|
||||
logger.debug('Searching doujinshis using keywords {0}'.format(keyword))
|
||||
result = []
|
||||
i = 0
|
||||
while i < 5:
|
||||
try:
|
||||
response = request('get', url=constant.SEARCH_URL, params={'query': keyword, 'page': page, 'sort': sorting}).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')
|
||||
|
||||
for row in response['result']:
|
||||
title = row['title']['english']
|
||||
title = title[:85] + '..' if len(title) > 85 else title
|
||||
result.append({'id': row['id'], 'title': title})
|
||||
|
||||
if not result:
|
||||
logger.warn('No results for keywords {}'.format(keyword))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def __api_suspended_tag_parser(tag_id, sorting, max_page=1):
|
||||
logger.info('Searching for doujinshi with tag id {0}'.format(tag_id))
|
||||
result = []
|
||||
response = request('get', url=constant.TAG_API_URL, params={'sort': sorting, 'tag_id': tag_id}).json()
|
||||
page = max_page if max_page <= response['num_pages'] else int(response['num_pages'])
|
||||
|
||||
for i in range(1, page + 1):
|
||||
logger.info('Getting page {} ...'.format(i))
|
||||
|
||||
if page != 1:
|
||||
response = request('get', url=constant.TAG_API_URL,
|
||||
params={'sort': sorting, 'tag_id': tag_id}).json()
|
||||
for row in response['result']:
|
||||
title = row['title']['english']
|
||||
title = title[:85] + '..' if len(title) > 85 else title
|
||||
result.append({'id': row['id'], 'title': title})
|
||||
|
||||
if not result:
|
||||
logger.warn('No results for tag id {}'.format(tag_id))
|
||||
logger.warning('No results for keywords {}'.format(keyword))
|
||||
|
||||
return result
|
||||
|
||||
|
@ -1,9 +1,11 @@
|
||||
# coding: utf-8
|
||||
import json
|
||||
import os
|
||||
from xml.sax.saxutils import escape
|
||||
from nhentai.constant import LANGUAGEISO
|
||||
|
||||
|
||||
def serialize(doujinshi, dir):
|
||||
def serialize_json(doujinshi, dir):
|
||||
metadata = {'title': doujinshi.name,
|
||||
'subtitle': doujinshi.info.subtitle}
|
||||
if doujinshi.info.date:
|
||||
@ -25,7 +27,54 @@ def serialize(doujinshi, dir):
|
||||
metadata['Pages'] = doujinshi.pages
|
||||
|
||||
with open(os.path.join(dir, 'metadata.json'), 'w') as f:
|
||||
json.dump(metadata, f, separators=','':')
|
||||
json.dump(metadata, f, separators=(',', ':'))
|
||||
|
||||
|
||||
def serialize_comic_xml(doujinshi, dir):
|
||||
from iso8601 import parse_date
|
||||
with open(os.path.join(dir, 'ComicInfo.xml'), 'w', encoding="utf-8") as f:
|
||||
f.write('<?xml version="1.0" encoding="utf-8"?>\n')
|
||||
f.write('<ComicInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" '
|
||||
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n')
|
||||
|
||||
xml_write_simple_tag(f, 'Manga', 'Yes')
|
||||
|
||||
xml_write_simple_tag(f, 'Title', doujinshi.name)
|
||||
xml_write_simple_tag(f, 'Summary', doujinshi.info.subtitle)
|
||||
xml_write_simple_tag(f, 'PageCount', doujinshi.pages)
|
||||
xml_write_simple_tag(f, 'URL', doujinshi.url)
|
||||
xml_write_simple_tag(f, 'NhentaiId', doujinshi.id)
|
||||
xml_write_simple_tag(f, 'Genre', doujinshi.info.categories)
|
||||
|
||||
xml_write_simple_tag(f, 'BlackAndWhite', 'No' if doujinshi.info.tags and
|
||||
'full color' in doujinshi.info.tags else 'Yes')
|
||||
|
||||
if doujinshi.info.date:
|
||||
dt = parse_date(doujinshi.info.date)
|
||||
xml_write_simple_tag(f, 'Year', dt.year)
|
||||
xml_write_simple_tag(f, 'Month', dt.month)
|
||||
xml_write_simple_tag(f, 'Day', dt.day)
|
||||
if doujinshi.info.parodies:
|
||||
xml_write_simple_tag(f, 'Series', doujinshi.info.parodies)
|
||||
if doujinshi.info.characters:
|
||||
xml_write_simple_tag(f, 'Characters', doujinshi.info.characters)
|
||||
if doujinshi.info.tags:
|
||||
xml_write_simple_tag(f, 'Tags', doujinshi.info.tags)
|
||||
if doujinshi.info.artists:
|
||||
xml_write_simple_tag(f, 'Writer', ' & '.join([i.strip() for i in
|
||||
doujinshi.info.artists.split(',')]))
|
||||
|
||||
if doujinshi.info.languages:
|
||||
languages = [i.strip() for i in doujinshi.info.languages.split(',')]
|
||||
xml_write_simple_tag(f, 'Translated', 'Yes' if 'translated' in languages else 'No')
|
||||
[xml_write_simple_tag(f, 'LanguageISO', LANGUAGEISO[i]) for i in languages
|
||||
if (i != 'translated' and i in LANGUAGEISO)]
|
||||
|
||||
f.write('</ComicInfo>')
|
||||
|
||||
|
||||
def xml_write_simple_tag(f, name, val, indent=1):
|
||||
f.write('{}<{}>{}</{}>\n'.format(' ' * indent, name, escape(str(val)), name))
|
||||
|
||||
|
||||
def merge_json():
|
||||
@ -74,7 +123,7 @@ def serialize_unique(lst):
|
||||
def set_js_database():
|
||||
with open('data.js', 'w') as f:
|
||||
indexed_json = merge_json()
|
||||
unique_json = json.dumps(serialize_unique(indexed_json), separators=','':')
|
||||
indexed_json = json.dumps(indexed_json, separators=','':')
|
||||
unique_json = json.dumps(serialize_unique(indexed_json), separators=(',', ':'))
|
||||
indexed_json = json.dumps(indexed_json, separators=(',', ':'))
|
||||
f.write('var data = ' + indexed_json)
|
||||
f.write(';\nvar tags = ' + unique_json)
|
||||
|
174
nhentai/utils.py
174
nhentai/utils.py
@ -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
|
||||
@ -12,24 +10,32 @@ import sqlite3
|
||||
|
||||
from nhentai import constant
|
||||
from nhentai.logger import logger
|
||||
from nhentai.serializer import serialize, set_js_database
|
||||
from nhentai.serializer import serialize_json, serialize_comic_xml, set_js_database
|
||||
|
||||
|
||||
def request(method, url, **kwargs):
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
'Referer': constant.LOGIN_URL,
|
||||
'User-Agent': 'nhentai command line client (https://github.com/RicterZ/nhentai)',
|
||||
'Cookie': constant.COOKIE
|
||||
'User-Agent': constant.CONFIG['useragent'],
|
||||
'Cookie': constant.CONFIG['cookie']
|
||||
})
|
||||
return getattr(session, method)(url, proxies=constant.PROXY, verify=False, **kwargs)
|
||||
|
||||
if not kwargs.get('proxies', None):
|
||||
kwargs['proxies'] = constant.CONFIG['proxy']
|
||||
|
||||
return getattr(session, method)(url, verify=False, **kwargs)
|
||||
|
||||
|
||||
def check_cookie():
|
||||
response = request('get', constant.BASE_URL).text
|
||||
username = re.findall('"/users/\d+/(.*?)"', response)
|
||||
response = request('get', constant.BASE_URL)
|
||||
if response.status_code == 503 and 'cf-browser-verification' in response.text:
|
||||
logger.error('Blocked by Cloudflare captcha, please set your cookie and useragent')
|
||||
exit(-1)
|
||||
|
||||
username = re.findall('"/users/\d+/(.*?)"', response.text)
|
||||
if not username:
|
||||
logger.error('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
|
||||
logger.warning('Cannot get your username, please check your cookie or use `nhentai --cookie` to set your cookie')
|
||||
else:
|
||||
logger.info('Login successfully! Your username: {}'.format(username[0]))
|
||||
|
||||
@ -64,7 +70,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:
|
||||
@ -72,6 +78,13 @@ def generate_html(output_dir='.', doujinshi_obj=None):
|
||||
else:
|
||||
doujinshi_dir = '.'
|
||||
|
||||
if not os.path.exists(doujinshi_dir):
|
||||
logger.warning('Path \'{0}\' does not exist, creating.'.format(doujinshi_dir))
|
||||
try:
|
||||
os.makedirs(doujinshi_dir)
|
||||
except EnvironmentError as e:
|
||||
logger.critical('{0}'.format(str(e)))
|
||||
|
||||
file_list = os.listdir(doujinshi_dir)
|
||||
file_list.sort()
|
||||
|
||||
@ -79,14 +92,14 @@ def generate_html(output_dir='.', doujinshi_obj=None):
|
||||
if not os.path.splitext(image)[1] in ('.jpg', '.png'):
|
||||
continue
|
||||
|
||||
image_html += '<img src="{0}" class="image-item"/>\n'\
|
||||
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(doujinshi_obj, doujinshi_dir)
|
||||
serialize_json(doujinshi_obj, doujinshi_dir)
|
||||
name = doujinshi_obj.name
|
||||
if sys.version_info < (3, 0):
|
||||
name = doujinshi_obj.name.encode('utf-8')
|
||||
@ -102,9 +115,9 @@ def generate_html(output_dir='.', doujinshi_obj=None):
|
||||
with open(os.path.join(doujinshi_dir, 'index.html'), 'wb') as f:
|
||||
f.write(data.encode('utf-8'))
|
||||
|
||||
logger.log(15, 'HTML Viewer has been write to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
|
||||
logger.log(15, 'HTML Viewer has been written to \'{0}\''.format(os.path.join(doujinshi_dir, 'index.html')))
|
||||
except Exception as e:
|
||||
logger.warning('Writen HTML Viewer failed ({})'.format(str(e)))
|
||||
logger.warning('Writing HTML Viewer failed ({})'.format(str(e)))
|
||||
|
||||
|
||||
def generate_main_html(output_dir='./'):
|
||||
@ -150,7 +163,7 @@ def generate_main_html(output_dir='./'):
|
||||
|
||||
image_html += element.format(FOLDER=folder, IMAGE=image, TITLE=title)
|
||||
if image_html == '':
|
||||
logger.warning('None index.html found, --gen-main paused.')
|
||||
logger.warning('No index.html found, --gen-main paused.')
|
||||
return
|
||||
try:
|
||||
data = main.format(STYLES=css, SCRIPTS=js, PICTURE=image_html)
|
||||
@ -160,17 +173,19 @@ def generate_main_html(output_dir='./'):
|
||||
else:
|
||||
with open('./main.html', 'wb') as f:
|
||||
f.write(data.encode('utf-8'))
|
||||
shutil.copy(os.path.dirname(__file__)+'/viewer/logo.png', './')
|
||||
shutil.copy(os.path.dirname(__file__) + '/viewer/logo.png', './')
|
||||
set_js_database()
|
||||
logger.log(
|
||||
15, 'Main Viewer has been write to \'{0}main.html\''.format(output_dir))
|
||||
15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
|
||||
except Exception as e:
|
||||
logger.warning('Writen Main Viewer failed ({})'.format(str(e)))
|
||||
logger.warning('Writing Main Viewer failed ({})'.format(str(e)))
|
||||
|
||||
|
||||
def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
|
||||
def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False, write_comic_info=True):
|
||||
if doujinshi_obj is not None:
|
||||
doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
|
||||
if write_comic_info:
|
||||
serialize_comic_xml(doujinshi_obj, doujinshi_dir)
|
||||
cbz_filename = os.path.join(os.path.join(doujinshi_dir, '..'), '{}.cbz'.format(doujinshi_obj.filename))
|
||||
else:
|
||||
cbz_filename = './doujinshi.cbz'
|
||||
@ -188,24 +203,67 @@ def generate_cbz(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
|
||||
if rm_origin_dir:
|
||||
shutil.rmtree(doujinshi_dir, ignore_errors=True)
|
||||
|
||||
logger.log(15, 'Comic Book CBZ file has been write to \'{0}\''.format(doujinshi_dir))
|
||||
logger.log(15, 'Comic Book CBZ file has been written to \'{0}\''.format(doujinshi_dir))
|
||||
|
||||
|
||||
def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
|
||||
try:
|
||||
import img2pdf
|
||||
|
||||
"""Write images to a PDF file using img2pdf."""
|
||||
if doujinshi_obj is not None:
|
||||
doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
|
||||
pdf_filename = os.path.join(
|
||||
os.path.join(doujinshi_dir, '..'),
|
||||
'{}.pdf'.format(doujinshi_obj.filename)
|
||||
)
|
||||
else:
|
||||
pdf_filename = './doujinshi.pdf'
|
||||
doujinshi_dir = '.'
|
||||
|
||||
file_list = os.listdir(doujinshi_dir)
|
||||
file_list.sort()
|
||||
|
||||
logger.info('Writing PDF file to path: {}'.format(pdf_filename))
|
||||
with open(pdf_filename, 'wb') as pdf_f:
|
||||
full_path_list = (
|
||||
[os.path.join(doujinshi_dir, image) for image in file_list]
|
||||
)
|
||||
pdf_f.write(img2pdf.convert(full_path_list))
|
||||
|
||||
if rm_origin_dir:
|
||||
shutil.rmtree(doujinshi_dir, ignore_errors=True)
|
||||
|
||||
logger.log(15, 'PDF file has been written to \'{0}\''.format(doujinshi_dir))
|
||||
|
||||
except ImportError:
|
||||
logger.error("Please install img2pdf package by using pip.")
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
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
|
||||
ban_chars = '\\\'/:,;*?"<>|\t'
|
||||
filename = s.translate(str.maketrans(ban_chars, ' ' * len(ban_chars))).strip()
|
||||
filename = ' '.join(filename.split())
|
||||
|
||||
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.
|
||||
while filename.endswith('.'):
|
||||
filename = filename[:-1]
|
||||
|
||||
"""
|
||||
valid_chars = "-_.()[] %s%s" % (string.ascii_letters, string.digits)
|
||||
filename = ''.join(c for c in s if c in valid_chars)
|
||||
if len(filename) > 100:
|
||||
filename = filename[:100] + '...]'
|
||||
filename = filename[:100] + u'…'
|
||||
|
||||
# Remove [] from filename
|
||||
filename = filename.replace('[]', '').strip()
|
||||
@ -217,6 +275,54 @@ 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
|
||||
|
||||
|
||||
def generate_metadata_file(output_dir, table, doujinshi_obj=None):
|
||||
logger.info('Writing Metadata Info')
|
||||
|
||||
if doujinshi_obj is not None:
|
||||
doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
|
||||
else:
|
||||
doujinshi_dir = '.'
|
||||
|
||||
logger.info(doujinshi_dir)
|
||||
|
||||
f = open(os.path.join(doujinshi_dir, 'info.txt'), 'w', encoding='utf-8')
|
||||
|
||||
fields = ['TITLE', 'ORIGINAL TITLE', 'AUTHOR', 'ARTIST', 'CIRCLE', 'SCANLATOR',
|
||||
'TRANSLATOR', 'PUBLISHER', 'DESCRIPTION', 'STATUS', 'CHAPTERS', 'PAGES',
|
||||
'TAGS', 'TYPE', 'LANGUAGE', 'RELEASED', 'READING DIRECTION', 'CHARACTERS',
|
||||
'SERIES', 'PARODY', 'URL']
|
||||
special_fields = ['PARODY', 'TITLE', 'ORIGINAL TITLE', 'CHARACTERS', 'AUTHOR',
|
||||
'LANGUAGE', 'TAGS', 'URL', 'PAGES']
|
||||
|
||||
for i in range(len(fields)):
|
||||
f.write('{}: '.format(fields[i]))
|
||||
if fields[i] in special_fields:
|
||||
f.write(str(table[special_fields.index(fields[i])][1]))
|
||||
f.write('\n')
|
||||
|
||||
f.close()
|
||||
|
||||
|
||||
class DB(object):
|
||||
conn = None
|
||||
cur = None
|
||||
|
@ -148,7 +148,7 @@ blockquote {
|
||||
-webkit-user-select: none; /* Safari */
|
||||
-khtml-user-select: none; /* Konqueror HTML */
|
||||
-moz-user-select: none; /* Old versions of Firefox */
|
||||
ms-user-select: none; /* Internet Explorer/Edge */
|
||||
-ms-user-select: none; /* Internet Explorer/Edge */
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
@ -157,7 +157,7 @@ blockquote {
|
||||
padding: 5px 0px 5px 15px;
|
||||
text-decoration: none;
|
||||
font-size: 15px;
|
||||
color: #0d0d0d9;
|
||||
color: #0d0d0d;
|
||||
display: block;
|
||||
text-align: left;
|
||||
}
|
||||
@ -329,4 +329,4 @@ html.theme-black .gallery:hover .caption {
|
||||
html.theme-black .caption {
|
||||
background-color: #404040;
|
||||
color: #d9d9d9
|
||||
}
|
||||
}
|
||||
|
25
nhentai/viewer/minimal/index.html
Normal file
25
nhentai/viewer/minimal/index.html
Normal file
@ -0,0 +1,25 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes, viewport-fit=cover" />
|
||||
<title>{TITLE}</title>
|
||||
<style>
|
||||
{STYLES}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<nav id="list" hidden=true>
|
||||
{IMAGES}</nav>
|
||||
|
||||
<div id="image-container">
|
||||
<div id="dest"></div>
|
||||
<span id="page-num"></span>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
{SCRIPTS}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
79
nhentai/viewer/minimal/scripts.js
Normal file
79
nhentai/viewer/minimal/scripts.js
Normal file
@ -0,0 +1,79 @@
|
||||
const pages = Array.from(document.querySelectorAll('img.image-item'));
|
||||
let currentPage = 0;
|
||||
|
||||
function changePage(pageNum) {
|
||||
const previous = pages[currentPage];
|
||||
const current = pages[pageNum];
|
||||
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
previous.classList.remove('current');
|
||||
current.classList.add('current');
|
||||
|
||||
currentPage = pageNum;
|
||||
|
||||
const display = document.getElementById('dest');
|
||||
display.style.backgroundImage = `url("${current.src}")`;
|
||||
|
||||
scroll(0,0)
|
||||
|
||||
document.getElementById('page-num')
|
||||
.innerText = [
|
||||
(pageNum + 1).toLocaleString(),
|
||||
pages.length.toLocaleString()
|
||||
].join('\u200a/\u200a');
|
||||
}
|
||||
|
||||
changePage(0);
|
||||
|
||||
document.getElementById('image-container').onclick = event => {
|
||||
const width = document.getElementById('image-container').clientWidth;
|
||||
const clickPos = event.clientX / width;
|
||||
|
||||
if (clickPos < 0.5) {
|
||||
changePage(currentPage - 1);
|
||||
} else {
|
||||
changePage(currentPage + 1);
|
||||
}
|
||||
};
|
||||
|
||||
document.onkeypress = event => {
|
||||
switch (event.key.toLowerCase()) {
|
||||
// Previous Image
|
||||
case 'w':
|
||||
scrollBy(0, -40);
|
||||
break;
|
||||
case 'a':
|
||||
changePage(currentPage - 1);
|
||||
break;
|
||||
// Return to previous page
|
||||
case 'q':
|
||||
window.history.go(-1);
|
||||
break;
|
||||
// Next Image
|
||||
case ' ':
|
||||
case 's':
|
||||
scrollBy(0, 40);
|
||||
break;
|
||||
case 'd':
|
||||
changePage(currentPage + 1);
|
||||
break;
|
||||
}// remove arrow cause it won't work
|
||||
};
|
||||
|
||||
document.onkeydown = event =>{
|
||||
switch (event.keyCode) {
|
||||
case 37: //left
|
||||
changePage(currentPage - 1);
|
||||
break;
|
||||
case 38: //up
|
||||
break;
|
||||
case 39: //right
|
||||
changePage(currentPage + 1);
|
||||
break;
|
||||
case 40: //down
|
||||
break;
|
||||
}
|
||||
};
|
75
nhentai/viewer/minimal/styles.css
Normal file
75
nhentai/viewer/minimal/styles.css
Normal file
@ -0,0 +1,75 @@
|
||||
|
||||
*, *::after, *::before {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
img {
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
html, body {
|
||||
display: flex;
|
||||
background-color: #e8e6e6;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
|
||||
#list {
|
||||
height: 2000px;
|
||||
overflow: scroll;
|
||||
width: 260px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#list img {
|
||||
width: 200px;
|
||||
padding: 10px;
|
||||
border-radius: 10px;
|
||||
margin: 15px 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
#list img.current {
|
||||
background: #0003;
|
||||
}
|
||||
|
||||
#image-container {
|
||||
flex: auto;
|
||||
height: 100%;
|
||||
background: rgb(0, 0, 0);
|
||||
color: rgb(100, 100, 100);
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
#image-container #dest {
|
||||
height: 2000px;
|
||||
width: 100%;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: top;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
max-width: 100%;
|
||||
max-height: 100vh;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
#image-container #page-num {
|
||||
position: static;
|
||||
font-size: 9pt;
|
||||
left: 10px;
|
||||
bottom: 5px;
|
||||
font-weight: bold;
|
||||
opacity: 0.9;
|
||||
text-shadow: /* Duplicate the same shadow to make it very strong */
|
||||
0 0 2px #222,
|
||||
0 0 2px #222,
|
||||
0 0 2px #222;
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
requests>=2.5.0
|
||||
soupsieve<2.0
|
||||
soupsieve
|
||||
BeautifulSoup4>=4.0.0
|
||||
threadpool>=1.2.7
|
||||
tabulate>=0.7.5
|
||||
future>=0.15.2
|
||||
iso8601 >= 0.1
|
||||
|
Reference in New Issue
Block a user