fix format

This commit is contained in:
RicterZ 2021-06-07 17:17:54 +08:00
parent ad1e876611
commit 7594625d72
4 changed files with 40 additions and 76 deletions

View File

@ -104,6 +104,8 @@ def cmd_parser():
help='generate PDF file') help='generate PDF file')
parser.add_option('--rm-origin-dir', dest='rm_origin_dir', action='store_true', default=False, parser.add_option('--rm-origin-dir', dest='rm_origin_dir', action='store_true', default=False,
help='remove downloaded doujinshi dir when generated CBZ or PDF 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 # nhentai options
parser.add_option('--cookie', type='str', dest='cookie', action='store', parser.add_option('--cookie', type='str', dest='cookie', action='store',
@ -119,9 +121,6 @@ def cmd_parser():
parser.add_option('--template', dest='viewer_template', action='store', parser.add_option('--template', dest='viewer_template', action='store',
help='set viewer template', default='') help='set viewer template', default='')
parser.add_option('--meta', dest='generate_metadata', action='store_true', help='generate a Metadata File in HDoujin Format')
try: try:
sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv] sys.argv = [unicode(i.decode(sys.stdin.encoding)) for i in sys.argv]
except (NameError, TypeError): except (NameError, TypeError):

View File

@ -13,7 +13,7 @@ from nhentai.doujinshi import Doujinshi
from nhentai.downloader import Downloader from nhentai.downloader import Downloader
from nhentai.logger import logger from nhentai.logger import logger
from nhentai.constant import BASE_URL from nhentai.constant import BASE_URL
from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, generate_metadatafile, \ from nhentai.utils import generate_html, generate_cbz, generate_main_html, generate_pdf, generate_metadata_file, \
paging, check_cookie, signal_handler, DB paging, check_cookie, signal_handler, DB
@ -84,8 +84,6 @@ def main():
if (i + 1) % 10 == 0: if (i + 1) % 10 == 0:
logger.info('Progress: %d / %d' % (i + 1, len(doujinshi_ids))) logger.info('Progress: %d / %d' % (i + 1, len(doujinshi_ids)))
if not options.is_show: if not options.is_show:
downloader = Downloader(path=options.output_dir, size=options.threads, downloader = Downloader(path=options.output_dir, size=options.threads,
timeout=options.timeout, delay=options.delay) timeout=options.timeout, delay=options.delay)
@ -99,9 +97,8 @@ def main():
doujinshi.download() doujinshi.download()
if options.generate_metadata: if options.generate_metadata:
table=doujinshi.table table = doujinshi.table
generate_metadatafile(options.output_dir,table,doujinshi) generate_metadata_file(options.output_dir, table, doujinshi)
if options.is_save_download_history: if options.is_save_download_history:
with DB() as db: with DB() as db:
@ -126,9 +123,7 @@ def main():
[doujinshi.show() for doujinshi in doujinshi_list] [doujinshi.show() for doujinshi in doujinshi_list]
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -6,7 +6,6 @@ from nhentai.constant import DETAIL_URL, IMAGE_URL
from nhentai.logger import logger from nhentai.logger import logger
from nhentai.utils import format_filename from nhentai.utils import format_filename
EXT_MAP = { EXT_MAP = {
'j': 'jpg', 'j': 'jpg',
'p': 'png', 'p': 'png',
@ -42,8 +41,7 @@ class Doujinshi(object):
name_format = name_format.replace('%s', self.info.subtitle) name_format = name_format.replace('%s', self.info.subtitle)
self.filename = format_filename(name_format) self.filename = format_filename(name_format)
self.table = [
self.table =[
["Parodies", self.info.parodies], ["Parodies", self.info.parodies],
["Doujinshi", self.name], ["Doujinshi", self.name],
["Subtitle", self.info.subtitle], ["Subtitle", self.info.subtitle],
@ -55,7 +53,6 @@ class Doujinshi(object):
["Pages", self.pages], ["Pages", self.pages],
] ]
def __repr__(self): def __repr__(self):
return '<Doujinshi: {0}>'.format(self.name) return '<Doujinshi: {0}>'.format(self.name)
@ -63,7 +60,6 @@ class Doujinshi(object):
logger.info(u'Print doujinshi information of {0}\n{1}'.format(self.id, tabulate(self.table))) logger.info(u'Print doujinshi information of {0}\n{1}'.format(self.id, tabulate(self.table)))
def download(self): def download(self):
logger.info('Starting to download doujinshi: %s' % self.name) logger.info('Starting to download doujinshi: %s' % self.name)
if self.downloader: if self.downloader:
@ -73,7 +69,7 @@ class Doujinshi(object):
logger.warning('Page count and ext count do not equal') logger.warning('Page count and ext count do not equal')
for i in range(1, min(self.pages, len(self.ext)) + 1): 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) self.downloader.download(download_queue, self.filename)

View File

@ -88,7 +88,7 @@ def generate_html(output_dir='.', doujinshi_obj=None, template='default'):
if not os.path.splitext(image)[1] in ('.jpg', '.png'): if not os.path.splitext(image)[1] in ('.jpg', '.png'):
continue continue
image_html += '<img src="{0}" class="image-item"/>\n'\ image_html += '<img src="{0}" class="image-item"/>\n' \
.format(image) .format(image)
html = readfile('viewer/{}/index.html'.format(template)) html = readfile('viewer/{}/index.html'.format(template))
css = readfile('viewer/{}/styles.css'.format(template)) css = readfile('viewer/{}/styles.css'.format(template))
@ -169,7 +169,7 @@ def generate_main_html(output_dir='./'):
else: else:
with open('./main.html', 'wb') as f: with open('./main.html', 'wb') as f:
f.write(data.encode('utf-8')) 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() set_js_database()
logger.log( logger.log(
15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir)) 15, 'Main Viewer has been written to \'{0}main.html\''.format(output_dir))
@ -235,6 +235,7 @@ def generate_pdf(output_dir='.', doujinshi_obj=None, rm_origin_dir=False):
except ImportError: except ImportError:
logger.error("Please install img2pdf package by using pip.") logger.error("Please install img2pdf package by using pip.")
def unicode_truncate(s, length, encoding='utf-8'): 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 """https://stackoverflow.com/questions/1809531/truncating-unicode-so-it-fits-a-maximum-size-when-encoded-for-wire-transfer
""" """
@ -251,7 +252,7 @@ def format_filename(s):
""" """
# maybe you can use `--format` to select a suitable filename # maybe you can use `--format` to select a suitable filename
ban_chars = '\\\'/:,;*?"<>|\t' ban_chars = '\\\'/:,;*?"<>|\t'
filename = s.translate(str.maketrans(ban_chars, ' '*len(ban_chars))).strip() filename = s.translate(str.maketrans(ban_chars, ' ' * len(ban_chars))).strip()
filename = ' '.join(filename.split()) filename = ' '.join(filename.split())
print(repr(filename)) print(repr(filename))
@ -282,7 +283,7 @@ def paging(page_string):
start, end = i.split('-') start, end = i.split('-')
if not (start.isdigit() and end.isdigit()): if not (start.isdigit() and end.isdigit()):
raise Exception('Invalid page number') raise Exception('Invalid page number')
page_list.extend(list(range(int(start), int(end)+1))) page_list.extend(list(range(int(start), int(end) + 1)))
else: else:
if not i.isdigit(): if not i.isdigit():
raise Exception('Invalid page number') raise Exception('Invalid page number')
@ -290,9 +291,9 @@ def paging(page_string):
return page_list return page_list
def generate_metadatafile(output_dir, table, doujinshi_obj=None):
logger.info("Writing Metadata Info")
def generate_metadata_file(output_dir, table, doujinshi_obj=None):
logger.info('Writing Metadata Info')
if doujinshi_obj is not None: if doujinshi_obj is not None:
doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename) doujinshi_dir = os.path.join(output_dir, doujinshi_obj.filename)
@ -301,48 +302,24 @@ def generate_metadatafile(output_dir, table, doujinshi_obj=None):
logger.info(doujinshi_dir) logger.info(doujinshi_dir)
f = open(os.path.join(doujinshi_dir, 'info.txt'), "w", encoding="utf-8") 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"] 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)):
for i in range(21): f.write('{}: '.format(fields[i]))
f.write("%s: " % fields[i]) if fields[i] in special_fields:
f.write(str(table[special_fields.index(fields[i])][1]))
if(i==19): f.write('\n')
f.write("%s" % table[0][1])
if(i==0):
f.write("%s" % table[1][1])
if(i==1):
f.write("%s" % table[2][1])
if(i==17):
f.write("%s" % table[3][1])
if(i==2):
f.write("%s" % table[4][1])
if(i==14):
f.write("%s" % table[5][1])
if(i==12):
f.write("%s" % table[6][1])
if(i==20):
f.write("%s" % table[7][1])
if(i==11):
f.write("%s" % table[8][1])
f.write("\n")
f.close() f.close()
class DB(object): class DB(object):
conn = None conn = None
cur = None cur = None
@ -368,6 +345,3 @@ class DB(object):
def get_all(self): def get_all(self):
data = self.cur.execute('SELECT id FROM download_history') data = self.cur.execute('SELECT id FROM download_history')
return [i[0] for i in data] return [i[0] for i in data]