kindlegarten 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kindlegarten-0.1.0/LICENSE +21 -0
- kindlegarten-0.1.0/PKG-INFO +75 -0
- kindlegarten-0.1.0/README.md +60 -0
- kindlegarten-0.1.0/kindlegarten/__init__.py +3 -0
- kindlegarten-0.1.0/kindlegarten/cli.py +721 -0
- kindlegarten-0.1.0/kindlegarten/constraints.txt +4 -0
- kindlegarten-0.1.0/kindlegarten.egg-info/PKG-INFO +75 -0
- kindlegarten-0.1.0/kindlegarten.egg-info/SOURCES.txt +11 -0
- kindlegarten-0.1.0/kindlegarten.egg-info/dependency_links.txt +1 -0
- kindlegarten-0.1.0/kindlegarten.egg-info/entry_points.txt +2 -0
- kindlegarten-0.1.0/kindlegarten.egg-info/top_level.txt +1 -0
- kindlegarten-0.1.0/pyproject.toml +33 -0
- kindlegarten-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kindlegarten
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A command-line backup tool for purchased Amazon Kindle books
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/yinyanfr/kindlegarten
|
|
7
|
+
Project-URL: Issues, https://github.com/yinyanfr/kindlegarten/issues
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Utilities
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# kindlegarten
|
|
17
|
+
|
|
18
|
+
> **使用范围**
|
|
19
|
+
>
|
|
20
|
+
> 本项目仅用于备份本人在 Amazon 合法购买的 Kindle 电子书。
|
|
21
|
+
|
|
22
|
+
从自己的 Amazon Kindle 书库下载电子书,以 EPUB 或 CBZ 保存到本地。下载时使用 Kindle for iPad 配置,保留亚马逊为该版本提供的彩色插图。
|
|
23
|
+
|
|
24
|
+
- 自动选择输出格式。文字书导出 EPUB,可提取为整页图片的固定版式漫画和杂志导出 CBZ。
|
|
25
|
+
- 按书名保存,自动处理文件名中的禁用字符和过长书名。下载过程只显示一条整书进度条。
|
|
26
|
+
- 支持 Amazon 日本站和美国站。登录一次后可复用本机登录状态。
|
|
27
|
+
|
|
28
|
+
## 安装
|
|
29
|
+
|
|
30
|
+
需要 Python 3.11 或更新版、[Calibre](https://calibre-ebook.com/download) 和用于登录 Amazon 的浏览器。命令面向 macOS、Windows 和 Linux,已在 macOS 实机验证。
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
python3 -m pip install kindlegarten
|
|
34
|
+
kindlegarten setup
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Windows 可用 `py -3 -m pip install kindlegarten`。若系统的 Python 由包管理器维护,可在虚拟环境中运行 `pip install kindlegarten`,或用 `pipx install kindlegarten` 安装命令。首次运行 `kindlegarten setup` 会安装导出所需的组件。
|
|
38
|
+
|
|
39
|
+
## 登录与下载
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
kindlegarten login --region jp
|
|
43
|
+
kindlegarten download B0EXAMPLE0
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
登录命令会打开 Amazon 页面并注册一个 Kindle for iPad 客户端。完成登录后,复制浏览器地址栏里的完整跳转网址,粘贴回终端并按回车。终端会隐藏粘贴的内容。
|
|
47
|
+
|
|
48
|
+
把示例中的 `B0EXAMPLE0` 替换为书籍的十位 ASIN。也可直接传入商品链接,程序会根据域名选择日本站或美国站。单独输入 ASIN 时默认使用日本站,美区账户请在登录和下载时加上 `--region us`。
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
kindlegarten download "https://www.amazon.co.jp/dp/B0EXAMPLE0"
|
|
52
|
+
kindlegarten download B0EXAMPLE0 --output "My Book.epub"
|
|
53
|
+
kindlegarten download --help
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
默认输出到当前目录下的 `books/<书名>.epub` 或 `books/<书名>.cbz`,缺少可用书名时使用 ASIN。`--output` 可以指定文件名和格式,相对路径以当前目录为准。指定 CBZ 时,程序会检查页面能否安全地作为纯图片导出。已有同名文件会提示冲突。
|
|
57
|
+
|
|
58
|
+
## 本地数据
|
|
59
|
+
|
|
60
|
+
通过 pip 安装的命令按用户保存登录状态和导出依赖。
|
|
61
|
+
|
|
62
|
+
- macOS 使用 `~/Library/Application Support/kindlegarten/`。
|
|
63
|
+
- Windows 使用 `%LOCALAPPDATA%\kindlegarten\`。
|
|
64
|
+
- Linux 使用 `$XDG_DATA_HOME/kindlegarten/`,其默认值为 `~/.local/share/kindlegarten/`。
|
|
65
|
+
|
|
66
|
+
可以用 `KINDLEGARTEN_DATA_DIR` 指定其他目录。如果之前用源码运行过,可将它设为原仓库中 `.kindle-data/` 的绝对路径,以复用现有登录状态和依赖。直接在源码仓库运行 `python3 kindle.py` 也可继续使用仓库内的 `.kindle-data/` 和 `books/`。
|
|
67
|
+
|
|
68
|
+
## 排查问题
|
|
69
|
+
|
|
70
|
+
- **找不到 Calibre**。将 `KINDLE_CALIBRE_BIN` 设置为 `calibre-debug` 和 `calibre-customize` 所在目录。Windows 使用相应的 `.exe` 文件。
|
|
71
|
+
- **登录失效或切换账户**。运行 `kindlegarten logout --region jp` 清除日本站的本地登录状态,再重新登录。可在 Amazon 的「管理内容和设备」页面注销已注册的设备。
|
|
72
|
+
- **某本书无法下载或转换**。先确认该书能从对应站点的 Kindle 书库打开。格式和加密兼容性取决于 Amazon 针对该书下发的资源。
|
|
73
|
+
- **迁移到另一台电脑**。安装 Calibre 和 kindlegarten 后,运行 `kindlegarten setup` 创建本机依赖。
|
|
74
|
+
|
|
75
|
+
程序使用 [kindl](https://github.com/bGFiMTI2/kindl) 下载、[DeDRM Tools](https://github.com/Satsuoni/DeDRM_tools) 解密、[KFX Input](https://www.mobileread.com/forums/showthread.php?t=291290) 转档。项目采用 [MIT 许可证](https://github.com/yinyanfr/kindlegarten/blob/main/LICENSE)。
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# kindlegarten
|
|
2
|
+
|
|
3
|
+
> **使用范围**
|
|
4
|
+
>
|
|
5
|
+
> 本项目仅用于备份本人在 Amazon 合法购买的 Kindle 电子书。
|
|
6
|
+
|
|
7
|
+
从自己的 Amazon Kindle 书库下载电子书,以 EPUB 或 CBZ 保存到本地。下载时使用 Kindle for iPad 配置,保留亚马逊为该版本提供的彩色插图。
|
|
8
|
+
|
|
9
|
+
- 自动选择输出格式。文字书导出 EPUB,可提取为整页图片的固定版式漫画和杂志导出 CBZ。
|
|
10
|
+
- 按书名保存,自动处理文件名中的禁用字符和过长书名。下载过程只显示一条整书进度条。
|
|
11
|
+
- 支持 Amazon 日本站和美国站。登录一次后可复用本机登录状态。
|
|
12
|
+
|
|
13
|
+
## 安装
|
|
14
|
+
|
|
15
|
+
需要 Python 3.11 或更新版、[Calibre](https://calibre-ebook.com/download) 和用于登录 Amazon 的浏览器。命令面向 macOS、Windows 和 Linux,已在 macOS 实机验证。
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
python3 -m pip install kindlegarten
|
|
19
|
+
kindlegarten setup
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Windows 可用 `py -3 -m pip install kindlegarten`。若系统的 Python 由包管理器维护,可在虚拟环境中运行 `pip install kindlegarten`,或用 `pipx install kindlegarten` 安装命令。首次运行 `kindlegarten setup` 会安装导出所需的组件。
|
|
23
|
+
|
|
24
|
+
## 登录与下载
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
kindlegarten login --region jp
|
|
28
|
+
kindlegarten download B0EXAMPLE0
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
登录命令会打开 Amazon 页面并注册一个 Kindle for iPad 客户端。完成登录后,复制浏览器地址栏里的完整跳转网址,粘贴回终端并按回车。终端会隐藏粘贴的内容。
|
|
32
|
+
|
|
33
|
+
把示例中的 `B0EXAMPLE0` 替换为书籍的十位 ASIN。也可直接传入商品链接,程序会根据域名选择日本站或美国站。单独输入 ASIN 时默认使用日本站,美区账户请在登录和下载时加上 `--region us`。
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
kindlegarten download "https://www.amazon.co.jp/dp/B0EXAMPLE0"
|
|
37
|
+
kindlegarten download B0EXAMPLE0 --output "My Book.epub"
|
|
38
|
+
kindlegarten download --help
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
默认输出到当前目录下的 `books/<书名>.epub` 或 `books/<书名>.cbz`,缺少可用书名时使用 ASIN。`--output` 可以指定文件名和格式,相对路径以当前目录为准。指定 CBZ 时,程序会检查页面能否安全地作为纯图片导出。已有同名文件会提示冲突。
|
|
42
|
+
|
|
43
|
+
## 本地数据
|
|
44
|
+
|
|
45
|
+
通过 pip 安装的命令按用户保存登录状态和导出依赖。
|
|
46
|
+
|
|
47
|
+
- macOS 使用 `~/Library/Application Support/kindlegarten/`。
|
|
48
|
+
- Windows 使用 `%LOCALAPPDATA%\kindlegarten\`。
|
|
49
|
+
- Linux 使用 `$XDG_DATA_HOME/kindlegarten/`,其默认值为 `~/.local/share/kindlegarten/`。
|
|
50
|
+
|
|
51
|
+
可以用 `KINDLEGARTEN_DATA_DIR` 指定其他目录。如果之前用源码运行过,可将它设为原仓库中 `.kindle-data/` 的绝对路径,以复用现有登录状态和依赖。直接在源码仓库运行 `python3 kindle.py` 也可继续使用仓库内的 `.kindle-data/` 和 `books/`。
|
|
52
|
+
|
|
53
|
+
## 排查问题
|
|
54
|
+
|
|
55
|
+
- **找不到 Calibre**。将 `KINDLE_CALIBRE_BIN` 设置为 `calibre-debug` 和 `calibre-customize` 所在目录。Windows 使用相应的 `.exe` 文件。
|
|
56
|
+
- **登录失效或切换账户**。运行 `kindlegarten logout --region jp` 清除日本站的本地登录状态,再重新登录。可在 Amazon 的「管理内容和设备」页面注销已注册的设备。
|
|
57
|
+
- **某本书无法下载或转换**。先确认该书能从对应站点的 Kindle 书库打开。格式和加密兼容性取决于 Amazon 针对该书下发的资源。
|
|
58
|
+
- **迁移到另一台电脑**。安装 Calibre 和 kindlegarten 后,运行 `kindlegarten setup` 创建本机依赖。
|
|
59
|
+
|
|
60
|
+
程序使用 [kindl](https://github.com/bGFiMTI2/kindl) 下载、[DeDRM Tools](https://github.com/Satsuoni/DeDRM_tools) 解密、[KFX Input](https://www.mobileread.com/forums/showthread.php?t=291290) 转档。项目采用 [MIT 许可证](https://github.com/yinyanfr/kindlegarten/blob/main/LICENSE)。
|
|
@@ -0,0 +1,721 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import errno
|
|
3
|
+
import getpass
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import unicodedata
|
|
13
|
+
import webbrowser
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from tempfile import TemporaryDirectory
|
|
17
|
+
from time import monotonic
|
|
18
|
+
from urllib.error import URLError
|
|
19
|
+
from urllib.parse import parse_qs, urlsplit
|
|
20
|
+
from urllib.request import Request, urlopen
|
|
21
|
+
from xml.etree import ElementTree
|
|
22
|
+
from zipfile import BadZipFile, ZipFile
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
SCRIPT = Path(__file__).resolve()
|
|
26
|
+
COMMAND = "kindlegarten"
|
|
27
|
+
VENV_PYTHON = Path("venv") / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
|
28
|
+
KINDL_SOURCE = (
|
|
29
|
+
"https://codeload.github.com/bGFiMTI2/kindl/tar.gz/a896621dde52fc052a960f4bab7af84036013e23",
|
|
30
|
+
"defb9e1647096013c94067e8eaea43dd1d7289afa7c953029f18e0c010675a4e",
|
|
31
|
+
)
|
|
32
|
+
DEDRM_SOURCE = (
|
|
33
|
+
"https://github.com/Satsuoni/DeDRM_tools/releases/download/v10.0.35/DeDRM_tools.zip",
|
|
34
|
+
"5c85cce954b17836c2b421d6ae8b313f0aaeb190a9a3f81881636dbc80e25bc3",
|
|
35
|
+
)
|
|
36
|
+
KFX_SOURCE = (
|
|
37
|
+
"https://plugins.calibre-ebook.com/291290.zip",
|
|
38
|
+
"338809c18e5f9bb721dc3570a64cf6f7add4a1711c8183e6179e90fcbadf3c1d",
|
|
39
|
+
)
|
|
40
|
+
PLUGINS = ("KFX Input.zip", "DeDRM.zip")
|
|
41
|
+
REGIONS = {"amazon.co.jp": "jp", "amazon.com": "us"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class KindleError(Exception):
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def user_data_directory():
|
|
49
|
+
if os.name == "nt":
|
|
50
|
+
base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData/Local")
|
|
51
|
+
elif sys.platform == "darwin":
|
|
52
|
+
base = Path.home() / "Library/Application Support"
|
|
53
|
+
else:
|
|
54
|
+
base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share")
|
|
55
|
+
return base / "kindlegarten"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def calibre_executable(name):
|
|
59
|
+
binary = name + ".exe" if os.name == "nt" else name
|
|
60
|
+
override = os.environ.get("KINDLE_CALIBRE_BIN")
|
|
61
|
+
if override:
|
|
62
|
+
candidate = Path(override).expanduser() / binary
|
|
63
|
+
if candidate.is_file():
|
|
64
|
+
return candidate
|
|
65
|
+
else:
|
|
66
|
+
on_path = shutil.which(binary)
|
|
67
|
+
if on_path:
|
|
68
|
+
return Path(on_path)
|
|
69
|
+
if os.name == "nt":
|
|
70
|
+
directories = [Path(root) / "Calibre2" for key in ("ProgramFiles", "ProgramFiles(x86)")
|
|
71
|
+
if (root := os.environ.get(key))]
|
|
72
|
+
elif sys.platform == "darwin":
|
|
73
|
+
directories = [Path("/Applications/calibre.app/Contents/MacOS"),
|
|
74
|
+
Path.home() / "Applications/calibre.app/Contents/MacOS"]
|
|
75
|
+
else:
|
|
76
|
+
directories = [Path("/opt/calibre"), Path("/usr/bin"), Path("/usr/local/bin")]
|
|
77
|
+
for directory in directories:
|
|
78
|
+
candidate = directory / binary
|
|
79
|
+
if candidate.is_file():
|
|
80
|
+
return candidate
|
|
81
|
+
raise KindleError(f"找不到 {binary}。请安装 Calibre,或用 KINDLE_CALIBRE_BIN 指定其可执行文件目录。")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@contextmanager
|
|
85
|
+
def project_lock():
|
|
86
|
+
DATA.mkdir(mode=0o700, exist_ok=True)
|
|
87
|
+
with (DATA / "lock").open("a+b") as lock:
|
|
88
|
+
lock.seek(0)
|
|
89
|
+
try:
|
|
90
|
+
if os.name == "nt":
|
|
91
|
+
import msvcrt
|
|
92
|
+
|
|
93
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
|
94
|
+
else:
|
|
95
|
+
import fcntl
|
|
96
|
+
|
|
97
|
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
98
|
+
except OSError as error:
|
|
99
|
+
if error.errno not in {errno.EACCES, errno.EAGAIN}:
|
|
100
|
+
raise
|
|
101
|
+
raise KindleError("另一个下载器进程正在运行,请结束后再试。") from None
|
|
102
|
+
yield
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def sha256(path):
|
|
106
|
+
with path.open("rb") as stream:
|
|
107
|
+
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def fetch_verified(source, destination):
|
|
111
|
+
url, digest = source
|
|
112
|
+
try:
|
|
113
|
+
request = Request(url, headers={"User-Agent": "kindle-downloader/1.0"})
|
|
114
|
+
with urlopen(request, timeout=60) as response, destination.open("xb") as output:
|
|
115
|
+
shutil.copyfileobj(response, output)
|
|
116
|
+
except (URLError, TimeoutError) as error:
|
|
117
|
+
raise KindleError(f"无法下载依赖 {url}({error})。") from None
|
|
118
|
+
if sha256(destination) != digest:
|
|
119
|
+
raise KindleError(f"依赖包的 SHA-256 与预期不符:{url}")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def calibre_config_dir():
|
|
123
|
+
override = os.environ.get("CALIBRE_CONFIG_DIRECTORY")
|
|
124
|
+
if override:
|
|
125
|
+
return Path(override).expanduser()
|
|
126
|
+
if os.name == "nt":
|
|
127
|
+
return Path(os.environ.get("APPDATA") or Path.home() / "AppData/Roaming") / "calibre"
|
|
128
|
+
if sys.platform == "darwin":
|
|
129
|
+
return Path.home() / "Library/Preferences/calibre"
|
|
130
|
+
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "calibre"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def configure_calibre(plugin_dir, config_dir):
|
|
134
|
+
customize = calibre_executable("calibre-customize")
|
|
135
|
+
env = dict(os.environ, CALIBRE_CONFIG_DIRECTORY=str(config_dir))
|
|
136
|
+
config_dir.mkdir()
|
|
137
|
+
for plugin in PLUGINS:
|
|
138
|
+
result = subprocess.run([customize, "--add-plugin", plugin_dir / plugin],
|
|
139
|
+
env=env, capture_output=True)
|
|
140
|
+
if result.returncode:
|
|
141
|
+
raise KindleError(f"Calibre 插件 {plugin} 加载失败。")
|
|
142
|
+
return env
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def setup_ready():
|
|
146
|
+
return all((RUNTIME / filename).is_file() for filename in (VENV_PYTHON, *PLUGINS))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def setup(_args):
|
|
150
|
+
calibre_executable("calibre-debug")
|
|
151
|
+
calibre_executable("calibre-customize")
|
|
152
|
+
if setup_ready():
|
|
153
|
+
print("依赖已安装。")
|
|
154
|
+
return
|
|
155
|
+
|
|
156
|
+
base_python = os.environ.get("KINDLE_PYTHON", sys.executable)
|
|
157
|
+
with TemporaryDirectory(prefix=".setup-", dir=DATA) as temporary:
|
|
158
|
+
staging = Path(temporary) / "runtime"
|
|
159
|
+
staging.mkdir()
|
|
160
|
+
print("正在安装 kindl、DeDRM 和 KFX Input…", flush=True)
|
|
161
|
+
archive = staging / "kindl.tar.gz"
|
|
162
|
+
fetch_verified(KINDL_SOURCE, archive)
|
|
163
|
+
subprocess.run([base_python, "-m", "venv", staging / "venv"], check=True)
|
|
164
|
+
subprocess.run([staging / VENV_PYTHON, "-m", "pip", "install",
|
|
165
|
+
"--disable-pip-version-check", "--no-cache-dir", "--constraint",
|
|
166
|
+
SCRIPT.with_name("constraints.txt"), archive], check=True)
|
|
167
|
+
archive.unlink()
|
|
168
|
+
|
|
169
|
+
dedrm_archive = staging / "DeDRM_tools.zip"
|
|
170
|
+
fetch_verified(DEDRM_SOURCE, dedrm_archive)
|
|
171
|
+
with ZipFile(dedrm_archive) as package:
|
|
172
|
+
(staging / "DeDRM.zip").write_bytes(package.read("DeDRM_plugin.zip"))
|
|
173
|
+
dedrm_archive.unlink()
|
|
174
|
+
|
|
175
|
+
kfx_archive = staging / "KFX Input.zip"
|
|
176
|
+
local_kfx = calibre_config_dir() / "plugins/KFX Input.zip"
|
|
177
|
+
if local_kfx.is_file() and sha256(local_kfx) == KFX_SOURCE[1]:
|
|
178
|
+
shutil.copyfile(local_kfx, kfx_archive)
|
|
179
|
+
else:
|
|
180
|
+
fetch_verified(KFX_SOURCE, kfx_archive)
|
|
181
|
+
|
|
182
|
+
configure_calibre(staging, Path(temporary) / "calibre")
|
|
183
|
+
if RUNTIME.exists():
|
|
184
|
+
shutil.rmtree(RUNTIME)
|
|
185
|
+
staging.rename(RUNTIME)
|
|
186
|
+
print("依赖安装完成。")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def require_setup():
|
|
190
|
+
if not setup_ready():
|
|
191
|
+
raise KindleError(f"请先运行 {COMMAND} setup。")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def account_path(region):
|
|
195
|
+
return DATA / f"account-{region}.json"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def book_target(value):
|
|
199
|
+
if re.fullmatch(r"[A-Z0-9]{10}", value, re.IGNORECASE | re.ASCII):
|
|
200
|
+
return value.upper(), None
|
|
201
|
+
try:
|
|
202
|
+
url = urlsplit(value)
|
|
203
|
+
host = re.sub(r"^(www|smile)\.", "", url.hostname or "")
|
|
204
|
+
except ValueError:
|
|
205
|
+
raise KindleError("请输入 10 位 ASIN 或 Amazon 商品链接。") from None
|
|
206
|
+
if url.scheme not in {"https", "http"} or host not in REGIONS:
|
|
207
|
+
raise KindleError("请输入 10 位 ASIN 或 amazon.co.jp / amazon.com 的完整商品链接。")
|
|
208
|
+
match = re.search(r"/(?:dp|gp/product|gp/aw/d)/([A-Z0-9]{10})(?:/|$)",
|
|
209
|
+
url.path, re.IGNORECASE | re.ASCII)
|
|
210
|
+
if not match:
|
|
211
|
+
raise KindleError("商品链接里找不到 ASIN。")
|
|
212
|
+
return match[1].upper(), REGIONS[host]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def book_filename(title, asin, extension):
|
|
216
|
+
stem = unicodedata.normalize("NFC", title)
|
|
217
|
+
stem = re.sub(r'[<>:"/\\|?*\x00-\x1f\x7f-\x9f\ud800-\udfff]+', "_", stem)
|
|
218
|
+
stem = re.sub(r"\s+", " ", stem).strip(" .")
|
|
219
|
+
if not stem.strip(" _."):
|
|
220
|
+
stem = asin
|
|
221
|
+
|
|
222
|
+
device = stem.split(".", 1)[0].rstrip().upper()
|
|
223
|
+
if re.fullmatch(r"CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|(?:COM|LPT)[1-9¹²³]", device):
|
|
224
|
+
stem = f"_{stem}"
|
|
225
|
+
|
|
226
|
+
max_bytes = 255 - len(extension.encode("utf-8"))
|
|
227
|
+
stem = stem.encode("utf-8")[:max_bytes].decode("utf-8", errors="ignore").rstrip(" .")
|
|
228
|
+
return f"{stem or asin}{extension}"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def publish_book(source, destination):
|
|
232
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
233
|
+
with TemporaryDirectory(prefix=".kindle-", dir=destination.parent) as temporary:
|
|
234
|
+
staged = Path(temporary) / source.name
|
|
235
|
+
shutil.copyfile(source, staged)
|
|
236
|
+
if os.name == "nt":
|
|
237
|
+
staged.rename(destination)
|
|
238
|
+
else:
|
|
239
|
+
os.link(staged, destination)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def start_login(args):
|
|
243
|
+
require_setup()
|
|
244
|
+
state = account_path(args.region)
|
|
245
|
+
if state.exists():
|
|
246
|
+
print(f"{args.region} 已有登录状态。更换账户前请先运行 {COMMAND} logout --region {args.region}。")
|
|
247
|
+
return
|
|
248
|
+
run_worker("_login", args.region, state)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def logout(args):
|
|
252
|
+
state = account_path(args.region)
|
|
253
|
+
state.unlink(missing_ok=True)
|
|
254
|
+
state.with_suffix(".json.tmp").unlink(missing_ok=True)
|
|
255
|
+
print(f"已清除 {args.region} 的本地登录状态。")
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def run_worker(command, *args):
|
|
259
|
+
result = subprocess.run([RUNTIME / VENV_PYTHON, SCRIPT, command, *args])
|
|
260
|
+
if result.returncode:
|
|
261
|
+
raise SystemExit(result.returncode)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def download_book(args):
|
|
265
|
+
asin, site_region = book_target(args.book)
|
|
266
|
+
if site_region and args.region and site_region != args.region:
|
|
267
|
+
raise KindleError("商品链接站点与 --region 不一致。")
|
|
268
|
+
region = args.region or site_region or "jp"
|
|
269
|
+
destination = args.output.expanduser().absolute() if args.output else None
|
|
270
|
+
requested_format = destination.suffix.lower()[1:] if destination else "auto"
|
|
271
|
+
if requested_format not in {"epub", "cbz"} and destination:
|
|
272
|
+
raise KindleError("--output 需要指定 .epub 或 .cbz 文件。")
|
|
273
|
+
if destination:
|
|
274
|
+
require_new_output(destination)
|
|
275
|
+
require_setup()
|
|
276
|
+
account = account_path(region)
|
|
277
|
+
if not account.is_file():
|
|
278
|
+
raise KindleError(f"请先运行 {COMMAND} login --region {region}。")
|
|
279
|
+
debug = calibre_executable("calibre-debug")
|
|
280
|
+
|
|
281
|
+
with TemporaryDirectory(prefix=".job-", dir=DATA) as temporary:
|
|
282
|
+
staging = Path(temporary)
|
|
283
|
+
env = configure_calibre(RUNTIME, staging / "calibre")
|
|
284
|
+
encrypted = staging / "download" / f"{asin}.kfx-zip"
|
|
285
|
+
decrypted = staging / "decrypted.kfx-zip"
|
|
286
|
+
print(f"正在请求 {region} 站 iPad 版 {asin}…", flush=True)
|
|
287
|
+
run_worker("_download", account, asin, encrypted)
|
|
288
|
+
print("正在去除 DRM 并转换文件…", flush=True)
|
|
289
|
+
result = subprocess.run([debug, "-e", SCRIPT, "--", "_decrypt", account, encrypted, decrypted],
|
|
290
|
+
env=env, capture_output=True)
|
|
291
|
+
if result.returncode or not decrypted.is_file():
|
|
292
|
+
raise KindleError("DeDRM 无法解密该书。请确认账户有访问权限,或检查该加密版本是否受支持。")
|
|
293
|
+
conversion = subprocess.run([debug, "-e", SCRIPT, "--", "_convert", decrypted, staging, requested_format],
|
|
294
|
+
env=env, capture_output=True)
|
|
295
|
+
messages = conversion.stdout + conversion.stderr
|
|
296
|
+
if conversion.returncode:
|
|
297
|
+
if b"CBZ_REQUIRES_IMAGE_PAGES" in messages:
|
|
298
|
+
raise KindleError("这本书含文字或使用了无法安全导出为 CBZ 的版式。请指定 .epub 输出。")
|
|
299
|
+
raise KindleError("KFX Input 无法转换这份 KFX。")
|
|
300
|
+
converted = [staging / name for name in ("book.epub", "book.cbz") if (staging / name).is_file()]
|
|
301
|
+
if len(converted) != 1:
|
|
302
|
+
raise KindleError("KFX Input 没有生成一个有效的输出文件。")
|
|
303
|
+
source = converted[0]
|
|
304
|
+
if destination is None:
|
|
305
|
+
title = json.loads((staging / "title.json").read_text(encoding="utf-8"))
|
|
306
|
+
destination = BOOKS / book_filename(title, asin, source.suffix)
|
|
307
|
+
require_new_output(destination)
|
|
308
|
+
publish_book(source, destination)
|
|
309
|
+
if b"Missing font family names" in messages:
|
|
310
|
+
print("还有出版方字体无法映射,已保留 EPUB 的字体回退设置。", file=sys.stderr)
|
|
311
|
+
print(f"已保存 {destination}")
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def require_new_output(path):
|
|
315
|
+
if path.exists() or path.is_symlink():
|
|
316
|
+
raise KindleError(f"输出文件已存在:{path}。请用 --output 指定新文件。")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def read_login_url():
|
|
320
|
+
prompt = "粘贴登录后的完整网址并按回车(输入隐藏):"
|
|
321
|
+
if os.name == "nt":
|
|
322
|
+
return getpass.getpass(prompt).strip()
|
|
323
|
+
|
|
324
|
+
# macOS limits a canonical terminal read to 1024 bytes, shorter than some callbacks.
|
|
325
|
+
import termios
|
|
326
|
+
|
|
327
|
+
fd = sys.stdin.fileno()
|
|
328
|
+
original = termios.tcgetattr(fd)
|
|
329
|
+
settings = termios.tcgetattr(fd)
|
|
330
|
+
settings[3] &= ~termios.ICANON
|
|
331
|
+
settings[6][termios.VMIN] = 1
|
|
332
|
+
settings[6][termios.VTIME] = 0
|
|
333
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
|
|
334
|
+
try:
|
|
335
|
+
return getpass.getpass(prompt).strip()
|
|
336
|
+
finally:
|
|
337
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, original)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def login(region, state):
|
|
341
|
+
from kindl.auth import Account, AccountStore, new_device_identity, pkce_pair
|
|
342
|
+
from kindl.client import AmazonDeviceClient
|
|
343
|
+
from kindl.regions import get_region
|
|
344
|
+
|
|
345
|
+
if not sys.stdin.isatty():
|
|
346
|
+
raise KindleError("请在交互式终端中运行登录命令。")
|
|
347
|
+
site = get_region(region).site
|
|
348
|
+
serial, pid = new_device_identity()
|
|
349
|
+
verifier, challenge = pkce_pair()
|
|
350
|
+
language = "ja_JP" if region == "jp" else "en_US"
|
|
351
|
+
url = AmazonDeviceClient.login_url(serial, challenge, language=language, region=region)
|
|
352
|
+
print(f"正在打开 {site} 登录页。请使用有该书访问权限的账户。", flush=True)
|
|
353
|
+
if not webbrowser.open(url):
|
|
354
|
+
print(f"请在浏览器手动打开此登录地址:\n{url}")
|
|
355
|
+
print("登录完成后,复制浏览器地址栏里的完整跳转网址。", flush=True)
|
|
356
|
+
while True:
|
|
357
|
+
callback = read_login_url()
|
|
358
|
+
try:
|
|
359
|
+
parsed = urlsplit(callback)
|
|
360
|
+
except ValueError:
|
|
361
|
+
print(f"请重新复制 {site} 登录后地址栏里的完整网址。")
|
|
362
|
+
continue
|
|
363
|
+
if (
|
|
364
|
+
parsed.scheme == "https"
|
|
365
|
+
and parsed.hostname in {site, f"www.{site}"}
|
|
366
|
+
and parse_qs(parsed.query).get("openid.oa2.authorization_code")
|
|
367
|
+
):
|
|
368
|
+
break
|
|
369
|
+
print(f"请重新复制 {site} 登录后地址栏里的完整网址。")
|
|
370
|
+
|
|
371
|
+
with AmazonDeviceClient(region=region) as client:
|
|
372
|
+
credentials = client.register(callback, verifier, serial, pid)
|
|
373
|
+
store = AccountStore()
|
|
374
|
+
store.add(Account("ipad", credentials))
|
|
375
|
+
store.save(state)
|
|
376
|
+
print(f"已为 {site} 保存本机登录状态。")
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def download(state, asin, destination):
|
|
380
|
+
import httpx
|
|
381
|
+
from kindl.auth import AccountStore
|
|
382
|
+
from kindl.bundle import package_kfx_zip
|
|
383
|
+
from kindl.client import AmazonDeviceClient
|
|
384
|
+
|
|
385
|
+
store = AccountStore.load(state)
|
|
386
|
+
account = store.get("ipad")
|
|
387
|
+
if account is None:
|
|
388
|
+
raise KindleError("本地登录状态不完整,请重新登录。")
|
|
389
|
+
|
|
390
|
+
folder = destination.parent
|
|
391
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
392
|
+
with AmazonDeviceClient(account.credentials) as client:
|
|
393
|
+
client.refresh_device_credentials()
|
|
394
|
+
store.save(state)
|
|
395
|
+
if not account.credentials.account_secrets:
|
|
396
|
+
try:
|
|
397
|
+
if client.restore_account_secrets():
|
|
398
|
+
store.save(state)
|
|
399
|
+
except (httpx.HTTPError, OSError, RuntimeError):
|
|
400
|
+
# Some vouchers can be decrypted with the device serial alone.
|
|
401
|
+
pass
|
|
402
|
+
with track_download(client):
|
|
403
|
+
client.download(asin, folder, include_optional=True, destination=folder)
|
|
404
|
+
package_kfx_zip(folder, destination)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def byte_label(amount):
|
|
408
|
+
for unit in ("B", "KiB", "MiB", "GiB"):
|
|
409
|
+
if amount < 1024 or unit == "GiB":
|
|
410
|
+
return f"{amount:.1f} {unit}"
|
|
411
|
+
amount /= 1024
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
class DownloadProgress:
|
|
415
|
+
def __init__(self):
|
|
416
|
+
self.tty = sys.stderr.isatty()
|
|
417
|
+
self.started = None
|
|
418
|
+
self.received = self.completed = self.width = 0
|
|
419
|
+
self.current_size = self.current_received = 0
|
|
420
|
+
|
|
421
|
+
def start(self, sizes):
|
|
422
|
+
self.files = len(sizes)
|
|
423
|
+
self.total = (sum(sizes) or None) if all(type(size) is int and size > 0 for size in sizes) else None
|
|
424
|
+
self.started = self.updated = monotonic()
|
|
425
|
+
if self.tty:
|
|
426
|
+
self.show(self.started)
|
|
427
|
+
|
|
428
|
+
def begin_resource(self, length):
|
|
429
|
+
self.current_size = int(length) if length.isascii() and length.isdecimal() else 0
|
|
430
|
+
|
|
431
|
+
def finish_resource(self):
|
|
432
|
+
self.completed += 1
|
|
433
|
+
self.current_size = self.current_received = 0
|
|
434
|
+
|
|
435
|
+
def advance(self, size):
|
|
436
|
+
self.received += size
|
|
437
|
+
self.current_received += size
|
|
438
|
+
now = monotonic()
|
|
439
|
+
if self.tty and now - self.updated >= 0.2:
|
|
440
|
+
self.show(now)
|
|
441
|
+
|
|
442
|
+
def show(self, now, finished=None):
|
|
443
|
+
self.updated = now
|
|
444
|
+
speed = byte_label(self.received / max(now - self.started, 0.001))
|
|
445
|
+
downloaded = byte_label(self.received)
|
|
446
|
+
if self.total is not None:
|
|
447
|
+
ratio = self.received / self.total
|
|
448
|
+
downloaded += f"/{byte_label(self.received if finished else self.total)}"
|
|
449
|
+
else:
|
|
450
|
+
fraction = min(1, self.current_received / self.current_size) if self.current_size else 0
|
|
451
|
+
ratio = (self.completed + fraction) / max(self.files, 1)
|
|
452
|
+
percent = 100 if finished else min(99, int(ratio * 100))
|
|
453
|
+
approximate = "~" if self.total is None and not finished else ""
|
|
454
|
+
filled = percent * 16 // 100
|
|
455
|
+
bar = "#" * filled + "-" * (16 - filled)
|
|
456
|
+
status = " 完成" if finished else " 中断" if finished is False else ""
|
|
457
|
+
line = f"下载 [{bar}] {approximate}{percent:3d}% {downloaded} {speed}/s{status}"
|
|
458
|
+
if self.tty:
|
|
459
|
+
print("\r" + line.ljust(self.width), end="\n" if finished is not None else "",
|
|
460
|
+
file=sys.stderr, flush=True)
|
|
461
|
+
self.width = len(line)
|
|
462
|
+
else:
|
|
463
|
+
print(line, file=sys.stderr, flush=True)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@contextmanager
|
|
467
|
+
def track_download(client):
|
|
468
|
+
from httpx import SyncByteStream
|
|
469
|
+
|
|
470
|
+
progress = DownloadProgress()
|
|
471
|
+
manifest = client.manifest
|
|
472
|
+
stream = client.http.stream
|
|
473
|
+
|
|
474
|
+
def prepare_progress(asin):
|
|
475
|
+
payload, correlation = manifest(asin)
|
|
476
|
+
sizes = [resource.get("size") for resource in payload.get("resources", [])
|
|
477
|
+
if (resource.get("endpoint") or {}).get("url") and resource.get("type") != "KINDLE_USER_ANOT"]
|
|
478
|
+
progress.start(sizes)
|
|
479
|
+
return payload, correlation
|
|
480
|
+
|
|
481
|
+
class MeasuredStream(SyncByteStream):
|
|
482
|
+
def __init__(self, wrapped):
|
|
483
|
+
self.wrapped = wrapped
|
|
484
|
+
|
|
485
|
+
def __iter__(self):
|
|
486
|
+
for chunk in self.wrapped:
|
|
487
|
+
progress.advance(len(chunk))
|
|
488
|
+
yield chunk
|
|
489
|
+
|
|
490
|
+
def close(self):
|
|
491
|
+
self.wrapped.close()
|
|
492
|
+
|
|
493
|
+
@contextmanager
|
|
494
|
+
def measure(*args, **kwargs):
|
|
495
|
+
with stream(*args, **kwargs) as response:
|
|
496
|
+
if not response.is_success:
|
|
497
|
+
yield response
|
|
498
|
+
return
|
|
499
|
+
progress.begin_resource(response.headers.get("Content-Length", ""))
|
|
500
|
+
response.stream = MeasuredStream(response.stream)
|
|
501
|
+
yield response
|
|
502
|
+
progress.finish_resource()
|
|
503
|
+
|
|
504
|
+
client.manifest = prepare_progress
|
|
505
|
+
client.http.stream = measure
|
|
506
|
+
finished = False
|
|
507
|
+
try:
|
|
508
|
+
yield
|
|
509
|
+
finished = True
|
|
510
|
+
finally:
|
|
511
|
+
client.manifest = manifest
|
|
512
|
+
client.http.stream = stream
|
|
513
|
+
if progress.started is not None:
|
|
514
|
+
progress.show(monotonic(), finished)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def decrypt(state, source, destination):
|
|
518
|
+
from calibre.customize.ui import find_plugin
|
|
519
|
+
from calibre_plugins.dedrm import ion
|
|
520
|
+
from calibre_plugins.dedrm.prefs import DeDRM_Prefs
|
|
521
|
+
|
|
522
|
+
account = next(item for item in json.loads(state.read_text())["accounts"] if item["name"] == "ipad")
|
|
523
|
+
credentials = account["credentials"]
|
|
524
|
+
serial = credentials["serial"]
|
|
525
|
+
if not ion.is_serial_id(serial):
|
|
526
|
+
raise KindleError("本地登录状态里的设备序列号无效,请重新登录。")
|
|
527
|
+
tokens = list(dict.fromkeys(
|
|
528
|
+
value
|
|
529
|
+
for token in credentials.get("account_secrets", [])
|
|
530
|
+
for value in (token, *ion.unwrap_secret_token(token, allow_plain=True))
|
|
531
|
+
))
|
|
532
|
+
preferences = DeDRM_Prefs()
|
|
533
|
+
preferences.set("serials", [serial])
|
|
534
|
+
preferences.set("pids", [*tokens, *(serial + token for token in tokens)])
|
|
535
|
+
preferences.writeprefs()
|
|
536
|
+
|
|
537
|
+
plugin = find_plugin("DeDRM")
|
|
538
|
+
if plugin is None:
|
|
539
|
+
raise KindleError("临时 Calibre 配置未加载 DeDRM。")
|
|
540
|
+
decrypted = Path(plugin.run(str(source)))
|
|
541
|
+
shutil.copyfile(decrypted, destination)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def picture_pages(book):
|
|
545
|
+
if not book.is_image_based_fixed_layout:
|
|
546
|
+
return []
|
|
547
|
+
resources, _, _ = book.get_ordered_image_resources()
|
|
548
|
+
if book.has_pdf_resource:
|
|
549
|
+
from calibre_plugins.kfx_input.kfxlib.resources import get_pdf_reader
|
|
550
|
+
from calibre_plugins.kfx_input.kfxlib.yj_to_image_book import KFX_IMAGE_BOOK
|
|
551
|
+
|
|
552
|
+
image_book = KFX_IMAGE_BOOK(book)
|
|
553
|
+
try:
|
|
554
|
+
for resource in resources:
|
|
555
|
+
image = image_book.get_resource_image(resource)
|
|
556
|
+
if image is None:
|
|
557
|
+
return []
|
|
558
|
+
if image.format == "$565":
|
|
559
|
+
pdf = get_pdf_reader(image.raw_media, book.pdf_cache)
|
|
560
|
+
for number in image.page_nums:
|
|
561
|
+
page = pdf.pages[number - 1]
|
|
562
|
+
if len(page.images) != 1 or page.extract_text().strip():
|
|
563
|
+
return []
|
|
564
|
+
except Exception:
|
|
565
|
+
# Retain EPUB if the PDF page content cannot be verified as images alone.
|
|
566
|
+
return []
|
|
567
|
+
return resources
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def convert_book(source, output_dir, requested_format):
|
|
571
|
+
from calibre_plugins.kfx_input import get_symbol_catalog_filename
|
|
572
|
+
from calibre_plugins.kfx_input.config import config_desaturate_notebooks
|
|
573
|
+
from calibre_plugins.kfx_input.kfxlib import YJ_Book
|
|
574
|
+
from calibre_plugins.kfx_input.kfxlib.yj_to_epub import KFX_EPUB
|
|
575
|
+
|
|
576
|
+
class JapaneseEPUB(KFX_EPUB):
|
|
577
|
+
def process_document_data(self):
|
|
578
|
+
# process_fonts() has registered the book's embedded families by now.
|
|
579
|
+
self.font_name_replacements.setdefault("ja", "serif")
|
|
580
|
+
super().process_document_data()
|
|
581
|
+
|
|
582
|
+
logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s")
|
|
583
|
+
book = YJ_Book(str(source), symbol_catalog_filename=get_symbol_catalog_filename())
|
|
584
|
+
book.decode_book(retain_yj_locals=True)
|
|
585
|
+
title = str(book.get_metadata_value("title") or "")
|
|
586
|
+
(output_dir / "title.json").write_text(json.dumps(title), encoding="utf-8")
|
|
587
|
+
|
|
588
|
+
pages = picture_pages(book) if requested_format != "epub" else []
|
|
589
|
+
if requested_format == "cbz" and not pages:
|
|
590
|
+
raise KindleError("CBZ_REQUIRES_IMAGE_PAGES")
|
|
591
|
+
if pages:
|
|
592
|
+
output = output_dir / "book.cbz"
|
|
593
|
+
output.write_bytes(book.convert_to_cbz())
|
|
594
|
+
with ZipFile(output) as archive:
|
|
595
|
+
images = [name for name in archive.namelist()
|
|
596
|
+
if Path(name).suffix.lower() in {".jpg", ".jpeg", ".png", ".gif"}]
|
|
597
|
+
if len(images) != len(pages) or archive.testzip() is not None:
|
|
598
|
+
raise KindleError("CBZ 的图片页数与原书不符,或存档校验失败。")
|
|
599
|
+
return
|
|
600
|
+
|
|
601
|
+
output = output_dir / "book.epub"
|
|
602
|
+
language = str(book.get_metadata_value("language") or "").lower().replace("_", "-").split("-")[0]
|
|
603
|
+
if language == "ja":
|
|
604
|
+
epub = JapaneseEPUB(book, desaturate_notebooks=config_desaturate_notebooks()).decompile_to_epub()
|
|
605
|
+
book.final_actions()
|
|
606
|
+
else:
|
|
607
|
+
epub = book.convert_to_epub(desaturate_notebooks=config_desaturate_notebooks())
|
|
608
|
+
output.write_bytes(epub)
|
|
609
|
+
check_epub(output)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def check_epub(path):
|
|
613
|
+
try:
|
|
614
|
+
with ZipFile(path) as epub:
|
|
615
|
+
if epub.read("mimetype") != b"application/epub+zip" or epub.testzip() is not None:
|
|
616
|
+
raise KindleError("EPUB 校验失败。")
|
|
617
|
+
container = ElementTree.fromstring(epub.read("META-INF/container.xml"))
|
|
618
|
+
rootfile = container.find(".//{*}rootfile")
|
|
619
|
+
if rootfile is None:
|
|
620
|
+
raise KindleError("EPUB 缺少目录清单。")
|
|
621
|
+
package = ElementTree.fromstring(epub.read(rootfile.attrib["full-path"]))
|
|
622
|
+
if not package.findall(".//{*}spine/{*}itemref"):
|
|
623
|
+
raise KindleError("EPUB 缺少正文阅读顺序。")
|
|
624
|
+
except (BadZipFile, KeyError, ElementTree.ParseError):
|
|
625
|
+
raise KindleError("生成的 EPUB 文件结构不完整。") from None
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def worker(command, args):
|
|
629
|
+
if command in {"_login", "_download"}:
|
|
630
|
+
for key in list(os.environ):
|
|
631
|
+
if key.startswith("KINDL_"):
|
|
632
|
+
del os.environ[key]
|
|
633
|
+
os.environ["KINDL_PROFILE"] = "ios-ipad"
|
|
634
|
+
try:
|
|
635
|
+
if command == "_login":
|
|
636
|
+
region, state = args
|
|
637
|
+
login(region, Path(state))
|
|
638
|
+
elif command == "_download":
|
|
639
|
+
state, asin, destination = args
|
|
640
|
+
download(Path(state), asin, Path(destination))
|
|
641
|
+
elif command == "_decrypt":
|
|
642
|
+
decrypt(*map(Path, args))
|
|
643
|
+
else:
|
|
644
|
+
source, output_dir, requested_format = args
|
|
645
|
+
convert_book(Path(source), Path(output_dir), requested_format)
|
|
646
|
+
except (KindleError, KeyboardInterrupt, EOFError):
|
|
647
|
+
raise
|
|
648
|
+
except Exception as error:
|
|
649
|
+
response = getattr(error, "response", None)
|
|
650
|
+
code = getattr(response, "status_code", None)
|
|
651
|
+
detail = f"HTTP {code}" if code is not None else type(error).__name__
|
|
652
|
+
raise KindleError(f"操作失败({detail})。请检查登录状态、网络及该书在对应站点的访问权限。") from None
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def main():
|
|
656
|
+
os.umask(0o077)
|
|
657
|
+
if len(sys.argv) > 1 and sys.argv[1] in {"_login", "_download", "_decrypt", "_convert"}:
|
|
658
|
+
worker(sys.argv[1], sys.argv[2:])
|
|
659
|
+
return
|
|
660
|
+
if sys.version_info < (3, 11):
|
|
661
|
+
raise KindleError("请使用 Python 3.11 或更新版。")
|
|
662
|
+
|
|
663
|
+
from kindlegarten import __version__
|
|
664
|
+
|
|
665
|
+
parser = argparse.ArgumentParser(prog=COMMAND, description="下载 Kindle iPad 版并导出彩色 EPUB 或 CBZ。")
|
|
666
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
667
|
+
commands = parser.add_subparsers(title="命令")
|
|
668
|
+
commands.add_parser("setup", help="安装独立依赖").set_defaults(action=setup)
|
|
669
|
+
for name, action, description in (("login", start_login, "登录 Amazon"),
|
|
670
|
+
("logout", logout, "清除本地登录状态")):
|
|
671
|
+
subparser = commands.add_parser(name, help=description)
|
|
672
|
+
subparser.add_argument("--region", choices=("jp", "us"), default="jp", help="账户站点,默认 jp")
|
|
673
|
+
subparser.set_defaults(action=action)
|
|
674
|
+
|
|
675
|
+
get = commands.add_parser("download", help="下载并转换一本书")
|
|
676
|
+
get.add_argument("book", metavar="ASIN_OR_URL", help="10 位 ASIN 或 Amazon 商品链接")
|
|
677
|
+
get.add_argument("--region", choices=("jp", "us"), help="账户站点,纯 ASIN 默认 jp")
|
|
678
|
+
get.add_argument("-o", "--output", type=Path, metavar="FILE",
|
|
679
|
+
help="指定 .epub 或 .cbz,省略时按内容选择格式并以书名存入 books/")
|
|
680
|
+
get.set_defaults(action=download_book)
|
|
681
|
+
args = parser.parse_args()
|
|
682
|
+
if not hasattr(args, "action"):
|
|
683
|
+
parser.print_help()
|
|
684
|
+
return
|
|
685
|
+
|
|
686
|
+
with project_lock():
|
|
687
|
+
for entry in DATA.iterdir():
|
|
688
|
+
temporary_job = re.fullmatch(r"\.(?:setup|job)-[A-Za-z0-9_]{8}", entry.name)
|
|
689
|
+
if temporary_job and entry.is_dir() and not entry.is_symlink():
|
|
690
|
+
shutil.rmtree(entry)
|
|
691
|
+
args.action(args)
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def entrypoint(checkout=None):
|
|
695
|
+
global BOOKS, COMMAND, DATA, RUNTIME
|
|
696
|
+
|
|
697
|
+
COMMAND = "python kindle.py" if checkout else "kindlegarten"
|
|
698
|
+
data_override = os.environ.get("KINDLEGARTEN_DATA_DIR")
|
|
699
|
+
default_data = checkout / ".kindle-data" if checkout else user_data_directory()
|
|
700
|
+
DATA = Path(data_override).expanduser().resolve() if data_override else default_data
|
|
701
|
+
RUNTIME = DATA / "runtime"
|
|
702
|
+
BOOKS = (checkout or Path.cwd()) / "books"
|
|
703
|
+
try:
|
|
704
|
+
main()
|
|
705
|
+
except KindleError as error:
|
|
706
|
+
print(error, file=sys.stderr)
|
|
707
|
+
return 1
|
|
708
|
+
except (KeyboardInterrupt, EOFError):
|
|
709
|
+
print("已取消。", file=sys.stderr)
|
|
710
|
+
return 130
|
|
711
|
+
except subprocess.CalledProcessError:
|
|
712
|
+
print("安装 Python 依赖失败,请检查 Python 安装及网络。", file=sys.stderr)
|
|
713
|
+
return 1
|
|
714
|
+
except OSError as error:
|
|
715
|
+
print(f"操作失败:{error}", file=sys.stderr)
|
|
716
|
+
return 1
|
|
717
|
+
return 0
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
if __name__ == "__main__":
|
|
721
|
+
sys.exit(entrypoint())
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kindlegarten
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A command-line backup tool for purchased Amazon Kindle books
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/yinyanfr/kindlegarten
|
|
7
|
+
Project-URL: Issues, https://github.com/yinyanfr/kindlegarten/issues
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Topic :: Utilities
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# kindlegarten
|
|
17
|
+
|
|
18
|
+
> **使用范围**
|
|
19
|
+
>
|
|
20
|
+
> 本项目仅用于备份本人在 Amazon 合法购买的 Kindle 电子书。
|
|
21
|
+
|
|
22
|
+
从自己的 Amazon Kindle 书库下载电子书,以 EPUB 或 CBZ 保存到本地。下载时使用 Kindle for iPad 配置,保留亚马逊为该版本提供的彩色插图。
|
|
23
|
+
|
|
24
|
+
- 自动选择输出格式。文字书导出 EPUB,可提取为整页图片的固定版式漫画和杂志导出 CBZ。
|
|
25
|
+
- 按书名保存,自动处理文件名中的禁用字符和过长书名。下载过程只显示一条整书进度条。
|
|
26
|
+
- 支持 Amazon 日本站和美国站。登录一次后可复用本机登录状态。
|
|
27
|
+
|
|
28
|
+
## 安装
|
|
29
|
+
|
|
30
|
+
需要 Python 3.11 或更新版、[Calibre](https://calibre-ebook.com/download) 和用于登录 Amazon 的浏览器。命令面向 macOS、Windows 和 Linux,已在 macOS 实机验证。
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
python3 -m pip install kindlegarten
|
|
34
|
+
kindlegarten setup
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Windows 可用 `py -3 -m pip install kindlegarten`。若系统的 Python 由包管理器维护,可在虚拟环境中运行 `pip install kindlegarten`,或用 `pipx install kindlegarten` 安装命令。首次运行 `kindlegarten setup` 会安装导出所需的组件。
|
|
38
|
+
|
|
39
|
+
## 登录与下载
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
kindlegarten login --region jp
|
|
43
|
+
kindlegarten download B0EXAMPLE0
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
登录命令会打开 Amazon 页面并注册一个 Kindle for iPad 客户端。完成登录后,复制浏览器地址栏里的完整跳转网址,粘贴回终端并按回车。终端会隐藏粘贴的内容。
|
|
47
|
+
|
|
48
|
+
把示例中的 `B0EXAMPLE0` 替换为书籍的十位 ASIN。也可直接传入商品链接,程序会根据域名选择日本站或美国站。单独输入 ASIN 时默认使用日本站,美区账户请在登录和下载时加上 `--region us`。
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
kindlegarten download "https://www.amazon.co.jp/dp/B0EXAMPLE0"
|
|
52
|
+
kindlegarten download B0EXAMPLE0 --output "My Book.epub"
|
|
53
|
+
kindlegarten download --help
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
默认输出到当前目录下的 `books/<书名>.epub` 或 `books/<书名>.cbz`,缺少可用书名时使用 ASIN。`--output` 可以指定文件名和格式,相对路径以当前目录为准。指定 CBZ 时,程序会检查页面能否安全地作为纯图片导出。已有同名文件会提示冲突。
|
|
57
|
+
|
|
58
|
+
## 本地数据
|
|
59
|
+
|
|
60
|
+
通过 pip 安装的命令按用户保存登录状态和导出依赖。
|
|
61
|
+
|
|
62
|
+
- macOS 使用 `~/Library/Application Support/kindlegarten/`。
|
|
63
|
+
- Windows 使用 `%LOCALAPPDATA%\kindlegarten\`。
|
|
64
|
+
- Linux 使用 `$XDG_DATA_HOME/kindlegarten/`,其默认值为 `~/.local/share/kindlegarten/`。
|
|
65
|
+
|
|
66
|
+
可以用 `KINDLEGARTEN_DATA_DIR` 指定其他目录。如果之前用源码运行过,可将它设为原仓库中 `.kindle-data/` 的绝对路径,以复用现有登录状态和依赖。直接在源码仓库运行 `python3 kindle.py` 也可继续使用仓库内的 `.kindle-data/` 和 `books/`。
|
|
67
|
+
|
|
68
|
+
## 排查问题
|
|
69
|
+
|
|
70
|
+
- **找不到 Calibre**。将 `KINDLE_CALIBRE_BIN` 设置为 `calibre-debug` 和 `calibre-customize` 所在目录。Windows 使用相应的 `.exe` 文件。
|
|
71
|
+
- **登录失效或切换账户**。运行 `kindlegarten logout --region jp` 清除日本站的本地登录状态,再重新登录。可在 Amazon 的「管理内容和设备」页面注销已注册的设备。
|
|
72
|
+
- **某本书无法下载或转换**。先确认该书能从对应站点的 Kindle 书库打开。格式和加密兼容性取决于 Amazon 针对该书下发的资源。
|
|
73
|
+
- **迁移到另一台电脑**。安装 Calibre 和 kindlegarten 后,运行 `kindlegarten setup` 创建本机依赖。
|
|
74
|
+
|
|
75
|
+
程序使用 [kindl](https://github.com/bGFiMTI2/kindl) 下载、[DeDRM Tools](https://github.com/Satsuoni/DeDRM_tools) 解密、[KFX Input](https://www.mobileread.com/forums/showthread.php?t=291290) 转档。项目采用 [MIT 许可证](https://github.com/yinyanfr/kindlegarten/blob/main/LICENSE)。
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
kindlegarten/__init__.py
|
|
5
|
+
kindlegarten/cli.py
|
|
6
|
+
kindlegarten/constraints.txt
|
|
7
|
+
kindlegarten.egg-info/PKG-INFO
|
|
8
|
+
kindlegarten.egg-info/SOURCES.txt
|
|
9
|
+
kindlegarten.egg-info/dependency_links.txt
|
|
10
|
+
kindlegarten.egg-info/entry_points.txt
|
|
11
|
+
kindlegarten.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kindlegarten
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "kindlegarten"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "A command-line backup tool for purchased Amazon Kindle books"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Environment :: Console",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Utilities",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
kindlegarten = "kindlegarten.cli:entrypoint"
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Repository = "https://github.com/yinyanfr/kindlegarten"
|
|
24
|
+
Issues = "https://github.com/yinyanfr/kindlegarten/issues"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools]
|
|
27
|
+
packages = ["kindlegarten"]
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.dynamic]
|
|
30
|
+
version = {attr = "kindlegarten.__version__"}
|
|
31
|
+
|
|
32
|
+
[tool.setuptools.package-data]
|
|
33
|
+
kindlegarten = ["constraints.txt"]
|