mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-30 03:46:29 -05:00
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
768 lines
32 KiB
Python
768 lines
32 KiB
Python
import pathlib
|
|
import re
|
|
import tempfile
|
|
from dataclasses import dataclass
|
|
from pathlib import Path, PurePosixPath
|
|
from typing import Any, List, Optional
|
|
from urllib.parse import urlparse
|
|
from xml.etree import ElementTree as ET
|
|
from xml.sax.saxutils import escape, quoteattr
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from modules.map import lib
|
|
from modules.map.species import pack_name, parse_pack_name
|
|
from wrolpi.common import logger, verify_gpg_signature
|
|
from wrolpi.downloader import (
|
|
Download,
|
|
DownloadContext,
|
|
Downloader,
|
|
DownloadResult,
|
|
download_manager,
|
|
)
|
|
|
|
__all__ = [
|
|
'MapCatalogDownloader', 'MapExtractDownloader', 'MapSearchIndexDownloader',
|
|
'PreparedMapCatalog', 'ExecutedMapCatalog',
|
|
'PreparedMapExtract', 'ExecutedMapExtract',
|
|
'PreparedMapSearchIndex', 'ExecutedMapSearchIndex',
|
|
'map_catalog_downloader', 'map_extract_downloader', 'map_search_index_downloader',
|
|
'SpeciesCatalogDownloader', 'SpeciesPackDownloader', 'PreparedSpeciesPack', 'ExecutedSpeciesPack',
|
|
'species_catalog_downloader', 'species_pack_downloader',
|
|
]
|
|
|
|
logger = logger.getChild(__name__)
|
|
|
|
METALINK_NS = {'ml': 'urn:ietf:params:xml:ns:metalink'}
|
|
SHA256_PATTERN = re.compile(r'[0-9a-f]{64}')
|
|
# aria2c's exit code when a downloaded file does not match the meta4's hash.
|
|
ARIA2C_CHECKSUM_ERROR = 32
|
|
# Map files are downloaded here, and moved into the map directory only once aria2c has checked them against the signed
|
|
# hash. A failed download must never leave a file where `prepare_download` would take it as already downloaded.
|
|
PARTIAL_DIRECTORY = '.partial'
|
|
|
|
|
|
async def verified_meta4_sha256(meta4_contents: bytes) -> Optional[str]:
|
|
"""Parse meta4 XML bytes, extract the sha-256 hash and its GPG signature, and verify.
|
|
|
|
Returns the hash if its signature is valid, None if invalid or missing. Only this hash is signed; nothing else in
|
|
the meta4 is trusted."""
|
|
try:
|
|
root = ET.fromstring(meta4_contents)
|
|
file_el = root.find('ml:file', METALINK_NS)
|
|
if file_el is None:
|
|
logger.warning('meta4 missing <file> element')
|
|
return False
|
|
|
|
hash_el = file_el.find('ml:hash[@type="sha-256"]', METALINK_NS)
|
|
sig_el = file_el.find('ml:signature', METALINK_NS)
|
|
|
|
if hash_el is None or hash_el.text is None:
|
|
logger.warning('meta4 missing <hash type="sha-256"> element')
|
|
return False
|
|
if sig_el is None or sig_el.text is None:
|
|
logger.warning('meta4 missing <signature> element')
|
|
return False
|
|
|
|
sha256_hash = hash_el.text.strip()
|
|
signature = sig_el.text.strip()
|
|
except ET.ParseError as e:
|
|
logger.warning(f'Failed to parse meta4 XML: {e}')
|
|
return None
|
|
|
|
if not SHA256_PATTERN.fullmatch(sha256_hash):
|
|
logger.warning('meta4 sha-256 hash is malformed')
|
|
return None
|
|
|
|
# Write hash and signature to temp files for GPG verification.
|
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
hash_path = Path(tmpdir) / 'hash'
|
|
sig_path = Path(tmpdir) / 'hash.sig'
|
|
hash_path.write_text(sha256_hash)
|
|
sig_path.write_text(signature)
|
|
|
|
if await verify_gpg_signature(hash_path, sig_path):
|
|
return sha256_hash
|
|
return None
|
|
|
|
|
|
async def get_signed_sha256(downloader: Downloader, url: str, manifest_sha256: Optional[str],
|
|
label: str) -> tuple[Optional[str], Optional[str]]:
|
|
"""The signed sha-256 hash a map file must match, or an error explaining why there is none.
|
|
|
|
The hash from the signed manifest is used when it has one: a meta4 signs only a bare hash, so any genuinely signed
|
|
meta4 (an older version, another region) would pass its own check. Downloads from a manifest without hashes use
|
|
the file's signed meta4."""
|
|
if manifest_sha256:
|
|
if SHA256_PATTERN.fullmatch(manifest_sha256):
|
|
return manifest_sha256, None
|
|
return None, f'Malformed hash in the manifest for {label}'
|
|
|
|
meta4_contents = await downloader.get_meta4_contents(url)
|
|
if not meta4_contents:
|
|
return None, f'No signed hash (meta4) available for {label}, not downloading'
|
|
if not (sha256 := await verified_meta4_sha256(meta4_contents)):
|
|
return None, f'meta4 hash signature verification failed for {label}'
|
|
logger.info(f'meta4 signature verified for {label}')
|
|
return sha256, None
|
|
|
|
|
|
def meta4_file_name(url: str) -> Optional[str]:
|
|
"""The name aria2c saves `url` as, or None if the URL's file name is not a plain one."""
|
|
name = PurePosixPath(urlparse(url).path).name
|
|
return name if re.fullmatch(r'\w[\w.-]*', name) else None
|
|
|
|
|
|
def make_meta4(url: str, name: str, sha256: str) -> bytes:
|
|
"""A meta4 for aria2c holding only `url`, the `name` to save it as, and its signed `sha256` hash.
|
|
|
|
The downloaded meta4 is never given to aria2c: it would also obey any other hash (e.g. a sha-512 of a tampered
|
|
file), pieces, files, or URLs in it, none of which are signed."""
|
|
return (
|
|
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
|
'<metalink xmlns="urn:ietf:params:xml:ns:metalink">\n'
|
|
f' <file name={quoteattr(name)}>\n'
|
|
f' <hash type="sha-256">{sha256}</hash>\n'
|
|
f' <url>{escape(url)}</url>\n'
|
|
' </file>\n'
|
|
'</metalink>\n'
|
|
).encode()
|
|
|
|
|
|
def remove_rejected_partial(error: Exception, partial_path: pathlib.Path):
|
|
"""Delete a partial download that aria2c rejected for not matching the signed hash; a retry would only reject it
|
|
again. Other failures keep it, so the next attempt resumes."""
|
|
if f'return code {ARIA2C_CHECKSUM_ERROR}' in str(error):
|
|
logger.warning(f'Deleting download that did not match its signed hash: {partial_path}')
|
|
partial_path.unlink(missing_ok=True)
|
|
partial_path.with_name(f'{partial_path.name}.aria2').unlink(missing_ok=True)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# MapCatalogDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@dataclass
|
|
class PreparedMapCatalog:
|
|
"""Plan produced by MapCatalogDownloader.prepare_download.
|
|
|
|
`subscribed_regions` is the list of {region: ...} dicts the user has chosen to track.
|
|
The manifest itself is fetched in execute_download.
|
|
"""
|
|
url: str
|
|
subscribed_regions: List[dict]
|
|
|
|
|
|
@dataclass
|
|
class ExecutedMapCatalog:
|
|
"""Output of MapCatalogDownloader.execute_download.
|
|
|
|
Either `manifest` is populated (success) or `error` is set (fetch failed). Child
|
|
download creation happens in finalize_download where the manager's session is in
|
|
scope.
|
|
"""
|
|
manifest: Optional[dict]
|
|
subscribed_regions: List[dict]
|
|
error: Optional[str] = None
|
|
|
|
|
|
class MapCatalogDownloader(Downloader):
|
|
"""Fetches the manifest and creates a child Download for each subscribed region."""
|
|
|
|
name = 'map_catalog'
|
|
listable = False
|
|
|
|
def prepare_download(self, session: Session, download: Download) -> PreparedMapCatalog:
|
|
subscribed = (download.settings or {}).get('regions', [])
|
|
return PreparedMapCatalog(url=download.url, subscribed_regions=subscribed)
|
|
|
|
async def execute_download(self, prepared: PreparedMapCatalog, ctx: DownloadContext,
|
|
download: Download = None) -> ExecutedMapCatalog:
|
|
try:
|
|
manifest = await lib.fetch_manifest(prepared.url)
|
|
except Exception as e:
|
|
logger.error(f'Failed to fetch map manifest: {e}')
|
|
return ExecutedMapCatalog(
|
|
manifest=None,
|
|
subscribed_regions=prepared.subscribed_regions,
|
|
error=f'Failed to fetch manifest: {e}',
|
|
)
|
|
return ExecutedMapCatalog(manifest=manifest,
|
|
subscribed_regions=prepared.subscribed_regions)
|
|
|
|
def finalize_download(self, session: Session, download: Download,
|
|
executed: ExecutedMapCatalog) -> DownloadResult:
|
|
if executed.error:
|
|
return DownloadResult(success=False, error=executed.error)
|
|
|
|
manifest = executed.manifest or {}
|
|
version = manifest.get('version', '')
|
|
manifest_regions = manifest.get('regions', {})
|
|
search_indexes = manifest.get('search_indexes', {})
|
|
hashes = manifest.get('sha256', {})
|
|
|
|
if not manifest_regions:
|
|
return DownloadResult(success=False, error='Manifest does not contain regions')
|
|
|
|
if not executed.subscribed_regions:
|
|
return DownloadResult(success=True)
|
|
|
|
map_directory = lib.get_map_directory()
|
|
|
|
created = 0
|
|
# Defer search-index downloads so they are all inserted AFTER every pmtiles
|
|
# download. Downloads process in insertion order; this prevents a search-index
|
|
# download from running before its companion pmtiles file exists on disk.
|
|
pending_search_downloads = []
|
|
for r in executed.subscribed_regions:
|
|
region = r.get('region', '')
|
|
region_url = manifest_regions.get(region)
|
|
if not region_url:
|
|
logger.warning(f'Subscribed region {region!r} not found in manifest — skipping')
|
|
continue
|
|
|
|
# Compute the expected PMTiles filename.
|
|
if version:
|
|
pmtiles_name = f'{region}-{version}.pmtiles'
|
|
else:
|
|
pmtiles_name = f'{region}.pmtiles'
|
|
|
|
# Delete stale download for this region if the URL changed (new version).
|
|
old = session.query(Download).filter(
|
|
Download.downloader == 'map_extract',
|
|
Download.settings['region'].as_string() == region,
|
|
Download.url != region_url,
|
|
).one_or_none()
|
|
if old:
|
|
logger.info(f'Deleting stale download for {region}: {old.url}')
|
|
session.delete(old)
|
|
session.flush()
|
|
|
|
child = download_manager.get_or_create_download(session, region_url, reset_attempts=True,
|
|
override_skip=True)
|
|
child.downloader = 'map_extract'
|
|
child.location = '/map/manage'
|
|
child.settings = {
|
|
'region': region,
|
|
'version': version,
|
|
'search_index_url': search_indexes.get(region, ''),
|
|
'sha256': hashes.get(region_url),
|
|
}
|
|
child.renew(reset_attempts=True)
|
|
created += 1
|
|
|
|
# Queue search index download if the CDN provides one and the
|
|
# .search.db file does not already exist on disk.
|
|
search_url = search_indexes.get(region)
|
|
search_db_path = (map_directory / pmtiles_name).with_suffix('.search.db')
|
|
if search_url and not search_db_path.is_file():
|
|
pending_search_downloads.append((region, search_url, pmtiles_name))
|
|
|
|
# Insert all search-index downloads after every pmtiles download, so they
|
|
# process in insertion order behind their companion pmtiles.
|
|
for region, search_url, pmtiles_name in pending_search_downloads:
|
|
search_child = download_manager.get_or_create_download(
|
|
session, search_url, reset_attempts=True, override_skip=True)
|
|
search_child.downloader = 'map_search_index'
|
|
search_child.location = '/map/manage'
|
|
search_child.settings = {'region': region, 'pmtiles_name': pmtiles_name,
|
|
'sha256': hashes.get(search_url)}
|
|
search_child.renew(reset_attempts=True)
|
|
logger.info(f'Created search index download for {region}')
|
|
|
|
if not created:
|
|
return DownloadResult(success=False, error='No matching region URLs found in manifest')
|
|
|
|
logger.info(f'Created {created} map region downloads')
|
|
|
|
return DownloadResult(success=True, location='/map/manage')
|
|
|
|
|
|
map_catalog_downloader = MapCatalogDownloader()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# MapExtractDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@dataclass
|
|
class PreparedMapExtract:
|
|
"""Plan produced by MapExtractDownloader.prepare_download.
|
|
|
|
Filenames are computed from settings; `already_done` short-circuits execute when
|
|
the output already exists. `error` carries an early validation failure (e.g. no
|
|
region in settings).
|
|
"""
|
|
region: str
|
|
version: str
|
|
map_directory: pathlib.Path
|
|
output_name: str
|
|
output_path: pathlib.Path
|
|
tmp_path: pathlib.Path
|
|
sha256: Optional[str] = None # From the signed manifest.
|
|
already_done: bool = False
|
|
error: Optional[str] = None
|
|
|
|
|
|
@dataclass
|
|
class ExecutedMapExtract:
|
|
"""Output of MapExtractDownloader.execute_download.
|
|
|
|
`skipped` covers the already-done short-circuit; `error` covers download/verify
|
|
failures. Otherwise the file is at output_path and finalize decides whether to
|
|
rebuild the search index locally.
|
|
"""
|
|
region: str
|
|
output_path: pathlib.Path
|
|
map_directory: pathlib.Path
|
|
skipped: bool = False
|
|
error: Optional[str] = None
|
|
|
|
|
|
class MapExtractDownloader(Downloader):
|
|
"""Downloads a pre-extracted region file from the CDN via aria2c.
|
|
|
|
Settings contain: region, version — set by MapCatalogDownloader.
|
|
|
|
aria2c checks the file against a signed hash (see `get_signed_sha256`), given to it in a meta4 that WROLPi writes.
|
|
"""
|
|
|
|
name = 'map_extract'
|
|
listable = False
|
|
|
|
def prepare_download(self, session: Session, download: Download) -> PreparedMapExtract:
|
|
settings = download.settings or {}
|
|
region = settings.get('region')
|
|
version = settings.get('version', '')
|
|
|
|
if not region:
|
|
return PreparedMapExtract(
|
|
region='', version='', map_directory=pathlib.Path('.'),
|
|
output_name='', output_path=pathlib.Path('.'), tmp_path=pathlib.Path('.'),
|
|
error='No region in download settings',
|
|
)
|
|
|
|
map_directory = lib.get_map_directory()
|
|
# Versioned filename.
|
|
if version:
|
|
output_name = f'{region}-{version}.pmtiles'
|
|
else:
|
|
output_name = f'{region}.pmtiles'
|
|
output_path = map_directory / output_name
|
|
tmp_path = map_directory / f'{output_name}.tmp'
|
|
|
|
prepared = PreparedMapExtract(
|
|
region=region, version=version, map_directory=map_directory,
|
|
output_name=output_name, output_path=output_path, tmp_path=tmp_path,
|
|
sha256=settings.get('sha256'),
|
|
)
|
|
|
|
# Skip if versioned file already exists.
|
|
if output_path.is_file():
|
|
logger.info(f'{output_name} already exists, skipping download')
|
|
prepared.already_done = True
|
|
return prepared
|
|
|
|
# Clean up any leftover temp file.
|
|
if tmp_path.is_file():
|
|
tmp_path.unlink()
|
|
|
|
return prepared
|
|
|
|
async def execute_download(self, prepared: PreparedMapExtract, ctx: DownloadContext,
|
|
download: Download = None) -> ExecutedMapExtract:
|
|
if prepared.error:
|
|
return ExecutedMapExtract(region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory, error=prepared.error)
|
|
if prepared.already_done:
|
|
return ExecutedMapExtract(region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory, skipped=True)
|
|
|
|
download = download if download is not None else Download(url=prepared.output_path.name)
|
|
# The original download URL is needed for download_file; the manager passes the real
|
|
# Download in production, so we read .url from it. In unit tests, callers must supply
|
|
# `download` with a URL.
|
|
url = download.url
|
|
|
|
# A map file is never downloaded without a signed hash.
|
|
sha256, error = await get_signed_sha256(self, url, prepared.sha256, prepared.region)
|
|
if error:
|
|
return ExecutedMapExtract(
|
|
region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory, error=error,
|
|
)
|
|
if not (name := meta4_file_name(url)):
|
|
return ExecutedMapExtract(
|
|
region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory,
|
|
error=f'No usable file name in {url}',
|
|
)
|
|
|
|
# Download via aria2c, which refuses a file that does not match the signed hash.
|
|
logger.warning(f'Downloading {prepared.region} from {url}')
|
|
partial_directory = prepared.map_directory / PARTIAL_DIRECTORY
|
|
partial_directory.mkdir(parents=True, exist_ok=True)
|
|
try:
|
|
downloaded_path = await self.download_file(
|
|
download, url, partial_directory,
|
|
check_for_meta4=False, concurrent=1, meta4_xml=make_meta4(url, name, sha256),
|
|
ctx=ctx,
|
|
)
|
|
# Only the file aria2c saved under the meta4's name was checked against the signed hash. The path
|
|
# download_file reports comes from the server's response, so it may name some other file.
|
|
if downloaded_path != partial_directory / name:
|
|
raise RuntimeError(f'Downloaded {downloaded_path.name!r}, expected {name!r}')
|
|
downloaded_path.rename(prepared.tmp_path)
|
|
except Exception as e:
|
|
logger.error(f'Download failed for {prepared.region}: {e}')
|
|
prepared.tmp_path.unlink(missing_ok=True)
|
|
remove_rejected_partial(e, partial_directory / name)
|
|
return ExecutedMapExtract(
|
|
region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory,
|
|
error=f'Download failed: {str(e)[:500]}',
|
|
)
|
|
|
|
if not prepared.tmp_path.is_file():
|
|
return ExecutedMapExtract(
|
|
region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory,
|
|
error=f'Output file was not created: {prepared.tmp_path}',
|
|
)
|
|
|
|
# Replace old file atomically.
|
|
prepared.tmp_path.rename(prepared.output_path)
|
|
|
|
# Delete older versions of this region.
|
|
for old_file in prepared.map_directory.glob(f'{prepared.region}-*.pmtiles'):
|
|
if old_file.name != prepared.output_name:
|
|
logger.warning(f'Deleting old map version: {old_file}')
|
|
old_file.unlink()
|
|
# Also delete unversioned file if it exists.
|
|
unversioned = prepared.map_directory / f'{prepared.region}.pmtiles'
|
|
if unversioned.is_file() and unversioned.name != prepared.output_name:
|
|
logger.warning(f'Deleting unversioned map file: {unversioned}')
|
|
unversioned.unlink()
|
|
|
|
size = prepared.output_path.stat().st_size
|
|
logger.warning(f'Successfully downloaded {prepared.region} ({size} bytes) to {prepared.output_path}')
|
|
|
|
return ExecutedMapExtract(region=prepared.region, output_path=prepared.output_path,
|
|
map_directory=prepared.map_directory)
|
|
|
|
def finalize_download(self, session: Session, download: Download,
|
|
executed: ExecutedMapExtract) -> DownloadResult:
|
|
if executed.error:
|
|
return DownloadResult(success=False, error=executed.error)
|
|
if executed.skipped:
|
|
return DownloadResult(success=True, location='/map')
|
|
|
|
# Build search index locally if tippecanoe is available and no CDN
|
|
# search index download already exists for this region.
|
|
has_search_download = session.query(Download).filter(
|
|
Download.downloader == 'map_search_index',
|
|
Download.settings['region'].as_string() == executed.region,
|
|
).count() > 0
|
|
if not has_search_download:
|
|
try:
|
|
from modules.map.search import rebuild_search_index
|
|
rebuild_search_index(executed.output_path.name)
|
|
except Exception as e:
|
|
logger.error(f'Failed to start search index build for {executed.region}: {e}')
|
|
|
|
return DownloadResult(success=True, location='/map')
|
|
|
|
|
|
map_extract_downloader = MapExtractDownloader()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# MapSearchIndexDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@dataclass
|
|
class PreparedMapSearchIndex:
|
|
"""Plan produced by MapSearchIndexDownloader.prepare_download.
|
|
|
|
`error` covers missing settings or a missing PMTiles file (the search index can't
|
|
exist without one). `already_done` short-circuits when the .search.db is on disk.
|
|
"""
|
|
region: str
|
|
pmtiles_name: str
|
|
map_directory: pathlib.Path
|
|
pmtiles_path: pathlib.Path
|
|
search_db_path: pathlib.Path
|
|
sha256: Optional[str] = None # From the signed manifest.
|
|
already_done: bool = False
|
|
error: Optional[str] = None
|
|
|
|
|
|
@dataclass
|
|
class ExecutedMapSearchIndex:
|
|
region: str
|
|
skipped: bool = False
|
|
error: Optional[str] = None
|
|
|
|
|
|
class MapSearchIndexDownloader(Downloader):
|
|
"""Downloads a pre-built .search.db file from the CDN via aria2c with meta4 verification.
|
|
|
|
Created by MapCatalogDownloader alongside map_extract downloads for each
|
|
subscribed region. Will wait (fail + retry) until the PMTiles file exists.
|
|
"""
|
|
|
|
name = 'map_search_index'
|
|
listable = False
|
|
|
|
def prepare_download(self, session: Session, download: Download) -> PreparedMapSearchIndex:
|
|
settings = download.settings or {}
|
|
region = settings.get('region', '')
|
|
pmtiles_name = settings.get('pmtiles_name', '')
|
|
|
|
map_directory = lib.get_map_directory()
|
|
|
|
prepared = PreparedMapSearchIndex(
|
|
region=region, pmtiles_name=pmtiles_name, map_directory=map_directory,
|
|
pmtiles_path=map_directory / pmtiles_name if pmtiles_name else map_directory,
|
|
search_db_path=(map_directory / pmtiles_name).with_suffix('.search.db')
|
|
if pmtiles_name else map_directory,
|
|
sha256=settings.get('sha256'),
|
|
)
|
|
|
|
if not region or not pmtiles_name:
|
|
prepared.error = 'Missing region or pmtiles_name in settings'
|
|
return prepared
|
|
|
|
if not prepared.pmtiles_path.is_file():
|
|
prepared.error = f'PMTiles file not found: {pmtiles_name}'
|
|
return prepared
|
|
|
|
if prepared.search_db_path.is_file():
|
|
logger.info(f'Search index already exists for {region}, skipping')
|
|
prepared.already_done = True
|
|
|
|
return prepared
|
|
|
|
async def execute_download(self, prepared: PreparedMapSearchIndex, ctx: DownloadContext,
|
|
download: Download = None) -> ExecutedMapSearchIndex:
|
|
if prepared.error:
|
|
return ExecutedMapSearchIndex(region=prepared.region, error=prepared.error)
|
|
if prepared.already_done:
|
|
return ExecutedMapSearchIndex(region=prepared.region, skipped=True)
|
|
|
|
download = download if download is not None else Download(url=prepared.pmtiles_name)
|
|
url = download.url
|
|
|
|
# A search index is never downloaded without a signed hash.
|
|
sha256, error = await get_signed_sha256(self, url, prepared.sha256, f'{prepared.region} search index')
|
|
if error:
|
|
return ExecutedMapSearchIndex(region=prepared.region, error=error)
|
|
if not (name := meta4_file_name(url)):
|
|
return ExecutedMapSearchIndex(
|
|
region=prepared.region,
|
|
error=f'No usable file name in {url}',
|
|
)
|
|
|
|
# Download via aria2c, which refuses a file that does not match the signed hash.
|
|
logger.warning(f'Downloading search index for {prepared.region} from {url}')
|
|
partial_directory = prepared.map_directory / PARTIAL_DIRECTORY
|
|
partial_directory.mkdir(parents=True, exist_ok=True)
|
|
try:
|
|
downloaded_path = await self.download_file(
|
|
download, url, partial_directory,
|
|
check_for_meta4=False, concurrent=1, meta4_xml=make_meta4(url, name, sha256),
|
|
ctx=ctx,
|
|
)
|
|
# Only the file aria2c saved under the meta4's name was checked against the signed hash. The path
|
|
# download_file reports comes from the server's response, so it may name some other file.
|
|
if downloaded_path != partial_directory / name:
|
|
raise RuntimeError(f'Downloaded {downloaded_path.name!r}, expected {name!r}')
|
|
# Rename to match the local PMTiles filename.
|
|
downloaded_path.rename(prepared.search_db_path)
|
|
except Exception as e:
|
|
logger.error(f'Search index download failed for {prepared.region}: {e}')
|
|
remove_rejected_partial(e, partial_directory / name)
|
|
return ExecutedMapSearchIndex(
|
|
region=prepared.region,
|
|
error=f'Download failed: {str(e)[:500]}',
|
|
)
|
|
|
|
size = prepared.search_db_path.stat().st_size
|
|
logger.warning(f'Downloaded search index for {prepared.region} ({size} bytes)')
|
|
return ExecutedMapSearchIndex(region=prepared.region)
|
|
|
|
def finalize_download(self, session: Session, download: Download,
|
|
executed: ExecutedMapSearchIndex) -> DownloadResult:
|
|
if executed.error:
|
|
return DownloadResult(success=False, error=executed.error)
|
|
return DownloadResult(success=True, location='/map')
|
|
|
|
|
|
map_search_index_downloader = MapSearchIndexDownloader()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# SpeciesCatalogDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class SpeciesCatalogDownloader(MapCatalogDownloader):
|
|
"""Fetches the signed species manifest and creates a `species_pack` Download for each subscribed region."""
|
|
|
|
name = 'species_catalog'
|
|
listable = False
|
|
|
|
def finalize_download(self, session: Session, download: Download,
|
|
executed: ExecutedMapCatalog) -> DownloadResult:
|
|
if executed.error:
|
|
return DownloadResult(success=False, error=executed.error)
|
|
|
|
manifest = executed.manifest or {}
|
|
version = manifest.get('version', '')
|
|
manifest_regions = manifest.get('regions', {})
|
|
hashes = manifest.get('sha256', {})
|
|
if not manifest_regions or not version:
|
|
return DownloadResult(success=False, error='Species manifest does not contain regions and a version')
|
|
if not executed.subscribed_regions:
|
|
return DownloadResult(success=True)
|
|
|
|
created = 0
|
|
for subscription in executed.subscribed_regions:
|
|
region = subscription.get('region', '')
|
|
if not (url := manifest_regions.get(region)):
|
|
logger.warning(f'Subscribed species region {region!r} not found in manifest, skipping')
|
|
continue
|
|
|
|
# A new version replaces the Download of the old one.
|
|
for old in session.query(Download).filter(
|
|
Download.downloader == 'species_pack',
|
|
Download.settings['region'].as_string() == region,
|
|
Download.url != url,
|
|
):
|
|
logger.info(f'Deleting stale species download for {region}: {old.url}')
|
|
session.delete(old)
|
|
session.flush()
|
|
|
|
child = download_manager.get_or_create_download(session, url, reset_attempts=True, override_skip=True)
|
|
child.downloader = 'species_pack'
|
|
child.location = '/map/manage'
|
|
child.settings = {'region': region, 'version': version, 'sha256': hashes.get(url)}
|
|
child.renew(reset_attempts=True)
|
|
created += 1
|
|
|
|
if not created:
|
|
return DownloadResult(success=False, error='No subscribed species regions found in manifest')
|
|
|
|
logger.info(f'Created {created} species pack downloads')
|
|
return DownloadResult(success=True, location='/map/manage')
|
|
|
|
|
|
species_catalog_downloader = SpeciesCatalogDownloader()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# SpeciesPackDownloader
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@dataclass
|
|
class PreparedSpeciesPack:
|
|
region: str
|
|
output_path: Optional[pathlib.Path] = None
|
|
sha256: Optional[str] = None # From the signed manifest.
|
|
already_done: bool = False
|
|
error: Optional[str] = None
|
|
|
|
|
|
@dataclass
|
|
class ExecutedSpeciesPack:
|
|
region: str
|
|
skipped: bool = False
|
|
error: Optional[str] = None
|
|
|
|
|
|
class SpeciesPackDownloader(Downloader):
|
|
"""Downloads a region's species pack into the species directory, checked by aria2c against its signed hash.
|
|
|
|
The pack replaces the region's older packs only once it has been downloaded and checked."""
|
|
|
|
name = 'species_pack'
|
|
listable = False
|
|
|
|
def prepare_download(self, session: Session, download: Download) -> PreparedSpeciesPack:
|
|
settings = download.settings or {}
|
|
region = settings.get('region', '')
|
|
name = pack_name(region, settings.get('version', ''))
|
|
# The name must parse back to this region, so a region can never name a path outside the directory.
|
|
if parse_pack_name(name) is None or parse_pack_name(name)[0] != region:
|
|
return PreparedSpeciesPack(region=region, error='Invalid region or version in download settings')
|
|
|
|
output_path = lib.get_species_directory() / name
|
|
prepared = PreparedSpeciesPack(region=region, output_path=output_path, sha256=settings.get('sha256'))
|
|
if output_path.is_file():
|
|
logger.info(f'{name} already exists, skipping download')
|
|
# An earlier download may have stopped before it deleted the older versions.
|
|
remove_old_species_packs(output_path)
|
|
prepared.already_done = True
|
|
return prepared
|
|
|
|
async def execute_download(self, prepared: PreparedSpeciesPack, ctx: DownloadContext,
|
|
download: Download = None) -> ExecutedSpeciesPack:
|
|
if prepared.error:
|
|
return ExecutedSpeciesPack(region=prepared.region, error=prepared.error)
|
|
if prepared.already_done:
|
|
return ExecutedSpeciesPack(region=prepared.region, skipped=True)
|
|
|
|
download = download if download is not None else Download(url=prepared.output_path.name)
|
|
url = download.url
|
|
|
|
# A species pack is never downloaded without a signed hash.
|
|
label = f'{prepared.region} species'
|
|
sha256, error = await get_signed_sha256(self, url, prepared.sha256, label)
|
|
if error:
|
|
return ExecutedSpeciesPack(region=prepared.region, error=error)
|
|
if not (name := meta4_file_name(url)):
|
|
return ExecutedSpeciesPack(region=prepared.region, error=f'No usable file name in {url}')
|
|
|
|
logger.warning(f'Downloading {label} from {url}')
|
|
partial_directory = lib.get_map_directory() / PARTIAL_DIRECTORY
|
|
partial_directory.mkdir(parents=True, exist_ok=True)
|
|
try:
|
|
downloaded_path = await self.download_file(
|
|
download, url, partial_directory,
|
|
check_for_meta4=False, concurrent=1, meta4_xml=make_meta4(url, name, sha256),
|
|
ctx=ctx,
|
|
)
|
|
# Only the file aria2c saved under the meta4's name was checked against the signed hash.
|
|
if downloaded_path != partial_directory / name:
|
|
raise RuntimeError(f'Downloaded {downloaded_path.name!r}, expected {name!r}')
|
|
downloaded_path.rename(prepared.output_path)
|
|
except Exception as e:
|
|
logger.error(f'Download failed for {label}: {e}')
|
|
remove_rejected_partial(e, partial_directory / name)
|
|
return ExecutedSpeciesPack(region=prepared.region, error=f'Download failed: {str(e)[:500]}')
|
|
|
|
remove_old_species_packs(prepared.output_path)
|
|
logger.warning(f'Downloaded {label} ({prepared.output_path.stat().st_size} bytes)')
|
|
return ExecutedSpeciesPack(region=prepared.region)
|
|
|
|
def finalize_download(self, session: Session, download: Download,
|
|
executed: ExecutedSpeciesPack) -> DownloadResult:
|
|
if executed.error:
|
|
return DownloadResult(success=False, error=executed.error)
|
|
return DownloadResult(success=True, location='/map/manage')
|
|
|
|
|
|
def remove_old_species_packs(current: pathlib.Path):
|
|
"""Delete the other versions of `current`'s region."""
|
|
region, _ = parse_pack_name(current.name)
|
|
for path in current.parent.iterdir():
|
|
if path != current and (parsed := parse_pack_name(path.name)) and parsed[0] == region:
|
|
logger.warning(f'Deleting old species pack: {path}')
|
|
path.unlink()
|
|
|
|
|
|
species_pack_downloader = SpeciesPackDownloader()
|