~cytrogen/kobo-manga

ref: 4e504823f4bf8d2b5f4279da3f4d4ebe98fc97ad kobo-manga/src/kobo_manga/transfer/usb.py -rw-r--r-- 1.9 KiB
4e504823 — HallowDem Initial commit: kobo-manga pipeline a day ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Kobo USB 传输

检测通过 USB 连接的 Kobo 设备(Windows 盘符扫描),
将 .kepub.epub 文件复制到设备上。
"""

import ctypes
import shutil
import string
from pathlib import Path


class USBTransfer:
    """通过 USB 将 KEPUB 文件传输到 Kobo 设备。"""

    def detect_kobo(self) -> Path | None:
        """扫描 Windows 可用盘符,查找含 .kobo 目录的 Kobo 设备。

        Returns:
            Kobo 设备根路径,未检测到返回 None
        """
        bitmask = ctypes.windll.kernel32.GetLogicalDrives()
        for i, letter in enumerate(string.ascii_uppercase):
            if not (bitmask & (1 << i)):
                continue
            kobo_dir = Path(f"{letter}:/.kobo")
            try:
                if kobo_dir.is_dir():
                    return Path(f"{letter}:/")
            except OSError:
                continue
        return None

    def transfer(
        self,
        kepub_paths: list[Path],
        manga_title: str = "",
    ) -> list[Path]:
        """将 .kepub.epub 文件复制到 Kobo 设备。

        Args:
            kepub_paths: 要传输的文件列表
            manga_title: 漫画标题,用于在设备上创建子目录

        Returns:
            设备上的目标路径列表

        Raises:
            RuntimeError: 未检测到 Kobo 设备
        """
        kobo_root = self.detect_kobo()
        if kobo_root is None:
            raise RuntimeError(
                "未检测到 Kobo 设备,请确认设备已通过 USB 连接并挂载"
            )

        # 目标目录
        if manga_title:
            dest_dir = kobo_root / manga_title
        else:
            dest_dir = kobo_root
        dest_dir.mkdir(parents=True, exist_ok=True)

        results = []
        for src in kepub_paths:
            dest = dest_dir / src.name
            shutil.copy2(src, dest)
            results.append(dest)

        return results