"""
作者:星隅(xing-yv)
版权所有(C)2023 星隅(xing-yv)
本软件根据GNU通用公共许可证第三版(GPLv3)发布;
你可以在以下位置找到该许可证的副本:
https://www.gnu.org/licenses/gpl-3.0.html
根据GPLv3的规定,您有权在遵循许可证的前提下自由使用、修改和分发本软件。
请注意,根据许可证的要求,任何对本软件的修改和分发都必须包括原始的版权声明和GPLv3的完整文本。
本软件提供的是按"原样"提供的,没有任何明示或暗示的保证,包括但不限于适销性和特定用途的适用性。作者不对任何直接或间接损害或其他责任承担任何责任。在适用法律允许的最大范围内,作者明确放弃了所有明示或暗示的担保和条件。
免责声明:
该程序仅用于学习和研究Python网络爬虫和网页处理技术,不得用于任何非法活动或侵犯他人权益的行为。使用本程序所产生的一切法律责任和风险,均由用户自行承担,与作者和项目协作者、贡献者无关。作者不对因使用该程序而导致的任何损失或损害承担任何责任。
请在使用本程序之前确保遵守相关法律法规和网站的使用政策,如有疑问,请咨询法律顾问。
无论您对程序进行了任何操作,请始终保留此信息。
"""
import os
import yaml
import requests
from ebooklib import epub
import re
import time
import json
from tqdm import tqdm
import public as p
from requests.exceptions import Timeout
from colorama import Fore, Style, init
init(autoreset=True)
def fanqie_epub(url, user_agent, path_choice, config_path):
headers = {
"User-Agent": user_agent
}
book = epub.EpubBook()
book_id = re.search(r'\d+', url).group()
try:
soup, title, author_name, intro, img_url = p.get_fanqie(url, user_agent, mode='epub')
response = requests.get(img_url, timeout=20)
except Timeout:
print(Fore.RED + Style.BRIGHT + "连接超时,请检查网络连接是否正常。")
return
except AttributeError:
print(Fore.RED + Style.BRIGHT + "获取详情失败:该小说不存在或禁止网页阅读!(或网络连接异常)")
return
img_data = response.content
with open("cover.jpg", "wb") as f:
f.write(img_data)
book.set_cover("image.jpg", open('cover.jpg', 'rb').read())
os.remove('cover.jpg')
book.set_title(title)
book.set_language('zh-CN')
book.add_author(author_name)
book.add_metadata('DC', 'description', intro)
yaml_data = {
'fqid': book_id
}
yaml_content = yaml.dump(yaml_data)
yaml_item = epub.EpubItem(uid='yaml', file_name='metadata.yaml', media_type='application/octet-stream',
content=yaml_content)
book.add_item(yaml_item)
page_directory_content = soup.find('div', class_='page-directory-content')
nested_divs = page_directory_content.find_all('div', recursive=False)
intro_e = epub.EpubHtml(title='Introduction', file_name='intro.xhtml', lang='hr')
intro_e.content = (f'<img src="image.jpg" alt="Cover Image"/>'
f'<h1>{title}</h1>'
f'<p>{intro}</p>')
book.add_item(intro_e)
font_file = p.asset_path("HarmonyOS_Sans_SC_Regular.ttf")
css1_file = p.asset_path("page_styles.css")
css2_file = p.asset_path("stylesheet.css")
with open(font_file, 'rb') as f:
font_content = f.read()
with open(css1_file, 'r', encoding='utf-8') as f:
css1_content = f.read()
with open(css2_file, 'r', encoding='utf-8') as f:
css2_content = f.read()
font = epub.EpubItem(
uid="font",
file_name="fonts/HarmonyOS_Sans_SC_Regular.ttf",
media_type="application/vnd.ms-opentype",
content=font_content,
)
nav_css1 = epub.EpubItem(
uid="style_nav1",
file_name="style/page_styles.css",
media_type="text/css",
content=css1_content,
)
nav_css2 = epub.EpubItem(
uid="style_nav2",
file_name="style/stylesheet.css",
media_type="text/css",
content=css2_content,
)
book.add_item(font)
book.add_item(nav_css1)
book.add_item(nav_css2)
book.toc = (epub.Link('intro.xhtml', '简介', 'intro'),)
book.spine = ['nav', intro_e]
try:
volume_id = 0
for div in nested_divs:
first_chapter = None
volume_id += 1
volume_div = div.find('div', class_='volume')
volume_title = volume_div.text
print(volume_title)
chapters = div.find_all("div", class_="chapter-item")
toc_index = ()
chapter_id_name = 0
for chapter in tqdm(chapters, desc="下载进度"):
chapter_id_name += 1
time.sleep(0.25)
result = p.get_api(chapter, headers, mode='epub')
if result == "skip":
continue
elif result == "terminate":
break
else:
chapter_title, chapter_text, chapter_id = result
text = epub.EpubHtml(title=chapter_title, file_name=f'chapter_{volume_id}_{chapter_id_name}.xhtml')
text.add_item(nav_css1)
text.add_item(nav_css2)
text.content = (f'<h2 class="titlecss">{chapter_title}</h2>'
f'{chapter_text}')
toc_index = toc_index + (text,)
book.spine.append(text)
if chapter_id_name == 1:
first_chapter = f'chapter_{volume_id}_{chapter_id_name}.xhtml'
book.add_item(text)
tqdm.write(f"已获取 {chapter_title}")
book.toc = book.toc + ((epub.Section(volume_title, href=first_chapter),
toc_index,),)
except BaseException as e:
print(Fore.RED + Style.BRIGHT + f"发生异常: \n{e}")
return
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
file_path = None
if path_choice == 1:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
print("您选择了自定义保存路径,请您在弹出窗口中选择路径。")
default_extension = ".epub"
default_filename = f"{title}"
while True:
file_path = filedialog.asksaveasfilename(
defaultextension=default_extension,
filetypes=[("Text Files", "*" + default_extension)],
initialfile=default_filename
)
if not file_path:
print("您没有选择路径,请重新选择!")
continue
break
cho = input("是否使用此路径覆盖此模式默认保存路径(y/n(d))?")
if not cho or cho == "n":
pass
else:
folder_path = os.path.dirname(file_path)
if not os.path.exists(config_path):
with open(config_path, "w") as c:
json.dump({"path": {"epub": folder_path}}, c)
else:
with open(config_path, "r") as c:
config = json.load(c)
config["path"]["epub"] = folder_path
with open(config_path, "w") as c:
json.dump(config, c)
elif path_choice == 0:
if not os.path.exists(config_path):
file_path = title + ".epub"
else:
with open(config_path, "r") as c:
config = json.load(c)
if "epub" in config["path"]:
file_path = os.path.join(config["path"]["epub"], f"{title}.epub")
else:
file_path = title + ".epub"
epub.write_epub(file_path, book, {})
print("文件已保存!")
return