diff --git a/skills/shelfmark/download_books.py b/skills/shelfmark/download_books.py index 3930f3a3..11b9c9b0 100755 --- a/skills/shelfmark/download_books.py +++ b/skills/shelfmark/download_books.py @@ -277,11 +277,23 @@ def clear_completed_downloads(page: Page) -> None: page.wait_for_timeout(2000) +def calibre_title_search(title: str) -> str: + """A calibre search expression matching this exact title. + + Calibre has its own query language: a term with spaces or quotes goes in + double quotes, and a quote or backslash inside it is escaped with a + backslash (manual, "Searching calibre"). Without that, a title containing + `"` ends the quoted term and the rest is read as more query syntax. + """ + escaped = title.replace("\\", "\\\\").replace('"', '\\"') + return f'title:"{escaped}"' + + def check_calibre(title: str) -> bool: """Check if a book is already in the calibre database.""" import subprocess - cmd = ["calibredb", "list", "--search", f'title:="{title}"'] + cmd = ["calibredb", "list", "--search", calibre_title_search(title)] result = subprocess.run(cmd, check=False, capture_output=True, text=True) output = result.stdout.strip() # calibredb output has header line "id title authors", count non-header lines diff --git a/tests/skills/test_check_calibre.py b/tests/skills/test_check_calibre.py index dfb1b38b..005b822a 100644 --- a/tests/skills/test_check_calibre.py +++ b/tests/skills/test_check_calibre.py @@ -1,4 +1,4 @@ -"""The calibre check must pass a title as data, never as shell syntax.""" +"""A book title reaches calibredb as data: one argv item and one query term.""" import importlib.util import subprocess @@ -40,9 +40,11 @@ def _load_module(): 'Dune"; touch /tmp/pwned; echo "', "Neuromancer$(id)", "Snow Crash`whoami`", + "The \"Ball\" and The \"Chain\"", + r"C:\Books\Dune", ], ) -def test_title_is_an_argument_not_shell_syntax(title): +def test_title_is_one_argument_and_one_query_term(title): module = _load_module() completed = subprocess.CompletedProcess(args=[], returncode=0, stdout="id title authors\n", stderr="") @@ -53,5 +55,43 @@ def test_title_is_an_argument_not_shell_syntax(title): command = args[0] assert isinstance(command, list), "the command must be an argv list" assert command[:3] == ["calibredb", "list", "--search"] - assert command[3] == f'title:="{title}"' assert not kwargs.get("shell"), "a shell must not re-parse the title" + + term = command[3] + assert term.startswith('title:"') and term.endswith('"'), term + inner = term[len('title:"'):-1] + # Nothing inside the term may end it early: every quote and every + # backslash is escaped, and unescaping gives the title back. + assert _unescape(inner) == title + assert _every_quote_escaped(inner), inner + + +def _every_quote_escaped(inner: str) -> bool: + i = 0 + while i < len(inner): + if inner[i] == "\\": + i += 2 + continue + if inner[i] == '"': + return False + i += 1 + return True + + +def _unescape(inner: str) -> str: + out = [] + i = 0 + while i < len(inner): + char = inner[i] + if char == "\\": + i += 1 + out.append(inner[i]) + else: + out.append(char) + i += 1 + return "".join(out) + + +def test_plain_title_is_unchanged_by_escaping(): + module = _load_module() + assert module.calibre_title_search("Mistborn") == 'title:"Mistborn"'