8000 feat: confirm a dropped book's metadata before filing by DArtagan · Pull Request #13 · DArtagan/bookdrop · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 39 additions & 9 deletions docs/design.md
8000
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,34 @@ unaffected, as they no longer carry DRM.

## Metadata

Read from the book's OPF. With an ISBN, gaps are filled from Open Library, then
Google Books. A Kobo EPUB may carry its ISBN only as `dc:source`, the print
edition it was made from, with `dc:identifier` a UUID; read both. The confirmation screen requires title, author, and series with
its index where there is one, and offers publisher, ISBN, date, description,
language and cover. An author alias table maps variant spellings to one
canonical name.
Read from the book's OPF, EPUB 2 or 3, including Calibre's series. A Kobo EPUB
may carry its ISBN only as `dc:source`, the print edition it was made from, with
`dc:identifier` a UUID; both are read, and an ISBN counts only when its check
digit holds.

With an ISBN, Open Library fills the fields the book leaves empty, never
overriding one it has. It needs no key and answered in two to four seconds on
2026-11-03, so the lookup runs once, at upload, with a timeout that turns a slow
answer into gaps. Google Books is not used: without a key it answered
Comment thread
DArtagan marked this conversation as resolved.
Resolved
`429 Quota exceeded … Queries per day`, as every keyless caller shares one
quota. A key would make it usable.

Two fields are never filled from Open Library. Authors, because it names each
only by a key costing another request, and EPUBs carry their own. Genres,
because its subjects are not genres: for *The Way of Kings* on 2026-11-05 they
mixed "Fantasy", "Epic Fantasy", "high fantasy" and "Fiction, fantasy, epic"
with "New York Times Bestseller" and `nyt:hardcover-fiction=2010-09-19`, and
each would become a genre in Stump. Genres come from the book's `dc:subject`,
which is where Stump reads them and Calibre writes its tags, or from the person.

The confirmation screen shows each field with where its value came from, the
book, Open Library, the alias table or the person, and every field is editable.
Confirming needs a title and an author, an ISBN only if its check digit holds,
and a series number only as a number beside its series; the screen says which
is missing.
An author alias table, `authors.toml` on the data volume, maps variant spellings
to one canonical name and is read on each request, so it changes without a
release.

The confirmed values are written into the EPUB itself, since Stump reads them
from there, and into a `metadata.opf` beside it.
Expand All @@ -109,9 +131,17 @@ and `cover.jpg` beside nearly every book, and series one level deeper
(`Frank Herbert/Dune/Dune Messiah/`). A colon in a title is written ` - `
(`Chapterhouse - Dune`).

Path components are folded to Latin-1 (`’` to `'`, `–` to `-`, `…` to `...`):
the share the library lives on fails any filename character above U+00FF with
`EIO`. The true title stays in the metadata. A target that already exists is
Several authors are joined with ` & `, as Calibre joins them; the library's
sidecars are Calibre's, and its folders show no convention of their own.

Path components are folded to ASCII (`’` to `'`, `–` to `-`, `é` to `e`,
`ß` to `ss`). The share the library lives on fails any filename character above
U+00FF with `EIO` and stores the rest as Latin-1, while the library's older
accented names are UTF-8 on disk and read through the share as mojibake: on
2026-11-05 Stump saw `China Miéville` among 96 such paths. ASCII is spelt
the same in all three, and stays so when the share moves to UTF-8. Characters Windows forbids become `_`, and a trailing dot or space is
dropped, as SMB clients cannot round-trip one. The true title stays in the
metadata. A target that already exists is
shown on the confirmation screen, never overwritten.

After filing, bookdrop starts a scan through Stump's API, authenticated with a
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ license = "MIT"
requires-python = ">=3.15"
dependencies = [
"fastapi>=0.115",
"httpx>=0.28",
"jinja2>=3.1",
"pydantic-settings>=2.6",
"python-multipart>=0.0.20",
"uvicorn>=0.32",
Expand Down
10 changes: 5 additions & 5 deletions src/bookdrop/adept.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class Refused(Exception):
@dataclass(frozen=True)
class Prepared:
book: Path
# What was done to reach a DRM-free book, said to the person who dropped it.
done: str
# How the upload became a DRM-free book, said to the person who dropped it.
preparation: str


def kind(path: Path) -> str:
Expand Down Expand Up @@ -89,19 +89,19 @@ def prepare(upload: Path, out_dir: Path, adept_dir: Path) -> Prepared:
_run(adept_dir, "adept_remove", "-o", str(book), str(source))
if encrypted(book, book_kind):
raise Refused("The DRM could not be removed from this book.")
done = (
preparation = (
"Downloaded from the store, DRM removed."
if fulfilled_from_store
else "DRM removed."
)
else:
shutil.copyfile(source, book)
done = (
preparation = (
"Downloaded from the store, which sent it DRM-free."
if fulfilled_from_store
else "It arrived DRM-free."
)
return Prepared(book, done)
return Prepared(book, preparation)


def _run(adept_dir: Path, tool: str, *args: str) -> None:
Expand Down
88 changes: 88 additions & 0 deletions src/bookdrop/drops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import json
import re
import shutil
import uuid
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from pathlib import Path

from bookdrop.metadata import Metadata

ID = re.compile(r"[0-9a-f]{32}")


@dataclass
class Drop:
"""One upload awaiting confirmation, kept in its own directory under /data."""

directory: Path
uploaded_as: str = ""
# How the upload became a DRM-free book; see adept.Prepared.
preparation: str = ""
book_name: str = ""
metadata: Metadata = field(default_factory=Metadata)
# Where each field's value came from: "book", "Open Library", "alias", "you".
sources: dict[str, str] = field(default_factory=dict)
confirmed: bool = False
created: str = ""

@property
def id(self) -> str:
return self.directory.name

@property
def book(self) -> Path:
return self.directory / self.book_name

@property
def extension(self) -> str:
return self.book.suffix.lstrip(".")

def save(self) -> None:
record = asdict(self)
# The directory is where the record lives, not part of it.
del record["directory"]
# Written beside and renamed over, which is atomic: a restart mid-write
# leaves the old record or the new, never a truncated one that every
# page listing the drops would fail to parse.
tmp = self.directory / "drop.json.tmp"
tmp.write_text(json.dumps(record, indent=2))
tmp.replace(self.directory / "drop.json")
Comment thread
DArtagan marked this conversation as resolved.
Resolved


def root(data_dir: Path) -> Path:
return data_dir / "drops"


def new_directory(data_dir: Path) -> Path:
directory = root(data_dir) / uuid.uuid4().hex
directory.mkdir(parents=True)
return directory


def discard(directory: Path) -> None:
shutil.rmtree(directory)


def load(data_dir: Path, drop_id: str) -> Drop | None:
if not ID.fullmatch(drop_id):
return None
directory = root(data_dir) / drop_id
try:
record = json.loads((directory / "drop.json").read_text())
except FileNotFoundError:
return None
record["metadata"] = Metadata.from_dict(record["metadata"])
return Drop(directory=directory, **record)


def all_drops(data_dir: Path) -> list[Drop]:
"""Every saved drop, newest first. A directory without drop.json is skipped."""
if not root(data_dir).exists():
return []
found = (load(data_dir, d.name) for d in root(data_dir).iterdir() if d.is_dir())
return sorted((d for d in found if d), key=lambda d: d.created, reverse=True)


def now() -> str:
return datetime.now(UTC).isoformat(timespec="seconds")
91 changes: 91 additions & 0 deletions src/bookdrop/layout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import re
import tomllib
import unicodedata
from pathlib import Path, PurePosixPath

from bookdrop.metadata import Metadata

# Paths are ASCII. The share's Samba fails any character above U+00FF with EIO
# and stores the rest as Latin-1, while the library's older accented names are
# UTF-8 on disk and read through SMB as mojibake ("Miéville"). ASCII bytes are
# the same in every one of those encodings, and stay so when the share moves to
# UTF-8. The true text stays in the metadata.
FOLDS = str.maketrans(
{
"\u2018": "'",
"\u2019": "'",
"\u02bc": "'",
"\u201c": '"',
"\u201d": '"',
"\u2013": "-",
"\u2014": "-",
"\u2015": "-",
"\u2026": "...",
"\u00a0": " ",
# Letters Unicode does not decompose into an ASCII base.
"\u00df": "ss",
"\u00c6": "AE",
"\u00e6": "ae",
"\u00d8": "O",
"\u00f8": "o",
"\u00de": "Th",
"\u00fe": "th",
"\u00d0": "D",
"\u00f0": "d",
"\u0141": "L",
"\u0142": "l",
"\u0110": "D",
"\u0111": "d",
"\u0152": "OE",
"\u0153": "oe",
}
)
# Not allowed in a Windows or SMB filename; Calibre writes these as "_".
RESERVED = re.compile(r'[\\/*?"<>|]')


def fold(text: str) -> str:
"""One path component, spelt so the share can store it."""
text = text.translate(FOLDS)
# The library writes "Chapterhouse: Dune" as "Chapterhouse - Dune".
text = re.sub(r"\s*:\s*", " - ", text)
text = RESERVED.sub("_", text)
out = []
for char in text:
if char.isascii():
out.append(char)
continue
base = "".join(
c
for c in unicodedata.normalize("NFKD", char)
if not unicodedata.combining(c)
)
out.append(base if base and base.isascii() else "_")
# Windows and Samba drop a trailing dot or space, so a name ending in one
# would not round-trip.
return " ".join("".join(out).split()).rstrip(". ") or "_"


def aliases(path: Path) -> dict[str, str]:
"""[aliases] from the TOML file at path; empty when it does not exist."""
if not path.exists():
return {}
with path.open("rb") as f:
table = tomllib.load(f).get("aliases", {})
return {str(k): str(v) for k, v in table.items()}


def canonical(authors: list[str], table: dict[str, str]) -> list[str]:
return [table.get(a, a) for a in authors]


def destination(meta: Metadata, extension: str) -> PurePosixPath:
"""Where the book goes under the books root: Author/[Series/]Title/Title.ext."""
# Calibre's own joining, as the library's sidecars come from Calibre.
author = fold(" & ".join(meta.authors) or "Unknown")
title = fold(meta.title or "Untitled")
parts = [author]
if meta.series:
parts.append(fold(meta.series))
parts.append(title)
return PurePosixPath(*parts, f"{title}.{extension}")
Loading
Loading
0