diff --git a/deeptutor/reading/epub_bilingual.py b/deeptutor/reading/epub_bilingual.py index a84ce3860..a232e95bb 100644 --- a/deeptutor/reading/epub_bilingual.py +++ b/deeptutor/reading/epub_bilingual.py @@ -12,16 +12,18 @@ from datetime import datetime, timezone import hashlib import json import os -from pathlib import Path +from pathlib import Path, PurePosixPath import re import threading -from typing import Any +from typing import TYPE_CHECKING, Any import uuid import xml.etree.ElementTree as ET import zipfile from deeptutor.reading.models import MaterialManifest, ReadingError -from deeptutor.reading.store import ReadingStore + +if TYPE_CHECKING: + from deeptutor.reading.store import ReadingStore PAIRINGS_NAME = "_epub_pairings.json" _PAIRING_WRITE_LOCK = threading.Lock() @@ -35,9 +37,17 @@ def _metadata(epub: Path) -> dict[str, str]: """Read enough OPF metadata to rank, never to pair automatically.""" try: with zipfile.ZipFile(epub) as archive: - opf_name = next(name for name in archive.namelist() if name.casefold().endswith(".opf")) + container = ET.fromstring(archive.read("META-INF/container.xml")) + rootfile = next( + element + for element in container.iter() + if _local_name(element.tag) == "rootfile" and element.get("full-path") + ) + opf_name = str(PurePosixPath(rootfile.attrib["full-path"])) + if opf_name.startswith("/") or ".." in PurePosixPath(opf_name).parts: + return {} root = ET.fromstring(archive.read(opf_name)) - except (OSError, StopIteration, zipfile.BadZipFile, ET.ParseError): + except (KeyError, OSError, StopIteration, zipfile.BadZipFile, ET.ParseError): return {} wanted = ("title", "creator", "identifier", "language") @@ -93,8 +103,8 @@ def recommend_epub_candidates(store: ReadingStore, material_id: str) -> list[dic and source_meta.get("identifier") == metadata.get("identifier") ) author_match = bool( - source_meta.get("author") - and source_meta.get("author").casefold() == metadata.get("creator", "").casefold() + source_meta.get("creator") + and source_meta.get("creator", "").casefold() == metadata.get("creator", "").casefold() ) candidate_language = _language(metadata.get("language") or "") language_bonus = float( @@ -177,8 +187,10 @@ def create_epub_pairing( chinese_path = _raw_epub(store, chinese.material_id, "The Chinese EPUB is unavailable.") english_language = _language(_metadata(english_path).get("language") or "") chinese_language = _language(_metadata(chinese_path).get("language") or "") - if english_language == chinese_language: - raise ReadingError("Pair an English EPUB with a different-language edition.") + if english_language != "en": + raise ReadingError("The English pairing source must declare an English language.") + if chinese_language != "zh": + raise ReadingError("The Chinese pairing source must declare a Chinese language.") pairing_id = hashlib.sha256( f"{english.material_id}\0{chinese.material_id}".encode("utf-8") @@ -203,8 +215,8 @@ def create_epub_pairing( def delete_epub_pairing(store: ReadingStore, pairing_id: str) -> bool: """Remove the pairing record while preserving both source materials.""" - rows = list_epub_pairings(store) with _PAIRING_WRITE_LOCK: + rows = list_epub_pairings(store) remaining = [row for row in rows if row.get("pairing_id") != pairing_id] if len(remaining) == len(rows): return False @@ -212,9 +224,27 @@ def delete_epub_pairing(store: ReadingStore, pairing_id: str) -> bool: return True +def delete_epub_pairings_for_material(store: ReadingStore, material_id: str) -> int: + """Remove every pairing that would dangle after a material is deleted.""" + + with _PAIRING_WRITE_LOCK: + rows = list_epub_pairings(store) + remaining = [ + row + for row in rows + if row.get("english_material_id") != material_id + and row.get("chinese_material_id") != material_id + ] + removed = len(rows) - len(remaining) + if removed: + _atomic_write(_pairing_path(store), json.dumps(remaining, ensure_ascii=False, indent=2)) + return removed + + __all__ = [ "create_epub_pairing", "delete_epub_pairing", + "delete_epub_pairings_for_material", "list_epub_pairings", "recommend_epub_candidates", ] diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py index a8b7bcc0d..1470f84a7 100644 --- a/deeptutor/reading/store.py +++ b/deeptutor/reading/store.py @@ -444,7 +444,12 @@ class ReadingStore: return False with self._locked(material_id): shutil.rmtree(material_dir, ignore_errors=True) - return not material_dir.exists() + removed = not material_dir.exists() + if removed: + from deeptutor.reading.epub_bilingual import delete_epub_pairings_for_material + + delete_epub_pairings_for_material(self, material_id) + return removed # -- annotations ------------------------------------------------------ diff --git a/tests/reading/test_epub_bilingual.py b/tests/reading/test_epub_bilingual.py index 33ef8d057..7b8bb88cc 100644 --- a/tests/reading/test_epub_bilingual.py +++ b/tests/reading/test_epub_bilingual.py @@ -4,14 +4,19 @@ from __future__ import annotations import base64 from pathlib import Path +import threading import zipfile +import pytest + +import deeptutor.reading.epub_bilingual as bilingual from deeptutor.reading.epub_bilingual import ( create_epub_pairing, delete_epub_pairing, list_epub_pairings, recommend_epub_candidates, ) +from deeptutor.reading.models import ReadingError from deeptutor.reading.store import ReadingStore PNG_BYTES = base64.b64decode( @@ -26,6 +31,7 @@ def _write_epub( chapter: str, paragraph: str, include_image: bool = False, + decoy_language: str | None = None, ) -> Path: image_manifest = ( "" if include_image else "" @@ -42,6 +48,13 @@ def _write_epub( "" "", ) + if decoy_language is not None: + archive.writestr( + "AAA/decoy.opf", + "" + f"{decoy_language}", + ) archive.writestr( "OPS/book.opf", " None: + store = ReadingStore(root=tmp_path / "materials") + english = store.ingest( + _write_epub( + tmp_path / "english.epub", + language="en-US", + chapter="One", + paragraph="English.", + decoy_language="zh", + ) + ) + chinese = store.ingest( + _write_epub( + tmp_path / "chinese.epub", + language="zh-Hans", + chapter="一", + paragraph="中文。", + decoy_language="en", + ) + ) + + pairing = create_epub_pairing(store, english.material_id, chinese.material_id) + + assert pairing["english_language"] == "en" + assert pairing["chinese_language"] == "zh" + + +@pytest.mark.parametrize( + ("english_language", "chinese_language"), + [ + ("", "zh"), + ("fr", "zh"), + ("en", ""), + ("en", "ja"), + ("zh", "en"), + ], +) +def test_pairing_requires_declared_english_and_chinese_roles( + tmp_path: Path, + english_language: str, + chinese_language: str, +) -> None: + store = ReadingStore(root=tmp_path / "materials") + english = store.ingest( + _write_epub( + tmp_path / "first.epub", + language=english_language, + chapter="One", + paragraph="First edition.", + ) + ) + chinese = store.ingest( + _write_epub( + tmp_path / "second.epub", + language=chinese_language, + chapter="Two", + paragraph="Second edition.", + ) + ) + + with pytest.raises(ReadingError, match="must declare"): + create_epub_pairing(store, english.material_id, chinese.material_id) + + +def test_deleting_material_removes_its_pairing(tmp_path: Path) -> None: + store = ReadingStore(root=tmp_path / "materials") + english = store.ingest( + _write_epub( + tmp_path / "english.epub", + language="en", + chapter="One", + paragraph="English.", + ) + ) + chinese = store.ingest( + _write_epub( + tmp_path / "chinese.epub", + language="zh", + chapter="一", + paragraph="中文。", + ) + ) + create_epub_pairing(store, english.material_id, chinese.material_id) + + assert store.delete(english.material_id) is True + assert list_epub_pairings(store) == [] + + +def test_concurrent_delete_cannot_overwrite_a_new_pairing( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + store = ReadingStore(root=tmp_path / "materials") + english = store.ingest( + _write_epub( + tmp_path / "english.epub", + language="en", + chapter="One", + paragraph="English.", + ) + ) + first_chinese = store.ingest( + _write_epub( + tmp_path / "first-chinese.epub", + language="zh", + chapter="一", + paragraph="第一版。", + ) + ) + second_chinese = store.ingest( + _write_epub( + tmp_path / "second-chinese.epub", + language="zh", + chapter="二", + paragraph="第二版。", + ) + ) + first = create_epub_pairing(store, english.material_id, first_chinese.material_id) + real_list = bilingual.list_epub_pairings + delete_read = threading.Event() + allow_delete = threading.Event() + + def controlled_list(target: ReadingStore) -> list[dict]: + rows = real_list(target) + if threading.current_thread().name == "pairing-delete": + delete_read.set() + assert allow_delete.wait(timeout=2) + return rows + + monkeypatch.setattr(bilingual, "list_epub_pairings", controlled_list) + errors: list[BaseException] = [] + + def deleting() -> None: + try: + bilingual.delete_epub_pairing(store, first["pairing_id"]) + except BaseException as exc: # pragma: no cover - surfaced below + errors.append(exc) + + def creating() -> None: + try: + create_epub_pairing(store, english.material_id, second_chinese.material_id) + except BaseException as exc: # pragma: no cover - surfaced below + errors.append(exc) + + delete_thread = threading.Thread(target=deleting, name="pairing-delete") + create_thread = threading.Thread(target=creating, name="pairing-create") + delete_thread.start() + assert delete_read.wait(timeout=2) + create_thread.start() + allow_delete.set() + delete_thread.join(timeout=2) + create_thread.join(timeout=2) + + assert not delete_thread.is_alive() + assert not create_thread.is_alive() + assert errors == [] + assert [row["chinese_material_id"] for row in real_list(store)] == [second_chinese.material_id]