@kinloom/cli 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/cached-ocr.py +786 -0
- package/dist/assets/ocr.md +76 -0
- package/dist/assets/prep-scan.md +97 -0
- package/dist/assets/prep-scan.py +1313 -0
- package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
- package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
- package/dist/bundled-skills/archive-org/SKILL.md +162 -0
- package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
- package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
- package/dist/bundled-skills/california-archives/SKILL.md +130 -0
- package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
- package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
- package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
- package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
- package/dist/bundled-skills/findagrave/SKILL.md +129 -0
- package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
- package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
- package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
- package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
- package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
- package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
- package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
- package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
- package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
- package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
- package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
- package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
- package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
- package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
- package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
- package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
- package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
- package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
- package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
- package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
- package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
- package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
- package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
- package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
- package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
- package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
- package/dist/bundled-skills/wikitree/SKILL.md +154 -0
- package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +488 -26
- package/dist/cli.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +30 -5
- package/dist/client.js.map +1 -1
- package/dist/commands/ops/audit.d.ts +138 -0
- package/dist/commands/ops/audit.d.ts.map +1 -0
- package/dist/commands/ops/audit.js +872 -0
- package/dist/commands/ops/audit.js.map +1 -0
- package/dist/commands/ops/context.d.ts +100 -0
- package/dist/commands/ops/context.d.ts.map +1 -0
- package/dist/commands/ops/context.js +917 -0
- package/dist/commands/ops/context.js.map +1 -0
- package/dist/commands/ops/dates.d.ts +87 -0
- package/dist/commands/ops/dates.d.ts.map +1 -0
- package/dist/commands/ops/dates.js +228 -0
- package/dist/commands/ops/dates.js.map +1 -0
- package/dist/commands/ops/help.d.ts +8 -0
- package/dist/commands/ops/help.d.ts.map +1 -0
- package/dist/commands/ops/help.js +107 -0
- package/dist/commands/ops/help.js.map +1 -0
- package/dist/commands/ops/index.d.ts +8 -0
- package/dist/commands/ops/index.d.ts.map +1 -0
- package/dist/commands/ops/index.js +8 -0
- package/dist/commands/ops/index.js.map +1 -0
- package/dist/commands/ops/integrate.d.ts +61 -0
- package/dist/commands/ops/integrate.d.ts.map +1 -0
- package/dist/commands/ops/integrate.js +1063 -0
- package/dist/commands/ops/integrate.js.map +1 -0
- package/dist/commands/ops/sync.d.ts +194 -0
- package/dist/commands/ops/sync.d.ts.map +1 -0
- package/dist/commands/ops/sync.js +1251 -0
- package/dist/commands/ops/sync.js.map +1 -0
- package/dist/commands/ops/telemetry.d.ts +79 -0
- package/dist/commands/ops/telemetry.d.ts.map +1 -0
- package/dist/commands/ops/telemetry.js +249 -0
- package/dist/commands/ops/telemetry.js.map +1 -0
- package/dist/commands/ops/verify.d.ts +76 -0
- package/dist/commands/ops/verify.d.ts.map +1 -0
- package/dist/commands/ops/verify.js +325 -0
- package/dist/commands/ops/verify.js.map +1 -0
- package/dist/commands/records/help.d.ts +18 -0
- package/dist/commands/records/help.d.ts.map +1 -0
- package/dist/commands/records/help.js +174 -0
- package/dist/commands/records/help.js.map +1 -0
- package/dist/commands/records/index.d.ts +5 -0
- package/dist/commands/records/index.d.ts.map +1 -0
- package/dist/commands/records/index.js +5 -0
- package/dist/commands/records/index.js.map +1 -0
- package/dist/commands/records/registry.d.ts +32 -0
- package/dist/commands/records/registry.d.ts.map +1 -0
- package/dist/commands/records/registry.js +227 -0
- package/dist/commands/records/registry.js.map +1 -0
- package/dist/commands/records/resolve.d.ts +14 -0
- package/dist/commands/records/resolve.d.ts.map +1 -0
- package/dist/commands/records/resolve.js +61 -0
- package/dist/commands/records/resolve.js.map +1 -0
- package/dist/commands/records/runner.d.ts +27 -0
- package/dist/commands/records/runner.d.ts.map +1 -0
- package/dist/commands/records/runner.js +255 -0
- package/dist/commands/records/runner.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,1039 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run --script
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "click>=8.1",
|
|
6
|
+
# "httpx>=0.27",
|
|
7
|
+
# "pillow>=10",
|
|
8
|
+
# ]
|
|
9
|
+
# ///
|
|
10
|
+
"""CLI for Library of Virginia research: Chancery Records Index, Primo catalog.
|
|
11
|
+
|
|
12
|
+
All routes below were verified live 2026-11-24 with plain
|
|
13
|
+
HTTP (no key, no account, no browser):
|
|
14
|
+
|
|
15
|
+
- Chancery search is a POST form to old.lva.virginia.gov/chancery/default.asp
|
|
16
|
+
accepting surname, match mode, and locality filters.
|
|
17
|
+
- Case detail is a GET: /chancery/case_detail.asp?CFN=<loc>-<year>-<number>.
|
|
18
|
+
- Case images are listed by /chancery/case_images.asp?CFN=<CFN> as
|
|
19
|
+
myImages[N]="/ChanceryImg/<locality>/Box<nnn>/<cfn>_<####>.pdf";
|
|
20
|
+
each page PDF and the whole-case ZIP
|
|
21
|
+
(/chancery/zip/download.php?cfn=<CFN>) return 200.
|
|
22
|
+
- The Primo catalog has a public, key-free JSON API (PNXS):
|
|
23
|
+
lva.primo.exlibrisgroup.com/primaws/rest/pub/pnxs?q=any,contains,<q>
|
|
24
|
+
&vid=01LVA_INST:01LVA&scope=MyInstitution.
|
|
25
|
+
|
|
26
|
+
Virginia Chronicle (virginiachronicle.com) is behind Cloudflare: curl and
|
|
27
|
+
headless Chromium both get "Just a moment..." (2026-11-24). No machine
|
|
28
|
+
interface was verified for it; use the `url --chronicle` pointer and search
|
|
29
|
+
in the browser. ARVAS (arvasarchive.org) returns an empty 202 to plain HTTP
|
|
30
|
+
and is likewise browser-only. The old Aleph Land Office index host
|
|
31
|
+
(lva1.hosted.exlibrisgroup.com) was unreachable on 2026-11-24.
|
|
32
|
+
|
|
33
|
+
Image and Rosetta routes verified live 2026-11-26:
|
|
34
|
+
|
|
35
|
+
- Land Office patent/grant scans are plain TIFFs on image.lva.virginia.gov,
|
|
36
|
+
e.g. /LONN/LO-3/372/372_0195.tif (image/tiff, CCITT G4 bi-level).
|
|
37
|
+
- Dunmore's War (1774) cards: /cgi-bin/GetDW.pl?dir=<dddd>/W<dddd>&card=<n>
|
|
38
|
+
redirects to a /cgi-bin/drawer page listing neighbouring page TIFFs under
|
|
39
|
+
/Microfilm/DW/<reel>/<nnnnn>.tif; the current card is the link without a
|
|
40
|
+
"Page N" label.
|
|
41
|
+
- Rosetta (rosetta.virginiamemory.com): DeliveryManagerServlet?dps_pid=IE<n>
|
|
42
|
+
embeds an iframe to /view/action/ieViewer.do?...&dps_dvs=<session>&dps_pid=IE<n>;
|
|
43
|
+
the viewer lists file pids (FL<n>, with METS titles such as Original /
|
|
44
|
+
Transcription); DeliveryManagerServlet?dps_pid=FL<n>&dps_func=stream returns
|
|
45
|
+
the delivered file (application/pdf for the sample checked). The session
|
|
46
|
+
cookie jar is kept for the whole resolution.
|
|
47
|
+
|
|
48
|
+
Every network response is cached on disk (see get_cache_root); pass the
|
|
49
|
+
global `--refresh` (or a command's own `--refresh`) to refetch.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
import hashlib
|
|
55
|
+
import html as _html
|
|
56
|
+
import json
|
|
57
|
+
import os
|
|
58
|
+
import re
|
|
59
|
+
import sys
|
|
60
|
+
import time
|
|
61
|
+
from contextlib import contextmanager
|
|
62
|
+
from pathlib import Path
|
|
63
|
+
from typing import Any, Iterator
|
|
64
|
+
from urllib.parse import quote, unquote, urlencode, urlsplit
|
|
65
|
+
|
|
66
|
+
import click
|
|
67
|
+
import httpx
|
|
68
|
+
|
|
69
|
+
CHANCERY_BASE = "https://old.lva.virginia.gov/chancery"
|
|
70
|
+
CHANCERY_SEARCH = CHANCERY_BASE + "/default.asp"
|
|
71
|
+
CHANCERY_DETAIL = CHANCERY_BASE + "/case_detail.asp"
|
|
72
|
+
CHANCERY_IMAGES = CHANCERY_BASE + "/case_images.asp"
|
|
73
|
+
CHANCERY_ZIP = CHANCERY_BASE + "/zip/download.php"
|
|
74
|
+
CHANCERY_AVAILABLE = CHANCERY_BASE + "/available.asp"
|
|
75
|
+
PRIMO_BASE = "https://lva.primo.exlibrisgroup.com"
|
|
76
|
+
PRIMO_PNXS = PRIMO_BASE + "/primaws/rest/pub/pnxs"
|
|
77
|
+
PRIMO_VID = "01LVA_INST:01LVA"
|
|
78
|
+
USER_AGENT = (
|
|
79
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
|
80
|
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
|
81
|
+
)
|
|
82
|
+
MATCH_OPS = ("Exact", "Starts", "Includes")
|
|
83
|
+
CATALOG_FIELDS = ("any", "title", "creator")
|
|
84
|
+
LVA_IMAGE_HOST = "image.lva.virginia.gov"
|
|
85
|
+
LVA_IMAGE_BASE = "https://" + LVA_IMAGE_HOST
|
|
86
|
+
DUNMORE_CGI = LVA_IMAGE_BASE + "/cgi-bin/GetDW.pl"
|
|
87
|
+
IMAGE_SUFFIXES = (".tif", ".tiff", ".jpg", ".jpeg", ".png", ".gif")
|
|
88
|
+
ROSETTA_HOST = "rosetta.virginiamemory.com"
|
|
89
|
+
ROSETTA_BASE = "https://" + ROSETTA_HOST
|
|
90
|
+
ROSETTA_DELIVERY = ROSETTA_BASE + "/delivery/DeliveryManagerServlet"
|
|
91
|
+
ROSETTA_VIEWER = ROSETTA_BASE + "/view/action/ieViewer.do"
|
|
92
|
+
DEFAULT_TTL_HOURS = 168.0
|
|
93
|
+
CACHE_ENV = "KINLOOM_VA_ARCHIVES_CACHE_DIR"
|
|
94
|
+
TTL_ENV = "KINLOOM_VA_ARCHIVES_TTL_HOURS"
|
|
95
|
+
|
|
96
|
+
# Per-invocation state: the group-level --refresh resets it, a command-level
|
|
97
|
+
# --refresh can only turn it on.
|
|
98
|
+
_STATE: dict[str, bool] = {"refresh": False}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
# Disk cache (atomic temp-file + rename writes, fcntl.flock per entry)
|
|
103
|
+
# ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
def get_cache_root() -> Path:
|
|
106
|
+
override = os.environ.get(CACHE_ENV)
|
|
107
|
+
if override:
|
|
108
|
+
return Path(override).expanduser()
|
|
109
|
+
xdg = os.environ.get("XDG_CACHE_HOME")
|
|
110
|
+
base = Path(xdg).expanduser() if xdg else Path.home() / ".cache"
|
|
111
|
+
return base / "kinloom-va-archives"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def resolve_ttl_hours() -> float:
|
|
115
|
+
raw = os.environ.get(TTL_ENV)
|
|
116
|
+
if raw is not None and raw.strip():
|
|
117
|
+
try:
|
|
118
|
+
val = float(raw.strip())
|
|
119
|
+
except ValueError as exc:
|
|
120
|
+
raise click.BadParameter(f"Invalid {TTL_ENV} value: {raw!r}.") from exc
|
|
121
|
+
if val < 0 or val != val:
|
|
122
|
+
raise click.BadParameter(f"Invalid {TTL_ENV} value: {raw!r} (must be >= 0).")
|
|
123
|
+
return val
|
|
124
|
+
return DEFAULT_TTL_HOURS
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@contextmanager
|
|
128
|
+
def file_lock(lock_path: Path) -> Iterator[None]:
|
|
129
|
+
"""Advisory exclusive lock (POSIX flock); no-op where fcntl is missing."""
|
|
130
|
+
try:
|
|
131
|
+
import fcntl
|
|
132
|
+
except ImportError:
|
|
133
|
+
yield
|
|
134
|
+
return
|
|
135
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
with open(lock_path, "a+b") as fh:
|
|
137
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
|
|
138
|
+
try:
|
|
139
|
+
yield
|
|
140
|
+
finally:
|
|
141
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _tmp_sibling(dest: Path) -> Path:
|
|
145
|
+
return dest.with_name(f".{dest.name}.{os.getpid()}.{time.time_ns()}.tmp")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def atomic_write_bytes(dest: Path, data: bytes) -> None:
|
|
149
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
150
|
+
tmp = _tmp_sibling(dest)
|
|
151
|
+
try:
|
|
152
|
+
tmp.write_bytes(data)
|
|
153
|
+
os.replace(tmp, dest)
|
|
154
|
+
except BaseException:
|
|
155
|
+
tmp.unlink(missing_ok=True)
|
|
156
|
+
raise
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def atomic_write_json(dest: Path, payload: Any) -> None:
|
|
160
|
+
atomic_write_bytes(dest, json.dumps(payload, ensure_ascii=False, indent=1).encode("utf-8"))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def read_json_if_valid(path: Path) -> dict | None:
|
|
164
|
+
if not path.is_file():
|
|
165
|
+
return None
|
|
166
|
+
try:
|
|
167
|
+
parsed = json.loads(path.read_text(encoding="utf-8"))
|
|
168
|
+
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
169
|
+
return None
|
|
170
|
+
return parsed if isinstance(parsed, dict) else None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _meta_path(cache_path: Path) -> Path:
|
|
174
|
+
return cache_path.with_name(cache_path.name + ".meta.json")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _host_ok(url: httpx.URL | str, allowed_hosts: tuple[str, ...] | None) -> bool:
|
|
178
|
+
if not allowed_hosts:
|
|
179
|
+
return True
|
|
180
|
+
u = httpx.URL(str(url))
|
|
181
|
+
return u.scheme == "https" and u.host in allowed_hosts
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _cache_valid(cache_path: Path, ttl_hours: float | None) -> dict | None:
|
|
185
|
+
meta = read_json_if_valid(_meta_path(cache_path))
|
|
186
|
+
if meta is None or not cache_path.is_file():
|
|
187
|
+
return None
|
|
188
|
+
if ttl_hours is not None:
|
|
189
|
+
cached_at = meta.get("cached_at")
|
|
190
|
+
if not isinstance(cached_at, (int, float)) or time.time() - cached_at > ttl_hours * 3600:
|
|
191
|
+
return None
|
|
192
|
+
return meta
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def cached_fetch(
|
|
196
|
+
c: httpx.Client,
|
|
197
|
+
url: str,
|
|
198
|
+
cache_path: Path,
|
|
199
|
+
*,
|
|
200
|
+
method: str = "GET",
|
|
201
|
+
params: dict | None = None,
|
|
202
|
+
data: dict | None = None,
|
|
203
|
+
ttl_hours: float | None = None,
|
|
204
|
+
allowed_hosts: tuple[str, ...] | None = None,
|
|
205
|
+
refresh: bool | None = None,
|
|
206
|
+
) -> tuple[Path, dict]:
|
|
207
|
+
"""Fetch url into cache_path (streamed, atomic) unless a fresh copy exists.
|
|
208
|
+
|
|
209
|
+
ttl_hours=None means the entry never expires (immutable scans/files).
|
|
210
|
+
allowed_hosts pins the final (post-redirect) https host.
|
|
211
|
+
"""
|
|
212
|
+
refresh = _STATE["refresh"] if refresh is None else refresh
|
|
213
|
+
if not refresh:
|
|
214
|
+
meta = _cache_valid(cache_path, ttl_hours)
|
|
215
|
+
if meta is not None:
|
|
216
|
+
return cache_path, meta
|
|
217
|
+
lock = cache_path.parent / f".{cache_path.name}.lock"
|
|
218
|
+
with file_lock(lock):
|
|
219
|
+
if not refresh:
|
|
220
|
+
meta = _cache_valid(cache_path, ttl_hours)
|
|
221
|
+
if meta is not None:
|
|
222
|
+
return cache_path, meta
|
|
223
|
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
|
224
|
+
tmp = _tmp_sibling(cache_path)
|
|
225
|
+
try:
|
|
226
|
+
with c.stream(method, url, params=params, data=data) as r:
|
|
227
|
+
r.raise_for_status()
|
|
228
|
+
if not _host_ok(r.url, allowed_hosts):
|
|
229
|
+
raise click.ClickException(f"Refusing redirect outside {allowed_hosts}: {r.url}")
|
|
230
|
+
with open(tmp, "wb") as fh:
|
|
231
|
+
for chunk in r.iter_bytes():
|
|
232
|
+
fh.write(chunk)
|
|
233
|
+
meta = {
|
|
234
|
+
"url": str(r.url),
|
|
235
|
+
"content_type": r.headers.get("content-type", ""),
|
|
236
|
+
"cached_at": time.time(),
|
|
237
|
+
"size": tmp.stat().st_size,
|
|
238
|
+
}
|
|
239
|
+
os.replace(tmp, cache_path)
|
|
240
|
+
except BaseException:
|
|
241
|
+
tmp.unlink(missing_ok=True)
|
|
242
|
+
raise
|
|
243
|
+
atomic_write_json(_meta_path(cache_path), meta)
|
|
244
|
+
return cache_path, meta
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _request_key(method: str, url: str, params: dict | None, data: dict | None) -> str:
|
|
248
|
+
canon = json.dumps(
|
|
249
|
+
{"m": method.upper(), "u": url, "p": params or {}, "d": data or {}},
|
|
250
|
+
sort_keys=True, separators=(",", ":"), ensure_ascii=False,
|
|
251
|
+
)
|
|
252
|
+
return hashlib.sha256(canon.encode("utf-8")).hexdigest()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def fetch_text(c: httpx.Client, url: str, *, method: str = "GET", params: dict | None = None,
|
|
256
|
+
data: dict | None = None) -> str:
|
|
257
|
+
"""Cached HTML/JSON GET/POST (TTL from $KINLOOM_VA_ARCHIVES_TTL_HOURS, default 168h)."""
|
|
258
|
+
key = _request_key(method, url, params, data)
|
|
259
|
+
path, meta = cached_fetch(
|
|
260
|
+
c, url, get_cache_root() / "http" / f"{key}.body",
|
|
261
|
+
method=method, params=params, data=data, ttl_hours=resolve_ttl_hours(),
|
|
262
|
+
)
|
|
263
|
+
return httpx.Response(200, headers={"content-type": meta.get("content_type", "")},
|
|
264
|
+
content=path.read_bytes()).text
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def fetch_file(c: httpx.Client, url: str, *, allowed_hosts: tuple[str, ...] | None = None) -> Path:
|
|
268
|
+
"""Cached immutable binary (PDF/ZIP/TIFF), keyed by URL. Returns cache path."""
|
|
269
|
+
key = hashlib.sha256(url.encode("utf-8")).hexdigest()
|
|
270
|
+
suffix = Path(urlsplit(url).path).suffix.lower()
|
|
271
|
+
if not re.fullmatch(r"\.[a-z0-9]{1,5}", suffix):
|
|
272
|
+
suffix = ".bin"
|
|
273
|
+
path, _ = cached_fetch(c, url, get_cache_root() / "files" / f"{key}{suffix}",
|
|
274
|
+
allowed_hosts=allowed_hosts)
|
|
275
|
+
return path
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def copy_atomic(src: Path, dest: Path) -> None:
|
|
279
|
+
atomic_write_bytes(dest, src.read_bytes())
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _refresh_callback(ctx: click.Context, _param: click.Parameter, value: bool) -> bool:
|
|
283
|
+
if value:
|
|
284
|
+
_STATE["refresh"] = True
|
|
285
|
+
return value
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
refresh_option = click.option(
|
|
289
|
+
"--refresh", is_flag=True, expose_value=False, callback=_refresh_callback,
|
|
290
|
+
help="Bypass the disk cache for this command and refetch.",
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
# ---------------------------------------------------------------------------
|
|
295
|
+
# Library of Virginia image server + Rosetta validation helpers
|
|
296
|
+
# ---------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
_SAFE_PATH = re.compile(r"/[A-Za-z0-9._~+\-/]+")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def normalize_lva_image_url(raw: str) -> str:
|
|
302
|
+
"""Validate an image.lva.virginia.gov image path or https URL; return the https URL.
|
|
303
|
+
|
|
304
|
+
Accepts 'https://image.lva.virginia.gov/<path>', '/<path>' or '<path>'.
|
|
305
|
+
Rejects other schemes/hosts, credentials, ports, queries, fragments,
|
|
306
|
+
'.'/'..' segments (raw or percent-encoded), backslashes, and non-image suffixes.
|
|
307
|
+
"""
|
|
308
|
+
if not isinstance(raw, str):
|
|
309
|
+
raise ValueError("image path must be a string")
|
|
310
|
+
text = raw.strip()
|
|
311
|
+
if not text or any(ch in text for ch in ("\x00", "\\", "\r", "\n", "\t", " ")):
|
|
312
|
+
raise ValueError(f"Invalid LVA image path: {raw!r}")
|
|
313
|
+
if "?" in text or "#" in text:
|
|
314
|
+
raise ValueError(f"Query strings/fragments are not allowed: {raw!r}")
|
|
315
|
+
if text.startswith("//"):
|
|
316
|
+
raise ValueError(f"Scheme-relative URLs are not allowed: {raw!r}")
|
|
317
|
+
if re.match(r"^[A-Za-z][A-Za-z0-9+.\-]*:", text):
|
|
318
|
+
parts = urlsplit(text)
|
|
319
|
+
if parts.scheme.lower() != "https":
|
|
320
|
+
raise ValueError(f"Only https URLs are allowed (got {parts.scheme!r}): {raw!r}")
|
|
321
|
+
if parts.username or parts.password or parts.port not in (None, 443):
|
|
322
|
+
raise ValueError(f"Credentials/ports are not allowed: {raw!r}")
|
|
323
|
+
if (parts.hostname or "").lower() != LVA_IMAGE_HOST:
|
|
324
|
+
raise ValueError(f"Only {LVA_IMAGE_HOST} is allowed: {raw!r}")
|
|
325
|
+
path = parts.path
|
|
326
|
+
else:
|
|
327
|
+
path = text if text.startswith("/") else "/" + text
|
|
328
|
+
decoded = unquote(path)
|
|
329
|
+
if "%" in decoded or decoded != unquote(decoded):
|
|
330
|
+
raise ValueError(f"Double/odd percent-encoding is not allowed: {raw!r}")
|
|
331
|
+
if not _SAFE_PATH.fullmatch(decoded):
|
|
332
|
+
raise ValueError(f"Unsafe characters in LVA image path: {raw!r}")
|
|
333
|
+
segments = decoded.split("/")[1:]
|
|
334
|
+
if any(seg in ("", ".", "..") for seg in segments):
|
|
335
|
+
raise ValueError(f"Empty, '.' or '..' path segments are not allowed: {raw!r}")
|
|
336
|
+
if not decoded.lower().endswith(IMAGE_SUFFIXES):
|
|
337
|
+
raise ValueError(f"Not an image path (expected {', '.join(IMAGE_SUFFIXES)}): {raw!r}")
|
|
338
|
+
return LVA_IMAGE_BASE + decoded
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def validate_ie_id(raw: str) -> str:
|
|
342
|
+
text = (raw or "").strip()
|
|
343
|
+
if not re.fullmatch(r"IE\d{1,12}", text):
|
|
344
|
+
raise click.BadParameter(f"Invalid Rosetta IE id (expected IE<digits>): {raw!r}")
|
|
345
|
+
return text
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def validate_fl_id(raw: str) -> str:
|
|
349
|
+
text = (raw or "").strip()
|
|
350
|
+
if not re.fullmatch(r"FL\d{1,12}", text):
|
|
351
|
+
raise click.BadParameter(f"Invalid Rosetta file id (expected FL<digits>): {raw!r}")
|
|
352
|
+
return text
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def save_image(src: Path, out: Path) -> str:
|
|
356
|
+
"""Write cached image bytes to out. TIFF->JPEG when out is .jpg/.jpeg and Pillow exists.
|
|
357
|
+
|
|
358
|
+
Returns 'jpeg' or 'raw'. Without Pillow a .jpg request writes the raw bytes
|
|
359
|
+
next to it with a .tif suffix instead of mislabelling TIFF data as JPEG.
|
|
360
|
+
"""
|
|
361
|
+
if out.suffix.lower() in (".jpg", ".jpeg"):
|
|
362
|
+
try:
|
|
363
|
+
from PIL import Image # type: ignore[import-not-found]
|
|
364
|
+
except ImportError:
|
|
365
|
+
alt = out.with_suffix(".tif")
|
|
366
|
+
click.echo(f"Pillow not installed; saving raw TIFF to {alt} instead of {out}", err=True)
|
|
367
|
+
copy_atomic(src, alt)
|
|
368
|
+
return "raw:" + str(alt)
|
|
369
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
370
|
+
tmp = _tmp_sibling(out)
|
|
371
|
+
try:
|
|
372
|
+
with Image.open(src) as im:
|
|
373
|
+
mode = "L" if im.mode in ("1", "L", "I;16", "I") else "RGB"
|
|
374
|
+
im.convert(mode).save(tmp, format="JPEG", quality=90)
|
|
375
|
+
os.replace(tmp, out)
|
|
376
|
+
except BaseException:
|
|
377
|
+
tmp.unlink(missing_ok=True)
|
|
378
|
+
raise
|
|
379
|
+
return "jpeg"
|
|
380
|
+
copy_atomic(src, out)
|
|
381
|
+
return "raw"
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def parse_dunmore_drawer(page: str) -> dict:
|
|
385
|
+
"""Parse a Dunmore's War /cgi-bin/drawer page into page TIFF links."""
|
|
386
|
+
title_m = re.search(r"Dunmore's War\s*-\s*Page\s*(\d+)", page, re.I)
|
|
387
|
+
current = int(title_m.group(1)) if title_m else None
|
|
388
|
+
images = []
|
|
389
|
+
for m in re.finditer(r'<a href="(/Microfilm/[^"]+)"\s*>(.*?)</a>', page, re.S | re.I):
|
|
390
|
+
try:
|
|
391
|
+
url = normalize_lva_image_url(_html.unescape(m.group(1)))
|
|
392
|
+
except ValueError:
|
|
393
|
+
continue
|
|
394
|
+
label_m = re.search(r"Page\s*(\d+)", _clean(m.group(2)))
|
|
395
|
+
is_current = label_m is None
|
|
396
|
+
num = int(label_m.group(1)) if label_m else current
|
|
397
|
+
images.append({"page": num, "url": url, "current": is_current})
|
|
398
|
+
return {"current_page": current, "images": images}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def parse_rosetta_delivery(page: str) -> dict:
|
|
402
|
+
"""Find the ieViewer iframe URL and dps_dvs session token on a delivery page."""
|
|
403
|
+
viewer = None
|
|
404
|
+
for m in re.finditer(r'src="([^"]*ieViewer\.do[^"]*)"', page, re.I):
|
|
405
|
+
viewer = _html.unescape(m.group(1))
|
|
406
|
+
break
|
|
407
|
+
dvs_m = re.search(r"dps_dvs=([0-9]+~[0-9]+)", page)
|
|
408
|
+
return {"viewer_url": viewer, "dps_dvs": dvs_m.group(1) if dvs_m else None}
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def parse_rosetta_viewer(page: str) -> dict:
|
|
412
|
+
"""List FL file pids (with METS titles) and the initially selected one."""
|
|
413
|
+
files: list[dict] = []
|
|
414
|
+
seen: set[str] = set()
|
|
415
|
+
for m in re.finditer(r"<item id='(FL\d+)' title='([^']*)'", page):
|
|
416
|
+
if m.group(1) not in seen:
|
|
417
|
+
seen.add(m.group(1))
|
|
418
|
+
files.append({"fl": m.group(1), "title": _html.unescape(m.group(2))})
|
|
419
|
+
for m in re.finditer(r"JSONObject\s*=\s*'(\{[^']*\})'", page):
|
|
420
|
+
try:
|
|
421
|
+
obj = json.loads(m.group(1))
|
|
422
|
+
except json.JSONDecodeError:
|
|
423
|
+
continue
|
|
424
|
+
for val in obj.values():
|
|
425
|
+
for fl in re.findall(r"FL\d+", str(val)):
|
|
426
|
+
if fl not in seen:
|
|
427
|
+
seen.add(fl)
|
|
428
|
+
files.append({"fl": fl, "title": ""})
|
|
429
|
+
init_m = re.search(r'initialSelect\s*=\s*"(FL\d+)"', page)
|
|
430
|
+
initial = init_m.group(1) if init_m else (files[0]["fl"] if files else None)
|
|
431
|
+
return {"files": files, "initial": initial}
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
_CT_EXT = {
|
|
435
|
+
"application/pdf": ".pdf", "image/jpeg": ".jpg", "image/jp2": ".jp2", "image/tiff": ".tif",
|
|
436
|
+
"image/png": ".png", "image/gif": ".gif", "text/plain": ".txt", "application/zip": ".zip",
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _ext_for(content_type: str) -> str:
|
|
441
|
+
return _CT_EXT.get(content_type.split(";")[0].strip().lower(), ".bin")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _client() -> httpx.Client:
|
|
445
|
+
return httpx.Client(headers={"User-Agent": USER_AGENT}, timeout=60.0, follow_redirects=True)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _clean(text: str) -> str:
|
|
449
|
+
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
|
|
450
|
+
text = re.sub(r"<[^>]+>", " ", text)
|
|
451
|
+
text = _html.unescape(re.sub(r"[ \t]+", " ", text))
|
|
452
|
+
return text.strip()
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _names(cell: str) -> list[str]:
|
|
456
|
+
return [line.strip() for line in _clean(cell).splitlines() if line.strip()]
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def parse_search_page(page: str) -> dict:
|
|
460
|
+
"""Parse a Chancery default.asp results page into records + paging info."""
|
|
461
|
+
total_m = re.search(r"Your search returned (\d+) record\(s\). You are now viewing records (\d+) through (\d+)", page)
|
|
462
|
+
total = int(total_m.group(1)) if total_m else 0
|
|
463
|
+
first = int(total_m.group(2)) if total_m else 0
|
|
464
|
+
last = int(total_m.group(3)) if total_m else 0
|
|
465
|
+
pat = re.compile(
|
|
466
|
+
r"<strong>Index Number:</strong>\s*([^<]+?)\s*</span>\s*"
|
|
467
|
+
r"<a href=\"case_detail\.asp\?CFN=([0-9\-]+)\"[^>]*>.*?"
|
|
468
|
+
r"<strong>Locality:</strong>\s*([^<]+?)\s*</td>.*?"
|
|
469
|
+
r"<td valign=\"top\">\s*(.*?)\s*</td>\s*<td valign=\"top\">\s*(.*?)\s*</td>",
|
|
470
|
+
re.S | re.I,
|
|
471
|
+
)
|
|
472
|
+
records = []
|
|
473
|
+
for m in pat.finditer(page):
|
|
474
|
+
records.append({
|
|
475
|
+
"index_number": _html.unescape(m.group(1).strip()),
|
|
476
|
+
"cfn": m.group(2),
|
|
477
|
+
"locality": _html.unescape(m.group(3).strip()),
|
|
478
|
+
"plaintiffs": _names(m.group(4)),
|
|
479
|
+
"defendants": _names(m.group(5)),
|
|
480
|
+
"case_url": CHANCERY_DETAIL + "?CFN=" + m.group(2),
|
|
481
|
+
})
|
|
482
|
+
return {"total": total, "first": first, "last": last, "records": records}
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def parse_case_page(page: str) -> dict:
|
|
486
|
+
"""Parse a Chancery case_detail.asp page."""
|
|
487
|
+
def section(label: str) -> str:
|
|
488
|
+
m = re.search(r"<strong>" + re.escape(label) + r"</strong></td></tr>\s*<tr>\s*<td[^>]*>(.*?)</td>", page, re.S | re.I)
|
|
489
|
+
return _clean(m.group(1)) if m else ""
|
|
490
|
+
head = re.search(
|
|
491
|
+
r"<strong>Locality</strong></td><td[^>]*><strong>Index Number</strong></td><td[^>]*><strong>Original Case Number</strong></td></tr>\s*<tr>\s*<td[^>]*>([^<]*)</td>\s*<td[^>]*>([^<]*)</td>\s*<td[^>]*>([^<]*)</td>",
|
|
492
|
+
page, re.S | re.I)
|
|
493
|
+
parties = re.search(
|
|
494
|
+
r"<strong>Plaintiff\(s\)</strong></td><td[^>]*><strong>Defendant\(s\)</strong></td></tr>\s*<tr>\s*<td[^>]*>(.*?)</td>\s*<td[^>]*>(.*?)</td>",
|
|
495
|
+
page, re.S | re.I)
|
|
496
|
+
surnames = re.search(r"<strong>Surname\(s\)</strong></td></tr>\s*<tr><td[^>]*>(.*?)</td>", page, re.S | re.I)
|
|
497
|
+
plat = re.search(r"<strong>Plat\?</strong></td></tr>\s*<tr><td[^>]*>([^<]*)</td>\s*<td[^>]*>([^<]*)</td>", page, re.S | re.I)
|
|
498
|
+
fmt = section("Format")
|
|
499
|
+
wills = ""
|
|
500
|
+
wm = re.search(r"<strong>Wills</strong></td><td[^>]*>.*?Plat\?.*?</tr>\s*<tr><td[^>]*>(.*?)</td>", page, re.S | re.I)
|
|
501
|
+
if wm:
|
|
502
|
+
wills = _clean(wm.group(1))
|
|
503
|
+
return {
|
|
504
|
+
"locality": _html.unescape(head.group(1).strip()) if head else "",
|
|
505
|
+
"index_number": _html.unescape(head.group(2).strip()) if head else "",
|
|
506
|
+
"original_case_number": _html.unescape(head.group(3).strip()) if head else "",
|
|
507
|
+
"plaintiffs": _names(parties.group(1)) if parties else [],
|
|
508
|
+
"defendants": _names(parties.group(2)) if parties else [],
|
|
509
|
+
"surnames": _names(surnames.group(1)) if surnames else [],
|
|
510
|
+
"wills": wills,
|
|
511
|
+
"plat": _html.unescape(plat.group(2).strip()) if plat else "",
|
|
512
|
+
"format": fmt,
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def parse_images_page(page: str) -> dict:
|
|
517
|
+
"""Parse case_images.asp: myImages[N] PDF list + total page count."""
|
|
518
|
+
urls = re.findall(r'myImages\[\d+\]\s*=\s*"([^"]+)"', page)
|
|
519
|
+
urls = [u for u in urls if u]
|
|
520
|
+
total_m = re.search(r"of\s+(\d+)\s+prev", _clean(page))
|
|
521
|
+
total = int(total_m.group(1)) if total_m else len(urls)
|
|
522
|
+
zip_m = re.search(r'href="([^"]*download\.php\?cfn=[^"]*)"', page, re.I)
|
|
523
|
+
return {
|
|
524
|
+
"total_pages": total,
|
|
525
|
+
"page_pdfs": [CHANCERY_BASE.rsplit("/chancery", 1)[0] + u if u.startswith("/") else u for u in urls],
|
|
526
|
+
"zip_url": ("https://old.lva.virginia.gov" + _html.unescape(zip_m.group(1))) if zip_m else CHANCERY_ZIP + "?cfn=",
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def parse_localities_page(page: str) -> list[dict]:
|
|
531
|
+
"""Parse available.asp locality availability table."""
|
|
532
|
+
rows = []
|
|
533
|
+
for m in re.finditer(
|
|
534
|
+
r"<TR><TD>([^<]*)</td><TD>([^<]*)</td><TD>([^<]*)</td><TD>([^<]*)</td><TD>(.*?)</td></TR>",
|
|
535
|
+
page, re.S | re.I):
|
|
536
|
+
rows.append({
|
|
537
|
+
"locality": _html.unescape(m.group(1).replace(" ", " ").strip()),
|
|
538
|
+
"region": _html.unescape(m.group(2).replace(" ", " ").strip()),
|
|
539
|
+
"time_frame": _html.unescape(m.group(3).replace(" ", " ").strip()),
|
|
540
|
+
"viewing_status": _html.unescape(m.group(4).replace(" ", " ").strip()),
|
|
541
|
+
"notes": _clean(m.group(5)),
|
|
542
|
+
})
|
|
543
|
+
return rows
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def parse_page_spec(spec: str, total: int) -> list[int]:
|
|
547
|
+
"""1-based page slice like '1-5,10' or 'all' (NARA CLI convention)."""
|
|
548
|
+
if spec.strip().lower() == "all":
|
|
549
|
+
return list(range(1, total + 1))
|
|
550
|
+
out: list[int] = []
|
|
551
|
+
for part in spec.split(","):
|
|
552
|
+
part = part.strip()
|
|
553
|
+
if "-" in part:
|
|
554
|
+
a, b = part.split("-", 1)
|
|
555
|
+
out.extend(range(int(a), int(b) + 1))
|
|
556
|
+
elif part:
|
|
557
|
+
out.append(int(part))
|
|
558
|
+
return sorted(set(n for n in out if 1 <= n <= total))
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _pnxs_record(doc: dict) -> dict:
|
|
562
|
+
pnx = doc.get("pnx", {})
|
|
563
|
+
disp = pnx.get("display", {})
|
|
564
|
+
control = pnx.get("control", {})
|
|
565
|
+
recordid = (control.get("recordid") or [""])[0]
|
|
566
|
+
def first(key: str) -> str:
|
|
567
|
+
vals = disp.get(key) or []
|
|
568
|
+
return vals[0].strip() if vals else ""
|
|
569
|
+
return {
|
|
570
|
+
"recordid": recordid,
|
|
571
|
+
"title": first("title"),
|
|
572
|
+
"creator": first("creator"),
|
|
573
|
+
"date": first("creationdate"),
|
|
574
|
+
"type": first("type"),
|
|
575
|
+
"source": first("source"),
|
|
576
|
+
"record_url": (
|
|
577
|
+
PRIMO_BASE + "/discovery/fulldisplay?docid=" + recordid
|
|
578
|
+
+ "&context=L&vid=" + quote(PRIMO_VID, safe="")
|
|
579
|
+
+ "&lang=en&search_scope=MyInstitution"
|
|
580
|
+
) if recordid else "",
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _fmt_record_text(rec: dict) -> str:
|
|
585
|
+
lines = [f"{rec['cfn']} {rec['locality']} index {rec['index_number']}"]
|
|
586
|
+
if rec["plaintiffs"]:
|
|
587
|
+
lines.append(" P: " + "; ".join(rec["plaintiffs"]))
|
|
588
|
+
if rec["defendants"]:
|
|
589
|
+
lines.append(" D: " + "; ".join(rec["defendants"]))
|
|
590
|
+
lines.append(" " + rec["case_url"])
|
|
591
|
+
return "\n".join(lines)
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
|
|
595
|
+
@click.option("--refresh", is_flag=True, help="Bypass the disk cache for every request in this run.")
|
|
596
|
+
def cli(refresh: bool) -> None:
|
|
597
|
+
"""Search the Library of Virginia: Chancery Records Index, Primo catalog, image server, Rosetta.
|
|
598
|
+
|
|
599
|
+
Responses are cached under $KINLOOM_VA_ARCHIVES_CACHE_DIR
|
|
600
|
+
(default $XDG_CACHE_HOME/kinloom-va-archives or ~/.cache/kinloom-va-archives).
|
|
601
|
+
"""
|
|
602
|
+
_STATE["refresh"] = refresh
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
@cli.group("chancery")
|
|
606
|
+
def chancery() -> None:
|
|
607
|
+
"""Chancery Records Index (old.lva.virginia.gov/chancery)."""
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
@chancery.command("search")
|
|
611
|
+
@click.argument("surnames", nargs=-1, required=True)
|
|
612
|
+
@click.option("--locality", default="All", show_default=True,
|
|
613
|
+
help="County/city, e.g. 'ALBEMARLE CO'. Default All. Use `chancery localities` to list values.")
|
|
614
|
+
@click.option("--match", type=click.Choice(["Exact", "Starts", "Includes"], case_sensitive=False), default="Starts", show_default=True,
|
|
615
|
+
help="How the surname match works (form values Exact/Starts/Includes).")
|
|
616
|
+
@click.option("--surname2", default=None, help="Second surname (ANDed by the index form).")
|
|
617
|
+
@click.option("--plaintiff-last", default=None, help="Plaintiff last name.")
|
|
618
|
+
@click.option("--plaintiff-first", default=None, help="Plaintiff first name.")
|
|
619
|
+
@click.option("--defendant-last", default=None, help="Defendant last name.")
|
|
620
|
+
@click.option("--defendant-first", default=None, help="Defendant first name.")
|
|
621
|
+
@click.option("--year-from", default=None, help="First year of case (strDate1).")
|
|
622
|
+
@click.option("--year-to", default=None, help="Last year of case (strDate2).")
|
|
623
|
+
@click.option("--index-number", default=None, help="Index number, e.g. YYYY-NNN (txtIndexNum).")
|
|
624
|
+
@click.option("--local-case-number", default=None, help="Local case file number (txtLclCFN).")
|
|
625
|
+
@click.option("--enslaved", is_flag=True, help="Only cases referencing enslaved persons.")
|
|
626
|
+
@click.option("--free", is_flag=True, help="Only cases referencing free persons.")
|
|
627
|
+
@click.option("--plats", is_flag=True, help="Only cases with plats available.")
|
|
628
|
+
@click.option("--pages", default="1", show_default=True, help="Result pages to fetch: '1', '1-3', '1,3', or 'all' (20 records per page).")
|
|
629
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
630
|
+
@refresh_option
|
|
631
|
+
def cmd_chancery_search(surnames, locality, match, surname2, plaintiff_last, plaintiff_first,
|
|
632
|
+
defendant_last, defendant_first, year_from, year_to, index_number,
|
|
633
|
+
local_case_number, enslaved, free, plats, pages, as_json):
|
|
634
|
+
"""Search the Chancery Records Index by surname (more surnames = OR)."""
|
|
635
|
+
match = match.capitalize()
|
|
636
|
+
all_records: list[dict] = []
|
|
637
|
+
total = 0
|
|
638
|
+
with _client() as c:
|
|
639
|
+
for surname in surnames:
|
|
640
|
+
form: dict[str, str] = {
|
|
641
|
+
"surname1": surname, "sn1select": match,
|
|
642
|
+
"plnlstName": plaintiff_last or "", "plselect": match,
|
|
643
|
+
"plnfrstName": plaintiff_first or "", "pfselect": match,
|
|
644
|
+
"deflstName": defendant_last or "", "dlselect": match,
|
|
645
|
+
"deffrstName": defendant_first or "", "dfselect": match,
|
|
646
|
+
"strDate1": year_from or "", "strDate2": year_to or "",
|
|
647
|
+
"txtIndexNum": index_number or "", "txtLclCFN": local_case_number or "",
|
|
648
|
+
"Submit": "Search",
|
|
649
|
+
}
|
|
650
|
+
if surname2:
|
|
651
|
+
form["surname2"] = surname2
|
|
652
|
+
form["sn2select"] = match
|
|
653
|
+
if enslaved:
|
|
654
|
+
form["chkEnslaved"] = "on"
|
|
655
|
+
if free:
|
|
656
|
+
form["chkFree"] = "on"
|
|
657
|
+
if plats:
|
|
658
|
+
form["chkPlat"] = "on"
|
|
659
|
+
first_page = 1
|
|
660
|
+
form["LOC"] = locality
|
|
661
|
+
parsed = parse_search_page(fetch_text(c, CHANCERY_SEARCH, method="POST", data=form))
|
|
662
|
+
total += parsed["total"]
|
|
663
|
+
if pages.strip().lower() == "all":
|
|
664
|
+
wanted = list(range(1, (total + 19) // 20 + 1)) or [1]
|
|
665
|
+
else:
|
|
666
|
+
wanted = parse_page_spec(pages, max((total + 19) // 20, 1))
|
|
667
|
+
for pn in wanted:
|
|
668
|
+
if pn == first_page:
|
|
669
|
+
all_records.extend(parsed["records"])
|
|
670
|
+
continue
|
|
671
|
+
form2 = dict(form)
|
|
672
|
+
form2["intPage"] = str(pn)
|
|
673
|
+
all_records.extend(parse_search_page(
|
|
674
|
+
fetch_text(c, CHANCERY_SEARCH, method="POST", data=form2))["records"])
|
|
675
|
+
if as_json:
|
|
676
|
+
click.echo(json.dumps({"total": total, "returned": len(all_records), "records": all_records}, indent=1))
|
|
677
|
+
return
|
|
678
|
+
click.echo(f"{total} record(s); showing {len(all_records)}:")
|
|
679
|
+
for rec in all_records:
|
|
680
|
+
click.echo(_fmt_record_text(rec))
|
|
681
|
+
click.echo()
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
@chancery.command("case")
|
|
685
|
+
@click.argument("cfn")
|
|
686
|
+
@click.option("--images", is_flag=True, help="Also list the scanned page PDFs and ZIP URL.")
|
|
687
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
688
|
+
@refresh_option
|
|
689
|
+
def cmd_chancery_case(cfn: str, images: bool, as_json: bool) -> None:
|
|
690
|
+
"""Show one chancery cause by CFN (locality-year-number)."""
|
|
691
|
+
with _client() as c:
|
|
692
|
+
detail = parse_case_page(fetch_text(c, CHANCERY_DETAIL, params={"CFN": cfn}))
|
|
693
|
+
detail["cfn"] = cfn
|
|
694
|
+
detail["case_url"] = CHANCERY_DETAIL + "?CFN=" + cfn
|
|
695
|
+
if images:
|
|
696
|
+
detail["images"] = parse_images_page(fetch_text(c, CHANCERY_IMAGES, params={"CFN": cfn}))
|
|
697
|
+
if as_json:
|
|
698
|
+
click.echo(json.dumps(detail, indent=1))
|
|
699
|
+
return
|
|
700
|
+
click.echo(f"{cfn} {detail['locality']} index {detail['index_number']} (original case no. {detail['original_case_number'] or 'n/a'})")
|
|
701
|
+
click.echo("Plaintiff(s): " + ("; ".join(detail["plaintiffs"]) or "n/a"))
|
|
702
|
+
click.echo("Defendant(s): " + ("; ".join(detail["defendants"]) or "n/a"))
|
|
703
|
+
click.echo("Surname(s): " + (", ".join(detail["surnames"]) or "n/a"))
|
|
704
|
+
click.echo(f"Wills: {detail['wills'] or 'n/a'} Plat: {detail['plat'] or 'n/a'} Format: {detail['format'] or 'n/a'}")
|
|
705
|
+
click.echo(detail["case_url"])
|
|
706
|
+
if images:
|
|
707
|
+
imgs = detail["images"]
|
|
708
|
+
click.echo(f"Images: {imgs['total_pages']} page(s)")
|
|
709
|
+
for u in imgs["page_pdfs"]:
|
|
710
|
+
click.echo(" " + u)
|
|
711
|
+
click.echo("ZIP: " + imgs["zip_url"])
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
@chancery.command("download")
|
|
715
|
+
@click.argument("cfn")
|
|
716
|
+
@click.option("--out", "out_dir", default=None, type=click.Path(path_type=Path),
|
|
717
|
+
help="Output directory (default: ./va-chancery-<cfn>).")
|
|
718
|
+
@click.option("--pages", default="all", show_default=True, help="1-based page selection, e.g. '1-5' or 'all'.")
|
|
719
|
+
@click.option("--zip", "as_zip", is_flag=True, help="Download the whole-case ZIP instead of page PDFs.")
|
|
720
|
+
@click.option("--overwrite", is_flag=True, help="Overwrite existing files.")
|
|
721
|
+
@refresh_option
|
|
722
|
+
def cmd_chancery_download(cfn: str, out_dir: Path | None, pages: str, as_zip: bool, overwrite: bool) -> None:
|
|
723
|
+
"""Download the scanned pages (or whole-case ZIP) for one chancery cause (disk-cached)."""
|
|
724
|
+
if not re.fullmatch(r"[0-9]+(?:-[0-9]+)*", cfn):
|
|
725
|
+
raise click.BadParameter(f"Invalid CFN (expected locality-year-number digits): {cfn!r}")
|
|
726
|
+
out_dir = out_dir or Path(f"va-chancery-{cfn}")
|
|
727
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
728
|
+
with _client() as c:
|
|
729
|
+
detail = parse_case_page(fetch_text(c, CHANCERY_DETAIL, params={"CFN": cfn}))
|
|
730
|
+
detail["cfn"] = cfn
|
|
731
|
+
detail["case_url"] = CHANCERY_DETAIL + "?CFN=" + cfn
|
|
732
|
+
imgs = None
|
|
733
|
+
if not as_zip:
|
|
734
|
+
imgs = parse_images_page(fetch_text(c, CHANCERY_IMAGES, params={"CFN": cfn}))
|
|
735
|
+
detail["images"] = imgs
|
|
736
|
+
(out_dir / "metadata.json").write_text(json.dumps(detail, indent=1), encoding="utf-8")
|
|
737
|
+
if as_zip:
|
|
738
|
+
zip_url = (imgs["zip_url"] if imgs else None) or (CHANCERY_ZIP + "?cfn=" + cfn)
|
|
739
|
+
dest = out_dir / f"{cfn}.zip"
|
|
740
|
+
if dest.exists() and not overwrite:
|
|
741
|
+
click.echo(f"exists, skipping: {dest}")
|
|
742
|
+
return
|
|
743
|
+
copy_atomic(fetch_file(c, zip_url), dest)
|
|
744
|
+
click.echo(f"saved {dest} ({dest.stat().st_size} bytes)")
|
|
745
|
+
return
|
|
746
|
+
assert imgs is not None
|
|
747
|
+
wanted = parse_page_spec(pages, imgs["total_pages"])
|
|
748
|
+
for n in wanted:
|
|
749
|
+
url = imgs["page_pdfs"][n - 1]
|
|
750
|
+
name = re.sub(r"[^A-Za-z0-9._-]+", "_", Path(urlsplit(url).path).name).lstrip(".") or f"{n:04d}.pdf"
|
|
751
|
+
dest = out_dir / name
|
|
752
|
+
if dest.exists() and not overwrite:
|
|
753
|
+
click.echo(f"exists, skipping: {dest.name}")
|
|
754
|
+
continue
|
|
755
|
+
copy_atomic(fetch_file(c, url), dest)
|
|
756
|
+
click.echo(f"saved {dest} ({dest.stat().st_size} bytes)")
|
|
757
|
+
click.echo(f"metadata: {out_dir / 'metadata.json'}")
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
@chancery.command("localities")
|
|
761
|
+
@click.option("--status", default=None, help="Filter by viewing status substring, e.g. Scanned.")
|
|
762
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
763
|
+
@refresh_option
|
|
764
|
+
def cmd_chancery_localities(status: str | None, as_json: bool) -> None:
|
|
765
|
+
"""List per-locality chancery coverage from available.asp."""
|
|
766
|
+
with _client() as c:
|
|
767
|
+
rows = parse_localities_page(fetch_text(c, CHANCERY_AVAILABLE))
|
|
768
|
+
if status:
|
|
769
|
+
rows = [r for r in rows if status.lower() in r["viewing_status"].lower()]
|
|
770
|
+
if as_json:
|
|
771
|
+
click.echo(json.dumps(rows, indent=1))
|
|
772
|
+
return
|
|
773
|
+
for r in rows:
|
|
774
|
+
click.echo(f"{r['locality']:20s} {r['region']:22s} {r['time_frame']:14s} {r['viewing_status']}")
|
|
775
|
+
click.echo(f"{len(rows)} localities")
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
@cli.command("catalog")
|
|
779
|
+
@click.argument("query")
|
|
780
|
+
@click.option("--field", type=click.Choice(list(CATALOG_FIELDS)), default="any", show_default=True,
|
|
781
|
+
help="PNXS search field (verified: any, title, creator).")
|
|
782
|
+
@click.option("--limit", default=10, show_default=True, type=int, help="Results per page (PNXS limit).")
|
|
783
|
+
@click.option("--offset", default=0, show_default=True, type=int, help="Result offset (PNXS offset).")
|
|
784
|
+
@click.option("--json", "as_json", is_flag=True, help="Output compact structured JSON.")
|
|
785
|
+
@refresh_option
|
|
786
|
+
def cmd_catalog(query: str, field: str, limit: int, offset: int, as_json: bool) -> None:
|
|
787
|
+
"""Search the Library of Virginia catalog via the public Primo PNXS API."""
|
|
788
|
+
params = {
|
|
789
|
+
"q": f"{field},contains,{query}",
|
|
790
|
+
"vid": PRIMO_VID, "scope": "MyInstitution", "lang": "en",
|
|
791
|
+
"limit": str(limit), "offset": str(offset),
|
|
792
|
+
}
|
|
793
|
+
with _client() as c:
|
|
794
|
+
data = json.loads(fetch_text(c, PRIMO_PNXS, params=params))
|
|
795
|
+
info = data.get("info", {})
|
|
796
|
+
records = [_pnxs_record(d) for d in data.get("docs", [])]
|
|
797
|
+
if as_json:
|
|
798
|
+
click.echo(json.dumps({"total": info.get("total"), "first": info.get("first"),
|
|
799
|
+
"last": info.get("last"), "records": records}, indent=1))
|
|
800
|
+
return
|
|
801
|
+
click.echo(f"{info.get('total')} result(s); showing {info.get('first')}-{info.get('last')}:")
|
|
802
|
+
for rec in records:
|
|
803
|
+
click.echo(f"{rec['title'] or '(no title)'}")
|
|
804
|
+
click.echo(f" {rec['creator'] or ''} {rec['date'] or ''} [{rec['type'] or ''}]".rstrip())
|
|
805
|
+
click.echo(f" {rec['record_url']}")
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
@cli.command("url")
|
|
809
|
+
@click.option("--chancery-case", "chancery_case", default=None, help="CFN (locality-year-number).")
|
|
810
|
+
@click.option("--catalog", "catalog_query", default=None, help="Catalog search term (Primo search URL).")
|
|
811
|
+
@click.option("--chronicle", is_flag=True, help="Virginia Chronicle home page (browser-only; Cloudflare blocks machine access).")
|
|
812
|
+
@click.option("--land", is_flag=True, help="Land Office patents/grants: libguide + LONN volume index.")
|
|
813
|
+
@click.option("--arvas", is_flag=True, help="ARVAS finding-aid search home (browser-only).")
|
|
814
|
+
@click.option("--chancery", is_flag=True, help="Chancery Records Index home page.")
|
|
815
|
+
def cmd_url(chancery_case, catalog_query, chronicle, land, arvas, chancery) -> None:
|
|
816
|
+
"""Print verified portal URLs (no search is run)."""
|
|
817
|
+
if chancery_case:
|
|
818
|
+
click.echo(CHANCERY_DETAIL + "?CFN=" + chancery_case)
|
|
819
|
+
if catalog_query:
|
|
820
|
+
click.echo(PRIMO_BASE + "/discovery/search?vid=" + quote(PRIMO_VID, safe="") +
|
|
821
|
+
"&query=any,contains," + quote(catalog_query) + "&lang=en")
|
|
822
|
+
if chancery:
|
|
823
|
+
click.echo("https://www.lva.virginia.gov/collections/chancery")
|
|
824
|
+
click.echo(CHANCERY_BASE + "/")
|
|
825
|
+
if chronicle:
|
|
826
|
+
click.echo("https://www.virginiachronicle.com/ (free; search in the browser -- Cloudflare blocks curl/headless Chromium, verified 2026-11-24)")
|
|
827
|
+
if land:
|
|
828
|
+
click.echo("https://lva-virginia.libguides.com/land-grants")
|
|
829
|
+
click.echo("https://image.lva.virginia.gov/LONN/LO.html (Virginia Land Office Patents and Grants Index, browse by volume)")
|
|
830
|
+
if arvas:
|
|
831
|
+
click.echo("https://arvasarchive.org/ (browser-only; plain HTTP returns an empty 202, verified 2026-11-24)")
|
|
832
|
+
if not any([chancery_case, catalog_query, chronicle, land, arvas, chancery]):
|
|
833
|
+
click.echo("https://www.lva.virginia.gov/collections")
|
|
834
|
+
click.echo("https://www.lva.virginia.gov/collections/digital-collections")
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _grant_tif(path_or_url: str, out: Path | None, as_json: bool) -> None:
|
|
838
|
+
try:
|
|
839
|
+
url = normalize_lva_image_url(path_or_url)
|
|
840
|
+
except ValueError as exc:
|
|
841
|
+
raise click.BadParameter(str(exc)) from exc
|
|
842
|
+
with _client() as c:
|
|
843
|
+
cached = fetch_file(c, url, allowed_hosts=(LVA_IMAGE_HOST,))
|
|
844
|
+
result: dict = {"url": url, "cache_path": str(cached), "bytes": cached.stat().st_size}
|
|
845
|
+
if out is not None:
|
|
846
|
+
mode = save_image(cached, out)
|
|
847
|
+
if mode.startswith("raw:"):
|
|
848
|
+
result.update(out=mode[4:], mode="raw")
|
|
849
|
+
else:
|
|
850
|
+
result.update(out=str(out), mode=mode)
|
|
851
|
+
if as_json:
|
|
852
|
+
click.echo(json.dumps(result, indent=1))
|
|
853
|
+
return
|
|
854
|
+
if out is not None:
|
|
855
|
+
click.echo(f"saved {result['out']} ({result['mode']}) from {url}")
|
|
856
|
+
else:
|
|
857
|
+
click.echo(f"cached {url} -> {cached} ({result['bytes']} bytes); pass --out FILE to save it")
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
_GRANT_TIF_HELP = (
|
|
861
|
+
"Fetch (and cache) one Library of Virginia image-server scan, e.g. a Land Office patent "
|
|
862
|
+
"/LONN/LO-3/372/372_0195.tif or a Dunmore's War /Microfilm/DW/... page. Accepts "
|
|
863
|
+
"https://image.lva.virginia.gov/<path> or a path on that host only. --out x.jpg converts "
|
|
864
|
+
"TIFF to JPEG when Pillow is available; any other suffix gets the raw bytes."
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
@cli.command("grant-tif", help=_GRANT_TIF_HELP)
|
|
869
|
+
@click.argument("path_or_url")
|
|
870
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Output file (.jpg/.jpeg converts; else raw).")
|
|
871
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
872
|
+
@refresh_option
|
|
873
|
+
def cmd_grant_tif(path_or_url: str, out: Path | None, as_json: bool) -> None:
|
|
874
|
+
_grant_tif(path_or_url, out, as_json)
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
@cli.command("lva-tif", help="Alias of grant-tif. " + _GRANT_TIF_HELP)
|
|
878
|
+
@click.argument("path_or_url")
|
|
879
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Output file (.jpg/.jpeg converts; else raw).")
|
|
880
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
881
|
+
@refresh_option
|
|
882
|
+
def cmd_lva_tif(path_or_url: str, out: Path | None, as_json: bool) -> None:
|
|
883
|
+
_grant_tif(path_or_url, out, as_json)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
@cli.command("dunmore")
|
|
887
|
+
@click.argument("drawer")
|
|
888
|
+
@click.argument("card")
|
|
889
|
+
@click.option("--page", "page_no", type=int, default=None, help="Page number to save (default: the card's own page).")
|
|
890
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Save the selected page image (.jpg converts; else raw TIFF).")
|
|
891
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
892
|
+
@refresh_option
|
|
893
|
+
def cmd_dunmore(drawer: str, card: str, page_no: int | None, out: Path | None, as_json: bool) -> None:
|
|
894
|
+
"""Resolve a Dunmore's War (1774) index card to its page TIFFs on image.lva.virginia.gov.
|
|
895
|
+
|
|
896
|
+
DRAWER and CARD come from the catalog's GetDW.pl links
|
|
897
|
+
(GetDW.pl?dir=<DRAWER>&card=<CARD> -> `dunmore <DRAWER> <CARD>`). Lists the
|
|
898
|
+
neighbouring page images; --out saves the card's page (or --page N).
|
|
899
|
+
"""
|
|
900
|
+
if not re.fullmatch(r"\d{1,5}/W\d{1,6}", drawer):
|
|
901
|
+
raise click.BadParameter(f"Invalid drawer (expected e.g. 0001/W0001): {drawer!r}")
|
|
902
|
+
if not re.fullmatch(r"\d{1,6}", card):
|
|
903
|
+
raise click.BadParameter(f"Invalid card number: {card!r}")
|
|
904
|
+
with _client() as c:
|
|
905
|
+
parsed = parse_dunmore_drawer(fetch_text(c, DUNMORE_CGI, params={"dir": drawer, "card": card}))
|
|
906
|
+
parsed.update(drawer=drawer, card=card, source_url=f"{DUNMORE_CGI}?dir={drawer}&card={card}")
|
|
907
|
+
if not parsed["images"]:
|
|
908
|
+
raise click.ClickException("No page images found on the Dunmore's War drawer page.")
|
|
909
|
+
chosen = None
|
|
910
|
+
if page_no is not None:
|
|
911
|
+
chosen = next((im for im in parsed["images"] if im["page"] == page_no), None)
|
|
912
|
+
if chosen is None:
|
|
913
|
+
raise click.ClickException(f"Page {page_no} is not listed for this card.")
|
|
914
|
+
else:
|
|
915
|
+
chosen = next((im for im in parsed["images"] if im["current"]), parsed["images"][0])
|
|
916
|
+
parsed["selected"] = chosen
|
|
917
|
+
if out is not None:
|
|
918
|
+
with _client() as c:
|
|
919
|
+
cached = fetch_file(c, chosen["url"], allowed_hosts=(LVA_IMAGE_HOST,))
|
|
920
|
+
mode = save_image(cached, out)
|
|
921
|
+
parsed["out"] = mode[4:] if mode.startswith("raw:") else str(out)
|
|
922
|
+
parsed["mode"] = "raw" if mode.startswith("raw") else mode
|
|
923
|
+
if as_json:
|
|
924
|
+
click.echo(json.dumps(parsed, indent=1))
|
|
925
|
+
return
|
|
926
|
+
click.echo(f"Dunmore's War drawer {drawer} card {card}: page {parsed['current_page']}")
|
|
927
|
+
for im in parsed["images"]:
|
|
928
|
+
mark = "*" if im is chosen else " "
|
|
929
|
+
click.echo(f" {mark} page {im['page']}: {im['url']}")
|
|
930
|
+
if out is not None:
|
|
931
|
+
click.echo(f"saved {parsed['out']} ({parsed['mode']})")
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
def resolve_rosetta(c: httpx.Client, ie: str) -> dict:
|
|
935
|
+
"""Resolve an IE to its FL file list via the delivery page + ieViewer (one cookie session)."""
|
|
936
|
+
cache_dir = get_cache_root() / "rosetta" / ie
|
|
937
|
+
files_path = cache_dir / "files.json"
|
|
938
|
+
if not _STATE["refresh"]:
|
|
939
|
+
cached = read_json_if_valid(files_path)
|
|
940
|
+
if cached and cached.get("files"):
|
|
941
|
+
return {**cached, "session": False}
|
|
942
|
+
r = c.get(ROSETTA_DELIVERY, params={"dps_pid": ie})
|
|
943
|
+
r.raise_for_status()
|
|
944
|
+
if not _host_ok(r.url, (ROSETTA_HOST,)):
|
|
945
|
+
raise click.ClickException(f"Unexpected Rosetta redirect: {r.url}")
|
|
946
|
+
info = parse_rosetta_delivery(r.text)
|
|
947
|
+
viewer_url = info["viewer_url"]
|
|
948
|
+
if viewer_url:
|
|
949
|
+
vu = httpx.URL(viewer_url)
|
|
950
|
+
if vu.scheme != "https" or vu.host != ROSETTA_HOST or not vu.path.endswith("/ieViewer.do") or vu.params.get("dps_pid") != ie:
|
|
951
|
+
viewer_url = None
|
|
952
|
+
if not viewer_url:
|
|
953
|
+
params = {"search": "hide", "dps_pid": ie}
|
|
954
|
+
if info["dps_dvs"]:
|
|
955
|
+
params["dps_dvs"] = info["dps_dvs"]
|
|
956
|
+
viewer_url = str(httpx.URL(ROSETTA_VIEWER, params=params))
|
|
957
|
+
v = c.get(viewer_url)
|
|
958
|
+
v.raise_for_status()
|
|
959
|
+
if not _host_ok(v.url, (ROSETTA_HOST,)):
|
|
960
|
+
raise click.ClickException(f"Unexpected Rosetta redirect: {v.url}")
|
|
961
|
+
listing = parse_rosetta_viewer(v.text)
|
|
962
|
+
if not listing["files"]:
|
|
963
|
+
raise click.ClickException(f"No delivered files found for {ie} (restricted or not a viewable IE).")
|
|
964
|
+
result = {"ie": ie, "delivery_url": f"{ROSETTA_DELIVERY}?dps_pid={ie}",
|
|
965
|
+
"files": listing["files"], "initial": listing["initial"], "cached_at": time.time()}
|
|
966
|
+
atomic_write_json(files_path, result)
|
|
967
|
+
return {**result, "session": True}
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def download_rosetta_file(c: httpx.Client, ie: str, fl: str) -> tuple[Path, dict]:
|
|
971
|
+
cache_dir = get_cache_root() / "rosetta" / ie
|
|
972
|
+
path, meta = cached_fetch(
|
|
973
|
+
c, ROSETTA_DELIVERY, cache_dir / f"{fl}.bin",
|
|
974
|
+
params={"dps_pid": fl, "dps_func": "stream"}, allowed_hosts=(ROSETTA_HOST,),
|
|
975
|
+
)
|
|
976
|
+
if meta.get("content_type", "").lower().startswith("text/html"):
|
|
977
|
+
path.unlink(missing_ok=True)
|
|
978
|
+
_meta_path(path).unlink(missing_ok=True)
|
|
979
|
+
raise click.ClickException(f"Rosetta returned HTML instead of a file for {ie}/{fl} (access restricted?).")
|
|
980
|
+
return path, meta
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
@cli.command("download-rosetta")
|
|
984
|
+
@click.argument("ie_id")
|
|
985
|
+
@click.option("--file", "file_index", type=int, default=None, help="1-based file number from --list (default: viewer's initial file).")
|
|
986
|
+
@click.option("--fl", "fl_id", default=None, help="Explicit Rosetta file pid (FL<digits>) belonging to this IE.")
|
|
987
|
+
@click.option("--list", "list_only", is_flag=True, help="Only list the IE's delivered files.")
|
|
988
|
+
@click.option("--out", type=click.Path(path_type=Path), default=None, help="Output file (default ./<IE>_<FL>.<ext>).")
|
|
989
|
+
@click.option("--json", "as_json", is_flag=True, help="Output structured JSON.")
|
|
990
|
+
@refresh_option
|
|
991
|
+
def cmd_download_rosetta(ie_id: str, file_index: int | None, fl_id: str | None, list_only: bool,
|
|
992
|
+
out: Path | None, as_json: bool) -> None:
|
|
993
|
+
"""Download a delivered file (PDF/image) for a Library of Virginia Rosetta IE id.
|
|
994
|
+
|
|
995
|
+
Resolves rosetta.virginiamemory.com DeliveryManagerServlet?dps_pid=IE... ->
|
|
996
|
+
ieViewer.do (same cookie session) -> FL file pid -> dps_func=stream. The
|
|
997
|
+
file list and bytes are cached per IE id.
|
|
998
|
+
"""
|
|
999
|
+
ie = validate_ie_id(ie_id)
|
|
1000
|
+
if fl_id is not None:
|
|
1001
|
+
fl_id = validate_fl_id(fl_id)
|
|
1002
|
+
with _client() as c:
|
|
1003
|
+
info = resolve_rosetta(c, ie)
|
|
1004
|
+
files = info["files"]
|
|
1005
|
+
if list_only:
|
|
1006
|
+
if as_json:
|
|
1007
|
+
click.echo(json.dumps({k: v for k, v in info.items() if k != "session"}, indent=1))
|
|
1008
|
+
else:
|
|
1009
|
+
for i, f in enumerate(files, 1):
|
|
1010
|
+
star = "*" if f["fl"] == info.get("initial") else " "
|
|
1011
|
+
click.echo(f" {star} {i}. {f['fl']} {f['title']}")
|
|
1012
|
+
return
|
|
1013
|
+
if fl_id is not None:
|
|
1014
|
+
if fl_id not in {f["fl"] for f in files}:
|
|
1015
|
+
raise click.ClickException(f"{fl_id} is not a file of {ie}; see --list.")
|
|
1016
|
+
fl = fl_id
|
|
1017
|
+
elif file_index is not None:
|
|
1018
|
+
if not 1 <= file_index <= len(files):
|
|
1019
|
+
raise click.BadParameter(f"--file must be 1..{len(files)}")
|
|
1020
|
+
fl = files[file_index - 1]["fl"]
|
|
1021
|
+
else:
|
|
1022
|
+
fl = info.get("initial") or files[0]["fl"]
|
|
1023
|
+
if not info.get("session") and (_STATE["refresh"] or _cache_valid(get_cache_root() / "rosetta" / ie / f"{fl}.bin", None) is None):
|
|
1024
|
+
# Listing came from cache: open a delivery session (cookies) before streaming.
|
|
1025
|
+
warm = c.get(ROSETTA_DELIVERY, params={"dps_pid": ie})
|
|
1026
|
+
warm.raise_for_status()
|
|
1027
|
+
path, meta = download_rosetta_file(c, ie, fl)
|
|
1028
|
+
dest = out or Path(f"{ie}_{fl}{_ext_for(meta.get('content_type', ''))}")
|
|
1029
|
+
copy_atomic(path, dest)
|
|
1030
|
+
result = {"ie": ie, "fl": fl, "content_type": meta.get("content_type", ""), "out": str(dest),
|
|
1031
|
+
"bytes": dest.stat().st_size, "cache_path": str(path)}
|
|
1032
|
+
if as_json:
|
|
1033
|
+
click.echo(json.dumps(result, indent=1))
|
|
1034
|
+
else:
|
|
1035
|
+
click.echo(f"saved {dest} ({result['bytes']} bytes, {result['content_type']}) from {ie}/{fl}")
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
if __name__ == "__main__":
|
|
1039
|
+
cli()
|