Repository navigation
feat: confirm a dropped book's metadata before filing #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d60d5d2
feat: confirm a dropped book's metadata before filing
DArtagan 6d149d5
fix: address review of the confirmation screen
DArtagan e5c034e
docs(design): date the mojibake measurement correctly
DArtagan 8179760
fix: drop the Open Library contact setting
DArtagan 2d66e80
fix: never look authors up on Open Library
DArtagan d8e0ffe
docs: say what open_library returns, not what it stopped doing
DArtagan ba7cf4d
docs(todos): record what Stump reads from an EPUB, for filing
DArtagan d58cfd1
docs(todos): keep writing metadata.opf when filing
DArtagan 3f8e481
feat: read and confirm a book's genres
DArtagan 877aac6
fix: confirm only a book that can be filed
DArtagan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | ||
|
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") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}") |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.