def epub_meta(path: pathlib.Path):
"""(title, author) from the EPUB's OPF, or (None, None) when unreadable."""
try:
with zipfile.ZipFile(path) as z:
container = ET.fromstring(z.read("META-INF/container.xml"))
opf = ET.fromstring(z.read(container.find(".//c:rootfile", NS).get("full-path")))
except (KeyError, AttributeError, ET.ParseError, zipfile.BadZipFile, OSError):
return None, None
def get(tag):
el = opf.find(f".//dc:{tag}", NS)
return re.sub(r"\s+", " ", "".join(el.itertext())).strip() if el is not None else ""
return get("title") or None, get("creator") or None
def is_book(p: pathlib.Path):
return p.is_file() and p.suffix.lower() in BOOK_TYPES and not p.name.startswith(".")
def count_books(folder: pathlib.Path) -> int:
return sum(1 for p in folder.rglob("*") if is_book(p) and not any(
part.startswith(".") for part in p.relative_to(folder).parts))
def entry(title, info, href, is_folder=False, file_name=None):
parts = [f"<title>{escape(title)}</title>"]
if info:
parts.append(f"<info>{escape(info)}</info>")
if file_name:
parts.append(f"<file>{escape(file_name)}</file>") # -> {id} -> the saved file name
parts.append(f"<link href={quoteattr(urllib.parse.quote(href))}/>")
if is_folder:
parts.append("<folder/>") # marks a navigable folder
return " <entry>" + "".join(parts) + "</entry>"