diff --git a/docs/how-to/export-cache-to-zotero.md b/docs/how-to/export-cache-to-zotero.md index 6f7628e..ad6190b 100644 --- a/docs/how-to/export-cache-to-zotero.md +++ b/docs/how-to/export-cache-to-zotero.md @@ -86,19 +86,31 @@ which cached references now have usable Zotero text or PDF attachments. It does not invoke **Find Full Text** and does not modify Zotero. After reviewing the matches, materialize them into the separate private research -cache: +cache (you can also pass `--zotero-dir ~/Zotero` to read your local Zotero SQLite +database and `storage/` folder directly without needing the Zotero desktop HTTP +API running, and `--referenced-in` or `--reference` to scope to specific data +files): ```bash uv run linkml-reference-validator cache enrich \ --provider zotero \ + --zotero-dir ~/Zotero \ --cache-dir /Users/cjm/repos/dismech/references_cache \ + --referenced-in 'kb/disorders/MyDisease.yaml' \ --apply ``` Apply mode leaves `references_cache` unchanged. Private content goes to `~/.cache/linkml-reference-validator/private` by default with owner-only -permissions. Agents may inspect it for context, but validation cannot use it as -evidence. +permissions (or to a private full-text repository such as `claimstore` when +`--private-cache-dir /path/to/claimstore/references_cache` is passed). When +`download_pdfs: true` is configured, `--zotero-dir` also copies the source PDF +into `/files/` even when Zotero has already pre-indexed the +full text (whereas the HTTP API backend only downloads the PDF when Zotero has +not indexed the text). Ordinary validation never reads `private_cache_dir` +directly, but `linkml-reference-validator excerpts sign` can verify quotes +against it and write fair-use bundles to `signed_excerpts/` (see +[Using Signed Excerpts](use-signed-excerpts.md)). ## 5. Validate reproducibly diff --git a/docs/how-to/use-signed-excerpts.md b/docs/how-to/use-signed-excerpts.md index 60aae76..6a2dbff 100644 --- a/docs/how-to/use-signed-excerpts.md +++ b/docs/how-to/use-signed-excerpts.md @@ -73,13 +73,19 @@ validation: ``` or with a directory of files named like cache files -(`DOI_10.1016_j.ajodo.2025.11.017.md` or `.txt`): +(`DOI_10.1016_j.ajodo.2025.11.017.md`, `.txt`, or `.pdf`): ```yaml validation: - local_full_text_dir: ~/private-papers + local_full_text_dir: ~/private-papers ``` +If you used `linkml-reference-validator cache enrich --provider zotero --apply` +(see [Export a Reference Cache to Zotero](export-cache-to-zotero.md)), its +output in `private_cache_dir` (`~/.cache/linkml-reference-validator/private`) is +checked automatically by `excerpts sign` as a fallback for any reference not +already mapped in `local_full_text` or `local_full_text_dir`. + Relative paths, including a relative `local_full_text_dir`, resolve against `reference_base_dir`, or the working directory if that is unset. Set `reference_base_dir` so the result does not depend on where you run the diff --git a/src/linkml_reference_validator/cache.py b/src/linkml_reference_validator/cache.py index 987dad3..7de1ece 100644 --- a/src/linkml_reference_validator/cache.py +++ b/src/linkml_reference_validator/cache.py @@ -218,13 +218,23 @@ def _hashed_filename(name: str, reference_id: str) -> str: return f"{prefix}_{digest}.md" -def _same_reference_id(first: str, second: str) -> bool: - """Compare stored IDs exactly, except for case-insensitive DOI identity.""" +def same_reference_id(first: str, second: str) -> bool: + """Compare stored IDs exactly, except for case-insensitive DOI identity. + + Examples: + >>> same_reference_id("DOI:10.1000/ABC", "doi:10.1000/abc") + True + >>> same_reference_id("PMID:1", "PMID:2") + False + """ if first.upper().startswith("DOI:"): return first.casefold() == second.casefold() return first == second +_same_reference_id = same_reference_id + + def _recover_legacy_scalars(metadata: dict) -> dict: """Recover scalar text that older writers emitted without YAML quoting. diff --git a/src/linkml_reference_validator/cli/cache.py b/src/linkml_reference_validator/cli/cache.py index 7b6723e..23a5741 100644 --- a/src/linkml_reference_validator/cli/cache.py +++ b/src/linkml_reference_validator/cli/cache.py @@ -4,7 +4,7 @@ import logging import tarfile from pathlib import Path -from typing import Optional +from typing import Iterable, Optional import requests # type: ignore import typer @@ -17,6 +17,11 @@ ) from linkml_reference_validator.etl.fulltext.base import FullTextProviderRegistry from linkml_reference_validator.etl.fulltext.bookshelf import LITARCH_URL, download_book +from linkml_reference_validator.models import ReferenceContent +from linkml_reference_validator.signed_excerpts import ( + expand_globs, + find_cited_reference_ids, +) from .shared import ( CacheDirOption, VerboseOption, @@ -260,6 +265,32 @@ def enrich_command( config_file: ConfigFileOption = None, cache_dir: CacheDirOption = None, private_cache_dir: PrivateCacheDirOption = None, + zotero_dir: Annotated[ + Optional[Path], + typer.Option( + "--zotero-dir", + envvar="ZOTERO_DIR", + help=( + "Local Zotero data directory (e.g. ~/Zotero) containing zotero.sqlite " + "and storage/. Reads Zotero directly without needing Zotero's HTTP API." + ), + ), + ] = None, + reference: Annotated[ + Optional[list[str]], + typer.Option( + "--reference", + "-r", + help="Only enrich this reference ID (repeatable)", + ), + ] = None, + referenced_in: Annotated[ + Optional[list[str]], + typer.Option( + "--referenced-in", + help="Glob of data files; only enrich cached references cited there (repeatable)", + ), + ] = None, dry_run: DryRunOption = True, verbose: VerboseOption = False, ): @@ -274,6 +305,9 @@ def enrich_command( linkml-reference-validator cache enrich --provider zotero --dry-run linkml-reference-validator cache enrich --provider zotero --apply + + linkml-reference-validator cache enrich --provider zotero \\ + --zotero-dir ~/Zotero --referenced-in 'kb/disorders/MyDisease.yaml' --apply """ setup_logging(verbose) @@ -286,24 +320,58 @@ def enrich_command( config.cache_dir = cache_dir if private_cache_dir: config.private_cache_dir = private_cache_dir + if zotero_dir: + config.zotero_dir = zotero_dir fetcher = ReferenceFetcher(config) + cached_refs: Iterable[ReferenceContent] = fetcher.iter_cached_references() + if reference or referenced_in: + all_cached = list(cached_refs) + + def _id_key(ref_id: str) -> str: + norm = fetcher.normalize_reference_id(ref_id) + return norm.casefold() if norm.upper().startswith("DOI:") else norm + + cached_keys = {_id_key(r.reference_id) for r in all_cached} + wanted_keys: set[str] = set() + for req in reference or []: + key = _id_key(req) + wanted_keys.add(key) + if key not in cached_keys: + typer.echo( + f"Warning: requested reference not found in cache: {req}", + err=True, + ) + if referenced_in: + try: + paths = expand_globs(referenced_in, Path(".")) + except ValueError as err: + typer.echo(str(err), err=True) + raise typer.Exit(2) + cited = find_cited_reference_ids( + (r.reference_id for r in all_cached), paths + ) + wanted_keys.update(_id_key(r) for r in cited) + cached_refs = [ + r for r in all_cached if _id_key(r.reference_id) in wanted_keys + ] + found = 0 applied = 0 errors = 0 scanned = 0 consecutive_errors = 0 - for reference in fetcher.iter_cached_references(): + for ref_item in cached_refs: scanned += 1 - if not fetcher.needs_full_text(reference): - typer.echo(f"{reference.reference_id}\talready_full_text\t-") + if not fetcher.needs_full_text(ref_item): + typer.echo(f"{ref_item.reference_id}\talready_full_text\t-") continue try: # provider is an external-system boundary - location = fetcher.locate_full_text(reference, provider) + location = fetcher.locate_full_text(ref_item, provider) except Exception as exc: errors += 1 consecutive_errors += 1 - typer.echo(f"{reference.reference_id}\terror\t{exc}") + typer.echo(f"{ref_item.reference_id}\terror\t{exc}") if consecutive_errors >= MAX_CONSECUTIVE_PROVIDER_ERRORS: typer.echo( "Stopping after " @@ -317,7 +385,7 @@ def enrich_command( consecutive_errors = 0 if location is None: - typer.echo(f"{reference.reference_id}\tnot_found\t-") + typer.echo(f"{ref_item.reference_id}\tnot_found\t-") continue if location.declined: @@ -325,22 +393,22 @@ def enrich_command( # A declined location carries no url and no text, so counting it # would inflate `Found:` by exactly the references the provider # refused -- and this command's whole output is an inventory. - typer.echo(f"{reference.reference_id}\tdeclined\t{location.declined}") + typer.echo(f"{ref_item.reference_id}\tdeclined\t{location.declined}") continue found += 1 source = f"{location.provider or provider}:{location.source_item_id or '-'}" if dry_run: - typer.echo(f"{reference.reference_id}\tfound\t{source}") + typer.echo(f"{ref_item.reference_id}\tfound\t{source}") continue if fetcher.apply_full_text_location( - reference, location, provider, private=True + ref_item, location, provider, private=True ): applied += 1 - typer.echo(f"{reference.reference_id}\tapplied\t{source}") + typer.echo(f"{ref_item.reference_id}\tapplied\t{source}") else: - typer.echo(f"{reference.reference_id}\tunusable\t{source}") + typer.echo(f"{ref_item.reference_id}\tunusable\t{source}") typer.echo(f"Scanned: {scanned}") typer.echo(f"Found: {found}") diff --git a/src/linkml_reference_validator/etl/acquire.py b/src/linkml_reference_validator/etl/acquire.py index 1734663..7d994af 100644 --- a/src/linkml_reference_validator/etl/acquire.py +++ b/src/linkml_reference_validator/etl/acquire.py @@ -290,3 +290,40 @@ def _read_local_file( ) return None, content_type return path.read_bytes(), content_type + + def read_zotero_storage_file( + self, file_url: str, config: ReferenceValidationConfig + ) -> tuple[Optional[bytes], Optional[str]]: + """Read a local Zotero storage file URI only when inside config.zotero_dir/storage. + + Examples: + >>> import tempfile + >>> from linkml_reference_validator.models import ReferenceValidationConfig + >>> d = Path(tempfile.mkdtemp()) + >>> (d / "storage" / "K1").mkdir(parents=True) + >>> pdf = d / "storage" / "K1" / "p.pdf" + >>> _ = pdf.write_bytes(b"%PDF-1.4") + >>> outside = d / "outside.pdf" + >>> _ = outside.write_bytes(b"%PDF-1.4") + >>> cfg = ReferenceValidationConfig(zotero_dir=d) + >>> ContentAcquirer().read_zotero_storage_file(pdf.as_uri(), cfg)[0] + b'%PDF-1.4' + >>> ContentAcquirer().read_zotero_storage_file(outside.as_uri(), cfg) + (None, None) + """ + if config.zotero_dir is None: + logger.warning("Refusing file URI without zotero_dir configured") + return None, None + parsed = urlparse(file_url) + if parsed.scheme != "file" or parsed.netloc not in {"", "localhost"}: + logger.warning("Refusing a non-local file URI") + return None, None + zotero_storage = (Path(config.zotero_dir).expanduser() / "storage").resolve() + resolved_path = Path(url2pathname(parsed.path)).resolve() + if not resolved_path.is_relative_to(zotero_storage): + logger.warning( + f"Refusing file URI outside Zotero storage directory: {resolved_path}" + ) + return None, None + return self._read_local_file(file_url, config) + diff --git a/src/linkml_reference_validator/etl/fulltext/zotero.py b/src/linkml_reference_validator/etl/fulltext/zotero.py index 110d600..2bbda13 100644 --- a/src/linkml_reference_validator/etl/fulltext/zotero.py +++ b/src/linkml_reference_validator/etl/fulltext/zotero.py @@ -7,8 +7,12 @@ """ import re +import shutil +import sqlite3 +import tempfile from collections import defaultdict -from typing import Optional +from pathlib import Path +from typing import Optional, Protocol import requests # type: ignore @@ -25,6 +29,7 @@ MIN_ZOTERO_INDEXED_TEXT_CHARS = 500 _EXTRA_IDENTIFIER_PATTERNS = { + "doi": re.compile(r"^DOI\s*:\s*(\S+)\s*$", re.IGNORECASE | re.MULTILINE), "pmid": re.compile(r"^PMID\s*:\s*(\d+)\s*$", re.IGNORECASE | re.MULTILINE), "pmcid": re.compile( r"^PMCID\s*:\s*(PMC\d+)\s*$", re.IGNORECASE | re.MULTILINE @@ -32,10 +37,228 @@ } +def _index_extra_identifiers( + extra: str, key: str, index: dict[tuple[str, str], set[str]] +) -> None: + """Extract DOI, PMID, and PMCID lines from a Zotero ``extra`` field into ``index``.""" + for kind, pattern in _EXTRA_IDENTIFIER_PATTERNS.items(): + match = pattern.search(extra) + if not match: + continue + raw = match.group(1) + if kind == "doi": + doi = normalize_doi(raw) + if doi: + index[("doi", doi)].add(key) + elif kind == "pmcid": + index[("pmcid", raw.upper())].add(key) + else: + index[(kind, raw)].add(key) + + + class ZoteroAPIError(RuntimeError): """Raised when Zotero's API cannot complete a read operation.""" +class ZoteroBackend(Protocol): + """Protocol implemented by both HTTP and local-directory Zotero clients.""" + + def find_parent_keys(self, ids: ReferenceIdentifiers) -> set[str]: + """Return unambiguous parent item keys matching supplied identifiers.""" + ... + + def pdf_attachments(self, parent_key: str) -> list[dict]: + """Return PDF attachment items belonging to a parent item.""" + ... + + def indexed_full_text(self, attachment_key: str) -> Optional[str]: + """Return Zotero-indexed attachment text, or None when unavailable.""" + ... + + def attachment_file_url(self, attachment_key: str) -> Optional[str]: + """Return the URL or file URI for downloading the attachment, or None.""" + ... + + +class ZoteroDirectoryClient: + """Read-only client backed by a local Zotero data directory (zotero.sqlite + storage/). + + Examples: + >>> import tempfile, sqlite3 + >>> d = Path(tempfile.mkdtemp()) + >>> (d / "storage" / "K1").mkdir(parents=True) + >>> _ = (d / "storage" / "K1" / "p.pdf").write_bytes(b"%PDF-1.4") + >>> conn = sqlite3.connect(d / "zotero.sqlite") + >>> _ = conn.executescript(''' + ... CREATE TABLE items (itemID INT, key TEXT); + ... CREATE TABLE itemAttachments (itemID INT, parentItemID INT, contentType TEXT, path TEXT); + ... CREATE TABLE fields (fieldID INT, fieldName TEXT); + ... CREATE TABLE itemDataValues (valueID INT, value TEXT); + ... CREATE TABLE itemData (itemID INT, fieldID INT, valueID INT); + ... INSERT INTO items VALUES (1, 'P1'), (2, 'K1'); + ... INSERT INTO itemAttachments VALUES (2, 1, 'application/pdf', 'storage:p.pdf'); + ... INSERT INTO fields VALUES (1, 'DOI'); + ... INSERT INTO itemDataValues VALUES (1, '10.1000/abc'); + ... INSERT INTO itemData VALUES (1, 1, 1); + ... ''') + >>> conn.commit(); conn.close() + >>> ZoteroDirectoryClient(d).find_parent_keys(ReferenceIdentifiers(doi="10.1000/ABC")) + {'P1'} + """ + + def __init__(self, zotero_dir: Path): + """Initialize with a Zotero data directory containing zotero.sqlite and storage/.""" + self.zotero_dir = Path(zotero_dir).expanduser() + self._identifier_index: Optional[dict[tuple[str, str], set[str]]] = None + self._attachments_by_parent: dict[str, list[dict]] = {} + self._pdf_paths_by_key: dict[str, Path] = {} + + def find_parent_keys(self, ids: ReferenceIdentifiers) -> set[str]: + """Return unambiguous parent candidates matching supplied identifiers.""" + index = self._get_identifier_index() + requested = { + "doi": normalize_doi(ids.doi), + "pmid": ids.pmid.strip() if ids.pmid else None, + "pmcid": ids.pmcid.strip().upper() if ids.pmcid else None, + } + matched_sets = [ + index[(kind, value)] + for kind, value in requested.items() + if value and index.get((kind, value)) + ] + if not matched_sets: + return set() + candidates = set(matched_sets[0]) + for matches in matched_sets[1:]: + candidates.intersection_update(matches) + return candidates + + def pdf_attachments(self, parent_key: str) -> list[dict]: + """Return PDF attachment items belonging to a parent item.""" + self._get_identifier_index() + return list(self._attachments_by_parent.get(parent_key, [])) + + def indexed_full_text(self, attachment_key: str) -> Optional[str]: + """Return Zotero's cached full-text file (.zotero-ft-cache) if present.""" + ft_cache = self.zotero_dir / "storage" / attachment_key / ".zotero-ft-cache" + if not ft_cache.is_file(): + return None + content = ft_cache.read_text(encoding="utf-8", errors="ignore") + return content if content.strip() else None + + def attachment_file_url(self, attachment_key: str) -> Optional[str]: + """Return a file:// URI for the attachment PDF, or None if not found.""" + self._get_identifier_index() + pdf_path = self._pdf_paths_by_key.get(attachment_key) + if pdf_path is not None: + return pdf_path.resolve().as_uri() + return None + + def _get_identifier_index(self) -> dict[tuple[str, str], set[str]]: + """Load and cache exact identifiers and PDF attachments from a temp copy of zotero.sqlite.""" + if self._identifier_index is not None: + return self._identifier_index + + db_path = self.zotero_dir / "zotero.sqlite" + if not db_path.is_file(): + raise ZoteroAPIError(f"Zotero database not found: {db_path}") + + storage_root = (self.zotero_dir / "storage").resolve() + try: # external system boundary: sqlite file may be locked or damaged + with tempfile.TemporaryDirectory() as tmpdir: + db_copy = Path(tmpdir) / "zotero.sqlite" + shutil.copy2(db_path, db_copy) + for sidecar in ("-wal", "-journal"): + sidecar_path = self.zotero_dir / f"zotero.sqlite{sidecar}" + if sidecar_path.is_file(): + shutil.copy2( + sidecar_path, Path(tmpdir) / f"zotero.sqlite{sidecar}" + ) + conn = sqlite3.connect(f"file:{db_copy}?mode=ro", uri=True) + try: + cur = conn.cursor() + cur.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='deletedItems'" + ) + has_deleted_items = cur.fetchone() is not None + trash_clause = ( + " AND p.itemID NOT IN (SELECT itemID FROM deletedItems)" + " AND a.itemID NOT IN (SELECT itemID FROM deletedItems)" + if has_deleted_items + else "" + ) + cur.execute( + f""" + SELECT p.itemID, p.key AS parent_key, a.key AS att_key, ia.path + FROM itemAttachments ia + JOIN items a ON ia.itemID = a.itemID + JOIN items p ON ia.parentItemID = p.itemID + WHERE ia.contentType = 'application/pdf' + AND ia.path LIKE 'storage:%'{trash_clause} + """ + ) + parent_id_to_key: dict[int, str] = {} + attachments_by_parent: dict[str, list[dict]] = defaultdict(list) + for parent_id, parent_key, att_key, raw_path in cur.fetchall(): + if not parent_id or not parent_key or not att_key: + continue + rel_name = str(raw_path).split("storage:", 1)[1] + att_dir = (storage_root / att_key).resolve() + if not att_dir.is_relative_to(storage_root): + continue + pdf_path = (att_dir / rel_name).resolve() + if not pdf_path.is_relative_to(att_dir) or not pdf_path.is_file(): + continue + parent_id_to_key[parent_id] = parent_key + self._pdf_paths_by_key[att_key] = pdf_path + attachments_by_parent[parent_key].append( + { + "key": att_key, + "data": { + "key": att_key, + "itemType": "attachment", + "contentType": "application/pdf", + "filename": rel_name, + }, + } + ) + + index: dict[tuple[str, str], set[str]] = defaultdict(set) + if parent_id_to_key: + parent_ids = tuple(parent_id_to_key.keys()) + cur.execute( + f""" + SELECT id.itemID, f.fieldName, idv.value + FROM itemData id + JOIN fields f ON id.fieldID = f.fieldID + JOIN itemDataValues idv ON id.valueID = idv.valueID + WHERE id.itemID IN ({",".join("?" for _ in parent_ids)}) + AND f.fieldName IN ('DOI', 'extra') + """, + parent_ids, + ) + for item_id, field_name, val in cur.fetchall(): + parent_key = parent_id_to_key[item_id] + if field_name == "DOI": + doi = normalize_doi(val) + if doi: + index[("doi", doi)].add(parent_key) + elif field_name == "extra" and isinstance(val, str): + _index_extra_identifiers(val, parent_key, index) + finally: + conn.close() + except (OSError, sqlite3.DatabaseError) as exc: + raise ZoteroAPIError( + f"Could not read Zotero database {db_path} " + f"(if Zotero is open, close it or retry): {exc}" + ) from exc + + self._attachments_by_parent = dict(attachments_by_parent) + self._identifier_index = dict(index) + return self._identifier_index + + class ZoteroClient: """Small read-only client for the Zotero v3 item API.""" @@ -132,13 +355,7 @@ def _get_identifier_index(self) -> dict[tuple[str, str], set[str]]: extra = data.get("extra", "") if isinstance(extra, str): - for kind, pattern in _EXTRA_IDENTIFIER_PATTERNS.items(): - match = pattern.search(extra) - if match: - value = match.group(1) - if kind == "pmcid": - value = value.upper() - index[(kind, value)].add(key) + _index_extra_identifiers(extra, key, index) self._identifier_index = dict(index) return self._identifier_index @@ -192,11 +409,16 @@ def _require_success(status_code: int, operation: str) -> None: class ZoteroFullTextProvider(FullTextProvider): """Find full text in a user's Zotero library by exact identifier.""" - def __init__(self, client: Optional[ZoteroClient] = None): + def __init__(self, client: Optional[ZoteroBackend] = None): """Initialize with an optional client for testing or custom embedding.""" self._client = client self._client_is_injected = client is not None - self._client_base_url = client.base_url if client is not None else None + self._client_base_url = ( + getattr(client, "base_url", None) if client is not None else None + ) + self._client_zotero_dir: Optional[Path] = ( + getattr(client, "zotero_dir", None) if client is not None else None + ) @classmethod def name(cls) -> str: @@ -207,12 +429,20 @@ def locate( self, ids: ReferenceIdentifiers, config: ReferenceValidationConfig ) -> Optional[FullTextLocation]: """Return indexed text or a PDF endpoint for an exact Zotero match.""" - if self._client is None or ( - not self._client_is_injected - and self._client_base_url != config.zotero_base_url.rstrip("/") - ): - self._client = ZoteroClient(config.zotero_base_url) - self._client_base_url = config.zotero_base_url.rstrip("/") + if not self._client_is_injected: + if config.zotero_dir is not None: + resolved_dir = Path(config.zotero_dir).expanduser() + if self._client is None or self._client_zotero_dir != resolved_dir: + self._client = ZoteroDirectoryClient(resolved_dir) + self._client_zotero_dir = resolved_dir + self._client_base_url = None + else: + base_url = config.zotero_base_url.rstrip("/") + if self._client is None or self._client_base_url != base_url: + self._client = ZoteroClient(config.zotero_base_url) + self._client_base_url = base_url + self._client_zotero_dir = None + assert self._client is not None client = self._client parent_keys = client.find_parent_keys(ids) if len(parent_keys) != 1: @@ -237,6 +467,7 @@ def locate( if text and len(text.strip()) >= MIN_ZOTERO_INDEXED_TEXT_CHARS: return FullTextLocation( text=text, + url=client.attachment_file_url(attachment_key), format_hint="text", provider=self.name(), access_type="user_library", diff --git a/src/linkml_reference_validator/etl/reference_fetcher.py b/src/linkml_reference_validator/etl/reference_fetcher.py index bea12cf..b80b4d0 100644 --- a/src/linkml_reference_validator/etl/reference_fetcher.py +++ b/src/linkml_reference_validator/etl/reference_fetcher.py @@ -83,7 +83,7 @@ LOCAL_FULL_TEXT_CONTENT_TYPE = "local_full_text" #: Suffixes tried, in order, for a file in ``local_full_text_dir``. -LOCAL_FULL_TEXT_SUFFIXES = (".md", ".txt") +LOCAL_FULL_TEXT_SUFFIXES = (".md", ".txt", ".pdf") NEEDS_FULL_TEXT_TYPES = { @@ -583,6 +583,21 @@ def _with_local_full_text( if local is None or not local.content: logger.warning("Local full text for %s is empty: %s", normalized_reference_id, path) return outcome + local_text = local.content + local_title = local.title + if path.suffix.lower() == ".md" and local_text.startswith("---\n"): + parsed = self._load_markdown_format(local_text, normalized_reference_id) + if parsed is not None: + if not parsed.content or self.needs_full_text(parsed): + logger.info( + "Skipping local cache file for %s without full text (%s): %s", + normalized_reference_id, + parsed.content_type, + path, + ) + return outcome + local_text = parsed.content + local_title = parsed.title or local_title content_type = ( local.content_type if local.content_type in FIGURE_CONTENT_TYPES.values() @@ -590,11 +605,11 @@ def _with_local_full_text( ) logger.info("Matching %s against local full text %s", normalized_reference_id, path) base = outcome.content or ReferenceContent( - reference_id=normalized_reference_id, title=local.title + reference_id=normalized_reference_id, title=local_title ) merged = replace( base, - content=local.content, + content=local_text, content_type=content_type, full_text_provider=LOCAL_FULL_TEXT_CONTENT_TYPE, ) @@ -1226,15 +1241,39 @@ def _materialize( structural extraction; a format hint alone does not certify raw HTML. """ if location.text: + pdf_bytes: Optional[bytes] = None + if ( + self.config.download_pdfs + and location.url + and location.url.startswith("file://") + and location.provider == "zotero" + and self.config.zotero_dir is not None + ): + fetched, _ = self._acquirer.read_zotero_storage_file( + location.url, self.config + ) + if fetched and sniff_format(fetched) == "pdf": + pdf_bytes = fetched if location.format_hint == "html" and re.search(r"<[A-Za-z][^>]*>", location.text): - return HTMLExtractor().extract_full_text(location.text), "html", None, False - return location.text, location.format_hint or "text", None, False + return HTMLExtractor().extract_full_text(location.text), "html", pdf_bytes, False + return location.text, location.format_hint or "text", pdf_bytes, False if not location.url: return None, None, None, False try: # external system boundary - data, content_type = self._acquirer.fetch_bytes(location.url, self.config) + if ( + location.url.startswith("file://") + and location.provider == "zotero" + and self.config.zotero_dir is not None + ): + data, content_type = self._acquirer.read_zotero_storage_file( + location.url, self.config + ) + else: + data, content_type = self._acquirer.fetch_bytes( + location.url, self.config + ) except Exception as exc: logger.warning(f"Download failed for {location.url}: {exc}") return None, None, None, True diff --git a/src/linkml_reference_validator/etl/sources/file.py b/src/linkml_reference_validator/etl/sources/file.py index 4206711..d17eac0 100644 --- a/src/linkml_reference_validator/etl/sources/file.py +++ b/src/linkml_reference_validator/etl/sources/file.py @@ -18,6 +18,7 @@ from linkml_reference_validator.etl.acquire import resolve_format from linkml_reference_validator.etl.extract import ExtractorRegistry +from linkml_reference_validator.etl.extract.pdf import PDFExtractor from linkml_reference_validator.matching import FIGURE_CONTENT_TYPES from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig from linkml_reference_validator.etl.sources.base import ReferenceSource, ReferenceSourceRegistry @@ -93,6 +94,19 @@ def fetch( figure_format = resolve_format(None, file_path.name, None) if figure_format in FIGURE_CONTENT_TYPES: return self._fetch_figure(file_path, figure_format, config) + if figure_format == "pdf": + raw_pdf = file_path.read_bytes() + extractor = PDFExtractor(backend=config.pdf_backend) + pdf_text = extractor.extract(raw_pdf, source=str(file_path)) + pdf_title = ( + extractor.extract_title(raw_pdf) if pdf_text else None + ) or file_path.name + return ReferenceContent( + reference_id=self.reference_id_for(file_path, config), + title=pdf_title, + content=pdf_text, + content_type="full_text_pdf" if pdf_text else "unavailable", + ) content = file_path.read_text(encoding="utf-8") title = self._extract_title(content, file_path) diff --git a/src/linkml_reference_validator/excerpt_signing.py b/src/linkml_reference_validator/excerpt_signing.py index ef5e324..adbfd1e 100644 --- a/src/linkml_reference_validator/excerpt_signing.py +++ b/src/linkml_reference_validator/excerpt_signing.py @@ -31,9 +31,9 @@ from linkml_reference_validator import __version__ from linkml_reference_validator.cache import ( - _same_reference_id, cache_filename, disambiguated_cache_filename, + same_reference_id, ) from linkml_reference_validator.models import ReferenceValidationConfig from linkml_reference_validator.signed_excerpts import BUNDLE_SUFFIXES @@ -151,7 +151,7 @@ def _bundle_path( if not candidate.is_file(): continue stored = _stored_reference_id(candidate) - if stored is None or _same_reference_id(normalize(stored), normalized_id): + if stored is None or same_reference_id(normalize(stored), normalized_id): return candidate taken[position] = True if not taken[0]: @@ -377,8 +377,24 @@ def sign_excerpts( directory = Path(directory) # Verify against the local text only: an existing bundle must not vouch - # for the quotes it is about to be extended with. - checking = config.model_copy(update={"signed_excerpts_dir": None}) + # for the quotes it is about to be extended with. If private_cache_dir + # exists (e.g. populated by `cache enrich --provider zotero --apply`), + # fall back to it for any reference not already mapped by local_full_text + # or local_full_text_dir. + private_dir = config.private_cache_dir.expanduser() + has_private_dir = private_dir.is_dir() + fallback_dir = ( + config.local_full_text_dir + if config.local_full_text_dir is not None + else (private_dir if has_private_dir else None) + ) + checking = config.model_copy( + update={ + "signed_excerpts_dir": None, + "local_full_text_dir": fallback_dir, + "local_full_text": dict(config.local_full_text), + } + ) validator = SupportingTextValidator(checking) fetcher = validator.fetcher report = SignReport() @@ -387,9 +403,18 @@ def sign_excerpts( quotes: dict[str, list[str]] = {} for reference_id, text in collect_quotes(data_files): normalized = fetcher.normalize_reference_id(reference_id) - if wanted and not any(_same_reference_id(w, normalized) for w in wanted): + if wanted and not any(same_reference_id(w, normalized) for w in wanted): continue quotes.setdefault(normalized, []).append(text) + if config.local_full_text_dir is not None and has_private_dir: + private_fetcher = SupportingTextValidator( + checking.model_copy(update={"local_full_text_dir": private_dir}) + ).fetcher + for reference_id in set(quotes) | set(wanted): + if fetcher.local_full_text_path(reference_id) is None: + priv_path = private_fetcher.local_full_text_path(reference_id) + if priv_path is not None: + checking.local_full_text[reference_id] = priv_path for reference_id in wanted: if fetcher.local_full_text_path(reference_id) is None: report.no_local_text.append(reference_id) @@ -452,7 +477,7 @@ def sign_excerpts( if stored is None: continue normalized = fetcher.normalize_reference_id(stored) - if any(_same_reference_id(normalized, c) for c in cited): + if any(same_reference_id(normalized, c) for c in cited): continue # Only the file validation would read for this reference: a # hand-named bundle, or the .yml twin of a .yaml, is skipped diff --git a/src/linkml_reference_validator/models.py b/src/linkml_reference_validator/models.py index 72b0bf9..94a1dfa 100644 --- a/src/linkml_reference_validator/models.py +++ b/src/linkml_reference_validator/models.py @@ -804,6 +804,15 @@ class ReferenceValidationConfig(BaseModel): "Zotero must be running with local API access enabled." ), ) + zotero_dir: Optional[Path] = Field( + default=None, + description=( + "Optional local Zotero data directory (e.g. ~/Zotero) containing " + "zotero.sqlite and storage/. When set, the zotero provider reads " + "a safe copy of zotero.sqlite and storage/ directly instead " + "of querying zotero_base_url over HTTP." + ), + ) def get_cache_dir(self) -> Path: """Create and return the cache directory. diff --git a/src/linkml_reference_validator/signed_excerpts.py b/src/linkml_reference_validator/signed_excerpts.py index dc4f0eb..d7ec610 100644 --- a/src/linkml_reference_validator/signed_excerpts.py +++ b/src/linkml_reference_validator/signed_excerpts.py @@ -99,7 +99,7 @@ def find_cited_reference_ids( return found -def _expand_globs(patterns: Iterable[str], base_dir: Path) -> list[Path]: +def expand_globs(patterns: Iterable[str], base_dir: Path) -> list[Path]: """Expand glob patterns relative to ``base_dir`` into existing files. Raises: @@ -120,6 +120,9 @@ def _expand_globs(patterns: Iterable[str], base_dir: Path) -> list[Path]: return paths +_expand_globs = expand_globs + + def _load_bundle(path: Path) -> dict[str, Any]: """Parse a bundle file, failing with the file named if it is not a mapping.""" data = YAML(typ="safe").load(path) diff --git a/tests/test_cli_cache_enrich.py b/tests/test_cli_cache_enrich.py index f781e72..228a3e3 100644 --- a/tests/test_cli_cache_enrich.py +++ b/tests/test_cli_cache_enrich.py @@ -225,3 +225,132 @@ def test_cache_enrich_fails_fast_after_repeated_provider_errors(tmp_path): assert _UnavailableProvider.calls == 3 assert "Stopping after 3 consecutive provider errors" in result.output assert "Scanned: 3" in result.output + + +def test_cache_enrich_filters_by_reference_and_referenced_in(tmp_path, monkeypatch): + """--reference and --referenced-in restrict enrichment to the selected references.""" + monkeypatch.chdir(tmp_path) + cache_dir = tmp_path / "cache" + cache_dir.mkdir() + _write_cached_reference(cache_dir, "DOI:10.1000/hit", "10.1000/hit") + _write_cached_reference(cache_dir, "DOI:10.1000/other", "10.1000/other") + kb_file = tmp_path / "entry.yaml" + kb_file.write_text("reference: DOI:10.1000/hit\n", encoding="utf-8") + FullTextProviderRegistry.register(_PrivateHitProvider) + + by_ref = CliRunner().invoke( + app, + [ + "cache", + "enrich", + "--provider", + "private_hit", + "--cache-dir", + str(cache_dir), + "--reference", + "doi:10.1000/HIT", + "--dry-run", + ], + ) + assert by_ref.exit_code == 0, by_ref.output + assert "Scanned: 1" in by_ref.output + assert "Found: 1" in by_ref.output + assert "DOI:10.1000/other" not in by_ref.output + + by_glob = CliRunner().invoke( + app, + [ + "cache", + "enrich", + "--provider", + "private_hit", + "--cache-dir", + str(cache_dir), + "--referenced-in", + "entry.yaml", + "--dry-run", + ], + ) + assert by_glob.exit_code == 0, by_glob.output + assert "Scanned: 1" in by_glob.output + assert "Found: 1" in by_glob.output + assert "DOI:10.1000/other" not in by_glob.output + + +def test_cache_enrich_referenced_in_no_matches_exits_2(tmp_path, monkeypatch): + """--referenced-in with a glob matching no files exits with code 2.""" + monkeypatch.chdir(tmp_path) + cache_dir = tmp_path / "cache" + cache_dir.mkdir() + _write_cached_reference(cache_dir, "DOI:10.1000/hit", "10.1000/hit") + FullTextProviderRegistry.register(_PrivateHitProvider) + + result = CliRunner().invoke( + app, + [ + "cache", + "enrich", + "--provider", + "private_hit", + "--cache-dir", + str(cache_dir), + "--referenced-in", + "does_not_match_*.yaml", + "--dry-run", + ], + ) + assert result.exit_code == 2 + assert "matches no files" in result.output + + +def test_cache_enrich_warns_when_requested_reference_not_in_cache(tmp_path): + """--reference with an uncached ID emits a warning instead of failing silently.""" + cache_dir = tmp_path / "cache" + cache_dir.mkdir() + _write_cached_reference(cache_dir, "DOI:10.1000/hit", "10.1000/hit") + FullTextProviderRegistry.register(_PrivateHitProvider) + + result = CliRunner().invoke( + app, + [ + "cache", + "enrich", + "--provider", + "private_hit", + "--cache-dir", + str(cache_dir), + "--reference", + "PMID:99999999", + "--dry-run", + ], + ) + assert result.exit_code == 0, result.output + assert "PMID:99999999" in result.output + assert "Scanned: 0" in result.output + + +def test_cache_enrich_missing_zotero_sqlite_reports_clear_error(tmp_path): + """A missing zotero.sqlite surfaces ZoteroAPIError in cache enrich output.""" + cache_dir = tmp_path / "cache" + cache_dir.mkdir() + _write_cached_reference(cache_dir, "DOI:10.1000/hit", "10.1000/hit") + empty_zotero = tmp_path / "EmptyZotero" + empty_zotero.mkdir() + + result = CliRunner().invoke( + app, + [ + "cache", + "enrich", + "--provider", + "zotero", + "--cache-dir", + str(cache_dir), + "--zotero-dir", + str(empty_zotero), + "--dry-run", + ], + ) + assert result.exit_code == 1 + assert "Zotero database not found" in result.output + diff --git a/tests/test_excerpts_sign.py b/tests/test_excerpts_sign.py index d2e0cc6..968f7de 100644 --- a/tests/test_excerpts_sign.py +++ b/tests/test_excerpts_sign.py @@ -118,6 +118,74 @@ def test_unverified_snippet_is_reported_and_not_signed(config): assert [e["text"] for e in load_bundle(config)["excerpts"]] == [QUOTE] +def test_sign_excerpts_falls_back_to_private_cache_dir(tmp_path): + """excerpts sign can verify against private_cache_dir written by cache enrich.""" + base = tmp_path / "repo" + base.mkdir() + cfg = ReferenceValidationConfig( + cache_dir=tmp_path / "cache", + private_cache_dir=tmp_path / "private", + reference_base_dir=base, + signed_excerpts_dir=base / "signed_excerpts", + fetch_full_text=False, + ) + fetcher = ReferenceFetcher(cfg) + fetcher._save_to_disk( + ReferenceContent( + reference_id=DOI, + title=TITLE, + content="Only the abstract.", + content_type="abstract_only", + full_text_attempted=True, + ) + ) + fetcher._save_to_disk( + ReferenceContent( + reference_id=DOI, + title=TITLE, + content=f"Only the abstract.\n\n{QUOTE}", + content_type="full_text_pdf", + full_text_provider="zotero", + full_text_access_type="user_library", + full_text_attempted=True, + ), + private=True, + ) + # Normal validation before signing must NOT read private_cache_dir + assert not SupportingTextValidator(cfg).validate(QUOTE, DOI).is_valid + + data = base / "kb.yaml" + data.write_text(evidence_yaml(QUOTE), encoding="utf-8") + report = sign_excerpts([data], cfg, today=TODAY) + assert report.written == [f"{STEM}.yaml"] + assert not report.failures + + # After signing, normal validation succeeds via signed_excerpts_dir + res = SupportingTextValidator(cfg).validate(QUOTE, DOI) + assert res.is_valid + assert res.match_result.match_location == "signed_excerpts" + + # Without signed_excerpts_dir, normal validation still ignores private_cache_dir + cfg_no_bundles = cfg.model_copy(update={"signed_excerpts_dir": None}) + assert not SupportingTextValidator(cfg_no_bundles).validate(QUOTE, DOI).is_valid + + # Even when local_full_text_dir is set to another directory, sign_excerpts + # still falls back to private_cache_dir for references not in local_full_text_dir + curated_dir = base / "curated" + curated_dir.mkdir() + cfg_both = cfg.model_copy( + update={ + "local_full_text_dir": curated_dir, + "signed_excerpts_dir": base / "signed_excerpts_both", + } + ) + report_both = sign_excerpts([data], cfg_both, today=TODAY) + assert report_both.written == [f"{STEM}.yaml"] + assert not report_both.failures + + + + def test_existing_bundle_does_not_vouch_for_a_snippet(config): """A hand-typed bundle entry must not let signing re-sign the same text.""" config.signed_excerpts_dir.mkdir() diff --git a/tests/test_local_full_text.py b/tests/test_local_full_text.py index 018e725..541bb40 100644 --- a/tests/test_local_full_text.py +++ b/tests/test_local_full_text.py @@ -192,3 +192,75 @@ def test_cache_reference_reports_the_cached_text_not_the_local_file(config, pape assert result.exit_code == 0, result.output assert "Content type: unavailable" in result.output assert "local_full_text" not in result.output + + +def test_local_full_text_strips_cache_frontmatter_and_header(config, tmp_path): + """A cache-formatted .md file in local_full_text_dir exposes only its Content body.""" + private_dir = tmp_path / "private_cache" + private_dir.mkdir() + (private_dir / f"{STEM}.md").write_text( + "---\n" + f"reference_id: {DOI}\n" + f"title: {TITLE}\n" + "authors:\n" + "- Secret Author Name\n" + "content_type: full_text_pdf\n" + "---\n\n" + f"# {TITLE}\n" + "**Authors:** Secret Author Name\n\n" + "## Content\n\n" + f"{QUOTE}\n", + encoding="utf-8", + ) + config.local_full_text_dir = private_dir + validator = SupportingTextValidator(config) + assert validator.validate(QUOTE, DOI).is_valid + assert not validator.validate("Secret Author Name", DOI).is_valid + + +def test_local_full_text_extracts_pdf_files(config, tmp_path): + """A .pdf file in local_full_text_dir is extracted via PDFExtractor.""" + from tests.test_extractors import _build_minimal_pdf + + papers = tmp_path / "pdf_papers" + papers.mkdir() + pdf_bytes = _build_minimal_pdf(QUOTE) + (papers / f"{STEM}.pdf").write_bytes(pdf_bytes) + config.local_full_text_dir = papers + assert SupportingTextValidator(config).validate(QUOTE, DOI).is_valid + + +def test_local_full_text_skips_abstract_only_cache_markdown(config, tmp_path, caplog): + """A cache-formatted .md with content_type: abstract_only in local_full_text_dir is skipped.""" + import logging + + private_dir = tmp_path / "private_cache" + private_dir.mkdir() + (private_dir / f"{STEM}.md").write_text( + "---\n" + f"reference_id: {DOI}\n" + f"title: {TITLE}\n" + "content_type: abstract_only\n" + "---\n\n" + f"# {TITLE}\n\n" + "## Content\n\n" + f"{QUOTE}\n", + encoding="utf-8", + ) + config.local_full_text_dir = private_dir + validator = SupportingTextValidator(config) + with caplog.at_level(logging.INFO): + result = validator.validate(QUOTE, DOI) + assert not result.is_valid + assert any("Skipping local cache file" in rec.message for rec in caplog.records) + + +def test_local_full_text_unreadable_pdf_does_not_raise(config, tmp_path): + """A corrupt .pdf in local_full_text_dir logs a warning and does not crash validation.""" + papers = tmp_path / "corrupt_pdfs" + papers.mkdir() + (papers / f"{STEM}.pdf").write_bytes(b"%PDF-1.7 truncated corrupt bytes") + config.local_full_text_dir = papers + result = SupportingTextValidator(config).validate(QUOTE, DOI) + assert not result.is_valid + diff --git a/tests/test_zotero_provider.py b/tests/test_zotero_provider.py index 7c8d14b..31e441d 100644 --- a/tests/test_zotero_provider.py +++ b/tests/test_zotero_provider.py @@ -275,3 +275,237 @@ def test_client_surfaces_disabled_local_api(): with pytest.raises(ZoteroAPIError, match="403"): client.find_parent_keys(ReferenceIdentifiers(doi="10.1000/a")) + + +def test_directory_client_reads_sqlite_and_storage_without_http(tmp_path): + """ZoteroDirectoryClient indexes zotero.sqlite and reads storage/ directly.""" + import sqlite3 + from linkml_reference_validator.etl.fulltext.zotero import ( + ZoteroDirectoryClient, + ZoteroFullTextProvider, + ) + + zotero_dir = tmp_path / "Zotero" + storage_dir = zotero_dir / "storage" / "ATTKEY1" + storage_dir.mkdir(parents=True) + pdf_file = storage_dir / "article.pdf" + pdf_file.write_bytes(b"%PDF-1.4\n...") + (storage_dir / ".zotero-ft-cache").write_text( + "indexed sqlite full text " * 30, encoding="utf-8" + ) + + db_path = zotero_dir / "zotero.sqlite" + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE items (itemID INTEGER PRIMARY KEY, key TEXT); + CREATE TABLE itemAttachments ( + itemID INTEGER PRIMARY KEY, + parentItemID INTEGER, + contentType TEXT, + path TEXT + ); + CREATE TABLE fields (fieldID INTEGER PRIMARY KEY, fieldName TEXT); + CREATE TABLE itemDataValues (valueID INTEGER PRIMARY KEY, value TEXT); + CREATE TABLE itemData (itemID INTEGER, fieldID INTEGER, valueID INTEGER); + + INSERT INTO items VALUES (1, 'PARENT1'), (2, 'ATTKEY1'); + INSERT INTO itemAttachments VALUES (2, 1, 'application/pdf', 'storage:article.pdf'); + INSERT INTO fields VALUES (10, 'DOI'), (11, 'extra'); + INSERT INTO itemDataValues VALUES (100, '10.1000/SqliteHit'), (101, 'PMID: 987654'); + INSERT INTO itemData VALUES (1, 10, 100), (1, 11, 101); + """ + ) + conn.commit() + conn.close() + + client = ZoteroDirectoryClient(zotero_dir) + assert client.find_parent_keys(ReferenceIdentifiers(doi="10.1000/sqlitehit")) == { + "PARENT1" + } + assert client.find_parent_keys(ReferenceIdentifiers(pmid="987654")) == {"PARENT1"} + + provider = ZoteroFullTextProvider() + cfg = ReferenceValidationConfig( + cache_dir=tmp_path / "public", + private_cache_dir=tmp_path / "private", + zotero_dir=zotero_dir, + rate_limit_delay=0.0, + download_pdfs=True, + ) + loc = provider.locate(ReferenceIdentifiers(doi="10.1000/sqlitehit"), cfg) + assert loc is not None + assert loc.source_item_id == "ATTKEY1" + assert loc.access_type == "user_library" + assert "indexed sqlite full text" in (loc.text or "") + assert loc.url == pdf_file.as_uri() + + from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher + from linkml_reference_validator.models import ReferenceContent + + fetcher = ReferenceFetcher(cfg) + ref = ReferenceContent( + reference_id="DOI:10.1000/sqlitehit", + doi="10.1000/sqlitehit", + title="SQLite Paper", + content=None, + content_type="unavailable", + ) + assert fetcher.apply_full_text_location(ref, loc, "zotero", private=True) + assert (cfg.private_cache_dir / "files" / "DOI_10.1000_sqlitehit.pdf").is_file() + + +def test_url_source_and_generic_providers_reject_file_urls(tmp_path): + """URLSource and non-Zotero providers must never read arbitrary file:// URLs.""" + import requests + from linkml_reference_validator.etl.acquire import ContentAcquirer + from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher + from linkml_reference_validator.etl.sources.url import URLSource + from linkml_reference_validator.models import FullTextLocation + + secret = tmp_path / "secret.txt" + secret.write_text("top secret local file contents " * 10, encoding="utf-8") + cfg = ReferenceValidationConfig( + cache_dir=tmp_path / "public", + private_cache_dir=tmp_path / "private", + zotero_dir=tmp_path / "Zotero", + rate_limit_delay=0.0, + ) + + assert URLSource().fetch(secret.as_uri(), cfg) is None + + with pytest.raises(requests.RequestException): + ContentAcquirer().fetch_bytes(secret.as_uri(), cfg) + + fetcher = ReferenceFetcher(cfg) + text, fmt, pdf_bytes, err = fetcher._materialize( + FullTextLocation(url=secret.as_uri(), provider="unpaywall") + ) + assert text is None + assert pdf_bytes is None + assert err is True + + # Even with provider="zotero", a file:// URL outside zotero_dir/storage is rejected + text, fmt, pdf_bytes, err = fetcher._materialize( + FullTextLocation(url=secret.as_uri(), provider="zotero") + ) + assert text is None + assert pdf_bytes is None + + +def test_directory_client_ignores_trashed_items_and_extra_doi(tmp_path): + """ZoteroDirectoryClient skips deletedItems rows and indexes DOIs in extra.""" + import sqlite3 + from linkml_reference_validator.etl.fulltext.zotero import ( + ZoteroClient, + ZoteroDirectoryClient, + ) + + zotero_dir = tmp_path / "Zotero" + for key in ("ATT_LIVE", "ATT_TRASHED_PARENT", "ATT_TRASHED_ATT", "ATT_EXTRA"): + d = zotero_dir / "storage" / key + d.mkdir(parents=True) + (d / "paper.pdf").write_bytes(b"%PDF-1.4\n...") + + outside = zotero_dir / "outside.pdf" + outside.write_bytes(b"%PDF-1.4\n...") + + db_path = zotero_dir / "zotero.sqlite" + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE items (itemID INTEGER PRIMARY KEY, key TEXT); + CREATE TABLE deletedItems (itemID INTEGER PRIMARY KEY); + CREATE TABLE itemAttachments ( + itemID INTEGER PRIMARY KEY, + parentItemID INTEGER, + contentType TEXT, + path TEXT + ); + CREATE TABLE fields (fieldID INTEGER PRIMARY KEY, fieldName TEXT); + CREATE TABLE itemDataValues (valueID INTEGER PRIMARY KEY, value TEXT); + CREATE TABLE itemData (itemID INTEGER, fieldID INTEGER, valueID INTEGER); + + INSERT INTO items VALUES + (1, 'PARENT_LIVE'), (2, 'ATT_LIVE'), + (3, 'PARENT_TRASHED'), (4, 'ATT_TRASHED_PARENT'), + (5, 'PARENT_ONLY_TRASHED_ATT'), (6, 'ATT_TRASHED_ATT'), + (7, 'PARENT_EXTRA_DOI'), (8, 'ATT_EXTRA'), + (9, 'PARENT_TRAVERSAL'), (10, 'ATT_TRAVERSAL'); + INSERT INTO deletedItems VALUES (3), (6); + INSERT INTO itemAttachments VALUES + (2, 1, 'application/pdf', 'storage:paper.pdf'), + (4, 3, 'application/pdf', 'storage:paper.pdf'), + (6, 5, 'application/pdf', 'storage:paper.pdf'), + (8, 7, 'application/pdf', 'storage:paper.pdf'), + (10, 9, 'application/pdf', 'storage:../../outside.pdf'); + INSERT INTO fields VALUES (10, 'DOI'), (11, 'extra'); + INSERT INTO itemDataValues VALUES + (100, '10.1000/DupWithTrash'), + (101, '10.1000/OnlyTrashedAtt'), + (102, 'DOI: 10.1000/ExtraDoi\nPMID: 555'), + (103, '10.1000/Traversal'); + INSERT INTO itemData VALUES + (1, 10, 100), + (3, 10, 100), + (5, 10, 101), + (7, 11, 102), + (9, 10, 103); + """ + ) + conn.commit() + conn.close() + + client = ZoteroDirectoryClient(zotero_dir) + # Trashed duplicate parent (item 3) is ignored, so item 1 is unambiguous: + assert client.find_parent_keys(ReferenceIdentifiers(doi="10.1000/dupwithtrash")) == { + "PARENT_LIVE" + } + # Parent whose only PDF attachment is trashed (item 6) is not indexed: + assert ( + client.find_parent_keys(ReferenceIdentifiers(doi="10.1000/onlytrashedatt")) + == set() + ) + # DOI in extra is indexed by both ZoteroDirectoryClient and ZoteroClient: + assert client.find_parent_keys(ReferenceIdentifiers(doi="10.1000/extradoi")) == { + "PARENT_EXTRA_DOI" + } + session = MagicMock() + session.get.return_value = _json_response( + [_zotero_item("PARENT_EXTRA_DOI", extra="DOI: 10.1000/ExtraDoi\nPMID: 555")] + ) + http_client = ZoteroClient("http://localhost:23119/api/users/0", session=session) + assert http_client.find_parent_keys( + ReferenceIdentifiers(doi="10.1000/extradoi") + ) == {"PARENT_EXTRA_DOI"} + + # Path traversal attachment (storage:../../outside.pdf) is rejected: + assert ( + client.find_parent_keys(ReferenceIdentifiers(doi="10.1000/traversal")) == set() + ) + # Unknown attachment key returns None instead of a directory URI: + assert client.attachment_file_url("UNKNOWN_KEY") is None + + +def test_directory_client_missing_or_corrupt_sqlite_raises_zotero_api_error(tmp_path): + """Missing or corrupt zotero.sqlite raises ZoteroAPIError.""" + from linkml_reference_validator.etl.fulltext.zotero import ( + ZoteroAPIError, + ZoteroDirectoryClient, + ) + + empty_dir = tmp_path / "EmptyZotero" + empty_dir.mkdir() + with pytest.raises(ZoteroAPIError, match="Zotero database not found"): + ZoteroDirectoryClient(empty_dir).find_parent_keys( + ReferenceIdentifiers(doi="10.1000/a") + ) + + corrupt_dir = tmp_path / "CorruptZotero" + corrupt_dir.mkdir() + (corrupt_dir / "zotero.sqlite").write_bytes(b"not a valid sqlite database") + with pytest.raises(ZoteroAPIError, match="Could not read Zotero database"): + ZoteroDirectoryClient(corrupt_dir).find_parent_keys( + ReferenceIdentifiers(doi="10.1000/a") + ) +