Compare commits

...
Sign in to create a new pull request.

272 commits

Author SHA1 Message Date
lrnselfreliance
d34b2a7088
Add QR codes to the ATAK map sources, share one QR component (#1034)
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Dead Code / vulture (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
The ATAK tab's HTTP and HTTPS map source rows get a QR code button beside
the copy button, so a phone can scan the address and download the map
source file.

QRCodeImage, QRCodeModal, and QRCodeButton (components/QRCode.js) replace
the five copies of the night-mode-safe white field + modal used by Share,
Donate, the hotspot settings, and the QR code calculator.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:27:26 -07:00
lrnselfreliance
2c3300b8b0
Torrents over a fail-closed VPN (#1026)
Torrents reach the Internet only through a fail-closed VPN (WireGuard or
OpenVPN, any provider), so peers never see a WROLPi's own address.

- A network namespace (Pi/Debian) or the vpn container (Docker) with an
  nftables kill switch; NAT-PMP or fixed port forwarding.
- qBittorrent inside it, sandboxed; torrents kept in config/torrents/.
- Torrent download form, Torrents page, Share as torrent, nav warning, and
  VPN settings in both Controller UIs.
- Help docs: Torrents, and The VPN for Torrents.

QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:26:24 -07:00
lrnselfreliance
633b125dc6
Controller: link to the main UI on :8443 for Docker installs (#1029)
The fallback Controller UI picked the main UI's port by sniffing its own URL:
only port 8080 mapped to 8443, and any https page dropped the port. Loaded
from https://host:8443/controller/, the Continue/Proceed links pointed at
https://host/. All four links now share one base chosen by docker_mode.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:49:43 -07:00
lrnselfreliance
b372a5fc90
Bump readability-extractor 0.0.6 → 0.0.16 in npm-tools (#1028)
Also bumps @mozilla/readability 0.4.4 → 0.6.0 and dompurify 2.x → 3.x.
Same CLI and the same output keys (plus publishedTime).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:00:17 -07:00
lrnselfreliance
34eeebb8b8
Bump serve 12.0.1 → 14.2.8 in npm-tools (#1027)
* build(deps): bump ajv and serve in /npm-tools

Bumps [ajv](https://github.com/ajv-validator/ajv) to 8.18.0 and updates ancestor dependency [serve](https://github.com/vercel/serve). These dependencies need to be updated together.


Updates `ajv` from 6.12.6 to 8.18.0
- [Release notes](https://github.com/ajv-validator/ajv/releases)
- [Commits](https://github.com/ajv-validator/ajv/compare/v6.12.6...v8.18.0)

Updates `serve` from 12.0.1 to 14.2.8
- [Release notes](https://github.com/vercel/serve/releases)
- [Changelog](https://github.com/vercel/serve/blob/main/CHANGELOG.md)
- [Commits](https://github.com/vercel/serve/compare/12.0.1...v14.2.8)

---
updated-dependencies:
- dependency-name: ajv
  dependency-version: 8.18.0
  dependency-type: indirect
- dependency-name: serve
  dependency-version: 14.2.8
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update serve test pin to 14.2.8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Disable serve's per-request logging

serve 14 logs every request by default; -L keeps the journal as quiet
as it was with serve 12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:40:19 -07:00
dependabot[bot]
712c4d9abc
build(deps): bump systeminformation from 5.33.1 to 5.33.26 in /app (#1015)
Bumps [systeminformation](https://github.com/sebhildebrandt/systeminformation) from 5.33.1 to 5.33.26.
- [Release notes](https://github.com/sebhildebrandt/systeminformation/releases)
- [Changelog](https://github.com/sebhildebrandt/systeminformation/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sebhildebrandt/systeminformation/compare/v5.33.1...v5.33.26)

---
updated-dependencies:
- dependency-name: systeminformation
  dependency-version: 5.33.26
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-28 11:30:56 -07:00
dependabot[bot]
762b5ff6a0
build(deps): bump follow-redirects from 1.16.1 to 1.16.3 in /app (#1013)
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.16.1 to 1.16.3.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.16.1...v1.16.3)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-version: 1.16.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-28 11:30:53 -07:00
lrnselfreliance
ee30d99212
Map tiles for ATAK and iTAK (#1024)
* Map tiles for ATAK and iTAK

A new service, wrolpi-tiles (tiles/), draws WROLPi's map as 256 px raster
tiles from the map's PMTiles with MapLibre Native (mapli), so ATAK and iTAK
can use the map as a map source, and ATAK can download an area of it.

- Tiles are drawn in blocks of 4x4 (ATAK asks for tiles in quadtree order),
  each block once however many requests wait on it, in render processes of
  their own.  Phones are served in turn.
- A tile is always a 200: blank where there is no map, or when it was not
  drawn before ATAK's 5 second timeout.  Five failed tiles in a row stop an
  ATAK download, and a 401/403 stops the map source.
- Drawn tiles are kept in /var/cache/wrolpi-tiles, with a size cap and a
  free-space floor; JPEG, about a seventh of a PNG.
- The basemap is the web map's (protomaps-themes-base, light), kept equal
  to it by a Jest test.  Unreadable map files and missing map fonts are
  left out rather than failing every tile.
- Caddy serves it at /tiles/ over HTTPS and on port 8088 over plain HTTP
  (a phone must trust WROLPi's CA for HTTPS).  /tiles/wrolpi.xml is the
  MOBAC map source to import.
- A separate service with lower CPU priority and a memory cap, so a phone
  downloading an area cannot slow the API.  Docker runs it from the api
  image.
- The map page has an ATAK tab: the map source links, how to use them, and
  what the tile service is doing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: bound PMTiles decompression before it happens

A few bytes of a downloaded map file could decompress to far more than the
cap, which was applied only afterwards.  Decompress at most MAX_METADATA_SIZE,
as modules.map.pmtiles does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: never send a blank for a late tile; start render processes with the service

QA on a Pi 4 found the first tile after a start sent blank: starting the
render processes and the first draw took 4.5 s, past the deadline.  A
downloader (ATAK's, iTAK's) keeps whatever a tile request returns, so a
blank sent for a late or failed tile is a hole in its offline map for
good.  Such a tile is now a 503 (ATAK tries each tile twice; only 401 and
403 stop a map source), and the render processes start with the service.

Also:
- OOMScoreAdjust=500: Raspberry Pi OS disables the memory cgroup, so
  MemoryMax does nothing there; the tile service is killed before the API.
- sanic-ext's auto extensions are off in the tile service.
- The map's ATAK tab is before Manage: Manage is the last tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: put backgroundColor back in the map source; iTAK requires it

iTAK refuses a MOBAC map source without <backgroundColor> ("The data couldn't
be read because it is missing").  ATAK ignores it.  It is the map's own
background color.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: leave out the map files hidden on the Manage tab, as the web map does

maps.yaml's ignored_files names the map files the user hid; the web map
does not draw them, and the tiles drew them anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: bound the render processes' memory and the tiles-per-second times

QA on a Pi 4, a phone taking 123,000 tiles offline: each render process
grew from about 270 MB to 370 MB (MapLibre keeps what it has read and
drawn) and did not shrink when idle.  A render process is now replaced
after 2,000 blocks.  The serve times behind tiles-per-second were only
forgotten when the status was asked for; they are forgotten as tiles are
served.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map ATAK tab: iTAK takes an area offline too

An iPhone downloaded 123,000 tiles with iTAK and showed them offline with
none missing; the tab said only ATAK could.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Map ATAK tab: a button to clear the tiles the tile service keeps

POST /tiles/cache/clear on the tile service (which keeps the cache's size)
removes the kept tiles; they are drawn again when next asked for.  The
button asks first, and says that maps already downloaded to phones are not
changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: measure the cache as the disk does; clear it at once, delete in the background

QA on a Pi 4 after a 123,000-tile download: the cache counted 375 MB of tile
bytes while its files took 660 MB of the SD card (each small file takes a
whole 4 KiB block), so the 1 GB cap allowed about 1.7 GB.  The cache is now
measured in disk blocks.

Clearing deleted 128,000 files in the request: about 40 seconds, with the
Pi's load warning on.  A clear (or a new style) now renames the tiles out of
the way at once and deletes them in a lowest-priority thread, pausing every
500 files; a deletion cut short is finished at the next start.  A tile drawn
again no longer counts twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Help: ATAK and iTAK

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: a page on port 8088 saying what it is

A person who finds port 8088 got a 404.  / (and /tiles/) is now a short page:
WROLPi's map tile service for ATAK and iTAK, the map source to open on a
phone, and links to the WROLPi app and the map's ATAK tab, made from the
address the page was reached by (Docker publishes the app on
TILES_HTTPS_PORT).  Port 8088 serves WROLPi's icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tiles: review fixes

- Caddy: a tile request is never redirected to the fallback page when the
  tile service is down or restarting (handle_errors on 443).  ATAK keeps
  whatever a tile request ends with, so the page was stored as the tile;
  it is now a 503 with Retry-After, which ATAK tries again.
- The cache's oldest tiles are found and deleted in a lowest-priority
  thread, pausing as it goes, not in the tile request which filled it.
- ATAK tab: only the newest status request writes the status, so a slow
  answer can not undo a newer one (or a clear).  It says when the page was
  opened on localhost and the addresses work only there, and names each
  map source as the app lists it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:21:45 -07:00
lrnselfreliance
92761e1c52
README: the food storage calculator is available (#1025)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:10:25 -07:00
lrnselfreliance
2db9e45d92
README: sync and backup are available (#1022)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 19:06:19 -07:00
lrnselfreliance
68d8eadd69
Fallout winds: make the daily download at 23 past the hour (#1020)
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Dead Code / vulture (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
Daily downloads are spread over the day in slots which fall on the hour, when the
forecast service is busiest.  On .5 its TLS handshake stalled for minutes there,
failing the download.  The weather downloader now schedules its next run itself, a
day later at 23 minutes past the hour.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 17:23:54 -07:00
lrnselfreliance
f58c86af88
Fallout winds: retry a batch once when the forecast service can't be connected to (#1019)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
A connection failure on any batch failed the whole daily download, discarding the
batches already fetched and deferring the field to the next day.  A batch which can't
connect is now asked again a minute later, once, as an HTTP 429 already is.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:03:14 -07:00
Roland
4c9f413322
Bump version to 0.33.0-beta
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
2026-11-25 17:35:11 -07:00
lrnselfreliance
fcd9f1bc40
Help: the fallout simulator (#1018)
* Help: the fallout simulator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Help: screenshots of the fallout simulator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:31:34 -07:00
Roland
b57f64ee71
Bumping yt-dlp requirement.
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
2026-11-25 14:06:30 -07:00
lrnselfreliance
45a8fefe48
The map's right-click menu takes the theme's colors (#1017)
It was drawn white with grey text in every theme, so in Dark its text was faint and the menu
stood out from the map's other panels.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:44:45 -07:00
lrnselfreliance
3ae978dc53
Fallout: say a forecast's last hour is held only when it is; check kept climatology months (#1016)
The winds follow the burst hour chosen, so an out-of-date forecast's last hour is held for the
whole simulation only when it is the hour chosen; otherwise from when the chosen hour's 48 hours
pass it, or not at all.  The panel now says just that, and says separately that the forecast is
out of date.

A kept climatology month is hashed against its pinned sha256 before it is listed or served (again
only once it changes); one that is not what is expected is fetched again.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:19:45 -07:00
lrnselfreliance
d4d288f84a
A fallout simulator on the map: nuclear mode, targets, live winds aloft (#1007)
* A fallout model, checked against six Nevada tests

The local fallout of a surface burst lands where layered winds carry particles of every size
from the stabilized cloud.  Cloud and particle sizes come from DNAF-1, WSEG-10 and DELFIC;
the air is the 1976 standard atmosphere.  The six shots' wind profiles, measured contour
areas and plume bearings are in nts-shots.json with their sources, alongside HPAC's
predictions of the same contours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A prototype fallout panel on the map

Right-click "Simulate Fallout Here" draws the dose rate at H+1 of one surface burst, in one
wind or in the winds aloft of one of the six Nevada tests.  Nothing is saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout lands where it meets the ground

A particle stops falling at the first level where it is at or below the ground under it, not
at a plane at the height of ground zero: early on a ridge in its way, later in a valley.  The
map panel reads the ground from the terrain files the user has downloaded; the Nevada tests
are checked against a small elevation grid of Mapterhorn terrain, as WROLPi publishes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout falls from the cloud's cap, skirt and stem

The cloud of a surface burst holds 77.5% of its activity in the cap, 15% in a skirt below it
and 7.5% in the stem (Philippe et al.); the stem starts as narrow as the early fireball at the
ground and widens up to the cap (DNAF-1).  More of the fallout lands near ground zero: a 1 Mt
burst now draws a 1000 R/hr contour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Close-in fallout measured after three Nevada surface bursts

Jangle Sugar, Small Boy and Johnie Boy, from DNAF-1's Table 3: the area, hotline length and
azimuth of each contour from 35 to 1000 R/hr, as observed and as DNAF-1, DELFIC and WSEG-10
predicted them, with each shot's winds.  The deposition grid can look closely at part of the
fallout, and measures hotlines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout rises with the cloud, and heavy particles drop out low

All of the activity starts in the early fireball and rises with the cloud, whose base and top
climb with the square root of time (SIMFIC).  Each particle rises with the air less its own
settling speed, so a heavy one leaves the cloud low and early and lands near ground zero, and a
light one rides to the top.  A burst above the ground puts down less, by its scaled height.

Against the close-in fallout of Jangle Sugar and Small Boy this is within 2.4x in area and 1.7x
in hotline length (it was 100x short); across the six Nevada tests, 4.2x a priori (it was 8.9x).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel offers the weapons in service today

Weapons deployed or stockpiled by each country, each with its yield quoted from the 2025-2026
Nuclear Notebook or SIPRI Yearbook, and the improvised devices FEMA plans for; no retired or
historical weapons, and none whose yield no source gives.  Variable-yield weapons have one entry
for each published setting.  Fission shares are not public; they are assumed as Glasstone and
Dolan plan for, and the user may change them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's dropdowns open above it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A variable-yield weapon is named once, with each setting's yield beside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel uses the forecast winds aloft

WROLPi fetches, on request, Open-Meteo's hourly forecast of the wind at nineteen pressure levels
(about 100 m to 24 km) and the rain, for the whole degree around the burst: the place is rounded
before it is sent.  The forecast is kept, so the panel can use it offline.  The panel picks the
hour nearest now, gives the forecast's age, and warns of rain, which brings fallout down in places
the map does not show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A nuclear mode on the map: targets, and fallout

A radiation button under the print button turns nuclear mode on and off.  In it, targets (likely
detonation sites) are shown alongside the pins, a pin added is saved as a target, and fallout can
be simulated at a target or anywhere on the map.  A pin's kind is kept in map_pins.yaml; a pin
without one is a plain pin, as every pin was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Targets keep their weapon, and nuclear mode shows the fallout of all of them

A target keeps the weapon chosen for it (or a yield of the user's own) and its fission share in
map_pins.yaml.  Nuclear mode opens on the fallout of every saved target at once, in the forecast
winds aloft fetched most recently; a burst tried out from the map can be saved as a target.

A whole-degree latitude or longitude, which a browser sends as an integer, is a valid pin, and a
pin's label and color may be left out of an update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An improvised device is named once, with each yield beside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout of many targets is calculated in seconds, and shown as it goes

A particle size's settling speed is read from a table by altitude rather than solved again for
every fall of every burst (a burst: 40 ms to 6 ms).  The view yields to the page only every 40 ms,
through a message channel, which a browser does not hold back in a hidden tab as it does timers;
it says how far it has got, and draws the fallout on flat ground while the terrain is read.

A target in the list shows its weapon, and is given a weapon picker when asked; one picker sets
every target's weapon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout grid covers where fallout shows, not past the poles

The faintest particles of a burst are carried thousands of km in two days; with many targets the
grid stretched past 90 degrees and the map refused the image ("Invalid LngLat latitude").  The grid
now covers the spots which can reach the faintest band drawn, the image's corners stay within
Web Mercator's 85 degrees, and so does the area whose terrain is read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout across a continent is drawn where it lands

The map stretches an image evenly in Web Mercator between its corners, but the fallout grid's rows
are evenly apart in latitude; over tens of degrees (targets across a country) they part ways, and
the southern part of the image was drawn far from its targets.  Each image row now takes the grid
row at its own latitude.  A burst far from the first target keeps its plume as wide, east to west,
as at its own latitude.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Terrain across the antimeridian, and ground with no number, do not break the fallout

Targets in Alaska and Hawaii carry fallout west of 180 degrees, where the terrain's tile arithmetic
read past the tile's pixels; one sample with no number made every target's lowest ground NaN and
every spot fall off the map, and the grid's size Infinity.  Longitudes wrap, a sample with no number
is left out (of the lowest ground, and of the elevation between samples), and a spot not on the map
is left out of the grid rather than breaking it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Every target's weapon is set in one change

Setting it target by target, eight at once, lost most of the changes: each request wrote the whole
pin list, undoing the others (QA: 47 of 156 changed).  PUT /api/map/pins/targets/weapon gives
every target the weapon in one change of the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The every-target weapon picker starts empty and always applies

It showed the first target's weapon, so choosing that weapon for all of them did nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout is carried by the winds where it is, region by region

A field of forecasts on a grid over the targets replaces the one forecast for
all of them. Each particle rises and falls through the wind at its place,
height and hour, read between the surrounding grid points, hours and heights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The winds aloft are fetched as a Job, ninety places a minute

The free forecast service allows 600 calls a minute and a place costs six, so
a field of up to 540 points is fetched in paced batches by a Job, which the
fallout panel follows, instead of inside one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A small burst's hot fallout is kept on a grid over many, and the panel says what it shows

- Each burst's narrow close-in fallout is also put on a fine grid, so the
  lethal zone of a small target is not averaged away in the cells kilometers
  wide of a grid over targets far apart.
- The legend says the dose rate is as at one hour, with all the fallout down,
  and what R/hr is; the error quoted is the unscaled model's.
- The TNA's yield is 150 kt: its source gives only an upper bound below 300.
- Weapons show their fission share beside their yield.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout can be watched landing, hour by hour

A timeline under the legend plays, or steps through, the 48 hours after the
bursts: each hour shows only the fallout which has landed by then, at its
dose rate then (t^-1.2 from H+1), on the same cells as the whole of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The map can show the total dose of someone outdoors, hour by hour

A "Show" picker switches from the dose rate to the total dose (R) someone
outdoors gets from when the fallout arrives: t^-1.2 added up from each spot's
arrival to the hour on the timeline, or over the first two weeks. Its bands
say what each dose does to a person.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The model is checked against the Army's fallout manuals

- FM 3-3-1's worked decay and dose problems are tests.
- FM 3-11.3's cloud and Zone I nomograms, read from their images, are a
  fixture; the model's cloud top is within 10% of them from 1 kt to 10 Mt,
  and its Zone I within 0.7-1.7 times from 10 kt to 1 Mt, the yields of
  modern weapons, which the test shots do not reach.
- The legend says real fallout may decay faster or slower than usual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The model is checked against two megaton bursts in the Pacific

Redwing Zuni (3.5 Mt), whose winds were measured above its cloud: the hot
fallout goes where it went and about as far. Castle Bravo (15 Mt), whose
winds were measured only below its cloud: its fallout arrives when it did,
and its hot fallout reaching a third as far is kept in view as a known gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Winds are read from the right points at every spacing, and cover the landing

- A field's points were filed by rounding (lat + 90) / spacing but looked up
  by flooring it: at 4 and 8 degrees, which do not divide 90, every point read
  half its neighbor's wind. Both now count whole spacings from the equator.
- The forecast starts at midnight UTC, so two days could end before the
  fallout of a burst this hour was down; three are fetched (the same call
  weight), and the panel says when the last hour's winds are held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bravo's known gap is not its unmeasured upper winds

Reanalysis winds above the 1954 sounding turn the plume to within 10 degrees
of the measured one but do not lengthen its hot contours; the fixture's caveat
and the test's explanation said otherwise, and now say what was found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rain takes fallout out of the air where it falls

A falling particle in rain loses a share of its activity every step: fast
inside the rain cloud ("rainout"), slower below it, by how hard it rains
("washout"), at Glasstone and Dolan's rates (Tables 9.74a and b), and none
above it. What is taken out comes down where the particle was. The forecast
now asks for relative humidity at 14 levels, and each hour's rain cloud is
taken as HYSPLIT takes it: from the lowest level 80% humid to the first above
it less than 60%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* With no forecast, the fallout of 30 past days of the month

- wrolpi/scripts/build_fallout_climatology.py builds, from NOAA's reanalysis,
  the winds aloft of 30 days of each month (one from each year 1991-2020) over
  the whole world: a gzip file a month, about 4 MB, for the release download
  location.
- WROLPi fetches the months it lacks once, while there is the Internet, each
  checked against a sha256 pinned in modules/map/climatology.py (none pinned
  until the files are published), and serves them to the panel.
- The panel's "Past days of a month" wind runs the bursts in each day and shows
  on what share of the days each place had the chosen dose rate; it is chosen
  for us when there is no forecast, or it has run out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The climatology's months are published, and their sha256 pinned

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The climatology worker waits for the Internet and the drive on startup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Counting the past days says flat ground at once, not the forecast's terrain

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Past days' fallout reuses each yield's paths, about 10 times faster

On flat ground in a day's held winds, how each parcel rises with the cloud
and falls does not depend on the wind, so it is worked out once per yield
and kept for every burst and day.  The rising cloud is carried by the winds
over ground zero (it drifts about 10 km); the fall still reads the winds
where the particle is.  A field of one hour is read without its hours, and
the nearest point to a cell past the field is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The rising cloud reads the winds over ground zero from arrays, by level

Each parcel's rise is kept as the levels of the column it passes through
(steps in the same level as one) and their seconds, so a burst reads the
column once and sums.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel shows a progress bar while it calculates

At the top of the panel, filled as far as the bursts are done, or moving
without a count until there is one.  A calculation stopped by removing the
last target no longer leaves the panel busy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Past days' fallout runs in Web Workers, with a Cancel button

The days are spread over workers, one for each core but one (left for the
page), at most 6, and at most 2 where the browser says it has 2 GB or less.
A worker is given the next day as it finishes one, and sends back only the
cells reached.  Where workers cannot be made, or fail, the days are
calculated on the page as before.

The days are counted on cells as wide as the coarsest day's grid, so the
count does not depend on which day finishes first.

Cancel, beside the progress bar, stops a calculation (and its workers) at
once; Calculate starts it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast's bursts are spread over Web Workers too

The workers now take any task: a past day, or a burst.  The page and the
workers build each burst's winds and terrain with the same functions
(work.js), so the fallout is the same either way; the flat pass and the
terrain pass each run on their own workers, and Cancel stops them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The bursts' grid is made in parts by the Web Workers

The grid is a sum over the bursts' spots, sharpened by the most any burst
raises a cell, so it is made in a fixed number of parts (a burst's spots
in one) on one frame, and joined on the page.  The page makes the same
parts when there are no workers, so the grid is the same either way.

The forecast's warnings (bursts outside the winds, rain) are no longer
worked out again on every progress update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast's hours are labeled once an hour, not on every progress update

Writing each hour's label (toLocaleString) took most of the page's time
while the workers calculated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Faster forecast fallout: the nearest point outside the field, progress, and what workers are sent

- Outside the forecast's field, the nearest point is looked for only
  among the points which can be nearest somewhere in the grid cell (kept
  for each cell); the same point as looking through them all.  Longitudes
  are wrapped however far round the world a particle is carried.
- The progress is shown at most ten times a second.
- The workers are sent the forecast's arrays, not the forecast as fetched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel in steps: the targets, then the fallout hour by hour or in total

Nuclear mode opens on the targets; nothing is calculated until the user goes on.
The winds and terrain wait under Options, with what is used said beside it.
The timeline runs from the first hour to two weeks, saying how much the fallout
has weakened since H+1; the view of all the fallout as if landed at H+1 is gone.
Going back and on again with nothing changed draws what was calculated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's winds: the forecast, past days, or one wind; no test shots' winds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's wind is a step of its own, between the targets and the fallout

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel says it is an estimate; how it compares with the test bursts goes in the help

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Targets are tried out until saved; the saved ones are loaded first, and saved all at once

Nuclear mode starts with no targets.  Targets added are tried out, and the saved
targets join them when the user loads them.  Saving replaces the saved targets
with the list, in one change, and is refused until they were loaded (or there are
none), so none are lost unseen.  A target can be taken out of the list.  The
burst tried out from the map's menu is gone: a target tried out does the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Nuclear targets are kept in their own config, map_nuclear.yaml, and listed apart from the pins

The pins are plain pins again.  The targets have their own endpoints, and their
own table on the Pins tab, where one can be deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The rest of keeping nuclear targets in map_nuclear.yaml: the config, its endpoints, and the table

The commit before this one was missing these files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's wind is the forecast when it has the winds until the fallout is down, else one wind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The weather is a subscription: a forecast around the saved targets, downloaded every day

The Open-Meteo fetch is a recurring Download (daily) instead of a Job the panel
starts.  The Manage tab has a Weather section: turning it on or off, what it
downloads, how its downloads went, and the forecast kept.  Only the newest
forecast is kept, and it covers four days.  The wind step asks the user to turn
the download on, and warns, there and beside the fallout, when the forecast runs
out before the fallout is down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast service may take three minutes to answer, and a timeout says so

A batch of four days' forecasts took 43 seconds, near the old 60-second limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's targets step has an Add a target button: the next click on the map places it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:01:41 -07:00
Roland
72b507116e
Bump version to 0.32.0-beta
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Dead Code / vulture (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 17:29:01 -07:00
lrnselfreliance
faf8e735d1
A map is exported as a PDF: a 1:24,000 quadrangle, in layers, on a sheet, which says where it is (#1006)
* The map can choose a 1:24,000 quadrangle to export (#971)

The first part of exporting a map as a PDF: a grid of 7.5-minute quadrangles is drawn over the
map, and a click chooses one.  The grid is arithmetic, so it needs no data.  Exporting itself is
not here yet; the button is disabled.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A quadrangle of the map is exported as a PDF with a layer for each map layer (#972)

* A quadrangle of the map is exported as a PDF with a layer for each map layer

The browser draws the quadrangle off the screen at the size of a 1:24,000 sheet, once for each
layer which is on, and the API puts the images in a PDF, each in a layer of its own which a
reader can show and hide.  A layer in which nothing is drawn is left out.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The exported map's canvas keeps what was drawn, and an export's memory is bounded

- The drawing buffer is asked for where this MapLibre reads it (canvasContextAttributes); as an
  option of the map it was ignored, so the canvas could be read after it was cleared.
- Each layer's pixels are compressed in the PDF as the layer is added.  PyMuPDF kept them
  uncompressed until the PDF was written: about 90 MB a layer of a quadrangle, all at once.
- The pixels of all the layers together are limited, before any image is decoded.
- pymupdf is imported when a PDF is made, not when the API starts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map says where on the Earth it is (#973)

* An exported map says where on the Earth it is

The PDF's page has a geospatial viewport (ISO 32000-2): the page is the map in Web Mercator,
with the latitude and longitude of each corner.  The corners are the edges of the picture the
browser drew, read from the map which drew it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A map whose edge is the antimeridian can be exported

The map's arithmetic puts the east edge of the last quadrangle before the antimeridian a rounding error past
180 degrees, and the export was refused.  An edge within 1e-8 of a degree of 180 is at 180 (it is not wrapped
to -180); a map which is really across the antimeridian is still refused.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map is on a sheet: a margin, a grid, scale bars and notes (#974)

* An exported map is on a sheet: a margin, a grid, scale bars and notes

The map is put on a larger page with what a topographic map has around it: a title, the latitude and longitude
of its corners and of ticks between them, scale bars (kilometers, miles, feet), and notes of the projection, the
grid and where the map's data is from.  Over the map is a 1,000 meter UTM grid, each line named in the margin.

The grid and the margin are PDF layers of their own.  The PDF says where the map is, not where the page is.  The
picker has a box to export the map alone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The scale of a narrow map is written under its name, not over it

A quadrangle near a pole is two inches wide, which is not room for its name and its scale on one line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map says where a compass points (#975)

* An exported map says where a compass points

The sheet has a diagram of the three norths (true, grid and magnetic) beside its scale bars, and a note of how
far magnetic north is from true north on the day the map was made, and how fast it moves.

The declination is from the World Magnetic Model 2025 (NOAA NCEI and the British Geological Survey; public
domain), whose coefficient file is shipped: nothing is downloaded.  The model is good until 2030; outside its
years nothing is said of a compass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A corner of an exported map is not also a tick

The edges of the picture the browser draws are a hair outside the quadrangle's, so the quadrangle's own edges
were taken for ticks inside the map, and each was written over the coordinate of its corner.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A compass which passes due south has moved a little, not most of the way around

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A map can be exported at 400 DPI (#976)

The picker has a choice of 300 or 400 DPI.  A map is drawn less sharp than was asked for, rather than refused,
when it would be more pixels than the API makes a PDF of: a quadrangle near the equator, or one with many layers
on.  The picker says so while it draws.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported quadrangle goes by the name the USGS gives it (#977)

* An exported quadrangle goes by the name the USGS gives it

The picker says what the chosen quadrangle is called, and the sheet's title, the PDF's title and the file's
name have it.  Where the USGS has no name, which is most of the world, a quadrangle goes by where it is, as
before.

The names are an index of the 65,600 7.5 minute quadrangles of The National Map (U.S. Geological Survey; public
domain), which is shipped: nothing is downloaded.  In Alaska a USGS quadrangle is wider than 7.5 minutes, so a
quadrangle of the picker's grid there is "Part of" the one which has its middle.

The places the tests of the map export are of are changed for others.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An area half of which is the last quadrangle of the land is a part of it

The middle of such an area is on the quadrangle's east or north edge, with no quadrangle beyond it, and it was
given no name.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* The PDF of a map is made by a Job, which the browser watches (#978)

* The PDF of a map is made by a Job, which the browser watches

A PDF of a quadrangle is a minute or two of work on a Raspberry Pi 4, and the request which waited for it was
cut off after a minute: only the smallest quadrangles could be exported there.

Now the browser describes the map, sends the image of each layer in a request of its own, and starts a Job; it
watches the Job, shows how far along it is, and fetches the PDF when the Job is done.  Cancel stops the Job.
The images are kept on disk until the PDF is made of them, and an export is removed when it is an hour old.

The credits on the sheet are no longer cut off: an attribution which names many sources is each of them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A cancelled map export stops, and is removed

- A cancelled Job is not over until the thread making the PDF has stopped, so the next Job does not start beside
  it; the work can also be stopped while the sheet is drawn and the PDF written.
- DELETE /api/map/export/<id> stops an export at any step and removes what was sent; the browser calls it when
  the person exporting cancels, while layers are sent as well as while the PDF is made.
- An export whose Job is waiting or running is not removed for being old; one whose Job was cancelled is removed
  at once.
- Cancel while the map is drawn stops the drawing between two layers.
- Exports are kept in a directory made for this user alone, which is refused when it is a link or is another
  user's; only what is an export there is removed.
- A request for the finished PDF which is lost is made again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An overlay's areas and lines go under the map's labels, and its own labels over them (#979)

An overlay was drawn whole over the basemap, so an area it filled covered the names of what is in it.  Labels are
now always on top: the areas, lines and pictures of every overlay are under the basemap's labels, and the text,
icons and points of every overlay are over them.  It is so in the map, the standalone viewer, and an exported PDF,
where an overlay with both is two layers ("Towers" and "Towers (labels)").

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An overlay's ground is over the ground of every basemap file (#980)

* An overlay's ground is over the ground of every basemap file

On a map of several basemap files, the ground of an overlay was put before the first label of the first file,
which is under the land, water and roads of every file after it: an overlay's areas and lines were hidden, and
in an exported PDF its layer was just above the background.  It goes where the basemap's labels begin: the first
of the labels which are over all of the basemap's ground.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The labels of every basemap file are over the ground of every file

A map of several basemap files was their layers one file after another, so only the labels of the last file were
on top: the labels of the others were under the land, water and roads of the files after them, and under the
ground of an overlay.  Both viewers now draw the ground of every file and then the labels of every file.

The contour lines are drawn after the basemap's labels and are not of the basemap: an overlay's ground goes under
the basemap's labels, not under the contours instead.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* Contours are drawn from as deep as the terrain file goes (#981)

The map read a terrain file to zoom 8, which is how deep the terrain WROLPi offers goes, however deep the file
was.  It now reads a file as deep as the file says it goes, in both viewers, and draws finer contour lines from a
deeper file: every 40 feet (or 20 meters) from zoom 11, as a 1:24,000 sheet has.  A file which goes to zoom 8 is
drawn as it was.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map names its small roads (#982)

* An exported map names its small roads

A quadrangle is drawn at about zoom 13.  The basemap's style names small roads
from zoom 15, and its tiles have no names for them below zoom 14, so the streets
of a town were printed as lines with no names.

Before the map is drawn, the tiles of zoom 14 which the quadrangle is in are
read, and the roads in them which have a name are given to the export map as a
source of its own.  The layer which names small roads draws from that source, as
its style says to.

At the scale of a sheet most streets are shorter than their names, and a map
writes a name along a line only where the line is longer.  Such a road is named
over its middle, turned as the road goes; a road in pieces is named once.

A source whose tiles can not be read is exported as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The names of small roads are placed by the export, at every latitude

A quadrangle nearer the equator is drawn at a little over zoom 14, where the
names were not read and the style still kept them for zoom 15: such a map had
no names of small roads.  They are now read wherever a layer would not name
roads.

Every name of a small road is now a point: over the middle of its road, turned
as the road goes under it, again every 400 pixels of a long road.  Before, a
road long enough was left for the map to name along its line, which the map
often does not (the line bends, or is in pieces), and a short piece beside it
was named too.  One place decides where a road is named, so a road in pieces is
named once, and a piece of another kind of road does not take the name.

Reading the names can be cancelled.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A sheet has a bar of meters, its norths in mils, and how far apart its contour lines are (#983)

Under the map are bars of kilometers, meters, miles and feet.

How far the grid's north and a compass's north are from true north is written in
mils as well as in degrees, in the diagram and in the notes: a compass may be
marked in either.

A map which is exported with its contour lines says how far apart they are
(CONTOUR INTERVAL 40 FEET), under the bars.  The browser knows: it is the
interval of the tiles the lines are made for at the zoom of the sheet, in the
unit the map measures in.  It says so with the sheet, and what is not an
interval is not written.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A sheet says what the quadrangles around it are called (#984)

* A sheet says what the quadrangles around it are called

Under the scale bars is a diagram of nine squares, the map the middle one, and
beside it what the USGS calls each of the eight around it: the sheets to print
to carry on off the edge of this one.

The names are from the index of quadrangles which names the sheet itself.  A
quadrangle with no name (out to sea, or over a border) has no number; a map of
where the USGS names nothing, and a map too narrow for the diagram, go without.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A sheet is never beside itself

Where a quadrangle of the USGS is wider than the map (Alaska), the area the
size of the map to its east or west is often more of the quadrangle the map is
in, and the diagram named the sheet as its own neighbor.  The quadrangle on a
side is now the next one which is not the map's own.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A sheet has a legend of the lines of its map (#985)

* A sheet has a legend of the lines of its map

Under the scale bars is what each kind of line of the map is: highway, major
road, minor road, path, railway, boundary, contour and index contour, each a
piece of the line as the map draws it, on the color of the map's land.

The map's style says how a line is drawn at each zoom, and a sheet is drawn at
one.  The browser, which has the style, says what each line's color, width,
dashes and edges are at that zoom; the API draws them.  A line is in the legend
when its layer is exported and draws something at that zoom.

What the browser sends is made into lines before it is kept: what is not a line
is left out, and the map is exported.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A legend has no line too thin to see, and no name longer than its room

A style brings a line in from nothing as the map is zoomed in: a path is a few
hundredths of a point wide on a quadrangle near the equator.  It was in the
legend, drawn several times wider than on the map.  A line under a tenth of a
point is now left out, by the browser and by the API.

What a line is called is cut to the room beside its line, as the name of an
adjoining quadrangle is.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* Fixes to the map PDF export: wrong neighbors, leftover exports, exports which outlive the map (#989)

* A sheet names what is around it, and its edges, by where they are and not a hair from there

The edges the browser gives of a map are a hair outside its quadrangle.  The quadrangles around a map whose
middle is on the edge two share (every other map of Alaska) were those around the map west of it, and one of
them was the map itself.  An edge a hair south of the equator was 0 degrees south, a map which ended where the
UTM zones do had no grid, and a sheet dated in the last year there is could not be made.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An export is removed when it is over, and its work stops when the API does

The images and the PDF of an export were kept until the next export began, however long that was.  The browser
now has the export removed however it ends, and old exports are removed when a PDF is made too.  The work of a
Job which ended because the API was stopping went on to the end of the PDF, with the API waiting for it.  What
is said of an export, and each image, is written whole.  Text which is no text is taken out when an export
begins, not found by the Job.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An export stops with its map, and waits for a page which can not be seen

Leaving the map while it was exported left the export going, to fail or to hand a PDF to another page; so did
closing the picker, which is now left open.  A PDF which arrives after the export was stopped is not saved.
The time a page is behind another tab is not counted against a map which is drawing.  The name of a road is
one line.  A photograph which ends a little inside the map is not made a JPEG with a black strip.  An accent
in the name of a quadrangle is not a gap in the name of its file.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A PDF is not kept from who made it by a server slow to remove the export

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map has its water over its parks (#990)

* A sheet names what is around it, and its edges, by where they are and not a hair from there

The edges the browser gives of a map are a hair outside its quadrangle.  The quadrangles around a map whose
middle is on the edge two share (every other map of Alaska) were those around the map west of it, and one of
them was the map itself.  An edge a hair south of the equator was 0 degrees south, a map which ended where the
UTM zones do had no grid, and a sheet dated in the last year there is could not be made.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An export is removed when it is over, and its work stops when the API does

The images and the PDF of an export were kept until the next export began, however long that was.  The browser
now has the export removed however it ends, and old exports are removed when a PDF is made too.  The work of a
Job which ended because the API was stopping went on to the end of the PDF, with the API waiting for it.  What
is said of an export, and each image, is written whole.  Text which is no text is taken out when an export
begins, not found by the Job.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An export stops with its map, and waits for a page which can not be seen

Leaving the map while it was exported left the export going, to fail or to hand a PDF to another page; so did
closing the picker, which is now left open.  A PDF which arrives after the export was stopped is not saved.
The time a page is behind another tab is not counted against a map which is drawing.  The name of a road is
one line.  A photograph which ends a little inside the map is not made a JPEG with a black strip.  An accent
in the name of a quadrangle is not a gap in the name of its file.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map has its water over its parks

A layer of the PDF was one image, drawn where the topmost of its layers is.  The parks of Land Cover are under
the water on the map and its piers are over it, so all of Land Cover was drawn over the water: a lake in a
park, or among houses, was not on the PDF.  A second basemap file put its water over the first's buildings.

A layer is now as many images as it must be, each where it is on the map, in one layer of the PDF: a part
which fills an area stays where it is, and a part which is only lines is drawn with the next.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A PDF is not kept from who made it by a server slow to remove the export

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A map file which is of somewhere else is not drawn when a map is exported

Each basemap file is several images of an exported map, and most files of a library are of other places: each
was an image of nothing, counted against how many images an export may be and how sharp it may be.  A file
whose own edges are outside the quadrangle is now left out before the layers are counted.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map has its streams (#991)

A basemap draws streams from zoom 14, and service roads and taxiways from 13.  A quadrangle is drawn a little
short of that (zoom 13.8 at 40 degrees, 13.2 at 61), from tiles which have them: none were on the PDF.  What
is drawn from a zoom no deeper than a quadrangle's detail is drawn.  Names are left as they are.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An export which is cancelled stops at once, in the middle of a request (#993)

* An export which is cancelled stops at once, in the middle of a request

An export was stopped between two requests.  The image of a layer is tens of megabytes, which is a long request
on a slow connection, and a request to a server which has stopped answering never ends: the export said it was
stopping until then.  Cancel, and leaving the map, now end the request.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The requests an export makes after its layers are sent are seen to be stopped too

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A map is exported as it is printed: on white, in dark lines (#996)

* A map is exported as it is printed: on white, in dark lines

The light and dark maps are made for a screen.  On paper their roads are white on pale gray and their streams
half a pixel of pale blue.  The printed map is a third look, of the map's own: white ground, dark road edges
and names, blue streams wide enough to see, paths drawn, brown contours.

It is what a map is exported in unless Light or Dark is chosen where the quadrangle is, and the choice is
remembered in the browser.  While a quadrangle is chosen the map is shown in the look it will be exported in.
The light and dark maps are as they were.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* Changing the look of the map does not move it

What is done when a new style is in place was asked for after the style was set.  A style which only differs
from the one the map has is in place before that, so it was done at the next change of style instead, with
where the map had been at this one: the map went back there when a quadrangle was chosen, and again when it was
not.  It is asked for first, and the map is not moved at all.  An export no longer waits for the map to be
still, which it need not and which nothing ended.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* The colors of the printed map are chosen where its layers are (#997)

* The colors of the printed map are chosen where its layers are

While a quadrangle is chosen and the map is shown as it is printed, each layer of the layer control has its
color beside it, to be changed: one for most, three for the land (what grows, what was built, sand and ice)
and two for names (the name, and what is around it).  A basemap has several colors where one is chosen, which
are shades of it.  The edge of a road stays dark.  What is chosen is remembered in the browser, and can be put
back.  The map on the screen is as it was.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A ramp on a bridge is the color of a major road, as it is off one

A basemap draws a ramp on a bridge in the color of a minor road on a bridge: on the printed map it was white
where the rest of the ramp is yellow, and followed the color chosen for minor roads.  What puts the colors
back is a button, which a keyboard reaches.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* A layer with nothing in it does not make an exported map less sharp (#1001)

* A layer with nothing in it does not make an exported map less sharp

How sharp a map may be depends on how many images it is, and every group of layers was counted: a basemap
file with no runway, highway or boundary in the quadrangle was images of nothing, drawn, sent, and counted
against the rest.  A map of 23 images asked for at 400 DPI was made at 330.  The groups are now looked at
first, on a small map, and only those with something in them are drawn, as sharp as that many may be.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* An image which arrives after its export was removed is not kept, and one mil is a mil

Stopping an export while an image was on its way left the image behind it, in a directory nothing would
remove for an hour.  An angle of one mil was "1 mils" on the sheet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* The map which is exported from is made as sharp as it is to be (#1002)

* The map which is exported from is made as sharp as it is to be

The groups of a map are looked at on a small map, which was then made larger to draw them.  A browser lets
a canvas be larger when it is made than it lets one be made larger afterwards: a quadrangle asked for at
400 DPI was 33 million pixels, 288 DPI at 40 degrees, less than before the groups were looked at first.  The
small map is now removed, and the map which is exported from is made in its place.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A canvas the browser stopped drawing on is not a layer with nothing in it

A canvas whose drawing was taken away by the browser reads as clear, and a group looked at then was left out
of the PDF without a word: the export fails instead.  An export stopped as the last group is looked at does
not make the map it would have been drawn on.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* An exported map says where it is in a projection Adobe Acrobat knows (#1003)

* An exported map says where it is in a projection Adobe Acrobat knows

The page was said to be in Web Mercator, which it is drawn in.  Acrobat does not know Web Mercator, in the
words of the standard or in Esri's: it took the page for a map, and put every place on it at 0, 0.  The page
is now said to be Mercator on the WGS 84 ellipsoid, which it reads, with the same corners.  Between the corners
the two differ by under three centimeters on the ground.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* How well a page is said to be where it is, is measured from what the PDF says

The test of it measured two formulas of its own.  It now reads the corners and the projection from the PDF and
does a reader's sum with them.  The few centimeters are of a quadrangle: a taller page is less well said, by
the square of how tall it is, which the comment now says and a test measures.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

* The help says how a map is exported as a PDF (#1004)

The help of the map is five pages, one of them the PDF export.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 17:22:31 -07:00
lrnselfreliance
d157057d81
Help: Sync (a secondary WROLPi) and the backup drive's trash (#1000)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
The final part of replacing the sync: the help documents it.  A new Sync page; Backup rewritten around the backup
drive and its delayed delete (it taught a hand-made rsync job over SSH); sync.yaml and sync_state.yaml in How
Configs Work.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:16:38 -07:00
lrnselfreliance
a5ab01198b
The backup drive keeps deleted files for 30 days, then removes them (#999)
* The backup drive keeps deleted files for 30 days, then removes them

The fifth part of replacing the sync.  A backup drive never deleted anything, so it grew forever and kept every file
the media directory had ever held.  Now, like a secondary:

- A file deleted from the media directory, or the old version of one that changed, is moved to a dated folder in
  .backup-trash on the backup drive.  Folders older than backup_delete_after_days (sync.yaml; 30 by default, also
  for drives set up before this; none never deletes) are removed, before and after each backup, and the oldest go
  sooner when the drive is nearly full.
- A backup refuses a media directory that is not mounted, or has no config/wrolpi.yaml: copied with deletes, an
  empty folder would move the whole backup drive to the trash.
- The Backup Drive panel has the same "Delete after N days / Never delete them" control as the Sync panel, now one
  component, and refuses an empty number of days.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A nearly full drive keeps the trash it just filled, and makes room for the database

Review found, in the backup drive's trash and in the secondary's sync, which share its shape:

- Below 1 GiB free, the purge after a copy removed the newest trash folder too.  Moving a file to the trash is a
  rename, which frees nothing, so on a nearly full drive a deleted file was gone at the end of the same run instead
  of 30 days later.  The newest folder is now only removed by age (0 days still deletes at once).
- The purge made room only down to 1 GiB, so a database larger than the free space failed to be copied every time
  while the trash was full.  Before the database is written (the backup's snapshot, the secondary's copy of its
  primary's), the trash now makes room for the whole database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:50:21 -07:00
lrnselfreliance
38885990f6
The old sync engine is removed (#998)
* The old sync engine is removed

Part 4 of replacing the sync.  Since the previous part a secondary copies its primary with rsync, run by the
Controller, so nothing used the HTTP engine any more:

- the manifest (/api/sync/manifest), the download of a FileGroup's files over HTTP, the copy and import of each
  synced config, the moving of a replaced file's links, the request, cancel and tick of the old sync;
- the API lock that answered 503 SYNCING while that engine ran, its Event, the sync_running flag, the old status
  record in /api/status and its schema, and the frontend's handling of 503 SYNCING;
- their tests.

What a primary says about itself (/api/sync/info), the secondary's settings (its primary, the folders it does not
copy, Test Connection, the folder chooser), taking the primary's library settings when the API starts, and the
daily window of the backup drive stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The primary's sync info no longer reports the largest FileGroup id

Only the old engine read it.  Review also found a docstring that still spoke of a manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync is announced again

Since the Controller runs a sync, nothing sent its events: the old engine did, and the Controller cannot send the
API's events (the API is stopped for most of a sync).  The API's loop now reads the Controller's record of the last
sync and sends one event per finished sync: "Synced N files from the primary" (with the files moved to the trash,
or a warning) or "Sync from the primary failed".  As before, a sync that changed nothing is not announced (within
the window that is every 15 minutes), nor one that was stopped on purpose.  What was announced is kept in
config/.sync, which a sync never touches, so the restart every sync makes neither repeats nor loses one.

Found by review, and by the dead-code check, which saw the two event methods unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:37:44 -07:00
lrnselfreliance
8cfe36b3ea
A secondary syncs by rsync: the Controller runs it on its schedule, and both pages follow it (#995)
* A secondary syncs by rsync: the Controller runs it on its schedule, and both pages follow it

The third part of replacing the sync.

- The Controller syncs within the daily window (every 15 minutes after the last sync finished, in WROLPi's
  timezone), as the API did.  The API's loop no longer runs the old engine, and its /api/sync/run and
  /api/sync/cancel ask the Controller.
- The Sync page and the overlay that covers the app read the sync's status from the Controller, which is the only
  one that can answer while the API is stopped.  The overlay is also shown when the settings cannot be read, as
  happens while the API is stopped.  Sync Now and Stop go to the Controller.
- The Controller's fallback page, where Caddy sends the browser while the API is down, shows the sync's progress
  and a Stop button.
- New on the Sync page: how long files the primary deletes are kept (30 days by default, or never), and a note that
  an excluded folder's files are still listed on a secondary.

The old engine's code is removed in the next part.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove SyncRunRequest, unused since a sync is asked of the Controller

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* In Docker, a sync's progress moves while a large file is copied

Docker's logs hold a line until it ends, and rsync's progress for one large file is a single line rewritten with
carriage returns, so the page showed 0% until the file was done (hours, for a large map).  The rsync helper's
output is now read by attaching to it, before it is started so that nothing is missed.

Found by a sync between two Docker WROLPis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync is recovered before the schedule can start another, and an empty days value is refused

Review found:

- The schedule and the recovery of an interrupted sync started side by side when the Controller started.  The state
  an interrupted sync leaves is due, so inside the window a new sync could start while the recovery restarted the
  API and wrote over the new sync's status.  Every tick of the schedule now recovers first, and only a status of
  "running" with no sync holding the lock counts as interrupted.  A sync records its outcome before it frees the
  lock, so a tick between the two cannot mistake it for an interrupted one.
- The Controller may start before the drive is mounted.  The empty record it read then was kept and saved over the
  real one, losing the last successful sync.  The state file is now read again until it can be.
- A cleared number of days was saved as 0, which empties the trash at the next sync.  It is now refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:06:25 -07:00
lrnselfreliance
6772762ce9
A secondary deletes its own stale write-ahead logs, and the sync leaves no stray files (#994)
* A secondary deletes its own stale write-ahead logs, and the sync leaves no stray files

Found by the first sync between two real machines:

- The primary's unfinished files (SQLite logs, partial downloads) were excluded from the copy, and an excluded path
  is never deleted on the receiving side.  So a secondary kept its own write-ahead log beside a map search
  database the primary had replaced, and SQLite would apply that log to the new database.  These patterns are now
  only hidden on the primary's side, so the secondary's stale ones are deleted (to the trash).
- Reading the incoming snapshot to check it made a -wal and -shm beside it, which stayed behind when the snapshot
  was moved into place.  It is now opened immutable.
- The primary's info, written by the Controller (root), belonged to root.  Files the Controller writes in the media
  directory now belong to its owner, like the directories it makes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* With deletes turned off, a secondary still drops its stale unfinished files

Review found that the hide rules of the previous commit only take effect through --delete, which is not given when
delete_after_days is null (never delete).  A secondary then kept its own write-ahead log beside a database the
primary had replaced, and SQLite applied it to the new database.

Without a trash, --delete is now given with every path protected except the unfinished patterns (and what is
inside an unfinished folder), so only those are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:19:09 -07:00
lrnselfreliance
ea7cc4dec2
The Controller can make a secondary a copy of its primary with rsync (#992)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Dead Code / vulture (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* The Controller can make a secondary a copy of its primary with rsync

The second part of replacing the sync.  The Controller runs it, because the secondary's API is stopped while its
library is replaced: checks, a database snapshot on the primary, stop the API, rsync every file from the primary's
daemon (ignored directories included), fetch the snapshot and put it in the database's place, start the API, purge.

- Files the primary deleted or changed are moved to a dated folder in .sync-trash, and removed after
  delete_after_days (a new sync.yaml setting, 30 by default; none never deletes), or sooner when the drive is nearly
  full.
- A primary of another version or database migration, or with its media unmounted, is refused before anything is
  touched.  The database is replaced last, so a sync that stops earlier leaves one that works.
- On a Raspberry Pi and Debian rsync runs as the wrolpi user; in Docker in a helper container made from the api
  container.  A Controller that starts after an interrupted sync starts the API.
- When a secondary's API starts it takes the library settings of the primary's wrolpi.yaml, which the sync left.

Reached only through the Controller's /api/sync/run for now; the existing sync and its schedule are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The sync copies no link that leaves the library, and root follows none in the media directory

Security review of the Controller's sync:

- An exclusion that ends in a slash matches only a directory.  A file or link named config/ssl, tags or
  config/backup on the primary would have replaced this machine's directory of that name.  The exclusions now match
  whatever has the name.
- Links were copied as they are.  One that points outside the primary's library would, on the secondary, point at
  the secondary's own files, which the web server then serves.  Only links that stay inside the library are copied,
  and no device files.
- The Controller is root, in a media directory that belongs to another user.  It no longer writes, reads, replaces
  or purges through a symbolic link there.

Found on the way: the directory the Controller made for the incoming database belonged to root, so rsync, which
runs as the library's owner, could not have written into it.  It now belongs to the media directory's owner.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A sync ends when its primary stops answering, and makes room before it copies

Review found:

- rsync waits forever by default.  A primary that lost power or its link during a copy left the secondary's API
  stopped until someone cancelled.  rsync now gives up after 30 seconds without a connection and 5 minutes without
  data, which ends the run and starts the API.
- The trash was only purged after a run that succeeded.  The trash is what fills the drive, and a full drive fails
  every run, so it never got its turn.  It is now also purged before the copy.
- A value in sync.yaml that could not be used raised after the run lock was taken and before the handlers that
  release it, leaving "A sync is already running" until the Controller restarted.
- The playlists directory left out of the copy was this machine's, not the primary's, whose hard links would have
  arrived as full copies.  The primary's wrolpi.yaml is now fetched before the copy, and both are left out.
- A primary whose media directory is elsewhere is refused: its database names every file by its full path.
- In Docker rsync is its own container, which outlives a Controller that stops.  A Controller that starts after an
  interrupted sync now removes it before it starts the API.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 20:21:55 -07:00
lrnselfreliance
2ac4a3a294
A WROLPi serves its library over rsync, and makes a database snapshot on request (#988)
* A WROLPi serves its library over rsync, and makes a database snapshot on request

The first part of replacing the sync: a secondary will copy its primary's whole media directory with rsync and
replace its database with the primary's, instead of downloading the files of FileGroups over HTTP (which never
copies an ignored directory, such as the map's).

- An rsync daemon serves the media directory read-only on port 8873, on every WROLPi.  It never serves the TLS keys,
  the cookies, or the database in use.  On a Raspberry Pi and Debian it is the wrolpi-rsyncd unit; in Docker the
  Controller runs it in a helper container made from the api container (its image, user and volumes), so the media
  directory is still configured in one place.  All three read controller/rsyncd.conf.
- POST /api/sync/snapshot asks for a snapshot of the database, which the daemon serves from config/.sync.  An
  unchanged database is not written again.
- /api/sync/info also says the database's migration and whether the media directory is mounted.

Nothing uses these yet; the existing sync is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* The rsync daemon follows no links, and no snapshot is made in WROL Mode

- A client that asked the daemon to follow symbolic links could read what a link in the library points at.  A
  relative link to config/ssl was read this way although that directory is left out of the module.  The daemon now
  refuses the three options that follow links; a link is sent as a link.
- A database snapshot is a new file on the primary's drive, so WROL Mode refuses it, as it does a backup.  A snapshot
  made earlier is still served.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* No rsync helper from an image without rsync, and the helper follows the api container

Review found:

- A helper made from an api image built before rsync was added exits at once, and Docker restarted it forever while
  the Controller reported it created.  The image is now looked at first; no helper is made from one without rsync,
  an older helper is left serving, and the reason is logged once.
- The helper was only checked when the Controller started, so a recreated or rebuilt api container left it stale.
  It is now checked every minute.
- A snapshot cut off by its process being killed stayed marked as running and held back every later request.
- The snapshot's half-written temporary file was served by the daemon.
- The comment on the daemon's refused options claimed more than they give: a link that is part of the requested
  path is still followed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 16:47:02 -07:00
lrnselfreliance
bb7a66b0d6
The calculators have no Temperature calculator (#987)
The Celsius/Fahrenheit/Kelvin converter is removed from the Calculators
page and from the search suggestions.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 15:49:45 -07:00
lrnselfreliance
d11b72bbd1
A file the sync replaces keeps its Tags Directory and playlist links (#986)
* A file the sync replaces keeps its Tags Directory and playlist links

A secondary replaces a changed file with a new inode, so the file's hard links in the Tags Directory and the
playlists directory were left holding the old version.  Both directories repair a link that is still wanted,
but refuse to delete one with no other link.  When the primary also changed the file's tags, or reordered the
playlist, in the same sync, the old link was no longer wanted and could never be deleted.

After each page's downloads, every link to a replaced version in those two directories now becomes a link to
the new version.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* A replaced file's links move before the new version takes its place

Review of the first version found three gaps:

- A playlist with its own directory keeps its links outside the playlists directory; those were not looked at.
- The links were repaired after a whole page of downloads, so a sync that stopped mid-page left the files it had
  already replaced with their old links, and a later sync saw nothing to do.
- Two library files that are hard links of each other share an inode, so the link of the one that did not change
  was pointed at the one that did.

The links of a page's files are now found before its downloads, in the Tags Directory, the playlists directory
and each playlist's own directory, and only by the name those give a link.  Each file's links are moved to the
new version just before it is renamed into place.  The temporary name is short, so a long file name still fits.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 17:06:22 -07:00
lrnselfreliance
dc219e0775
Only offer an update when the remote tip is signed by the release key (#970)
check_for_update reported update_available whenever origin/<branch> was ahead, but upgrade.sh refuses an
unsigned tip (exit 5).  On master, merges land before they are re-signed, so users saw the update icon and
then an upgrade error.  The remote tip is now checked with verify_wrolpi_commit.sh (pinned fingerprint, key
from the running checkout) before an update is offered.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:36:02 -07:00
dependabot[bot]
3e23022418
build(deps): bump node-forge from 1.4.0 to 1.4.3 in /app (#964)
Bumps [node-forge](https://github.com/digitalbazaar/forge) from 1.4.0 to 1.4.3.
- [Changelog](https://github.com/digitalbazaar/forge/blob/main/CHANGELOG.md)
- [Commits](https://github.com/digitalbazaar/forge/compare/v1.4.0...v1.4.3)

---
updated-dependencies:
- dependency-name: node-forge
  dependency-version: 1.4.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-14 11:18:16 -07:00
lrnselfreliance
0389e4659c
An overlay's layers which the basemap already draws start hidden (#969)
A file of features often carries a basemap's layers too (roads, water, buildings, place names).
Drawn over the basemap they double every road and label.  Those layers, by the names of the
Protomaps and OpenMapTiles schemas, are now off until they are checked; every other layer is on
as before, and a choice already made is kept.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 11:17:31 -07:00
lrnselfreliance
38832870c9
Help: map overlays, their styles and icons, and ignoring a map file (#968)
Bump the help docs to document overlays, the style which can sit beside a
map file, the map's own overlay icons, the Type and Visible columns of the
Map's Manage tab, and maps.yaml.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 11:09:20 -07:00
lrnselfreliance
b2b8e2075c
The map draws its own icons on an overlay (#967)
An overlay drawn with a style of its own names icons, which needed the sprite sheet that style was made for.  The map now ships icons for overlays, the Maki and Temaki sets (both CC0), and always draws those, in both viewers.

The sprite sheet is the translation: its index lists every icon under its own name, under each other name it answers to (modules/map/icons/aliases.json), and in both spellings of each.  A name with no icon is drawn as a plain dot.  The icons are signed distance fields, so a style's icon color and halo apply.

A pattern is not an icon: what it filled (a fill, a line or an extrusion) is drawn in a translucent color, where removing a pattern used to leave MapLibre's opaque black.

A sprite sheet beside a map file is no longer used, served or reported.  wrolpi/scripts/build_map_icons.py builds the sheet from the SVGs; the sheet is committed.
2026-11-13 17:59:21 -07:00
lrnselfreliance
177d0dba4b
The standalone map viewer draws overlays, as the map does (#966)
The standalone viewer (port 8084) drew basemaps only: a map file which is
not a basemap was skipped.  It now offers each overlay in its layer panel,
hidden until turned on, with a checkbox per layer, draws it with the style
beside it when there is one, and shows a feature's attributes on a click.

The overlay logic is the map viewer's own.  It moved to dependency-free
modules (app/src/map-shared) which a browser can load as they are; the
standalone viewer, which has no build step, loads copies of them from
modules/map/static/js.  A test fails while a copy differs from its module
(`npm run sync:map-shared` makes the copies).  What differs between the
viewers is passed in: where a map file and its style are fetched from, and
whether a layer can be checked before MapLibre is given it.

The standalone viewer cannot check a layer first, so it adds an overlay's
layers to the map one at a time once the style has loaded: MapLibre refuses a
whole style over one layer it cannot draw, but only that layer when it is
added by itself.

The API also names a style by its path within the map directory, which is
what the standalone viewer is served.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 17:28:41 -07:00
lrnselfreliance
113e70a402
Contour labels are drawn in a font the map has (#965)
The contour label layer named no font, so MapLibre asked for its default
("Open Sans Regular,Arial Unicode MS Regular"), which the map does not ship.
The request failed and the labels were drawn with glyphs the browser made up
locally.  The layer now names Noto Sans Regular, in the map viewer and in the
standalone viewer.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 15:53:01 -07:00
lrnselfreliance
4f58d2862f
A style beside a PMTiles overlay says how the map draws it (#963)
When a MapLibre style (and optionally a sprite sheet) sits beside a PMTiles file, the overlay is drawn with it instead of the generic colors: `<name>.style.json` and `<name>.sprite.json/.png`, or `style.json` and `sprite.json/.png` shared by the files of a directory.

Only the style's layers which draw that file are used; its sources, sprite and glyph URLs never are.  Fonts are replaced by the ones the map has, images are pointed at the overlay's own sprite (as strings, expressions or property functions), and each layer is validated so one the map could not draw is skipped instead of stopping the map.

The sprite is served by the API, which falls back to the single resolution sheet when there is no double resolution one.
2026-11-13 15:41:43 -07:00
lrnselfreliance
adb0adbd94
The map draws any PMTiles file as an overlay, in any sub-directory (#962)
Any PMTiles file under the map directory, at any depth, can be shown.  The API reads each file's header and metadata and says what it is (basemap, terrain, overlay, unreadable).  Overlays are offered in the layer control under the name the file gives itself, hidden until turned on, with a checkbox per vector layer, and are drawn generically.

Map files are named by their path within the map directory everywhere, and unfinished downloads are no longer listed.  A file can be ignored from the Manage page; ignored files are kept in a new maps.yaml config.

PMTiles metadata is not decompressed past its size limit, and the standalone viewer encodes map file paths.
2026-11-13 15:11:01 -07:00
lrnselfreliance
4072ac30ed
Docs sort by their title, ignoring case (#961)
The title sort ordered by `a_text` (the indexed words) with binary collation:
uppercase titles sorted before all lowercase ones ("AWLS" before "Alps"), and
Docs with no indexed words sorted last though they show a title.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:34:59 -07:00
lrnselfreliance
30b2bf6df0
Any Tag alone searches the library, and Zim search does not offer it (#960)
On the search page, choosing Any Tag without a search string left the
Dashboard showing: the page, the Files results and the Files count all waited
for a search string or tag names.

Zim search has no "any tag" search, and its tag picker's Any button left no
filter applied, so the picker no longer offers it.  Zim and Other counts are
only requested when there is a search string or tag names to count by.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:44:14 -07:00
lrnselfreliance
f1d344d8a2
Search results sort as the filter dialog says (#959)
* Search results sort as the filter dialog says

Docs sorted ascending orders backwards and fell back to id order for every
descending order (`-size`, `-published_datetime`); it now takes the same `-`
prefixed orders as the other searches and rejects unknown ones with a 400.

Archives and Docs searches without an order now put the most relevant results
first, as Videos does and as the dialog shows.

Rank has no direction in the dialog: choosing it sends `rank` (most relevant
first) instead of inheriting a descending `-rank` (least relevant first).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An old -rank link becomes rank when the filter dialog closes

The dialog shows Rank without a direction, but it seeded its draft from the URL
unchanged, so Done left a saved `-rank` (least relevant first) in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:42:23 -07:00
lrnselfreliance
2800112f3e
The Any Tag filter works on the Videos, Archives and Docs searches (#958)
The filter modal on these pages offered "Any Tag", but only the Files search
sent it; the module searches had no `any_tag` field.  Docs also matched any of
the listed tag_names, while every other search requires all of them.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:21:06 -07:00
Roland
a0f30a0a60
Bump version to 0.31.0-beta 2026-11-11 13:15:42 -07:00
lrnselfreliance
6cd233dce6
Sync and backup: a secondary WROLPi and a backup drive copy the library (#957)
* A secondary WROLPi copies its primary's library over HTTP

A WROLPi with role "secondary" pulls from its primary: a manifest of every
FileGroup's files (/api/sync/manifest), then each missing or changed file
from the primary's Caddy /media/ (resumable, written to a hidden partial and
renamed with the primary's mtime), a refresh, then the library configs,
imported as the primary wrote them.  wrolpi.yaml contributes only its library
settings.  Files deleted on the primary are kept.

A secondary never saves the synced configs and never downloads.  Its API
answers 503 SYNCING while a sync runs, and every page warns that it is a
copy.  It syncs in a daily window or on "Sync now"; WROL Mode stops it.

On a Pi 4 (no AES instructions) the client uses TLS 1.2 ChaCha20, which
pulls ~110 MB/s from Caddy versus ~41 MB/s for rsync over ssh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sync has its own /admin tab; a sync's reads from the primary are bounded

The sync settings and progress move from Settings (and the component
gallery, which is for library components) to /admin/sync.

A download never writes past the size in the primary's manifest, and configs,
listings, and manifest pages are capped.  A primary address may not carry a
user name or password (it is logged and shown).  While a sync runs, the API
answers only the exact requests that show its progress or stop it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync keeps the secondary's replaced configs in today's config backup

The first copy of the day is kept, like a save, so a config backup import
undoes a sync's config changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Docker's Caddy logs every request

`docker compose logs -f web` shows each request with its status, size and
duration, e.g. a secondary's /media/ downloads during a sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync reports its progress as it downloads, and refuses quietly

The status updated only when a page of 500 FileGroups finished, so a page of
large files looked stuck; it now updates every 2 seconds.  Requests refused
while syncing are answered by the middleware instead of raised, so the UI's
polling no longer logs an error each time.  The primary's version is stored
without its trailing newline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A WROLPi can back up to a second drive; sync settings live in sync.yaml

The Sync tab's Backup Drive copies the media directory to a second mounted
drive with rsync during the sync window (hourly), or on "Back Up Now".
Nothing on the backup drive is deleted.  The Tags and playlists directories
are left out (WROLPi rebuilds them from the configs), and the database is
written as an SQLite snapshot rather than copied as files, so the drive can be
mounted as the media directory and start.  A backup is written only while the
chosen drive (by UUID) is mounted where it was chosen, and is not the media or
system drive; rsync is stopped if the drive disappears.  Not in Docker, which
cannot reach other drives.

Role, primary, window and backup drive move from wrolpi.yaml to sync.yaml:
they belong to this machine, and are never copied from a primary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The Sync tab shows the configured backup drive

getSettings copies each setting by name and did not list the backup drive,
so the Sync tab showed "None" while one was configured.  It also dropped
`version`.  A test now fails for any setting the API sends that getSettings
drops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A backup can go to a folder on its drive, and remembers its last success

The Backup Drive panel takes a folder on the chosen drive.  The drive is
checked through the folder's mount point: the folder is written only when the
drive with the saved UUID is mounted there, so a folder left on the system
drive by an unplugged drive, or on another drive mounted inside the chosen
one, is refused.  A missing folder is created once the drive is checked.

When the last backup succeeded is saved in sync.yaml, so it is known after a
restart.  "Stop Backup" is disabled while the database snapshot is written (it
runs to the end), and a finished backup clears the request to stop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The backup drive has its own window

The sync window was shown in the Sync panel but also scheduled the backup
drive.  The Backup Drive panel now has its own window (sync.yaml
backup_window_start/end), saved with the drive; the sync window is shown,
and used, only for a secondary's sync.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sync and the backup drive can each exclude folders

A secondary or a backup drive may be smaller than the primary's library.
Each Sync tab panel has its own excluded folders in sync.yaml, chosen in
a folder browser: a secondary browses its primary's folders (through
Caddy), the backup drive browses this WROLPi's media directory.  Excluded
folders are never copied; what was copied before is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The folder browser does not offer lost+found

Every ext4 drive has a root-only lost+found folder; a sync and a backup
never copy it, so it is not offered for exclusion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A sync never writes into config or tags, whatever their case

On a media drive that ignores case (exFAT, NTFS, macOS), a manifest path
like Config/wrolpi.db is the real config folder. The protected and
unlisted top-level folders are now compared case-insensitively in the
manifest, in resolve_destination, in excluded-folder validation, and in
both folder listings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A backup writes the database snapshot only when the database changed

Every backup rewrote the whole database snapshot (2.5 GB on a busy
WROLPi), even on the window's idle hourly runs. The snapshot is now
skipped when the live database (its size and mtime, and those of a
non-empty WAL) and the drive's copy are both unchanged since the last
snapshot. The record is in memory, so the first backup after a restart
writes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove the unused save_sync_config switch

Nothing activated it; SyncConfig saves directly.  The test server's
log_message override is called by http.server, so it goes in the
vulture baseline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:53:45 -07:00
lrnselfreliance
86f168d2c1
A script's result reads the journal when systemd has cleared its timestamps (#956)
The upgrade reloads systemd, which clears the run's exit timestamp, so a
successful upgrade looked like a script that never ran: finished false and
success null. The journal keeps systemd's unit success/failure record of the
run's end, so it now decides whether a run finished, and when.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:25:38 -07:00
lrnselfreliance
19ff59d5e0
A failed upgrade is shown on the upgrade page instead of redirecting home (#955)
* A failed upgrade is shown on the upgrade page instead of redirecting home

A failed upgrade restarts the services it stopped, so the upgrade page saw
them come back and redirected home as if the upgrade had worked.  The
Controller now reports how the last run of a script ended
(GET /api/scripts/{name}/result, from systemd's Result and exit status),
and the upgrade page reads it before redirecting.  A failure turns the
banner red, gives the exit code, opens the output, and offers a link back.

Only a run the page has seen start counts, because the result of an
earlier run is still reported until the new run begins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An upgrade's result survives the daemon-reload it does

The upgrade reinstalls its unit and reloads systemd, which clears the run's
timestamps but keeps Result and the exit status.  A failure is now known
from those alone, and the result reports whether the script is running, so
the upgrade page waits on that instead of on a timestamp that may never come.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:11:59 -07:00
lrnselfreliance
d88db90ce9
The Settings upgrade can switch to a chosen branch (#954)
* The Settings upgrade can switch to a chosen branch

The Upgrade panel gains a Branch input: a dropdown listing the current
branch, master, and release that also takes a typed branch name.
/api/upgrade/start accepts an optional {"branch": ...}; without it the
current branch is upgraded as before.  A branch is written into the systemd
env file and passed to `upgrade.sh -b`, so only plain git branch names are
accepted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The Controller upgrade refuses a branch that is not a plain branch name

The Controller's upgrade script wrote its branch straight into the systemd
env file, so a newline in it added a variable, and a leading dash became an
upgrade.sh option.  It now accepts the same branch names as the API, and no
script parameter may span lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 08:49:26 -07:00
lrnselfreliance
f3f762ef1b
Controller logs: an unparseable since is a 400, not empty logs (#953)
journalctl exits 1 with nothing on stdout when it cannot parse --since
(a bare "1h" is one such value); the controller returned that empty
stdout as the logs, with a 200.  A failed journalctl is now an error:
400 when it could not parse since, 500 otherwise.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 08:02:48 -07:00
Roland
d25ebb9e63
Bump version to 0.30.6-beta 2026-11-07 17:14:13 -07:00
lrnselfreliance
2e0e50c3aa
3D previews load ASCII STLs, stand upright, and fit the preview modal (#952)
* STL files preview with three's own STLLoader

react-stl-viewer inlines a copy of three-stdlib 2.17.2's STLLoader, which reads
ASCII STL text with LoaderUtils.decodeText.  three removed that in r175, so
every ASCII STL preview failed.  The three-stdlib override never reached that
copy, and react-stl-viewer has had no release since January 2024.

The 3MF preview's three.js viewer now previews STL files too, loading each
format with the loader that ships with three, so the loader always matches the
installed three.  react-stl-viewer and the three-stdlib override are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An e2e spec previews ASCII and binary STL files in a real browser

The STL preview only fails in a browser with WebGL, so the spec opens both
encodings on the live stack and checks the dimensions line appears without a
load error.  fb:reset can now write binary files ({base64: ...}).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* STL previews stand Z-up models upright

STLs are Z-up (the 3D printing convention) and three is Y-up, so the
preview rotates STL geometry to stand the model upright, as react-stl-viewer
did.  Model Z reads as Height again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 3MF previews stand Z-up models upright too

3MF is Z-up like STL, so the rotation moves from the STL loader into the
shared viewer and applies to every model.  Model Z reads as Height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* File previews show their buttons without scrolling

.preview-fit reserved a fixed 18.75rem for the rest of the preview modal,
which was short: every framed preview overflowed a little, and a 3D model's
dimensions line pushed the action buttons below the fold.  The preview modal
now fills its height as a flex column, and the .preview-fit takes whatever
height is left.  Previews without a .preview-fit keep their content's height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 3D previews frame the model and light it brightly

- The camera fits the model's bounding sphere into the narrower field of view,
  from a raised three-quarter front view, instead of backing off 2.2x along Z.
- A hemisphere light and a headlight that follows the camera (from a little
  above and left) replace lights whose intensities were set before three's
  r155 lighting change and read dim.
- Geometry without normals (3MF) gets creased normals, so flat faces no longer
  shade into their neighbors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 15:33:58 -07:00
lrnselfreliance
6c24d7d762
A move neither scans every FileGroup nor stalls the downloader's writes (#951)
* A move neither scans every FileGroup nor stalls the downloader's writes

Two stalls made a 109 file move take three minutes on a large library:

- Planning joined the move_sources temp table to file_group.  The temp
  table has no statistics, so with a real library's statistics SQLite
  scanned all of file_group (233k rows, 2.4 GB) instead of looking up 109
  paths in the primary_path index.  CROSS JOIN fixes the join order.

- The move's write transaction yielded to the event loop between chunks.
  The process that moves files also downloads; a download's write then
  waited on the move's lock synchronously, so the event loop could not
  resume the move: each write waited out the 30 s busy_timeout and failed
  ("Unable to renew downloads!").  The transaction now runs in a thread
  (inline in tests, which share one connection), so another writer waits
  only until the move commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A cancelled move waits for its thread however often it is cancelled

Review fix: the move waited for its thread on the first cancellation by
awaiting the thread's future again, unshielded.  Shutdown cancels twice
(run_loops cancels the file worker loop and stops waiting after 15 s, then
asyncio.run cancels every pending task, including the thread's future), so
the second cancellation raised while the thread was still in its
transaction, and handle_move reverted the files the thread then committed.

The move now waits on a threading.Event the thread sets when it leaves its
transaction, absorbing every cancellation meanwhile.  A cancelled future
reads "done" while its thread still runs, so it cannot be that signal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:47:12 -07:00
lrnselfreliance
aff5f1eb1f
A directory rename is finished by the file worker, not the request (#950)
* A directory rename is finished by the file worker, not the request

A directory rename queued a move, waited for it, then removed the old
directory and updated nested Collections itself.  A rename that outlasted
Sanic's RESPONSE_TIMEOUT (60 s) was cancelled while waiting: the move still
finished, but the old directory and its emptied subdirectories were left
behind, nested Collections kept their old directories, and the browser was
told the rename failed.

The move job now finishes the rename (nested Collections, then removing the
old directory, empty directories only), and the request returns once the
move is queued.  A failure is reported by the job's event.  An empty
directory can be renamed (it raised before).  The worker status carries
`rename_from`, so the Files page progress bar labels the rename, and the
file browser fetches again when the file worker is done.

A directory rename no longer queues a refresh of its parent: the file
worker runs the newest task first, so it scanned the directory before the
rename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A queued rename returns its job, and the file browser waits for it

Review fixes:

- The cancellation test patched `wait_for_job`, which this path no longer
  calls, so it cancelled nothing.  It now asserts the invariant: the
  request only queues the rename (it never waits, and nothing has moved
  when it returns), and the file worker alone finishes it.

- The file browser inferred the end of a rename from the file worker's
  polled status.  A short job can start and finish between two polls, and
  the first idle poll (before the job started) spent the "fetch once"
  token, so the table could keep the old name.  POST /api/files/rename now
  returns `{"job_id": ...}` (null when the rename is already done), GET
  /api/files/jobs/<job_id> reports pending/complete/failed, and the file
  browser polls that job before fetching.

- useBrowseFiles ignores a fetch that settles after a newer one, so a
  listing requested before a rename cannot replace the one after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:09:33 -07:00
lrnselfreliance
c7bafaa7fb
Starting the app again adds no signal routes (#949)
Sanic's SignalRouter.finalize appends a `sanic.__signal__.__init__` handler
before it checks whether the router is already finalized.  Every start of the
app finalizes it again (the test client, Sanic's startup, and
finalize_signals_after_auto_routes), so each test left two more routes.  After
a few hundred tests in one process the compiled router was too deep for the
compiler (RecursionError in sanic_routing, intermittently failing whichever
tests a worker happened to run late).

api_app's signal router now skips a finalize when it is already finalized, and
registers that handler once.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:00:41 -07:00
lrnselfreliance
e5987fdd7e
ASCII STL files preview again (#948)
react-stl-viewer pins three-stdlib 2.17.2, whose STLLoader decodes ASCII STL
files with three's LoaderUtils.decodeText.  three removed that function, so
every ASCII STL preview failed while binary STLs (which never decode text)
still worked.  Override three-stdlib to 2.36.1, which ships its own decodeText.

Jest can now load three: a small transform converts three/three-stdlib ES
modules to CommonJS without babel-preset-react-app, whose class-properties
plugin rejects three's static class blocks at our pinned Babel version.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 11:55:55 -07:00
lrnselfreliance
20439437f8
Subtitle language-region suffixes are checked against the codes, not a 336,000-entry set (#947)
Every API process built a set of every language-region and language-auto
.srt/.vtt suffix at import: about 1 s and 73 MiB per process on a Pi 4.  A
suffix is now split into its language and region, and each is checked against
its own code set.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:19:14 -07:00
lrnselfreliance
ba9b47edf3
API startup no longer imports pymupdf (#946)
pymupdf 2.0 imports pymupdf.layout and onnxruntime, which every API start
paid for (about 2.5 s on a Pi 4) although only PDF extraction uses it.  It is
now imported when a PDF is extracted.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:01:45 -07:00
lrnselfreliance
cafa2a2279
Workers finalize the signal router once at startup, not once per route (#945)
sanic-ext adds the automatic HEAD and OPTIONS routes one at a time in a
before_server_start listener.  Each route re-finalized the already-finalized
signal router (Sanic.amend), and each finalize registered one more
`sanic.__signal__` route, so a worker rebuilt an ever-growing router about 245
times.  The signal router is now left unfinalized while sanic-ext adds those
routes and finalized once afterwards.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:50:10 -07:00
Roland
89b84c9765
Bump version to 0.30.5-beta 2026-11-02 20:12:14 -07:00
lrnselfreliance
479aa2254e
A Zim search without a search string or tag names is a 400, not a 500 (#944)
Both Zim search endpoints handed an empty request to the worker-job builder,
whose RuntimeError surfaced as a 500 "Unexpected error" with a traceback.  The
request is the client's mistake: the handlers now raise ValidationError, as the
other endpoints do, before any work is scheduled.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 19:55:47 -07:00
lrnselfreliance
87137cc40c
Zim names with a re-release letter are parsed, and an undated Zim no longer warns at every start (#943)
The kiwix naming scheme is {name}_{YYYY-MM}.zim, and a re-release in the same
month carries a letter: 3dprinting.stackexchange.com_en_all_2026-07a.zim.
parse_name rejected the letter, so such a Zim was never checked for newer
releases and zims.yaml keyed it by its full stem instead of its name.  The
letter is now accepted and folded into the day of the month-precision date, so
a re-release orders after the plain release wherever dates are compared.  The
pattern also anchors the ".zim" extension instead of matching any character.

A Zim that is not kiwix-named (edibleplantdb.zim) has no date to compare and is
simply not checked.  find_outdated_zim_files logged that at WARNING for every
such file at every start; it is a DEBUG line now.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 19:36:07 -07:00
lrnselfreliance
9797af157a
Removing a duplicate video keeps the Download that is finishing (#942)
* A refresh that finishes before tags.yaml is imported no longer reports a failed save (#941)

Every refresh fires save_tags_config at its cleanup.  In the first seconds
after a start, a refresh can finish before the startup import of tags.yaml,
which on a rebuilt database happens while the first refresh runs.  The dump
then asked ConfigFile.save to write a database that held no tags over the
file; the save guard refused, as it must, but it did so with an ERROR traceback
and a "Failed to save config: config/tags.yaml" event for the user, although
nothing was lost: the import that followed read the file and recreated the tags.

save_tags_config now skips the dump while the config has not been imported and
says so at WARNING.  The file stays the source of truth until the import.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

* Removing a duplicate video keeps the Download that is finishing

After a video download, Video.delete_duplicate_videos removes the other copies
of the same video, which happens when the file name changed (a renamed file, a
new title).  Each copy was deleted through FileGroup.delete, which also deletes
the Download of the copy's URL and, without one, adds the URL to the skip list.
The duplicates share that URL with the video just downloaded, so the Download
still running was deleted from under its worker: the worker read its row again
to record the result and failed with NoResultFound ("Unexpected error"), and the
download's record was gone.

FileGroup.delete and Video.delete take keep_download; the duplicate cleanup
passes it, so the URL's Download and the skip list are left alone.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Only a duplicate at the downloaded URL keeps its Download

delete_duplicate_videos also finds copies by source_id, and those can sit under
another URL.  Such a copy is deleted as any video is, with that URL's Download
or a skip-list entry; only a copy that shares the URL being downloaded leaves
the finishing Download alone.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 19:18:46 -07:00
lrnselfreliance
0aa4019f86
A refresh that finishes before tags.yaml is imported no longer reports a failed save (#941)
Every refresh fires save_tags_config at its cleanup.  In the first seconds
after a start, a refresh can finish before the startup import of tags.yaml,
which on a rebuilt database happens while the first refresh runs.  The dump
then asked ConfigFile.save to write a database that held no tags over the
file; the save guard refused, as it must, but it did so with an ERROR traceback
and a "Failed to save config: config/tags.yaml" event for the user, although
nothing was lost: the import that followed read the file and recreated the tags.

save_tags_config now skips the dump while the config has not been imported and
says so at WARNING.  The file stays the source of truth until the import.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 19:12:41 -07:00
lrnselfreliance
871a26324d
Startup no longer renews failed once-downloads (#940)
retry_downloads_on_startup set pending, deferred and failed Downloads back to
"new".  A failed once-download has already given up: its downloader raised
UnrecoverableDownloadError or it reached its attempt limit.  Renewed at every
boot, it only failed again at once and logged a traceback-level warning each
time.  Startup now renews only the pending and deferred Downloads, which were
interrupted or are waiting for their next try.  The user's Retry button still
renews failed Downloads and resets their attempts.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 18:36:57 -07:00
lrnselfreliance
c78378d4f5
The Zim list reads each Zim's metadata in the libzim worker instead of opening it in the API (#939)
GET /api/zim went through Zims.get_all, which opened every Zim's Archive in the
API process, and then Zim.__json__ opened each one again for its metadata.
python-libzim holds the GIL and a cold open of a large Zim takes seconds, so
loading the Zims page stalled that API worker for every other request (27.8 s
cold against 0.75 s warm for 44 Zims).  #928 moved estimates and searches to the
worker process; the list now uses the same worker for metadata, and a Zim the
worker cannot read is left out as before.  count_tagged_zim_entries shares the
new readable_zims helper.  Zims.get_all had no other callers and is removed.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 18:19:29 -07:00
lrnselfreliance
b8122a4637
The tail-decode check ignores the h264 decoder's "mmco: unref short failure" note (#938)
After a download, ffmpeg decodes the last 30 seconds of the video and any stderr
line not on the ignore list marks the video incomplete.  Seeking into an h264
stream can make the decoder print "mmco: unref short failure": a note about
reference-picture marking for frames before the seek point.  The frames decode
and ffmpeg exits 0, but the verdict was "Video was incomplete", so the download
was deferred and the same sound video was downloaded again on every retry.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 18:00:03 -07:00
Roland
6c8ea61eaa
Bump version to 0.30.4-beta 2026-11-02 16:55:04 -07:00
lrnselfreliance
2991f737da
test_get_custom_videos_directory attaches the shared context it needs (#937)
Setting a config field calls ConfigFile.update(), which takes
api_app.shared_ctx.config_update_lock.  The test did not use async_client,
so the lock only existed when another test in the same process had already
attached the shared context; running first in a worker, it failed with
"'SharedContext' object has no attribute 'config_update_lock'".

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 16:31:55 -07:00
dependabot[bot]
662a41afc3
build(deps): update pytest-asyncio requirement in /controller (#926)
Updates the requirements on [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) to permit the latest version.
- [Release notes](https://github.com/pytest-dev/pytest-asyncio/releases)
- [Commits](https://github.com/pytest-dev/pytest-asyncio/compare/v1.4.0...v1.4.1)

---
updated-dependencies:
- dependency-name: pytest-asyncio
  dependency-version: 1.4.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 12:05:36 -07:00
lrnselfreliance
31b47dacf8
The inventory legacy-date repair no longer takes the save lock during import (#915)
MultiFileConfig.initialize() imports every file while holding the shared save
lock, which is not reentrant. The repair added in #901 took that lock again from
inside import_all, so any WROLPi whose inventory still held epoch-second dates
hung every API process at startup.

The repair now only rewrites the in-memory entities during import and records
which inventories changed. import_inventories_config() writes those files once
it runs, outside the lock. A regression test runs initialize() against an
epoch-date file with a timeout.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 11:58:42 -07:00
dependabot[bot]
7f275284a1
build(deps): bump query-string from 9.5.1 to 10.0.0 in /app (#917)
Bumps [query-string](https://github.com/sindresorhus/query-string) from 9.5.1 to 10.0.0.
- [Release notes](https://github.com/sindresorhus/query-string/releases)
- [Commits](https://github.com/sindresorhus/query-string/compare/v9.5.1...v10.0.0)

---
updated-dependencies:
- dependency-name: query-string
  dependency-version: 10.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:53:24 -07:00
dependabot[bot]
f782f347d1
build(deps): bump qs and body-parser in /app (#891)
Bumps [qs](https://github.com/ljharb/qs) and [body-parser](https://github.com/expressjs/body-parser). These dependencies needed to be updated together.

Updates `qs` from 6.15.3 to 6.16.2
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.15.3...v6.16.2)

Updates `qs` from 6.16.0 to 6.16.2
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.15.3...v6.16.2)

Updates `body-parser` from 1.20.6 to 1.20.9
- [Release notes](https://github.com/expressjs/body-parser/releases)
- [Changelog](https://github.com/expressjs/body-parser/blob/1.20.9/HISTORY.md)
- [Commits](https://github.com/expressjs/body-parser/compare/1.20.6...1.20.9)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.16.2
  dependency-type: indirect
- dependency-name: qs
  dependency-version: 6.16.2
  dependency-type: indirect
- dependency-name: body-parser
  dependency-version: 1.20.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:53:19 -07:00
dependabot[bot]
ab6f17fb5b
build(deps): bump postcss-selector-parser from 6.0.11 to 6.1.5 in /app (#892)
Bumps [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser) from 6.0.11 to 6.1.5.
- [Release notes](https://github.com/postcss/postcss-selector-parser/releases)
- [Changelog](https://github.com/postcss/postcss-selector-parser/blob/6.1.5/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss-selector-parser/compare/v6.0.11...6.1.5)

---
updated-dependencies:
- dependency-name: postcss-selector-parser
  dependency-version: 6.1.5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:53:14 -07:00
dependabot[bot]
7487cb07a1
build(deps): bump fast-uri from 3.1.8 to 3.1.9 in /app (#893)
Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.8 to 3.1.9.
- [Release notes](https://github.com/fastify/fast-uri/releases)
- [Commits](https://github.com/fastify/fast-uri/compare/v3.1.8...v3.1.9)

---
updated-dependencies:
- dependency-name: fast-uri
  dependency-version: 3.1.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:53:09 -07:00
dependabot[bot]
b9aae3f049
build(deps): bump the npm-dependencies group in /app with 6 updates (#916)
Bumps the npm-dependencies group in /app with 6 updates:

| Package | From | To |
| --- | --- | --- |
| [@tabler/icons-react](https://github.com/tabler/tabler-icons/tree/HEAD/packages/icons-react) | `3.49.0` | `3.50.0` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.7` | `14.6.8` |
| [react-router](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router) | `7.18.4` | `7.18.5` |
| [@types/lodash](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/lodash) | `4.17.25` | `4.17.27` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.6.4` | `26.6.6` |
| [webpack-dev-server](https://github.com/webpack/webpack-dev-server) | `5.2.6` | `5.2.7` |


Updates `@tabler/icons-react` from 3.49.0 to 3.50.0
- [Release notes](https://github.com/tabler/tabler-icons/releases)
- [Changelog](https://github.com/tabler/tabler-icons/blob/main/packages/icons-react/CHANGELOG.md)
- [Commits](https://github.com/tabler/tabler-icons/commits/v3.50.0/packages/icons-react)

Updates `@testing-library/user-event` from 14.6.7 to 14.6.8
- [Release notes](https://github.com/testing-library/user-event/releases)
- [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/user-event/compare/v14.6.7...v14.6.8)

Updates `react-router` from 7.18.4 to 7.18.5
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router@7.18.5/packages/react-router/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router@7.18.5/packages/react-router)

Updates `@types/lodash` from 4.17.25 to 4.17.27
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/lodash)

Updates `@types/node` from 26.6.4 to 26.6.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `webpack-dev-server` from 5.2.6 to 5.2.7
- [Release notes](https://github.com/webpack/webpack-dev-server/releases)
- [Changelog](https://github.com/webpack/webpack-dev-server/blob/v5.2.7/CHANGELOG.md)
- [Commits](https://github.com/webpack/webpack-dev-server/compare/v5.2.6...v5.2.7)

---
updated-dependencies:
- dependency-name: "@tabler/icons-react"
  dependency-version: 3.50.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: "@testing-library/user-event"
  dependency-version: 14.6.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: react-router
  dependency-version: 7.18.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@types/lodash"
  dependency-version: 4.17.27
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@types/node"
  dependency-version: 26.6.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: webpack-dev-server
  dependency-version: 5.2.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:53:04 -07:00
dependabot[bot]
9c9b740d55
build(deps): update pytest requirement in /controller (#924)
Updates the requirements on [pytest](https://github.com/pytest-dev/pytest) to permit the latest version.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/9.1.1...9.2.0)

---
updated-dependencies:
- dependency-name: pytest
  dependency-version: 9.2.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:52:23 -07:00
dependabot[bot]
9af8ee89f5
build(deps): update certifi requirement (#919)
Updates the requirements on [certifi](https://github.com/certifi/python-certifi) to permit the latest version.
- [Commits](https://github.com/certifi/python-certifi/compare/2026.10.19...2026.10.23)

---
updated-dependencies:
- dependency-name: certifi
  dependency-version: 2026.10.23
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:52:18 -07:00
dependabot[bot]
c6d7084527
build(deps): update pymupdf requirement from >=1.28.2 to >=2.0 (#922)
Updates the requirements on [pymupdf](https://github.com/pymupdf/pymupdf) to permit the latest version.
- [Release notes](https://github.com/pymupdf/pymupdf/releases)
- [Changelog](https://github.com/pymupdf/PyMuPDF/blob/main/changes.txt)
- [Commits](https://github.com/pymupdf/pymupdf/compare/1.28.2...2.0)

---
updated-dependencies:
- dependency-name: pymupdf
  dependency-version: '2.0'
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:52:14 -07:00
dependabot[bot]
03a904d31a
build(deps): update fastapi requirement in /controller (#925)
Updates the requirements on [fastapi](https://github.com/fastapi/fastapi) to permit the latest version.
- [Release notes](https://github.com/fastapi/fastapi/releases)
- [Commits](https://github.com/fastapi/fastapi/compare/0.142.2...0.162.0)

---
updated-dependencies:
- dependency-name: fastapi
  dependency-version: 0.162.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:52:10 -07:00
dependabot[bot]
00fdfad8e2
build(deps): update pydantic requirement in /controller (#927)
Updates the requirements on [pydantic](https://github.com/pydantic/pydantic) to permit the latest version.
- [Release notes](https://github.com/pydantic/pydantic/releases)
- [Changelog](https://github.com/pydantic/pydantic/blob/main/HISTORY.md)
- [Commits](https://github.com/pydantic/pydantic/compare/v2.13.5...v2.14.1)

---
updated-dependencies:
- dependency-name: pydantic
  dependency-version: 2.14.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-02 11:52:05 -07:00
lrnselfreliance
5be899bf1f
Saving zims.yaml keeps the entries of Zims the database does not have yet (#935)
A rebuilt database imports zims.yaml before the refresh has modeled a single
Zim.  That import has no database version to compare with, so it saves the
config afterward, and the save wrote only the Zims in the database: none.  The
file's choices were erased and every Zim was then modeled with the default.

The dump now starts from the file's entries and overlays the database's, so a
choice survives until its Zim is modeled again, and a Zim in the database still
decides its own line.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 11:11:41 -07:00
lrnselfreliance
c0452e29e6
Hiding a Calibre book's cover and metadata uses the modeler's session (#936)
Doc._hide_calibre_files opened a second write session while the modeler held
the item's transaction.  SQLite has one writer, so the second session waited
out the 30 s busy timeout and failed with "database is locked"; the modeler
retried three times, so every Calibre epub cost about 98 s and stayed
unmodeled, and the cover.jpg / metadata.opf FileGroups it should have deleted
survived.  On a library of 1663 Calibre books the global refresh's modeling
phase would have taken about two days.

The nested session dates from before the SQLite cutover, when Postgres row
locks let it work.  The delete now runs in the caller's session.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 11:04:28 -07:00
lrnselfreliance
e6b7b9e5dd
Map downloads are checked against the hash in the signed manifest (#934)
* Map downloads are checked against the hash in the signed manifest

A meta4 signs only a bare hash, so any genuinely signed meta4 (an older version of a region, another region) passed
its own check.  The manifest now lists each file's sha256; it is signed as a whole, so the hash is tied to the URL.
The catalog copies each hash into its download's settings, and aria2c checks the file against it.  Downloads from a
manifest without hashes still require the file's signed meta4.

build_map_regions.py writes the hashes, and hash_map_manifest.py adds them to the published manifest from the
verified meta4s without rebuilding any maps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* hash_map_manifest.py hashes each file's bytes instead of trusting its meta4's name

Only the bare hash in a meta4 is signed, so an older version's meta4 with its name rewritten (or terrain's, whose name
never changes) passed the name and duplicate-hash checks.  Each file is now hashed from a local copy of the published
files (--files) or downloaded from the CDN, and must match its signed meta4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:38:57 -07:00
lrnselfreliance
ee6c384dc6
A refresh keeps a FileGroup's tags and viewing state when its primary file changes (#932)
_upsert_files deleted the FileGroup of every companion file before
inserting, so a FileGroup whose primary file became a companion (foo.jpg,
then foo.mp4 arrives) was replaced by a new, untagged row.  A FileGroup
whose primary file was replaced (foo.txt deleted, foo.mp4 added) still owned
the (directory, stem), and the INSERT failed on the unique index.

Before inserting, the FileGroup owning each incoming (directory, stem) is
renamed to the new primary path, keeping its id, tags, collection
membership, model and viewing state.  When a different FileGroup owns the
primary path, the two collapse into the one dedupe prefers (modeled, then
tagged).  A companion's leftover FileGroup gives its tags, collection
membership and viewing state to its group's FileGroup before it is deleted.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:21:34 -07:00
lrnselfreliance
851b12b060
A Zim's Search toggle is saved in zims.yaml so a rebuilt database or a newer Zim keeps it (#931)
The toggle was only the zim.auto_search column, which defaults to on.  The
database is rebuilt from files and configs, and a Zim's newer version is a new
row, so every rebuild and every subscription update turned search back on for
every Zim.  On a large library the global search then searched all of them.

zims.yaml records auto_search for each Zim, keyed by the Zim's name without
its date, so a newer version of a Zim is the same Zim.  A Zim the file does not
name is searched (the default stays on).  The config is imported on startup
with the usual version gating, saved when the toggle changes, and a newly
modeled Zim takes its setting from it.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 13:09:52 -07:00
lrnselfreliance
6fc147ccdf
A refresh re-indexes a FileGroup whose files changed even when their count did not (#933)
_upsert_files kept a FileGroup's files and indexed state when the size,
newest modification time and number of files were unchanged.  A file that
replaced another (foo.png for foo.jpg, same size, older than foo.mp4) left the
old file in `files` and the FileGroup indexed.

The upsert now compares the sorted file names.  FileGroups that still store
absolute paths (the old format) compare by name too, so they are not
re-indexed when nothing changed.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:04:32 -07:00
lrnselfreliance
21006eae09
Map files are never downloaded without a signed hash (#930)
* Map files are never downloaded without a signed hash

A region, terrain, or search index download whose .meta4 is missing or unfetchable now fails (and retries later)
instead of downloading with TLS as its only check.  The search index downloader had no fallback branch at all, so it
downloaded with no hash whenever the .meta4 was missing.

A real aria2c test pins what this relies on: aria2c refuses a file that does not match the signed hash, even when
the meta4's unsigned name differs from the URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* aria2c checks map files only against the signed hash, and a rejected file is never kept

Only the sha-256 hash in a meta4 is signed, but aria2c was given the whole downloaded meta4.  A sha-512 of a tampered
file added beside the signed sha-256 made aria2c accept the tampered file.  aria2c now gets a meta4 built from the
signed hash and the download URL alone.

A rejected download was left in the map directory under its final name, where the next attempt took it as already
downloaded.  Map files now download into map/.partial and move into place only once aria2c accepts them; a file that
fails the hash check is deleted so a retry starts over, other failures keep it so the download resumes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Only the map file aria2c checked is moved into place

download_file reports the path named by the server's HEAD response (Content-Disposition, redirects), while aria2c
saves and checks the file under the name in the meta4 WROLPi writes.  When they differed, an unchecked file (such as
an interrupted download's leftover in map/.partial) could be moved into place.  The meta4 name now comes from the
URL, must be a plain file name, and any other reported path fails the download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:03:16 -07:00
lrnselfreliance
bfe7b8afbd
Zim estimates and searches run in a libzim worker process so a cold Zim cannot stall the API worker (#928)
* Zim search estimates run in a separate process so a cold estimate cannot stall the API worker

The global search estimates every auto-search Zim on each keystroke.  On a
large library that estimate took tens of seconds when the Zims' pages were not
cached, and every other request routed to the same Sanic worker, such as the
channel suggestions, waited behind it.  Two things held the worker: opening a
large Zim cold takes seconds (ten for a 75 GB Zim) and `Zims.get_all` did that
on the event loop; and python-libzim never releases the GIL, so the estimate
offloaded with asyncio.to_thread still froze the worker.

Everything libzim does for an estimate now runs in a standalone script started
as a subprocess (Sanic workers are daemonic, so a multiprocessing pool cannot
be forked from them).  It reads the Zim paths and search string on stdin and
writes the counts on stdout.  A Zim it cannot read is reported and left out, as
`Zims.get_all` would leave it out.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Zim searches run in the libzim worker process too

The /api/zim/search endpoints had the same stall as the estimate: they opened
every Zim through Zims.get_all and searched them with libzim, which holds the
GIL, so a thread offload still froze the Sanic worker.

The estimate script is now a general libzim worker with estimate, search and
entries jobs.  A search of all Zims sends every Zim's job to one worker
process; the API worker only headlines the returned HTML and looks up tags.
The worker also returns each Zim's metadata so Zim.__json__ does not open the
Zim again on the event loop.  Zim.entries_with_tags is split so the tagged
paths come from the database without opening the Zim.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Tagged Zim estimates count from the database, and a cancelled request kills the libzim worker

Review of the earlier commits found two gaps.  Estimates with tags selected
still went through Zims.entries_with_tags, which opened every Zim in the API
process, and after the thread offload was removed it did so on the event loop;
they now count the tagged paths in SQL and ask the worker only for metadata.
And Sanic cancels a handler at its response timeout or on disconnect, which
left the worker process running until its stdout pipe filled; the runner now
kills and reaps it on cancellation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 13:02:26 -07:00
lrnselfreliance
9c258b41ee
A refresh groups each stem's files together even when another stem sorts between them (#929)
group_files_by_stem and chunks_by_stem assumed a stem's files are adjacent
once sorted.  They are not: foo.f137.mp4 (stem foo.f137) sorts between
foo.en.vtt and foo.mp4 (stem foo), and foo.tar.gz between foo.jpg and
foo.txt.  _upsert_files then built two FileGroups for one (directory, stem)
and the refresh failed with "UNIQUE constraint failed: file_group.directory,
file_group.stem".  A chunk boundary could split a stem the same way.

Both helpers now group by (directory, stem).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 12:38:48 -07:00
lrnselfreliance
8edace08bd
Python packages install from hash-locked requirements; yt-dlp still floats (#913)
* Python packages install from hash-locked requirements; yt-dlp still floats

Every pip install trusted PyPI over TLS: requirements.txt pins only top-level versions
(some with >=), the controller's are almost all >=, and dependencies were never pinned, so
a forged certificate (as the eMudhra key compromise allowed) could change code in the API,
the controller, or the archive container.  scripts/lock_requirements.sh generates a
universal, hash-locked .lock beside each requirements.txt, and
install_python_requirements.sh installs it with --require-hashes at every site.  yt-dlp is
left out of the lock and upgraded afterwards so devices still get YouTube fixes; its
dependencies are locked.  The unpinned `pip install --upgrade pip` steps are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The unhashed yt-dlp install cannot replace locked packages, and nothing builds from source

Review of #913 found two holes.  The yt-dlp step ran without --no-deps, so pip's
only-if-needed strategy would still fetch an unhashed dependency whenever yt-dlp's metadata
asked for a version the lock did not install.  And srt is published only as a source
archive, whose build installed setuptools with hash checking off on every install.

The yt-dlp step now uses --no-deps (its dependencies come only from the lock), both steps
are retried as the image builds did before, and installs and locks are wheels-only.  srt
3.5.3 is vendored unmodified as wrolpi/vendor/srt.py (MIT), verified against the sdist
hash the lock pinned; webvtt-py's SRT reader rejects WROLPi's own test file, so it is not
a replacement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 12:00:39 -07:00
Joel Shearon
fe85815c35
Format inventory expiration dates instead of epoch timestamps (#901)
Legacy inventory items stored date fields as Unix epoch seconds. The table showed the raw numbers, and sorting and expired highlighting did not treat them as dates.

- Frontend parses date values as YYYY-MM-DD or legacy epoch seconds; display, mobile view, export, search, sort and the expired check all use calendar dates with no timezone shift.
- The legacy migration converts epoch seconds to YYYY-MM-DD, and import repairs already-migrated files once.
- Jest runs with a pinned timezone; the expiry tests pass under any process timezone.

Closes #41

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-31 12:27:21 -06:00
lrnselfreliance
d69f8317aa
serve, single-file and readability-extractor install from a committed lockfile (#912)
They were installed with `npm i -g`, which pinned only the three top-level versions and
resolved their 156 dependencies fresh from the registry, so a forged TLS certificate (as
the eMudhra key compromise allowed) could change code WROLPi runs on every archive.
npm-tools/package-lock.json pins every package with its sha512, and install_npm_tools.sh
runs `npm ci` and links the commands into /usr/local/bin for every install path, upgrades,
both images and the archive container.  The app container's unpinned, unused global serve
is removed.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:39:08 -06:00
lrnselfreliance
ecdad6c3e0
Caddy's apt repository is trusted through the key committed with WROLPi (#911)
The install scripts, the nginx-to-Caddy upgrade, and the Pi image downloaded Caddy's apt
signing key and source list over TLS and trusted them as-is, so a forged certificate could
serve a key that signs other caddy packages.  add_caddy_apt_repo.sh installs the key the
ISO already uses (fingerprint 65760C51EDEA2017CEA2CA15155B6D79CA56EA34) as an armored
keyring and names it in the source's signed-by.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:22:19 -06:00
lrnselfreliance
bde1209c63
An upgrade refuses to roll back to an older commit of the current branch (#910)
* An upgrade refuses to roll back to an older commit of the current branch

upgrade.sh verifies the fetched commit's signature, but a signature proves a commit is
WROLPi's, not that it is the newest; an intercepted fetch could serve an old signed
release and the forced checkout would roll the device back to it.  refuse_rollback stops
when the target is an older commit of the branch the device is on (a detached HEAD from a
release image counts as that branch).  Branch switches, the same commit, and history the
device does not contain (Debian 12 devices on debian12-final) are allowed, and -d allows
a deliberate downgrade; it reaches the upgrade service through the env file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An upgrade also refuses a signed commit with a lower version from other history

Ancestry alone only caught older commits in the device's own history; any other signed
commit, such as debian12-final or an old experimental branch, passed.  refuse_rollback
now also compares wrolpi/version.txt, which is inside the signed tree, and refuses a lower
or missing version.  A force-pushed branch at the same or a higher version still upgrades.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tests pin the two parts of refuse_rollback that only one rule catches

An earlier commit of the same version is refused only by the ancestry check, and
0.30.10-beta after 0.30.3-beta only orders correctly with sort -V; the fixture's
single-digit versions passed with either part removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:33:25 -06:00
lrnselfreliance
fb3b959fff
install.sh and both image builds run WROLPi only from a signed checkout (#909)
Only upgrade.sh checked the release key's signature.  install.sh and the Pi and ISO
builds cloned by branch or tag name and ran what GitHub returned, so a forged TLS
certificate (as the eMudhra key compromise allowed) could change what a fresh install
or a published image runs.  verify_wrolpi_commit.sh requires a VALIDSIG from the pinned
release-key fingerprint.  The image builds verify their clone with the verifier and key
from the build checkout; install.sh carries an identical copy of the function, since it
runs before any verified checkout exists.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:27:41 -06:00
lrnselfreliance
70e915f610
An upgrade installs Deno only when its sha256 matches (#908)
upgrade.sh downloaded Deno on every device whose Deno was older than the pinned
version and installed it without a check, so a forged TLS certificate (as the eMudhra
key compromise allowed) could replace the runtime yt-dlp uses.  The zip is now checked
against the same sha256 the install scripts pin; a mismatch skips the Deno install and
the upgrade continues.  A test requires every Deno download in the repo to be checked.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 20:48:12 -06:00
lrnselfreliance
dc3a8bb313
The Pi image builds from a pinned pi-gen commit and a checksummed Deno (#907)
The Pi build downloaded pi-gen's `arm64` branch head as a zip and ran it as root, and
downloaded Deno without checking it, so a forged TLS certificate (as the eMudhra key
compromise allowed) could change what went into the image.  pi-gen is now fetched by
commit hash, which git verifies against the objects, and the Deno zip is checked
against the same sha256 the other installers pin.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 20:36:00 -06:00
Roland
2caa2609ec
Bump version to 0.30.3-beta 2026-10-30 19:44:38 -06:00
lrnselfreliance
78e2741db8
A transcode or remux refreshes the sha256 sums a download recorded (#906)
The Job replaces the video file (and its ffprobe json), so the sums in the info json's
wrolpi section described files that were gone.  Once the refresh has re-modeled the
Video, its files are hashed again, without a session held, and the sums replaced.
A Video without recorded sums gains none.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:41:29 -06:00
lrnselfreliance
4c8e9fb68c
The modelers and indexers find unindexed FileGroups through an index (#905)
apply_modelers and apply_indexers count `file_group WHERE indexed != 1` for progress
and apply_indexers selects its batches with it.  SQLite cannot use an index for `!=`,
so each of these read every file_group row; on a large library with a cold disk cache
the first count took close to a minute.  A partial index holds only the unindexed rows.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:40:46 -06:00
lrnselfreliance
32405a9132
A download records the sha256 of its files in the wrolpi section (#904)
* A download records the sha256 of its files in the wrolpi section

A video download writes `wrolpi.sha256` into its .info.json; an archive download writes it into
its .readability.json.  Sums are keyed by suffix, so a rename or Reorganize keeps them valid,
and the metadata JSON holding them is not hashed.

Large files are hashed in execute_download (in a thread, without the DB session).  Finalize
reuses those sums while a file's mtime is unchanged and hashes only files finalize created or
changed (a converted poster, the ffprobe json).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A video download hashes only for an info json, and finalize never suspends

Finalize holds the write session; awaiting the hash let the loop run a switch whose
write waited on that session, stalling the loop for the busy timeout.  Finalize now
hashes inline: the large files were hashed in execute_download.

A download that writes no info json has nowhere to keep the sums, so it no longer
reads its files to hash them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:34:49 -06:00
lrnselfreliance
a40beac0f6
A delete returns once its FileGroups are removed, and models the library afterward (#903)
lib.delete() ran the modelers, indexers, and refresh cleanup inline.  Those cover the
whole library (any unmodeled or unindexed FileGroup anywhere), so a single-file delete
waited on unrelated work and could exceed the response timeout.  The deleted FileGroups
are still removed before the delete returns; the post-processing now runs in the
FileWorker through a queued refresh of the same paths.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:02:01 -06:00
lrnselfreliance
44052741d3
An author or subject beginning with a non-ASCII capital finds its collection (#902)
The lookup compared SQLite's lower(name), which folds only ASCII, with Python's
str.lower(), which folds Unicode.  "Édouard Hospitalier" never matched its own
collection, so the doc modeler inserted a duplicate, hit the unique constraint, and
re-extracted and failed on that doc on every modeler run.  Both sides now use
SQLite's lower().

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 18:37:50 -06:00
lrnselfreliance
56fee562b7
A directory lookup uses the directory index and matches only that directory (#900)
Uploads, deletes, and file refreshes looked up a missing path's descendants with
`directory LIKE 'path/%'`.  SQLite cannot use an index for that LIKE, so each lookup
scanned the whole file_group table; with a cold page cache on a large library this
held the first upload chunk or a delete for tens of seconds.  LIKE also treated `_`
and `%` in a path as wildcards, so refreshing a missing `a_b` removed the FileGroups of
an existing `aXb/sub`.

`directory_or_descendant` matches with a range the directory index can serve.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 19:57:00 -06:00
Roland
49eeef68e8
Bump version to 0.30.2-beta 2026-10-29 18:55:44 -06:00
lrnselfreliance
576f631d95
The Internet check is configurable and no longer stalls background work (#899)
* The Internet check is configurable and no longer stalls background work

The check connected to one host (one.one.one.one, port 80) with no timeout, in
the perpetual process's event loop.  On a network that drops traffic to that
host, each attempt hung for about two minutes and froze every other perpetual
loop (config saves, downloads, the file worker, the media mount check), so
WROLPi reported "No Internet" and "No drive mounted" though both were fine.

- wrolpi.yaml's internet_check_hostname (default one.one.one.one, needs DNS) and
  internet_check_ip (default 1.1.1.1) choose what to connect to; the Internet is
  up when either answers.  Either may be empty.  The INTERNET_SERVER environment
  variable is gone.
- A connection gives up after 5 seconds.
- The check runs in a thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The Internet check tries its IP address first

socket.create_connection resolves a hostname before its timeout applies, so a
name lookup that hangs (a firewall dropping DNS) postponed the IP address, which
needs no lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:05:57 -06:00
lrnselfreliance
a44cc8a456
A channels.yaml import keeps a Channel's once-Downloads (#898)
channels.yaml saves only a Channel's recurring Downloads (Channel.downloads), but
its import compared every Download of a Channel's Collection.  A once-Download of
a Channel's video was "removed from the file", so an import with deletes deleted
it, even one that had not run yet.  The import now compares, and deletes, only
recurring Downloads.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:59:56 -06:00
lrnselfreliance
ce7095c0a1
A config import records the version of the file it read (#897)
* A config import records the version of the file it read

Every Sanic process initializes the configs it shares with the others while one of them imports the
database configs.  `ConfigFile.initialize` reset the shared dict to the defaults (version 0) before
loading the file, and the import read the file's version from that shared dict.  When the two
overlapped, the import recorded version 0 in `config_version`; every later save of that config was
refused as older than its file, and the next startup's import undid the unsaved changes.

- `ConfigFile.initialize` sets the shared dict in one call, and `MultiFileConfig.initialize` no longer
  empties it first, so other processes never see the defaults in place of the file.
- An import reads the version and rows from the file it read (`import_file_config`), never the shared
  dict.

Tests run the race for every config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Playlists import steps read the file's config; tests restore switch handlers

- `PlaylistsConfig._keep_unreadable_items` and `_merge_items` read `import_file_config`, not the
  shared `_config`.
- `test_import_steps_read_the_file`: no versioned config's `prepare`/`after_import` (or the methods
  they call) reads the shared config.
- The new tests create configs, which replaced the global configs' switch handlers for later tests
  (repos tests then dumped a test's config).  `restore_switch_handlers` puts them back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Only the first process loads a shared config; the others attach

A restarted perpetual process initializes the configs while the other processes serve them.
Re-loading the files then reverted or dropped newer changes in the shared dict (an inventory
created or saved since, a config updated but not saved yet).

- `ConfigFile.initialize` loads the file only into an empty shared dict, under
  `config_update_lock`; otherwise it keeps what the dict holds.
- `MultiFileConfig.initialize` imports only into an empty shared store, under `save_lock()`, and
  points `_configs` back at the shared store if the import fails.
- `MultiFileConfig.create` checks for the slug and inserts it under `save_lock()`.

`test_initialize_keeps_the_shared_config` now changes the shared config between two processes'
initializes (an inventory renamed and another created), and requires the second to keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 21:03:52 -06:00
lrnselfreliance
98ceb67321
A malformed entry stops a backup preview or merge with an error naming it (#896)
* A malformed entry stops a backup preview or merge with an error naming it

Backup previews and merges read every config entry as well-formed: a malformed one (an entry that is not a
mapping, a missing or non-text identity, a short tag_files line) raised an AttributeError or TypeError, so the
preview was a 500 and a merge failed with a generic message.  `ConfigFile.backup_entries` now checks each entry
a preview or merge reads, in the backup and in the current config, and raises InvalidConfig naming the file and
the entry; the merge endpoint passes that message on.  A malformed entry may be corrupt, so it is not skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A falsy "tags" that is not a mapping is an error in a backup preview or merge

`tags: []`, `''`, `0` or `false` became no tags through `or dict()` before the mapping check.  Only a missing
or null `tags` means no tags now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 20:59:49 -06:00
lrnselfreliance
3c815245b4
An archive detects a browser when the configured one is not installed (#895)
A configured browser_executable was used without checking it exists.  A config on the media drive can outlive the
OS it was written on: Raspberry Pi OS's /usr/bin/chromium-browser is /usr/bin/chromium on Debian.  The wrapper
discards the browser's stderr, so its failed exec only showed as single-file's "Connection refused ... Child
process has already terminated", and every archive failed.  Now a missing configured browser is logged and one is
detected, as when none is configured.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:59:00 -06:00
lrnselfreliance
9352002d07
Map downloads compare a Download's region with SQLite's JSON operator (#894)
`Download.settings['region'].astext` is PostgreSQL's JSONB operator.  On SQLite it raises AttributeError, so the
map catalog failed before queuing any region Download, and an extract never checked for a CDN search index.  Use
`.as_string()`.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:58:19 -06:00
lrnselfreliance
f4cd3b6f77
Fail CI when vulture finds new dead code (#889)
* Fail CI when vulture finds new dead code

scripts/check_dead_code.py runs vulture and compares its findings with
scripts/vulture_baseline.txt.  The baseline is keyed by file and name, not
line number, so unrelated edits do not invalidate it.  Class fields,
attributes, test arguments (side-effect fixtures), and alembic revision
names are not reported, because nearly all of them are false positives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* TEMP: add a dead function to prove the Dead Code check fails

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Revert the temporary dead function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:10:52 -06:00
lrnselfreliance
4365e23327
Remove code that only tests called (#888)
Deletes functions nothing in the app calls, along with the tests that only
exercised them.  Tests that covered live logic through a dead wrapper now call
the live functions: the Download-linking tests use `domain_download_links` /
`channel_download_links` with `_link_downloads`, the archive tests create
Archives with `write_archive_files` + `register_archive`, and the collection
lifecycle test removes an item with `Collection.remove_item`.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:00:27 -06:00
lrnselfreliance
edca3f610f
Channel downloads follow yt-dlp's playlist redirect and refuse non-channel URLs (#886)
A video URL that names a playlist (watch?v=...&list=...) makes yt-dlp return a
redirect to the playlist instead of the playlist itself.  The ChannelDownloader
now follows up to 10 redirects.  Info without "entries" is not a channel or
playlist, so it is rejected before a Channel is created from it.  Previously
such a Channel was named after the URL ("watch"), and the download then failed
with KeyError: 'entries'.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:00:00 -06:00
lrnselfreliance
8befb23e38
Skip a playlist whose directory is outside the media directory (#884)
playlists.yaml's directory was only made media-relative, so a directory with ".." parts (e.g. "../outside")
was stored as a path outside the media directory, where the playlist's files are synced.  It is now validated
with validate_collection_directory, as domains and channels are; such an entry is skipped and counted, and the
playlist keeps what the database has.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:58:07 -06:00
lrnselfreliance
b14a32c7bc
A recurring Download with more than one URL is an error (#887)
POST /api/download created a recurring Download from the first URL and silently dropped the rest, while answering
201.  No client sends more than one URL with a frequency (each recurring form has one URL field), so reject it, as
PUT /api/download/<id> already does.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:57:47 -06:00
lrnselfreliance
22ada7eb57
Remove unused code found by vulture (#885)
Deletes functions, methods, classes, schema dataclasses, error classes, Events
senders, and module-level constants that nothing references, including tests.
Also drops the unused `doc_cleanup(test_directory)` and
`_wait_for_sub_job_with_progress(collection_idx)` parameters, and the imports
that only served removed code.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:50:09 -06:00
lrnselfreliance
a248104b2f
Starting a Controller script writes its env file every time and rejects unknown parameters (#883)
The upgrade service reads BRANCH from /tmp/wrolpi-upgrade.env, which upgrade.sh removes when it finishes.  The
Controller wrote that file only when a request had parameters, so starting an upgrade without a branch (the simple UI
sends no body when the field is empty) left the service unable to start, while the API answered success.  A request
like {"branch": "master"} was accepted with the key ignored, the same way.

Now the env file is always written, and a missing branch is the current one, as upgrade.sh chooses; a file left by an
interrupted run no longer chooses it.  Unknown parameters and unknown request keys are errors.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:35:23 -06:00
lrnselfreliance
bc58a5cc35
Save download_manager.yaml after new Downloads are committed (#882)
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
create_downloads activated save_downloads_config right after its flush, before the caller committed.  The
switch runs in the perpetual process, which cannot see uncommitted Downloads, so a save that ran first wrote
the file without them and nothing saved them later.  The switch is now activated when the session commits, and
not at all when it rolls back.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 20:32:18 -06:00
lrnselfreliance
eb82489426
Keep playlists.yaml in shared memory so the perpetual process can save it (#881)
playlists_config was the only config not attached to a shared_ctx dict.  Switches save configs in the perpetual
process, which never imports the files, so its playlists_config kept the default version 0.  While the database had
no version row for playlists.yaml, the dump wrote version 1 and `save` refused to overwrite the newer file; the
refused save never recorded the row, so every later save was refused too, and new playlists never reached the
config.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:57:29 -06:00
lrnselfreliance
ae97727b98
Save channels.yaml with the database's version (#880)
save_channels_config wrote the Channels with `update()`, which keeps the version the config already had in
memory.  After a Channel changed, the database's version was ahead of the saved file's, so the next import
treated the file as older and saved the database over it: an edit made to channels.yaml in the meantime was
lost.  It now saves with `dump_config`, which writes the database's version, as every other database config
does.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:39:45 -06:00
lrnselfreliance
d16bac29e8
Renaming a Tag commits its Download renames with the request (#879)
* Renaming a Tag commits its Download renames with the request

update_tag renamed Downloads in a background task using the request's
session, after RequestDB.write() had committed.  Its flush was never
committed, so the rename was lost, and the open write transaction held
SQLite's write lock: every later write failed with "database is locked"
until the API restarted.  Only the Channel moves stay in the background.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Save the Downloads config after a Tag rename commits; scan Downloads only on a rename

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:34:34 -06:00
lrnselfreliance
fffb2ed981
Link a Download to its domain by its destination column (#878)
`domain_download_links` read the destination only from a Download's settings, but the destination is now a column
(the config import moves an old settings destination into it), so no Download was linked to a domain by its
directory.  Read the column, and the settings for an old Download, as channels already do.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:21:55 -06:00
lrnselfreliance
c577cae9d8
Renaming a Tag renames it in Download settings (#877)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
update_tag never renamed settings.tag_names, and its channel_tag_name
edit mutated the JSON in place, so it was never saved.  The old name
stayed, and a Download that later found a new Channel failed (UnknownTag).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:34:47 -06:00
lrnselfreliance
79526afebe
A malformed config entry is skipped and counted instead of failing the import (#875)
* A malformed config entry is skipped and counted instead of failing the import

An entry that is not a mapping (or whose key is not text, or a list that is not a list) made the whole file fail to
import in playlists.yaml, repos.yaml, download_manager.yaml and tags.yaml (tag_files/tag_zims), and a non-text name
did in domains.yaml.  Each is now skipped and counted in import_skipped, so the config is not saved over it, and the
rest of the file imports.  A Channel whose `downloads` is not a list keeps its Downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An unreadable entry keeps no row and does not make a section present

The key of an entry too malformed to name a row is now `Unreadable(position)`.  It is still counted in
import_skipped, but `present` ignores it, so a section whose entries are all unreadable removes nothing (as an empty
section), instead of deleting every row.  A playlist whose `items` is not a list keeps its items, and a Channel
Download whose url is not text is counted (its Channel keeps its Downloads) instead of failing the import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:28:34 -06:00
lrnselfreliance
0dd61b8e64
Strip whitespace from Tag names (#876)
* Tag names have leading and trailing whitespace stripped

A padded name now finds the existing Tag instead of creating a
near-duplicate, and a whitespace-only name is rejected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Migration strips whitespace from Tag names and merges collisions

Tags whose names match once stripped are merged (tagged files, Zim
entries, Collections); the first color by id is kept.  Downloads and the
configs that name Tags are rewritten too, so the next import is in step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tags.yaml keeps the database's color for merged Tags

The file was merged in sorted key order, not by Tag id, and the next
import copies the file's color over the database's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:22:16 -06:00
lrnselfreliance
c3e25b84d6
Configs without database rows read and validate only; imports run off the event loop (#874)
The base import for a config with no sections now reads its file once, reports a 0-byte file as empty, treats a
missing file as the defaults, and records success or failure itself (sending the failure Event on request).  The
per-config overrides that only set successful_import are removed.

wrolpi.yaml and the downloader settings import in a thread at startup (import_file_configs), and the Import, Save
and backup Import buttons run their config work in a thread.

The pre-diff import path (import_decision, record_import_version) has no callers left and is removed.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:17:31 -06:00
lrnselfreliance
ee10b34b15
recently_viewed.yaml imports by diffing (#873)
* recently_viewed.yaml imports by diffing

recently_viewed.yaml declares one section, its files keyed by
media-relative path, comparing viewed, progress and position.  The
database's rows are the window the config saves (the newest
RECENTLY_VIEWED_LIMIT views, inside the media directory), so an
unchanged import writes nothing.

A file removed from the config has its viewing history cleared
(decision 6), but only when its view is at least as recent as the
config's oldest entry: an older view fell off the end of the window.  A
malformed entry keeps its file's history and is not counted as skipped
(that would stop every recently viewed save).  Without deletes, progress
written after the config is kept, and a newer plain view keeps its
`viewed` but takes the config's position (as before).  prepare finds the
files of new entries on disk before the write; a deleted file's history
goes with it.

Moving a viewed FileGroup counts as a recently_viewed.yaml change (ORM,
the bulk move, and a refresh that changes the primary file).  The media
directory checks are batched (each resolved the media directory again).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* recently_viewed.yaml: the no-delete merge covers files outside the window

Without a database version, newer history in the database wins (its
progress is kept; a newer plain view keeps its `viewed` and takes the
config's position).  That applied only to files among the newest views;
a file listed in the config that had fallen out of them was "added",
and its stale entry replaced the newer history.  prepare now reads the
database's history of added files and applies the same rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 14:39:45 -06:00
lrnselfreliance
315b60e9eb
channels.yaml imports by diffing (#872)
* channels.yaml imports by diffing

channels.yaml declares two sections: Channels keyed by directory
(comparing name, URL, Tag, file format, and the source id and flags,
which keep the database's value when missing), and the Downloads listed
under each Channel, keyed by (directory, URL); an existing Download keeps
its own frequency.  An unchanged import writes nothing (it ran about a
thousand queries and committed several times).

Removed Channels are deleted with their Collection (and Downloads);
a Download removed from a Channel is deleted.  A channel Collection
without a Channel is deleted unless listed (then it gets its Channel).
A Channel whose directory changed, with the same name, is moved.  An
invalid entry is skipped and counted, and keeps its Channel (by name when
its directory is invalid) and that Channel's Downloads; so does an entry
without a list of Downloads.  Duplicate directories still refuse the
import.  Unknown Tags are dropped once tags.yaml is imported.

New Downloads are created in the import's one write (commit=False on
Channel.get_or_create_download, Download.delete and delete_with_videos).
After the import, Videos are claimed and source ids fetched only for new
and changed Channels; Downloads are linked without a query per Download,
and not while entries are skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* channels.yaml: moves, invalid Downloads, and saves after the write

- A moved Channel's Download diff is retargeted to its new directory:
  one its new entry lists is the same Download, one it does not is
  deleted in the same import (the old directory was treated as kept).
- An unreadable Download is counted as skipped, and its Channel keeps
  its Downloads (it was dropped, and the Channel's Download deleted).
- A new Download without a frequency is dropped before the write and
  counted (it re-opened a write on every import).
- No source id is fetched while entries are skipped (its save would be
  refused, leaving the database newer than the file); a fetched one is
  saved with dump_config, which records the database's version.
- Download.delete(commit=False) neither changes the skip list nor starts
  config saves, which would read the database before the import commits
  (and write a removed Download back into channels.yaml).  The import
  saves download_manager.yaml after its write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 13:13:42 -06:00
lrnselfreliance
57c2a29022
domains.yaml imports by diffing (#871)
* domains.yaml imports by diffing

domains.yaml declares one section, its domain Collections keyed by name,
comparing description, directory, Tag and file format.  An unchanged
import writes nothing.

A removed domain without Archives is deleted; one with Archives is reset
to its default settings (decision 7c: a refresh of its Archives would
re-create it), and the config is saved with it.  An invalid entry (name
or directory) is skipped, counted, and its domain kept.  Once tags.yaml
is imported, a domain's Tag that no longer exists is dropped and the
config saved without it (`unknown_tag_names`).

Linking Downloads to domains reads first (the domains once, not one query
per RSS Download) and opens a short write only when there is something to
link; the config is then saved with the links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test_bookmarks_config_import starts the app like its siblings

It imports a config without `async_client`, so it fails (no
shared_ctx.configs_imported) whenever it is the first test on its
worker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* domains.yaml: converge without a save; no links while entries are skipped

A save after the import is refused while an entry is skipped, so the
import must converge without one:
- a removed domain with Archives that is already reset is left as it is
  (prepare reads `import_db_rows`); before, every import reset it again;
- after prepare, the framework drops changed rows that now match the
  database (a dropped unknown Tag), so they are not written again.

Linking Downloads changes domains.yaml after its version is recorded;
while entries are skipped the save is refused, the database stays newer,
and the next startup would save over the skipped entries.  Linking now
waits for an import without skipped entries.

An entry that is not a mapping is skipped and counted, instead of failing
the whole file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 11:41:59 -06:00
lrnselfreliance
5cdb4aaac0
repos.yaml imports by diffing (#870)
* repos.yaml imports by diffing

repos.yaml declares one section, its Repos keyed by repo_url_key (another
URL of the same Repo is that Repo), comparing name, description,
directory, Tag, mode, branch, submodules, frequency and clone token (a
missing directory or clone token keeps the database's).  An unchanged
import writes nothing (every import rewrote every Repo and its
Download).

An invalid entry is skipped and counted, and its Repo is kept; before,
a Repo whose entry failed validation was deleted.  New Repos are created
inside the import's one write: recurring_download (via
get_or_create_download and _set_repository_download) takes commit=False,
and the URL is not looked up again for each new Repo (O(N^2)).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* repos.yaml: a branch URL is keyed by its Repo's URL

file_rows keyed the raw URL, but stores parse_repo_url's URL, which
turns a forge's branch URL (GitHub /tree/<branch>, GitLab
/-/tree/<branch>) into the repo URL and a branch.  The entry looked like
a new Repo: its insert hit the existing Repo's name (rolling back every
import of that file), and an invalid such entry did not protect its Repo
from deletion.  Rows and invalid keys now use the parsed URL; a URL that
cannot be parsed is skipped by its raw key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 10:36:12 -06:00
lrnselfreliance
adbcf944a5
playlists.yaml imports by diffing (#869)
* playlists.yaml imports by diffing

playlists.yaml declares two sections: playlists, keyed by name, and
their items, keyed by what each points to (a file's or Zim's
media-relative path and entry, or a URL) with position and title
compared.  A playlist has at most one item per reference, so a moved
item changes only its position and keeps its row; an unchanged import
writes nothing (every import deleted and re-created every item).

prepare skips items whose file or Zim is not indexed before the write
(their place is kept), drops a Tag that no longer exists once tags.yaml
is imported (the config is then saved), and, without deletes, keeps the
database's order and adds the file's other items after the item that
precedes them.

Moving a FileGroup in a playlist counts as a playlists.yaml change (ORM,
the bulk move, and a refresh that changes the primary file).

media_relative moves to wrolpi.config_import for both configs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Playlist items: keep database order without deletes; empty lists delete

Without a database version, every playlist with an added or changed item
keeps the database's order (the file's new items go after their
predecessor; only titles come from the file), and a row whose merged
position and title equal the database's is not written.  Before, only
playlists that gained an item were merged, so a file that only reordered
(or lacked an item the database had) gave two items one position.

A section can say it is present without rows (`ConfigSection.present`):
a listed playlist with an empty items list has its items removed; an
empty or missing playlists list still removes nothing.  An item that
cannot be read, or repeats another, is counted in import_skipped, so the
config is not saved over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 09:42:26 -06:00
lrnselfreliance
b67d51b69a
tags.yaml imports by diffing (#868)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* tags.yaml imports by diffing

tags.yaml declares three sections (Tags, tagged files, tagged Zim
entries), so its import reads the file once, diffs it against a snapshot,
and writes only the differences, with the file's version, in one write.
An unchanged import writes nothing.

A removed Tag is deleted with its tagged files and Zim entries; a
Collection using it loses only the Tag.  A removed tagged file or Zim
entry is untagged.  A tagged file whose Tag the config does not list is
skipped.  prepare finds files without a FileGroup on disk, skips missing
ones before the write, moves Zim entries of a replaced Zim to the newest
one, and maps a file named by a secondary member to its group; the
config is then saved with the database's paths.

Moving a tagged FileGroup counts as a tags.yaml change (ORM, the bulk
move, and a refresh that changes the primary file), so a restart before
the save does not untag it.

Sections can define `same` (a tagged file without a date matches any
date), and prepare can count skipped rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A removed Tag leaves no Download that would apply it

The tags import removes a deleted Tag's name from every Download's
tag_names and from the tag_names and channel_tag_name its settings pass
on (a change to download_manager.yaml, which is then saved).  Applying a
Tag that does not exist fails the download, and it is retried.  Once
tags.yaml is imported, a newer download_manager.yaml drops names no Tag
has, and is saved without them.

A replaced Zim's entry tags move to the newest Zim of the same parsed
name, by the date in its name (as migrate_outdated_zim_tags picks it),
not by name prefix and path order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:16:39 -06:00
lrnselfreliance
6434d5ca20
Database configs import by diffing; download_manager.yaml first (#867)
* Database configs import by diffing; download_manager.yaml first

Step 2 of the config import rework.  A database config can now declare a
ConfigSection for each kind of row it saves, and ConfigFile.import_config runs
a fixed sequence for it:

- read and validate the file once;
- decide from the versions (wrolpi.config_version) what the import may do;
- snapshot each section's rows as plain data keyed the way the file names them,
  and diff: added, changed, removed (none from an empty section, or without a
  current version);
- prepare (files, network) with no transaction open;
- write only the differences, and the file's version, in one short write.  A
  failure writes nothing.  If the database's version changed since the
  snapshot, the import decides again (and saves a newer database).

Subclasses override the section methods (file_rows, db_rows, upsert, delete)
and the prepare/after_import hooks.  The other database configs keep their
importers until their own steps.

download_manager.yaml is the first: an unchanged config imports with no write
(was 5,000 statements for 2,500 Downloads), new Downloads are one INSERT, and a
missing ZimSubscription is restored without rewriting the rest.  Settings equal
to the global defaults compare as unset, as they are saved.  A destination
written relative to the media directory is stored absolute.  Completed
once-downloads are never removed (they are not saved; #679).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sync Zim subscriptions directly during the downloads import

A row now compares its subscription's (name, language), derived from the
URL, instead of whether one exists.  The import moves a subscription of
that name onto the written Download (a changed language or URL), removes
one the file no longer implies, and leaves the Download's own columns as
the file has them; change_download renamed the old Download's URL into
the one just inserted, and reset attempts and the downloaders.  A Kiwix
URL that names no known subscription is a plain Download instead of
failing the whole write.

prepare runs only when there are differences, and its docstring states
that it must be safe to repeat and to abandon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 18:49:24 -06:00
lrnselfreliance
946043450e
Database configs carry a version the database keeps too (#866)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* Benchmark every database config import (#865)

An opt-in test (WROLPI_CONFIG_BENCH=1) that builds a large library in bulk,
writes each config with its own dump_config, then times every import in
startup order: a steady pass (the database already matches) and a rebuild
(config-owned rows deleted, everything restored from the configs).  It
prints seconds, SQL statements and writes per import, and asserts the
rebuild restored every row so no timed import silently skipped its work.
WROLPI_CONFIG_BENCH_SCALE multiplies the row counts.

The baseline for the config import rework.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* Database configs carry a version the database keeps too

Step 1 of the config import rework.  A database config (tags, downloads,
channels, domains, playlists, repos, recently viewed) and the database now
each carry an integer version, so an import can tell which side is newer
without a clock (a Raspberry Pi's resets at boot):

- config_version (new table) holds the database's version of each config.
- An after_flush hook adds one to it for every config whose rows a flush
  changed, in the same transaction.  Each config registers what it owns
  (register_ownership): models, optionally only some columns, optionally
  only some rows (a Collection's kind; a Download's Collection's kind).
  Raw SQL writes to owned tables count explicitly.
- dump_config writes the database's version, read with the rows it saves;
  save() no longer adds one for these configs.
- An import compares versions first: file == database or newer imports
  with deletes; file older (the database changed and was not saved before a
  restart) saves the database instead of undoing that change; no database
  row (a config this code never imported) imports without deletes.  The
  import records the file's version last.
- The Import button and backup imports apply the file whatever its version
  (import_forced).

Importers only gate their existing deletes on the decision here; they are
otherwise unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Config versions: keep unsaved rows after a no-delete import, count every owned write

Review fixes:

- An import without deletes (no database version yet) no longer records the
  file's version, which let the next startup delete the rows it had kept.
  The version stays unknown, and the database is saved into the file instead;
  a successful save records the version.  A save after a partial import is
  refused, so the version stays unknown until an import applies the whole file.
- An import removes the database's version while it runs, so its own writes
  do not count: one that fails partway no longer looks newer than the file
  and gets saved over it on the next startup.
- Playlists imported without deletes keep their database items in order; the
  file's other items are added after their neighbor from the file.
- A Download leaving a Channel or Repo counts for that Collection's config
  (collection_id loads its previous value).
- Bulk writes count: untagging, retrying Downloads, deleting a duplicate's
  Download, removing many items from a playlist.  Deleting Downloads by id
  counts channels.yaml/repos.yaml only for their Downloads.
- Only a playlist's items count for playlists.yaml (author and subject
  Collections have items too).  Collection kinds are looked up once per flush.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Config versions count only the columns each config saves

A Repo's fetch (head_sha, last_fetch), a Channel's refresh (video_count,
info_json), a Collection's counts, and a Download attempt (attempts, error)
counted as config changes, so the next import of that config saved instead of
importing: a hand edit to repos.yaml was overwritten after any fetch.  Each
model now registers only the columns its config saves.

domains.yaml saves its domains' Downloads, which now count for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:58:18 -06:00
lrnselfreliance
b5fa59a5c4
Benchmark every database config import (#865)
An opt-in test (WROLPI_CONFIG_BENCH=1) that builds a large library in bulk,
writes each config with its own dump_config, then times every import in
startup order: a steady pass (the database already matches) and a rebuild
(config-owned rows deleted, everything restored from the configs).  It
prints seconds, SQL statements and writes per import, and asserts the
rebuild restored every row so no timed import silently skipped its work.
WROLPI_CONFIG_BENCH_SCALE multiplies the row counts.

The baseline for the config import rework.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:02:34 -06:00
lrnselfreliance
a93630576f
Tests fail when a request writes outside request.ctx.db.write() (#864)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* Tests fail when a request writes outside request.ctx.db.write()

A request's transaction begins deferred.  A write in it after a read fails
instantly ("database is locked") when another connection wrote in between,
and a write left for the response middleware's commit can be lost after the
response was sent.  #846-#853 and #863 moved handlers' writes into
request.ctx.db.write(); this keeps it that way.

Under pytest, a listener records every INSERT/UPDATE/DELETE/REPLACE made
while a request runs (or in a task it started) outside RequestDB.write()
or get_db_session(commit=True), and the autouse no_deferred_request_writes
fixture fails the test.  allow_deferred_request_writes opts a test out.
The test-only response listener now runs switches outside the request,
as production's perpetual process does.

It found three more:
- DELETE /api/zim/<ids> deleted the .zim file, returned 204, then lost the
  row's delete when the middleware's commit failed under contention.  It
  now writes in request.ctx.db.write().
- Viewing a file recorded the view in a background task on the request's
  Session, after the request ended.  set_file_viewed opens its own write.
- tags.import_config (startup and config import) read, then wrote, in a
  deferred get_db_session().  It now begins as a writer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tasks don't inherit a declared write; tags import change backed out

From review of #864:

- background_task's task copied its creator's Context, including
  _write_intent when started inside get_db_session(commit=True) or
  RequestDB.write(), so the guard ignored the task's own writes for its
  lifetime.  The task now starts with no declared write.  That exposes
  fetch_channel_source_id (started by the channels config import): it read
  the Channel, asked the remote site for its source_id, then committed in
  the same deferred transaction.  It now reads, fetches with no
  transaction open, then writes in a short get_db_session(commit=True).
- tags.import_config: commit=True held the write lock through its directory
  walk, and its exit commit saved changes the need_commit gate used to
  drop.  Reverted to master; splitting its reads from a short write is its
  own change.  The two tests that run it through a request are marked
  allow_deferred_request_writes until then.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:09:39 -06:00
lrnselfreliance
604d467861
Renaming a directory with Collections waits for a concurrent writer (#863)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* Remove a file's Tags Directory links when WROLPi deletes it (#861)

* Remove a file's Tags Directory links when WROLPi deletes it

When WROLPi deleted a tagged file (a forced delete, duplicate Video cleanup, or a poster conversion), the
source was unlinked but its Tags Directory hardlink was not.  The link became the only copy, so the tags sync
refused to delete it and warned on every sync.  The links of a file are now removed before WROLPi removes it,
and only if the link is the same file as its source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove Tags Directory links on path deletes; keep a valid poster's link

The file browser deletes by path (`lib.delete`), which unlinks the sources before any FileGroup is
deleted, so its tagged files still left orphaned links.  It now removes the links of the files it is about
to delete, or of every FileGroup in a deleted directory.

A poster is no longer unlinked from the Tags Directory unless it is actually removed: a valid JPEG that is
not named .jpg is kept with its link, and a converted poster's links are removed only once the conversion
succeeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* Renaming a directory with Collections waits for a concurrent writer

POST /api/files/rename on a directory changed Collections on the request's
deferred transaction.  For a plain directory, that transaction was opened
before the FileWorker moved the files and wrote only after, so if anything
else wrote meanwhile the Collection update failed ("database is locked"):
the request returned 409 with the files already moved, and the nested
Collections still pointed at the old directory.  Renaming a Collection's
own directory failed the same way, before moving anything.

rename_directory now changes Collections in a `write` (request.ctx.db.write
from the endpoint), which begins as a writer.  Files are moved outside it;
nested Collections are read inside it, after the move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:42:34 -06:00
lrnselfreliance
9bbef50ca1
Remove a file's Tags Directory links when WROLPi deletes it (#861)
* Remove a file's Tags Directory links when WROLPi deletes it

When WROLPi deleted a tagged file (a forced delete, duplicate Video cleanup, or a poster conversion), the
source was unlinked but its Tags Directory hardlink was not.  The link became the only copy, so the tags sync
refused to delete it and warned on every sync.  The links of a file are now removed before WROLPi removes it,
and only if the link is the same file as its source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Remove Tags Directory links on path deletes; keep a valid poster's link

The file browser deletes by path (`lib.delete`), which unlinks the sources before any FileGroup is
deleted, so its tagged files still left orphaned links.  It now removes the links of the files it is about
to delete, or of every FileGroup in a deleted directory.

A poster is no longer unlinked from the Tags Directory unless it is actually removed: a valid JPEG that is
not named .jpg is kept with its link, and a converted poster's links are removed only once the conversion
succeeds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:40:57 -06:00
lrnselfreliance
da3dadde07
Apply the offset in a SingleFile saved date, and repair misread Archive dates (#862)
* Apply the offset in a SingleFile saved date

SingleFile writes the browser's local time with its offset ("... 18:36:23 GMT-0700").  The parser dropped
the offset and treated the local time as UTC, so an uploaded Archive's download_datetime was off by the
browser's UTC offset, and a Collection reorganize renamed its files with that shifted timestamp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Repair Archive download datetimes misread from a SingleFile saved date

Archives parsed before the offset fix keep the shifted download_datetime, because the parser only fills
an empty value.  A one-time background repair (gated by a wrolpi_kv version, after the first refresh)
re-reads each Archive's saved date and corrects a download_datetime that equals the offset-dropped value.
Any other download_datetime is left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Read the whole SingleFile header; finish the date repair only when every Archive was read

The header was read in 1000 bytes, so a long URL cut the saved date's offset off, and the cut-off date was
stored as GMT.  The header is now read through the end of its comment, and a malformed offset leaves the
date unset instead of guessing.

The repair is no longer marked done when an Archive could not be read (a missing file is a deleted Archive,
not a failure), and it waits for the media to be mounted, because `refresh_complete` is restored from the
database before the drives are checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:34:29 -06:00
lrnselfreliance
1f3762ff20
Clear the FileWorker private queue between tests (#860)
The test harness resets the shared file worker public queue for each test,
but the FileWorker's private LifoQueue is per-process state that survived
from one test to the next. Tests that process only a count task leave its
chained refresh task queued, and it later ran inside an unrelated test.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:03:55 -06:00
dependabot[bot]
58192a7052
build(deps): bump dompurify from 3.4.16 to 3.4.17 in /app (#857)
* Distrust compromised eMudhra intermediates in certifi and Deno (#854)

* Distrust compromised eMudhra intermediates in certifi and Deno

The private keys of eight eMudhra intermediate CAs can be recovered from
their certificates, so anyone can mint a trusted certificate for any host.

* Require certifi>=2026.10.19; yt-dlp, requests and curl-cffi use its bundle,
  and 2026.10.19 removes the emSign ECC Root CA - G3 root they chain to.
* Set DENO_TLS_CA_STORE=system for the API (systemd + Docker) and the archive
  container so Deno follows the apt-patched system store instead of roots
  that only change with a Deno upgrade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep Deno's bundled roots in the archive container

browserless/chrome:1.61.1 is Ubuntu 22.04 whose newest ca-certificates is
from 2023, older than Deno 2.8.3's bundled roots.  The system store only
becomes the better choice once the archive base image is upgraded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* build(deps): bump dompurify from 3.4.16 to 3.4.17 in /app

Bumps [dompurify](https://github.com/cure53/DOMPurify) from 3.4.16 to 3.4.17.
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.4.16...3.4.17)

---
updated-dependencies:
- dependency-name: dompurify
  dependency-version: 3.4.17
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-23 12:33:35 -06:00
dependabot[bot]
dd2e778fea
build(deps): bump launch-editor from 2.14.1 to 2.14.2 in /app (#855)
Bumps [launch-editor](https://github.com/vitejs/launch-editor) from 2.14.1 to 2.14.2.
- [Commits](https://github.com/vitejs/launch-editor/compare/v2.14.1...v2.14.2)

---
updated-dependencies:
- dependency-name: launch-editor
  dependency-version: 2.14.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-23 12:33:26 -06:00
lrnselfreliance
74e4654a26
Refresh keeps a duplicate FileGroup's tags when collapsing duplicates (#859)
When refresh finds FileGroups sharing (directory, stem) it keeps the highest-id row and deletes the
rest.  Deleting cascades, so the loser's tags and collection membership were silently lost, and the
next tags config save persisted the loss.  Before the duplicate is deleted, its tags and collection
membership now move onto the FileGroup that survives it, reusing the merge the stem migration uses.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:33:11 -06:00
Roland
d992dc99d2
Ignore the null muxer's duplicate-DTS warning in the tail-decode check (#858)
ffmpeg exits 0 but prints "non monotonically increasing dts to muxer"
from the null output when two frames share a timestamp, collapsed into
"Last message repeated N times" when piped.  Any stderr failed the
completeness check, so such videos (common on X) were rejected as
incomplete on every retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:33:23 -06:00
lrnselfreliance
9ccf19b82b
Distrust compromised eMudhra intermediates in certifi and Deno (#854)
* Distrust compromised eMudhra intermediates in certifi and Deno

The private keys of eight eMudhra intermediate CAs can be recovered from
their certificates, so anyone can mint a trusted certificate for any host.

* Require certifi>=2026.10.19; yt-dlp, requests and curl-cffi use its bundle,
  and 2026.10.19 removes the emSign ECC Root CA - G3 root they chain to.
* Set DENO_TLS_CA_STORE=system for the API (systemd + Docker) and the archive
  container so Deno follows the apt-patched system store instead of roots
  that only change with a Deno upgrade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Keep Deno's bundled roots in the archive container

browserless/chrome:1.61.1 is Ubuntu 22.04 whose newest ca-certificates is
from 2023, older than Deno 2.8.3's bundled roots.  The system store only
becomes the better choice once the archive base image is upgraded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:54:57 -06:00
lrnselfreliance
cbf69e3013
Repo changes wait for a concurrent writer (#853)
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
Adding, importing, changing, deleting and updating a Repo read, then
wrote, in the request's deferred transaction, so they failed with a 500
("database is locked") when another connection wrote in between.  They
now write inside request.ctx.db.write().

Importing reads the clone with git and walks it for its size; those run
before the write transaction, so it is not held for them.  Everything
that can refuse the import still runs before the clone is changed.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:50:09 -06:00
lrnselfreliance
bcf977cfae
which() prefers the executable found in $PATH (#852)
which() kept looking after shutil.which found a name in $PATH, so a later
fallback path (e.g. '/usr/bin/git' in which('git', '/usr/bin/git'))
always replaced it.  Its docstring says $PATH comes first; stop at the
first match.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:49:41 -06:00
dependabot[bot]
82cc824fb7
build(deps): bump markdown-it from 15.0.2 to 15.0.3 in /app (#844)
Bumps [markdown-it](https://github.com/markdown-it/markdown-it) from 15.0.2 to 15.0.3.
- [Changelog](https://github.com/markdown-it/markdown-it/blob/master/CHANGELOG.md)
- [Commits](https://github.com/markdown-it/markdown-it/compare/15.0.2...15.0.3)

---
updated-dependencies:
- dependency-name: markdown-it
  dependency-version: 15.0.3
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-21 16:49:27 -06:00
dependabot[bot]
72bea377ee
build(deps): bump pillow from 12.3.0 to 13.0.0 (#843)
Bumps [pillow](https://github.com/python-pillow/Pillow) from 12.3.0 to 13.0.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/12.3.0...13.0.0)

---
updated-dependencies:
- dependency-name: pillow
  dependency-version: 13.0.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-21 16:49:13 -06:00
lrnselfreliance
3946e315fc
Channel and map subscription changes wait for a concurrent writer (#851)
PUT/DELETE /api/videos/channels/<id>, POST /api/videos/channels/<id>/tag,
and POST/DELETE /api/map/subscribe read, then wrote, in the request's
deferred transaction, so they failed with a 500 ("database is locked")
when another connection wrote in between.  They now write inside
request.ctx.db.write().

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:48:52 -06:00
lrnselfreliance
cb830594ae
Zim tagging, auto-search and subscriptions wait for a concurrent writer (#850)
POST /api/zim/<id>/auto_search, /tag, /untag, /subscribe and
DELETE /api/zim/subscribe/<id> read, then wrote, in the request's deferred
transaction, so they failed with a 500 ("database is locked") when another
connection wrote in between.  They now write inside request.ctx.db.write().

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:48:39 -06:00
lrnselfreliance
212366c2eb
Tagging, untagging and deleting files wait for a concurrent writer (#849)
POST /api/files/tag, /untag and /delete_groups read, then wrote, in the
request's deferred transaction.  SQLite fails that lock upgrade instantly
("database is locked") when another connection wrote in between.  Tag and
untag returned a 500; delete_groups returned 204 after FileGroup.delete had
unlinked the files, then its commit failed in the response middleware, so
the FileGroup row outlived its files.  They now write inside
request.ctx.db.write(), which begins as a writer and lets busy_timeout
absorb the contention.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:48:27 -06:00
lrnselfreliance
a40b69cee9
Download and tag requests wait for a concurrent writer (#848)
Deleting, restarting, clearing and batch-editing Downloads, and creating,
renaming and deleting Tags, read then wrote in the request's deferred
transaction.  SQLite fails that lock upgrade instantly ("database is
locked") when another connection wrote in between, so these failed with a
500 while a download or refresh was writing.  They now write inside
request.ctx.db.write(), which begins as a writer and lets busy_timeout
absorb the contention.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:48:16 -06:00
lrnselfreliance
22afb81879
Reorganize conflicts and no-move reorganize wait for a concurrent writer (#847)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Follow-up to #846, from review:

- The reorganize conflicts endpoint read the preview, ran ffprobe, then
  flushed and committed in the request's deferred transaction.  It now
  reads, runs ffprobe through get_or_create_ffprobe_json (no session),
  and stores the results in one short request.ctx.db.write().
- Its ffprobe step never ran: it matched model_type == 'channel', but a
  conflicting video's model_type is its FileGroup's model, 'video'.
- execute_reorganization's no-move path stored the new file_format with
  session.commit() on the caller's deferred session, from the reorganize
  endpoint and from the batch job.  The scan stays a read; the store is a
  short write (request.ctx.db.write() in a request, its own connection
  otherwise).  Called without a session it now opens a read session, so
  that write does not wait on its own caller's lock.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:16:17 -06:00
lrnselfreliance
97d7eb260c
Collection create/update/tag/delete wait for a concurrent writer (#846)
These endpoints read, then wrote, in the request's deferred transaction.
SQLite fails a deferred transaction's lock upgrade instantly ("database
is locked") when another connection wrote in between, so a collection
change during a refresh or download could fail with a 500.  They now
write inside request.ctx.db.write(), which begins as a writer and lets
busy_timeout absorb the contention; errors are mapped outside the block
so a 4xx rolls back.

Fixes #674

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:42:14 -06:00
lrnselfreliance
2f5d88ad4e
Live USB: allow password SSH (#845)
live-config's openssh-server component rewrites sshd_config to
"PasswordAuthentication no" on every live boot, so the live session only
accepted SSH keys.  An sshd_config.d drop-in sets it back to yes; sshd uses
the first value it reads and sshd_config includes the drop-ins first, so the
drop-in wins.  The login is user / live (live-config's default), now noted
in INSTALL.md.  check-iso.sh fails the build if the drop-in is missing.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:29:40 -06:00
dependabot[bot]
4becad7d36
build(deps): bump follow-redirects from 1.16.0 to 1.16.1 in /app (#842)
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.16.0 to 1.16.1.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.16.0...v1.16.1)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-version: 1.16.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-20 15:05:21 -06:00
lrnselfreliance
3a9beae119
Debian ISO: WROLPi banner in the graphical installer (#841)
The installer opened with Debian's "debian 13" banner.  Debian's
derivative guidelines say derivatives must not be presented as Debian,
and its trademark policy forbids implying endorsement, so the installer
now shows a WROLPi banner in the boot splash's style (pie logo, WROLPi,
"Off-grid library", purple accent).

The banner replaces rootskel-gtk's logo_debian.png and logo_debian_dark.png
(logo_installer*.png link to them) via config/includes.installer, which
live-build adds to the installer initrd.  It is 800x75 like Debian's; the
installer stretches its edge columns to the screen width, so the edges are
solid color.  check-iso.sh fails the build if the graphical installer's
initrd does not carry it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:00:09 -06:00
lrnselfreliance
1e89cb55f6
Fresh Live USBs don't report an ownership update (#840)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
The library-ownership migration compared the owner of
/mnt/persistence/wrolpi after creating it, so on a new persistence
partition the root-owned directory always looked like an old library and
the first-boot dialog said "Updated the library's ownership for this
WROLPi version".  Only re-own a library that already existed.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 19:52:26 -06:00
lrnselfreliance
22be73a1c9
Debian ISO: advertise wrolpi.local with Avahi (#839)
INSTALL.md and the onboarding wizard send people to wrolpi.local, but the
Debian image had no mDNS responder, so the name never resolved on a Debian
install or Live USB.  Raspberry Pi OS ships Avahi; the ISO now does too.

libnss-mdns lets the WROLPi's own desktop resolve .local names (apt
recommends are off in the build, so it is listed explicitly).  check-iso.sh
fails the build if either package is missing.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 19:39:33 -06:00
Roland
c6bdd759e4
Bump version to 0.30.1-beta
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:57:29 -06:00
lrnselfreliance
1f07b5f944
Readability extraction no longer takes minutes on image-heavy pages (#838)
* Readability extraction no longer takes minutes on image-heavy pages

SingleFile inlines every image as a base64 data URI, and readability-extractor
(jsdom) slows to minutes on a page carrying megabytes of them, so these pages
hit the readability timeout and were saved without readability text.

Replace each base64 payload with a short placeholder before running
readability-extractor, then restore the payloads in its output.  Applied in
both the archive container and the native (Raspberry Pi/Debian) path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Data URI placeholders cannot be forged by page text

The placeholder was a fixed string, so a page containing placeholder-like
text could index past the payloads (IndexError, failing the archive on the
native path) or repeat a placeholder to copy a large image into the output
many times.  Each extraction now uses a random token, and text that is not a
known placeholder is left as-is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Data URI placeholders survive Readability's lazy-image cleanup

Readability's _fixLazyImages removes an <img> src whose base64 payload is
shorter than 133 characters when another attribute names an image file
(alt="cat.png", title, a leftover data-src), treating it as a lazy-load
placeholder.  The ~50 character placeholder triggered this, so those images
lost their inline data.  The token is now 160 hex characters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:50:21 -06:00
lrnselfreliance
06e35e1095
Archive container reaps its zombie processes (#837)
The archive service is PID 1 in its container and never reaps orphans.
check_output kills each command's process group, so every archive leaves
chrome, cat, and node grandchildren behind as zombies.  A long-running
container accumulated hundreds of them, counting against its PID limit.

init: true runs tini as PID 1, matching the web container.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:10:17 -06:00
lrnselfreliance
c6613dfee0
Debian ISO: hostname defaults to wrolpi, boot menu times out (#836)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* Debian ISO: hostname defaults to wrolpi, boot menu times out

The installer's hostname question defaulted to "debian", so an install that
kept the default was not reachable at wrolpi.local.  A preseed in the
installer initrd now defaults it to wrolpi; the question is still shown (and
a DHCP-provided hostname still wins).

The ISO's GRUB and ISOLINUX menus had no timeout, so a Live USB waited at the
boot menu forever after any reboot or power loss.  The menus now boot the
default entry ("Run WROLPi (live)") after 10 seconds.

check-iso.sh fails the build if either regresses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Debian ISO: say what the wrolpi hostname is for

The image does not include avahi-daemon, so the hostname alone does not make
wrolpi.local resolve.  The default still names the TLS certificate, the
SMB/NetBIOS share, and the DHCP hostname a router may publish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 06:59:21 -06:00
lrnselfreliance
baa86b4ad1
Upgraded Live USBs keep a writable library (#835)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
ISOs before wrolpi became a system account wrote the Live USB's library on
the persistence partition as UID 1000.  Upgrading such a USB with a newer
ISO (wrolpi-usb.sh upgrade) keeps the persistence partition, so the library
would belong to the live session's "user" and the services could not write
to it.  Bootstrap now re-owns the library once when its owner is not this
image's wrolpi.  Live USBs only: installed systems' drives are left alone.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:23:53 -06:00
lrnselfreliance
f644a80c9a
Debian installs create the user the installer asks for (#834)
The ISO's chroot hook created wrolpi as a login user (UID 1000, password
"wrolpi", full sudo, LightDM autologin).  The Debian installer creates the
user it asks for only when no UID 1000-59999 user exists, so it silently
skipped that user: the only login on an installed system was wrolpi/wrolpi,
with SSH and sudo.

wrolpi is now a system account with no password or login sudo, as on every
other WROLPi deployment.  The installer creates the user it asks for (with
sudo, no autologin).  The live session logs in as live-config's "user".
Desktop shortcuts moved to /etc/skel so every user gets them.

check-iso.sh now fails the build when the image has a UID 1000-59999 user.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:23:40 -06:00
lrnselfreliance
826f1cdc42
The drive wizard never offers an EFI system partition (#833)
On a Debian install the onboarding wizard offered the EFI system partition
(unlabeled vfat at /boot/efi) as the primary WROLPi drive; choosing it would
mount the boot partition over /media/wrolpi.  Candidates were filtered by
the "EFI" label only, and the Debian installer leaves the ESP unlabeled.

/boot/efi is now an excluded mountpoint, and partitions with the EFI system
partition type (GPT GUID or MBR 0xef, from lsblk PARTTYPE) are excluded even
when unmounted, e.g. on a second internal disk.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:26:18 -06:00
lrnselfreliance
80678e1f6e
A library on the internal disk gets a database (#832)
"Run repair without external drive" kept the library on the internal disk,
but the API's unmounted-media guard refuses to create or use a database
beneath /media/wrolpi when it is not a mount.  After onboarding without a
drive the API restarted forever with no database, and downloads were
blocked as "media not mounted".

The Controller now records the choice as drives.library_on_internal_disk in
controller.yaml -- the only source of it.  The database guard and the
media_mounted check both read that marker, so require_media_mounted keeps
its meaning and needs no change.  Onboarding a drive later clears the
marker, so it is never copied onto the drive.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:15:33 -06:00
lrnselfreliance
ad56134851
install.sh installs on Debian 13 (#830)
install.sh only accepted Debian 12, which cannot run this version, and
rejected Debian 13.  It now requires Debian 13 or newer on both PCs and
Raspberry Pis.  The install scripts point to the drive wizard instead of
manual mounting.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:51:40 -06:00
lrnselfreliance
559bfebc56
Installed Debian systems keep Caddy (#831)
* Installed Debian systems keep Caddy

The Debian installer purges every package listed in the ISO's
live/filesystem.packages-remove.  live-build lists there every package
installed after the package-lists install pass, which includes anything a
chroot hook installs with apt -- and the hook installed Caddy that way.
An installed system therefore had no Caddy: wrolpi-bootstrap failed copying
the Caddyfile, the API/app/Kiwix were never enabled, and HTTPS never came up.

Caddy now comes from package-lists/, with its repository and signing key in
config/archives/ (installed into both the build chroot and the image).
check-iso.sh fails the build when the installer would remove any package,
and can be run by hand against any ISO.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Debian ISOs install Caddy from Caddy's repository

Moving caddy into package-lists/ made apt read config/archives/ before
ca-certificates was installed, so the HTTPS fetch of Caddy's repository
failed certificate verification.  apt ignores a failed repository, and the
image silently got Debian's much older caddy 2.6.2 instead of 2.11.

ca-certificates is now part of the bootstrap, and Debian's caddy is pinned
to -1, so an unreachable Caddy repository fails the build and installed
systems never switch to Debian's caddy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:42:37 -06:00
lrnselfreliance
7aa7481a56
The hotspot starts on boot (#829)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Nothing started the hotspot since hotspot_on_startup moved out of the
API, and NetworkManager does not autoconnect the Hotspot connection.
The Controller now starts it once per boot unless hotspot.on_startup is
false; a legacy wrolpi.yaml hotspot_on_startup: false is migrated.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:29:15 -06:00
lrnselfreliance
b83a9cf017
Onboarding a drive keeps a library on the internal disk (#828)
The onboarding wizard deleted /media/wrolpi/config before mounting a
drive, and the shadowed data check ignored config/.  A library kept on
the internal disk keeps wrolpi.db and its configs there, so onboarding
a drive later deleted them without warning.  Only a config/ holding
nothing but the ssl/ CA is now treated as transient.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:19:41 -06:00
lrnselfreliance
1554dfb268
A new database is refreshed on startup (#827)
Download and Upload are disabled until a full refresh completes, and a
fresh install never had one until the user found the refresh link.
Startup now queues it, and the dashboard says why Download and Upload
are disabled meanwhile.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:07:04 -06:00
lrnselfreliance
295b3ccfc8
INSTALL.md points to the Controller drive wizard (#825)
* INSTALL.md points to the Controller drive wizard

Debian installs are Debian 13 from the amd64 ISO.  The Raspberry Pi
steps no longer hand-edit fstab or run repair.sh; a shared First Boot
section covers the drive, certificate trust, and the first refresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* INSTALL.md: Debian installs use the drive wizard

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:57:10 -06:00
lrnselfreliance
dc2ab22ae0
Debian installs show the Controller drive wizard (#826)
wrolpi-bootstrap.sh created controller.yaml on installed systems, which
hid the onboarding wizard.  Installed systems now wait for the wizard,
whose repair.sh finishes setup.

"Run repair without external drive" now writes controller.yaml before
starting repair, so the wizard does not return after repair.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:50:20 -06:00
Roland
697a8180c7
Bump version to 0.30.0-beta
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:13:56 -06:00
lrnselfreliance
ce923cbff0
Video transcodes run at the least CPU priority (#824)
Some checks failed
Backend Tests / api-tests (core) (push) Has been cancelled
Backend Tests / api-tests (files) (push) Has been cancelled
Backend Tests / api-tests (media) (push) Has been cancelled
Backend Tests / api-tests (rest) (push) Has been cancelled
Backend Tests / api-contract-tests (push) Has been cancelled
Backend Tests / api-migrations-and-start (push) Has been cancelled
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Cypress Tests / cypress-component-tests (push) Has been cancelled
Cypress Tests / cypress-e2e-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
ffmpeg is wrapped in `nice -n19` so a multi-hour transcode never competes
with the API, downloads, or other background work.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 12:10:44 -06:00
lrnselfreliance
4e53e02519
Notifications without a URL are not links (#823)
Transcode, job, and Kiwix notifications send no URL, but every user notify
toast said "Click here to view the shared page" and opened /null on click.
Only a notification carrying a URL is followable now.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 08:37:26 -06:00
lrnselfreliance
87e146487b
Database schema lists each column's foreign key (#822)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Without them a model guessed joins: it joined video.channel_id to collection.id
(it is channel.id), and the query silently returned the wrong channel names.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:38:39 -06:00
lrnselfreliance
61e58fac17
Controller script elapsed time is correct outside UTC (#821)
systemd prints the start timestamp in local time, which was subtracted from
utcnow(), so elapsed_seconds was off by the UTC offset (6 hours in MDT).  Ask
systemd for a Unix timestamp instead.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:30:08 -06:00
Roland
06ca3d421f
Sign master for device upgrades
upgrade.sh only installs a branch tip signed with the WROLPi key; the tip was a
GitHub squash merge (#820).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:49:54 -06:00
lrnselfreliance
f27720683d
Read-only SQL query endpoint for advanced users (#820)
* Read-only SQL query endpoint for advanced users

POST /api/db/query runs one read-only statement; GET /api/db/schema describes
the tables.  Both are refused unless `allow_database_query: true` is set in
wrolpi.yaml (there is no UI for it).  The connection is opened with mode=ro and
an authorizer that allows only reads; queries are interrupted after 10 seconds,
rows are capped, and long values are truncated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Database queries cannot be enabled through the API, and use bounded memory

The config update API refuses to change `allow_database_query`; only an edit of
wrolpi.yaml on the WROLPi can enable queries.  Query connections refuse values
over 32 MB and rows over 100 columns, rows are read one at a time, and the
response stops at 5 million characters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The database query setting can be changed like any other config

WROLPi is meant to be as secure as a bookshelf in your home; a LAN user who can
reach the API is trusted, so gating one key in the config API adds nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Database queries can search FTS5 tables on SQLite 3.46

FTS5 reads `PRAGMA data_version` through the authorizer when it opens a table
on SQLite 3.46 (Debian 13), so every MATCH and the schema endpoint failed with
"vtable constructor failed".  A denied VACUUM INTO also explains itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A config status test attaches the shared context it reads

It passed only when an earlier test in the same worker had attached it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:34:00 -06:00
lrnselfreliance
3ea8eb81f6
Model reprs read only loaded state (#819)
A repr runs inside log calls. Reading a relationship or an expired column there runs a query, and
on an object whose session is gone it raises DetachedInstanceError instead of logging. Archive's
repr also stat'ed its SingleFile file on disk.

`wrolpi.common.loaded()` follows attributes through state that is already loaded (primary keys
from the identity key) and never runs SQL. Every model repr uses it; with everything loaded the
output is unchanged, except Video and Archive now show the FileGroup's primary path.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:47:32 -06:00
lrnselfreliance
c717f11821
Duplicate video cleanup keeps a complete copy and its viewing history (#818)
`delete_duplicate_videos` kept whichever duplicate had the largest
FileGroup and deleted the rest.  A leftover yt-dlp format file (video only,
or audio only) is often the largest, so it could be kept while every
playable copy was deleted.  The deleted copies' `viewed`, `progress` and
`position` were also lost; only tags were carried over.

Rank copies by completeness first (has audio, has video, from the stored
ffprobe data; unknown counts as complete so no ffprobe runs inside the write
transaction), then by size, keeping the oldest of equals as before.  The kept
copy takes the most recent view, and the resume position of the most
recently viewed duplicate when it has none of its own.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:25:25 -06:00
lrnselfreliance
a95b187edc
A yt-dlp format file is not the primary file when merged media is present (#817)
`get_primary_file` returned the first video/audio file in whatever order it
was given, so a group holding both `<stem>.mp4` and a leftover video-only
`<stem>.f313.webm` could make the leftover the primary file.  The Video then
pointed at a file without audio, and a download of it was deferred with
"Download did not contain audio stream" on every retry.

Skip yt-dlp per-format files (`.fNNN` stems) when a merged media file is in
the group.  A group of only format files still gets one as its primary.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:20:44 -06:00
lrnselfreliance
fc7db34864
Video download deletes yt-dlp format leftovers of any extension (#816)
A merge that never finished leaves `<stem>.f313.webm` (video-only) next to
where the merged file belongs.  A later download of the same video globs
every `<stem>.*` file into its FileGroup, but only `.part` files and format
files with the *same* extension as the merged video were deleted.  A `.webm`
leftover beside a new `.mp4` survived, joined the new FileGroup, and could
become the Video's file.

Delete every `<stem>.fNNN.*` file in the group, whatever its extension, which
also covers WROLPi's poster/ffprobe sidecars of an indexed leftover and
yt-dlp's `.ytdl` state files.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:20:25 -06:00
lrnselfreliance
4adc4e6a15
Drop the SQLAlchemy asyncio extra (#815)
Nothing uses sqlalchemy.ext.asyncio; an AsyncSession pilot on the request path was measured on a
Pi and dropped. SQLAlchemy 2.0 still requires greenlet on aarch64 and x86_64, so installs on the
Pi, Debian and Docker are unchanged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:18:16 -06:00
lrnselfreliance
8e2ab935af
Archive search counts from the search index (#814)
The total for an archive search joined `archive LEFT JOIN file_group` to the FTS table. A LEFT JOIN
fixes `archive` as the outer table, so SQLite scanned every Archive and ran the MATCH once per row:
about 20 seconds of CPU on a Pi with 128k Archives, every time the 60-second totals cache expired.
An inner join lets the planner start from the FTS matches (the same count in milliseconds). Every
Archive has a FileGroup, so the count is unchanged.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:37:27 -06:00
lrnselfreliance
99a0fc275d
Archive and doc pages record a view in its own write transaction (#813)
Viewing an archive or a doc marked it viewed on the request's read transaction. SQLite cannot
upgrade a read to a writer once another connection has committed (during a download or refresh),
and it does not wait on busy_timeout for that. The archive page returned a 500; the doc page
returned 200 but its view was lost when the request's commit failed.

Build the response on the read, then record the view in `request.ctx.db.write()`, as the video
page already does.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 14:13:50 -06:00
lrnselfreliance
4202e6a7e5
Downloads and uploads: don't read ORM objects after their session is gone (#812)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* File downloads: return plain values from upsert_file

Every file download failed after the file was saved, with DetachedInstanceError reading
`fg.location`.  `upsert_file` returned a FileGroup from a session it had committed, and the
caller read it after the session was gone.  SQLAlchemy 1.3 kept that session alive in a
reference cycle until the next garbage collection, so the read worked by accident; 2.0 frees it
as the `with` block ends.  Failed downloads retry, re-downloading their files.

`upsert_file` now returns `UpsertedFile(file_group_id, location)`, read inside its session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Archive uploads: return plain values from singlefile_to_archive

Same failure as upsert_file: `singlefile_to_archive` returned an Archive from a committed session,
and the upload handler read `archive.file_group.title/url` and `archive.location` after the
session was freed, so every SingleFile upload raised DetachedInstanceError after the Archive was
saved.  It now returns `UploadedArchive(file_group_id, name, url, location)`, read inside its
session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:41:04 -06:00
lrnselfreliance
673c23188c
Request sessions keep objects after commit; guard dict() serializers (#811)
A RequestSession no longer expires loaded objects at commit, so a handler serializes what it
committed without a reload query.  An AsyncSession cannot run that reload at all, so this is
groundwork for moving request handling to async.  Background sessions (get_db_session) keep
SQLAlchemy's default: they change data outside the ORM (raw SQL, triggers) and rely on the reload.

Collection, CollectionItem and Channel dict() now run inside the serializer guard.  Fixes it found:
- Channel.dict() no longer loads the deferred yt-dlp catalog (info_json), which the channel
  handler loaded only to discard.
- get_channel eager-loads what Channel.dict() reads (populate_existing replaces a refresh query).
- create_channel / get_or_create_download link through relationships, so a loaded
  Collection.downloads stays current.
- Setting a Repo to Never removes the deleted Download from the loaded collection; the response
  reported the old frequency.
- The downloader no longer calls channel.dict() to preload a Channel; its callers read it inside
  the session.

Tests run each request with expiry off, as production does, and turn it back on for the background
work that shares the test Session.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:15:33 -06:00
dependabot[bot]
1f8a887c11
build(deps): bump shell-quote from 1.10.0 to 1.12.0 in /app (#792)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Bumps [shell-quote](https://github.com/ljharb/shell-quote) from 1.10.0 to 1.12.0.
- [Changelog](https://github.com/ljharb/shell-quote/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/shell-quote/compare/v1.10.0...v1.12.0)

---
updated-dependencies:
- dependency-name: shell-quote
  dependency-version: 1.12.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:48 -06:00
dependabot[bot]
d8d28503b5
build(deps): bump compression from 1.8.1 to 1.8.2 in /app (#793)
Bumps [compression](https://github.com/expressjs/compression) from 1.8.1 to 1.8.2.
- [Release notes](https://github.com/expressjs/compression/releases)
- [Changelog](https://github.com/expressjs/compression/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/compression/compare/v1.8.1...v1.8.2)

---
updated-dependencies:
- dependency-name: compression
  dependency-version: 1.8.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:43 -06:00
dependabot[bot]
562150631c
build(deps): bump proxy-addr from 2.0.7 to 2.0.8 in /app (#794)
Bumps [proxy-addr](https://github.com/jshttp/proxy-addr) from 2.0.7 to 2.0.8.
- [Release notes](https://github.com/jshttp/proxy-addr/releases)
- [Changelog](https://github.com/jshttp/proxy-addr/blob/master/HISTORY.md)
- [Commits](https://github.com/jshttp/proxy-addr/compare/v2.0.7...v2.0.8)

---
updated-dependencies:
- dependency-name: proxy-addr
  dependency-version: 2.0.8
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:39 -06:00
dependabot[bot]
d205f7ca72
build(deps): bump source-map-js from 1.2.1 to 1.2.2 in /app (#795)
Bumps [source-map-js](https://github.com/7rulnik/source-map-js) from 1.2.1 to 1.2.2.
- [Release notes](https://github.com/7rulnik/source-map-js/releases)
- [Changelog](https://github.com/7rulnik/source-map-js/blob/main/CHANGELOG.md)
- [Commits](https://github.com/7rulnik/source-map-js/compare/v1.2.1...v1.2.2)

---
updated-dependencies:
- dependency-name: source-map-js
  dependency-version: 1.2.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:34 -06:00
dependabot[bot]
a36e3a3770
build(deps): bump the npm-dependencies group in /app with 3 updates (#807)
Bumps the npm-dependencies group in /app with 3 updates: [@tabler/icons-react](https://github.com/tabler/tabler-icons/tree/HEAD/packages/icons-react), [web-vitals](https://github.com/GoogleChrome/web-vitals) and [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node).


Updates `@tabler/icons-react` from 3.48.0 to 3.49.0
- [Release notes](https://github.com/tabler/tabler-icons/releases)
- [Changelog](https://github.com/tabler/tabler-icons/blob/main/packages/icons-react/CHANGELOG.md)
- [Commits](https://github.com/tabler/tabler-icons/commits/v3.49.0/packages/icons-react)

Updates `web-vitals` from 6.2.2 to 6.2.3
- [Changelog](https://github.com/GoogleChrome/web-vitals/blob/main/CHANGELOG.md)
- [Commits](https://github.com/GoogleChrome/web-vitals/compare/v6.2.2...v6.2.3)

Updates `@types/node` from 26.6.3 to 26.6.4
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@tabler/icons-react"
  dependency-version: 3.49.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: web-vitals
  dependency-version: 6.2.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@types/node"
  dependency-version: 26.6.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:30 -06:00
dependabot[bot]
d5c02b34ae
build(deps): bump aiohttp (#806)
---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.14.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: controller-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:26 -06:00
dependabot[bot]
226f955dd0
build(deps): bump the python-dependencies group with 6 updates (#808)
---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.14.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: cachetools
  dependency-version: 7.2.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: libzim
  dependency-version: 3.13.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: python-dotenv
  dependency-version: 1.2.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: pytz
  dependency-version: '2026.5'
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: selenium
  dependency-version: 4.50.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-10 11:00:21 -06:00
lrnselfreliance
ab6a40be20
API JSON: encode paths without a lookup per path (#810)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
CustomJSONEncoder looked up the media directory and called Path.relative_to
for every path it encoded.  A response with hundreds of paths (an Archive's
page with 51 history entries holds 416) spent most of its encoding time
there: 18.8 ms of 19 ms per response, measured on a Mac.  The encoder now
looks up the media directory once per response and strips it as a string
prefix: 1.5 ms for the same response.

Paths outside the media directory, relative paths, and siblings that share
the media directory's name prefix are still returned unchanged; the media
directory itself and "." are still "".

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 19:45:43 -06:00
lrnselfreliance
a8dde44d4f
Archive page: load history and tags eagerly (#809)
GET /api/archive/<id> loaded each history Archive's FileGroup and Tags with
their own queries while serializing: two queries per history Archive.  An
Archive with 51 history entries ran 107 statements per request.  Both the
Archive and its history now use Archive.json_options(), so the count no
longer grows with the history (5 statements for the same Archive).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 19:45:13 -06:00
lrnselfreliance
dab333124e
Upgrade to SQLAlchemy 2.0 (synchronous) (#803)
SQLAlchemy 1.3 has been end-of-life since 2021, and alembic was held at 1.10
because newer releases need SQLAlchemy 2.  This is a mechanical port; the code
stays synchronous.

- SQLAlchemy[asyncio]==2.0.54, alembic==1.20.0.
- Model annotations use Mapped[...] (2.0 rejects bare annotations on mapped
  attributes); declarative_base moves to sqlalchemy.orm.
- Plain SQL strings go through text() or exec_driver_sql; schema_ddl.execute_sql
  accepts a SQLAlchemy Connection or a raw sqlite3 connection, so rebuild_fts
  works from the baseline migration again.
- Session.get replaces Query.get; session.in_transaction() replaces
  session.transaction; cache_ok on MediaPathType and FancyJSON.
- The tag-directory sync query joins through TagFile's relationships instead of
  the legacy two-entity outerjoin.
- Section-hint rows use attribute access (2.0 rows are tuples).
- Migrations run on an AUTOCOMMIT connection, matching 1.3, where each
  statement committed on its own.  2.0 autobegins, so the unique-stem
  migration's read snapshot could not become a writer after its helpers wrote
  on another connection ("database is locked").  The begin listener emits no
  BEGIN for AUTOCOMMIT connections.
- Newer alembic compares column types: WrolpiKV now describes the TEXT table
  its migration created.
- The test database installs its DDL inside engine.begin(); 2.0 connections
  no longer autocommit, so the FTS tables were rolled back.
- Dependabot now holds SQLAlchemy at 2.0 instead of 1.3.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:08:40 -06:00
lrnselfreliance
bb8945e8ad
Render unknown URLs as a 404 page inside the app layout (#805)
An unknown URL (e.g. /archive instead of /archives) had no matching route,
so react-router rendered the root errorElement in place of Root.  That put
PageNotFound outside ThemeProvider, and its Mantine Box threw
"MantineProvider was not found", leaving a blank page.

- A catch-all route renders PageNotFound inside Root, with the navigation
  bar, footer and theme.
- The root errorElement brings its own ThemeProvider, so it can render when
  Root itself fails.
- App exports its routes so a test can mount them in a memory router.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:00:36 -06:00
lrnselfreliance
d75be8e1a4
Download forms: allow a frequency of "Once" (#804)
* app: a download frequency of "Once" no longer blocks submission

useForm treated any falsy value as a missing required field.  "Once" is
frequency 0, so the Channel/Playlist, RSS, and Zim download forms never
became ready and the Download button stayed disabled.  Only null,
undefined, '', false, and NaN count as missing now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* downloads: editing to "Once" stores a once-download, not frequency 0

Once-downloads have a NULL frequency.  A 0 frequency counted as recurring
(frequency != None) but could never be scheduled (not frequency), so an
edited download stayed on the recurring list and could break renewal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:00:24 -06:00
lrnselfreliance
c8d5765ea3
Scrape: fix multiple suffixes and relative link resolution (#801)
Some checks are pending
Backend Tests / api-tests (core) (push) Waiting to run
Backend Tests / api-tests (files) (push) Waiting to run
Backend Tests / api-tests (media) (push) Waiting to run
Backend Tests / api-tests (rest) (push) Waiting to run
Backend Tests / api-contract-tests (push) Waiting to run
Backend Tests / api-migrations-and-start (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Cypress Tests / cypress-component-tests (push) Waiting to run
Cypress Tests / cypress-e2e-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* Scrape: match any of the comma-separated suffixes

The UI's File Suffixes field accepts a comma-separated list, but the
downloader compared each link against the whole string, so a scrape with
more than one suffix never matched anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Scrape: resolve relative links against the page's directory

resolve_url appended a relative href to the page URL, so a link to
"a.txt" on ".../dir/page.html" became ".../dir/page.html/a.txt" and the
file download 404'd. Use urljoin, and resolve against the final URL after
redirects so a directory URL without a trailing slash still works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:05:59 -06:00
lrnselfreliance
22b8b9c878
Scrape: honor <meta> charset when decoding pages (#800)
aiohttp's response.text() ignores <meta> charset declarations and assumes
UTF-8 when the Content-Type header has no charset, so legacy Latin-1 pages
crashed the Scrape downloader with UnicodeDecodeError. Decode with
UnicodeDammit instead: header charset first, then the page's declared
charset, then detection.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:39:39 -06:00
lrnselfreliance
5ec85c3e04
Help: document resuming where you left off (#799)
Bumps the help docs for the new "Resume Where You Left Off" page and the
recently_viewed.yaml config.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 18:25:29 -06:00
lrnselfreliance
3c362799b5
Resume EPUBs and comic books where the reader left off (#798)
* Resume EPUBs and comic books where the reader left off

The EPUB viewer (epub.html) accepts `?cfi=` and posts its location and
progress to the page that embeds it on every page turn.  Progress comes from
the chapter and the page within it, rather than book.locations.generate(),
which stalls a Raspberry Pi on a large book.  A search result's `loc` still
wins over the saved position.

The comic viewer opens at the saved page and saves each page shown.

Both resume on the doc page and in the file preview.  The resume point is
decided once per opened file, so saves made while reading do not change the
EPUB viewer's URL and reload it.  The doc page tracks only the FileGroup's
primary file; another format beside it is not tracked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* EPUB/comic progress: never save a place the server would discard

The server treats a position at the start (the cover, under 1%) as not
started, and replaces the saved place with progress 0.  Both viewers
reported the place they opened on, so opening a finished book un-finished
it, and peeking at the cover erased the reader's page.

- The comic viewer does not save the page it opens on, nor the cover; a
  peek at the cover keeps the last page saved.
- The EPUB viewer posts nothing at the start of the book.
- Progress before the end is kept between 1% and 94% (resumableProgress), so
  early pages of a long book and the last pages before the end keep their
  position.  Only the last page (comics) or the end (EPUB) is finished.
- Non-finite EPUB progress is ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 18:19:51 -06:00
lrnselfreliance
1ad451cddf
Resume videos and audio where the user left off; show progress on cards (#791)
* Resume videos and audio where the user left off; show progress on cards

Videos and audio resume where the user left off, on the video page and in
the file preview, and keep playing.  `?t=` starts at an explicit time
instead.

useFileProgress saves how far the user is through a file: every 15 seconds
while it changes, and a final save (a beacon, which survives the page
closing) on pause, end, hiding the page, leaving it, or switching files.
Each save is also kept in sessionStorage; on open the newer of that and the
server's position wins, so coming straight back resumes exactly even if the
final save is still in flight.

Cards show a progress bar along the bottom of their poster.  The dashboard's
Recently Viewed Files gains All / Continue; Continue uses the new
`in_progress` file search filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Progress review fixes: in_progress totals, latest dashboard request, preview viewed

- The in_progress search filter skips the uncounted fast path and is part of
  the totals cache key, so Continue never reports All's (or the library's)
  count.
- The dashboard's Recently Viewed hook applies only its latest response, and
  clears the list when switching All/Continue until the new files arrive.
- POST /api/files/file returns `viewed`, so a preview can tell a file
  finished elsewhere from an older position this tab holds.
- The progress hook tests restore Blob, fetch and sendBeacon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:29:22 -06:00
lrnselfreliance
fbdf5bac82
Rename skip_circleci to skip_ci (#797)
CircleCI is gone, so the skip and its flag (CIRCLECI → IS_CI) are named for
CI in general, and the flag reads only GITHUB_ACTIONS.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:28:13 -06:00
lrnselfreliance
bcbc42632d
Remove CircleCI (#796)
GitHub Actions runs every job CircleCI did (#789), so CircleCI only
duplicated them.  The README badge now shows the backend tests on master.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:19:38 -06:00
lrnselfreliance
1e112b678a
Run the CircleCI jobs on GitHub Actions (#789)
* Run the CircleCI jobs on GitHub Actions

Backend tests (pytest, API contract, migrations + API start) and Cypress
(component, e2e) now run as GitHub Actions workflows.  CircleCI stays in
place until these have run green alongside it.

- pip and npm caches via setup-python/setup-node, plus the Cypress binary;
  node_modules is no longer cached, to stay inside the 10 GB cache cap.
- Superseded pull request runs are cancelled to stay under the concurrent
  job limit.
- react-app-start is dropped: the e2e job waits for `npm start`, and
  jest-tests.yml already runs `npm run build`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Skip the CI-unsupported tests on GitHub Actions too

skip_circleci only read CIRCLECI, so on GitHub Actions test_archive_upload
ran without the readability tooling it needs, and failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Run the backend tests on every vCPU

-nauto counts physical cores when psutil is installed, so the four-vCPU
runner got two workers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Split the backend tests into four jobs by directory

The groups are balanced by test time, so each runs about a quarter of the
suite.  `rest` ignores the other groups' paths rather than listing its own,
so a new directory is tested before it is assigned to a group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:08:16 -06:00
lrnselfreliance
cb189bacb1
Give the repos ownership tests a fixed git identity (#790)
test_ownership.py's git() helper did not use TEST_GIT_ENV, so its commits
read the machine's git identity.  CI runners have none and cannot guess one,
so seven tests failed there on every run.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:01:59 -06:00
lrnselfreliance
184c95e250
Ignored directories: match whole directories, and check where a link points (#788)
An ignored directory was matched as a string prefix, so ignoring `private`
also ignored `private-notes`.  A file is now ignored only when it is the
ignored directory or inside it.

Viewing a file, or saving its progress, checked only the path it was given,
so a link outside an ignored directory to a file inside it was tracked.
is_ignored_file checks the link and its target.  Refresh does not follow
links, so the bulk paths keep the cheaper lexical check.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:29:06 -06:00
lrnselfreliance
9588af2601
Track how far the user is through a file, kept in recently_viewed.yaml (#787)
* Track how far the user is through a file, kept in recently_viewed.yaml

FileGroup gains `progress` (0.0 to 1.0, 1.0 is finished) and `position` (where
to resume: a time, a page, or an EPUB CFI).  Both are returned with the file,
including by POST /api/files/file.

POST /api/files/progress records progress and is also a view.  A file 95%
through is finished and keeps no position; one barely started (under 10 s,
the first page, under 1%) is not worth resuming.  The write happens before
the response, so the next request sees it.  POST /api/files/progress/clear
starts a file over.  Both refuse files outside the media directory.

recently_viewed.yaml keeps the 1000 most recently viewed files so viewing
history and positions survive a database rebuild.  On import the newer
`viewed` wins, so a file viewed while WROLPi was starting keeps its newer
position.  The config is saved when a file is opened, when progress is final
(paused or closed), when it is cleared, and after refresh cleanup (moves,
renames, deletes); heartbeats during playback only write the database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Progress: write as a writer, confine and merge the import, keep FTS on downgrade

- The progress endpoints begin as writers (request.ctx.db.write()), so a
  heartbeat during a refresh waits instead of failing a lock upgrade.  The
  config switch fires after the commit.
- `..` is collapsed before the ignored-directory check.  Clear only resets
  an existing FileGroup; it never indexes a file.
- Import confines config paths to the media directory.  A newer plain view
  keeps its `viewed` but takes the config's position; only progress written
  after the config wins.  Files are globbed before the write transaction.
- The dump skips a row outside the media directory instead of failing.
- The downgrade drops the columns with ALTER TABLE, which keeps file_group's
  FTS triggers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:15:25 -06:00
lrnselfreliance
531721c157
Fix file view tracking: docs mark viewed, previews count one view (#786)
Opening a doc on its page never set FileGroup.viewed, so docs were missing
from Recently Viewed.  GET /api/docs/:id now marks the doc viewed, with the
same skip_viewed parameter as archives and videos.

The file preview marked a file viewed more than once: opening from a
?preview= URL sent two tracked requests, and every tag change re-fetched the
file with tracking on.  The fetches now skip tracking, and the preview marks
each opening viewed once.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:04:13 -06:00
lrnselfreliance
a1292005ce
Other search tab: search Channels by name, add Domains and Playlists, fix the estimate (#785)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* Count Channels with any of the Tags in the Other search estimate

The Other tab lists Channels with any of the selected Tags, but its estimate
only counted Channels with the first Tag, so the two disagreed when several
Tags were selected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Search Channels by name in the Other search tab

The Other tab only listed Channels with the selected Tags, so typing a
Channel's name found nothing.  Channels now match the search text by name,
and the Tags when there are both.  The list and its estimate share one query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add Domains to the Other search tab

Domains match the search text by name and/or any of the Tags, like Channels.
The list and its estimate share one query.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add Playlists to the Other search tab

Domains and Playlists are Collections, so the Other tab searches both with
the existing /api/collections/search (by kind) instead of a Domain-only
endpoint.  The search and the estimate share search_collections_query.  The
search now loads each Collection's Downloads up front instead of once per
Collection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 18:22:12 -06:00
lrnselfreliance
93d878952c
Add a Repos module that mirrors git repositories (#783)
Repos keeps local mirrors of git repositories, cloned over https and kept up to date on a schedule.

- A Repo is a Collection (kind='repo') plus a `repository` row.  The new `git` downloader clones it, then updates it
  (weekly by default, or Never: the clone is kept as it is and only updated on request).
- Repos are saved in `repos/<tag>/<name>` (the Repos Directory, ignored by default) or a directory the user chooses.
  An existing clone can be imported where it is.  repos.yaml is the source of truth.
- A GitHub-like page shows each repo's README, files, and history, with a ZIP download.  READMEs are searchable
  under the global search's Other tab.
- git is hardened against hostile repos and configs: https only, pinned addresses with no private addresses (for the
  repo and its submodules), sanitized configs, no hooks or links, and only clones WROLPi made or imported are
  updated.
- Tagging a Repo moves its clone as one directory.  Repo changes wait for repos.yaml to be imported at startup.
- The file mover groups unindexed files with no primary file as one FileGroup, and never replaces a file at the
  destination.  A failed tag move restores the Collection's tag.  A Collection's directory cannot leave the media
  directory.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:16:58 -06:00
lrnselfreliance
1ded249fc7
Collections: changes wait for their config's import; domains with archives survive the import (#784)
* collections: refuse playlist changes until playlists.yaml is imported

While WROLPi starts, the API accepts requests before every config is imported.  A playlist created then could not be
saved, and the import which followed deleted it as "no longer in config" (and rebuilt every playlist's items from
the config, undoing any change).  Playlist changes now wait for the import (503, "still starting").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* collections: refuse domain changes until domains.yaml is imported

A domain created, changed, tagged or deleted through the API before domains.yaml was imported (e.g. while WROLPi
starts) was undone by the import.  These now wait for the import (503, "still starting").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* archive: importing domains.yaml keeps domains which have archives

Archives create their domain (e.g. one uploaded, or found by a refresh, while WROLPi starts, before domains.yaml is
imported).  The import deleted every domain missing from the config, and the database deleted that domain's Archives
with it.  A domain with Archives is now kept (and saved to the config with the next change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* videos: refuse Channel changes until channels.yaml is imported

A Channel created through the API before channels.yaml was imported (e.g. while WROLPi starts) could not be saved,
and the import which followed deleted it, and its Downloads, as "not in the config".  Creating, changing, tagging and
deleting a Channel (through the Channel or Collection API) now wait for the import (503, "still starting").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:33:51 -06:00
lrnselfreliance
b742a4a25f
Keep the API's logging when migrating at startup (#782)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
WROLPi runs alembic migrations in-process at startup (db_bootstrap).
alembic/env.py called fileConfig unconditionally, which replaced the
root handlers, set the root level to WARN, and disabled every logger
that already existed, so the API's logs went quiet after any startup
migration until the next restart.  env.py now configures logging only
when alembic runs from its command line (cmd_opts is set).

This also caused an order-dependent test failure: test_jobs's capture
test failed whenever test_db_bootstrap ran first in the same worker.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:55:53 -06:00
lrnselfreliance
2b2361ed64
Save playlists config when a playlist's file is renamed or moved (#781)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
playlists.yaml references file items by path. Renaming, moving, or
reorganizing a FileGroup updated the database but not the config, so the
next import (startup or global refresh) could not find the file and
silently dropped the item from the playlist.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 15:03:45 -06:00
lrnselfreliance
04779b8557
Preview markdown files formatted, with a raw toggle (#780)
* Preview markdown files formatted, with a raw toggle

Markdown files are typed text/markdown (libmagic reports them as text/plain, or
as a programming language when they hold code) and keep the text indexer, so
they stay deep-searchable.  Existing files switch type on their next refresh.

The file preview renders markdown with markdown-it into the page, so it follows
the theme tokens and the night media filter.  A Formatted/Raw toggle shows the
source instead, and the choice is remembered.  Relative links and images
resolve against the file's directory; URLs that climb out of /media/ are
dropped.  Raw HTML in a file is escaped rather than parsed, and the output is
also sanitized with DOMPurify.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Do not load images from other sites in the markdown preview

An image from another site (http:, https:, or protocol-relative //) loaded as
soon as the preview opened, telling that site who was reading the file and
when.  Such an image now becomes a link labeled with its alt text, so the
reader chooses whether to follow it.  Inside a link (a README badge) it becomes
the outer link's text, since links cannot nest.  Media and embedded data:
images still load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:26:42 -06:00
lrnselfreliance
9739dc9e1b
tests: fix the midnight and event-loop timing flakes (#779)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
test_import_config_preserves_completed_once_downloads created a download "5 minutes ago" and expected it to
count toward today's limit, which starts at local midnight; in the first five minutes after local midnight it
was yesterday's.  It failed in CI started at 00:00:35 UTC, and reproduces on master with the clock at 00:02.
The test now pins the clock to local noon, as the download manager reckons local time.

test_import_all_db_configs_does_not_block_event_loop required 90% of the expected 50 ms ticks, so timer
overshoot on a busy runner added up across the run (CI got 28 of the 28.8 required).  It now measures the
longest gap between ticks, including after the last tick: an import on the loop freezes it for the whole 0.2 s
sleep, while jitter delays a tick by milliseconds.  Moving the first or the last import onto the loop still
fails it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:43:00 -06:00
lrnselfreliance
cc8afa5370
Add a Solar calculator (#778)
* Add a Solar calculator with offline NASA POWER data

Estimates a solar array's typical-year production from a location and the
panels; everything else has defaults under an optional "Fine-tune" section.

The model works from 12 monthly averages: Klein's average day per month, the
Erbs monthly diffuse fraction, Collares-Pereira & Rabl / Liu & Jordan hourly
split, HDKR transposition for fixed, single-axis and dual-axis arrays, then
PVWatts' ASHRAE incidence loss, SAPM cell temperature, DC power, system
losses and optional inverter.  "Best for the year" and "Best for winter" sweep
the tilt.

Sunlight, diffuse, albedo and temperature come from NASA POWER's 2001-2020
climatology on a 1 degree grid, packed into app/public/data (3.1 MB, ~1 MB
gzipped) by scripts/build_solar_climatology.py and fetched only when the
calculator opens.  Users can replace it with their own monthly values.

Every setting lives in the URL, with defaults left out, so the Share button
shares the whole configuration.

Against PVWatts v8 for a 1 kW fixed array: Phoenix +0.6%, Seattle +8.8%,
Anchorage +8.0% annually; these are recorded as tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Open the Solar calculator from the map, pins and current location

The map's right-click (or long-press) menu gains "Calculate Solar
Performance", and each saved pin a sun button; both open the calculator at
that location.  A button beside Latitude fills in the browser's current
location.  Locations are rounded to 4 decimals, and longitudes from a map
panned around the world are wrapped back to -180..180.

The map removed lat/lon/z from the URL when it closed, even after navigating
to another page, which stripped the calculator's location from its URL (and
from links shared with the Share button).  It now only cleans up while the
URL is still a map page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add off-grid sizing to the Solar calculator

A new "Off-grid sizing" tab sizes a battery system for the darkest month
from a list of devices (watts x hours per day):

- Battery bank for a number of days without sun, for LiFePO4 or lead-acid,
  at 12, 24 or 48 V.  Outdoor lead-acid is enlarged for the cold; outdoor
  lithium warns against charging below 0 C.
- Panels needed, from the worst month's DC production per kW at the chosen
  angle, with a button to apply the count.  A PWM controller's loss (battery
  voltage over the panel's Vmp) raises the count.
- Charge controller current, and the string voltage on the coldest morning
  against the controller's limit, since cold panels exceed their rated Voc.
  The coldest morning defaults to 25 C below the coldest monthly average.

All inputs live in the URL like the rest of the calculator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bump wrolpi-help for the Solar calculator help page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Credit NASA POWER as it asks, and say how the data was changed

- The calculator gains a "Data attribution" link under the location with
  NASA POWER's requested acknowledgment, the data reference (Climatology API
  v2.10.0, downloaded 2026/10/04), the CC BY 4.0 license, and how WROLPi
  modified the data (rounded to one byte per value, temperature averaged
  into 1 degree cells, interpolated between cells), which CC BY 4.0 requires.
- The build script writes the same text to solar-climatology.LICENSE.txt
  beside the data, with the API version taken from NASA's responses and the
  date the tiles were downloaded.  A test keeps the page and file in step.
- Bumps wrolpi-help for the updated attribution in the help page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Solar: fix PWM sizing, Voc sign, unit switching and loading on review

- PWM usable power now uses the string's voltage (Vmp x panels in series),
  delivers nothing when the charging voltage is at or above the string's Voc,
  and falls off between Vmp and Voc.  The "too little voltage" warning covers
  PWM as well as MPPT.  Previously two panels in series counted double, and a
  panel that could not charge a 48 V bank counted as fully usable.
- A Voc temperature coefficient entered without its minus sign is treated as
  negative, in the math, the URL and the input, so the cold-morning check
  cannot be made too generous.
- Switching Fahrenheit on or off converts the entered temperatures instead
  of reinterpreting them.
- While the sunlight data downloads, the off-grid tab shows a loader rather
  than asking for a location, and holds the cold-morning verdict until the
  site's temperatures are known or one has been entered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Solar: move the data attribution to the bottom of the page

The full NASA POWER acknowledgment, license and changes now sit in a small
"Data attribution" section at the end of the calculator, always visible,
instead of behind a link under the location.  The source line under the
location points to it.  Bumps wrolpi-help to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Solar: drop the data source line under the location

The attribution at the bottom of the page is enough.  The line under the
location now only appears to report the data's state: loading, failed to
load, or replaced by the user's own values.  Bumps wrolpi-help for the
refreshed screenshot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:36:45 -06:00
lrnselfreliance
cfbed9e4d7
db: serializers read only loaded data (#777)
* db: serializers read only loaded data

Serializing a model must not query.  A lazy load there is a hidden query per row (search serialized 24 rows
with 55 statements), and would be a `MissingGreenlet` error under an async Session.

- `wrolpi.db.no_db_access(reason)` and `@serializer` (on every model `__json__`, and around `json_response`):
  an engine `before_cursor_execute` listener raises `UnexpectedQuery` during tests, and in production logs once
  per serializer and lets the query run.  Tests record each trip as well, and the autouse
  `no_unexpected_queries` fixture fails a test even when the code caught the error (Video's serializer was
  swallowing its per-row loads of the deferred `ffprobe_json`).
- Relationships serializers read load with their parent: `selectin` for FileGroup.tag_files and
  Collection.downloads; `joined` for TagFile.tag, Collection.tag, Channel.collection, Video.channel,
  Archive.collection, ZimSubscription.download, CollectionItem.zim, and the file_group of Video, Archive, Doc,
  Zim and CollectionItem.
- Search and the Video lookups the video page uses load the deferred `ffprobe_json` (`undefer`).
- `wrolpi/test/test_serializers.py`: every serialized model, freshly loaded, serializes without SQL.

Search: 55 -> 5 statements for 24 videos (31 -> 5 for archives), and a few ms faster locally.

Not in this change: guarding the `dict()` serializers and `expire_on_commit=False`, which go together (about 50
serialize-after-commit sites, and 40 tests that read values changed elsewhere after a commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* db: serializer loads per query; the guard ignores transaction control

The query guard reported the engine's own BEGIN (emitted through the same event as the first statement on a
Session with no open transaction) instead of the lazy load after it, and in production that BEGIN used up the
one warning per serializer.  Transaction-control statements are now ignored.

Mapper-level eager loads reached background code: every Video/Archive load in the modelers (one per file,
inside the write transaction) joined file_group/channel/collection/tag and selectin-loaded the Collection's
Download rows with their yt-dlp info_json.  A second refresh of 100 videos took 0.40 s instead of 0.16 s.

Serializer needs are now declared per model (`json_options()`) and added only by the queries whose results
are serialized; Download.info_json is deferred there (no serializer reads it).  Mapper defaults keep only
narrow joins nearly every use needs: TagFile.tag, Collection.tag and Channel.collection.  A second refresh is
back to master's statement count and time; search still drops from 55 to 3 statements.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:28:08 -06:00
lrnselfreliance
1f687fa825
Move entry tags to the current Zim when deleting outdated Zims (#776)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Deleting a Zim cascade-deletes its TagZimEntry rows, and the next tags
save writes them out of the config, so every outdated-Zim delete lost
its entry tags.  The config-import migration only runs at startup, too
late to help.  Move each outdated Zim's tags to the current Zim of the
same name before deleting, then save the tags config.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:04:11 -06:00
lrnselfreliance
8713a6136b
Reset file worker status when a synchronous refresh is cancelled (#775)
* Reset file worker status when a synchronous refresh is cancelled

refresh_sync runs inside request handlers.  When Sanic cancelled one on
response timeout, the phase flag cleared as its `with` block unwound but
the shared status did not, so the worker reported 'modeling' forever while
nothing ran.  Reset to idle on cancellation.

Deleting outdated Zims also ran the global modelers inside the request,
which is what timed out.  Skip post-processing there and update the
outdated_zims flag directly, the only cleanup step it relied on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: observe the modeling flag in the cancelled refresh_sync test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 11:25:25 -06:00
lrnselfreliance
bed25b429d
db: request-path library functions use the request's connection (#774)
* db: request-path library functions use the request's connection

Library functions an API request reaches now take the request's Session (first argument) instead of
opening their own session or cursor, so a request needs one SQLite connection.  Raw SQL runs through the
new `wrolpi.db.session_curs(session)`, a cursor on the Session's connection; `RequestDB.curs()` uses it.

- Search: files, videos, archives, flasher, and docs search share the request connection for the total,
  the page of ids, and the page's models (3 connections -> 1).
- Zim search, including tag-filtered search and estimates (2 -> 1).
- Channel detail (`Channel.get_statistics` reads on the Channel's own Session) and the channel list.
- Video detail, edit, description, captions, comments and transcode.  `get_video_for_app` and
  `update_video` no longer commit; their handlers use `request.ctx.db.write()`, so editing a Video and
  reading it back is one transaction.
- Tags (list, overlaps, recent), file statistics and estimates, other estimates, bulk tag preview, the
  download list, retry, kill and the status summary, and docs/videos/archive statistics.

Not converted: file operations that refresh files inside the request (delete, rename, upload, channel
and collection tag/move) commit page by page in code shared with the file worker; the cached zim entry
lookup; config import.

The connection-count tests now assert one connection for every endpoint they cover (no xfails left), and
cover the videos and archive statistics endpoints, which had no API test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* downloads: startup retries in a write session of its own

start_single_tasks still called retry_downloads() without a Session after it began requiring one, so any
start after a completed refresh raised TypeError there: incomplete downloads were not reset and the
download_on_startup enable after it never ran.  Startup is not a request, so
DownloadManager.retry_downloads_on_startup() opens and commits its own short write transaction.

Tested through the method, not start_single_tasks: importing main registers its startup listeners on the
shared app, and every later test in that worker then runs them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 11:05:20 -06:00
lrnselfreliance
a2bef48c6c
db: one request-scoped database handle per API request (#773)
Some checks failed
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
* db: one request-scoped database handle per API request

Every API request now gets `request.ctx.db` (`wrolpi.db.RequestDB`): a Session plus raw cursors on that
Session's connection, so a request needs at most one SQLite connection.  Creating it does no I/O; requests
that never touch the database never connect.  `request.ctx.session` remains the handle's Session.

A `RequestSession` binds itself to one lazily-opened Connection.  An engine-bound Session releases its
connection at every commit, and NullPool closes it, so a request that read and then wrote reconnected.

Handlers write in `request.ctx.db.write()`: BEGIN IMMEDIATE, committed when the block exits, so the
write lock is not held for the rest of the handler or by background work it starts.  This replaces the
handler-level `get_db_session(commit=True)` blocks (download create, collection item add/remove/reorder,
channel create).  The zim search handlers use the request's Session in their worker thread.

Tests count the connections a request opens with production's per-call sessions
(`count_request_connections`).  Endpoints whose library functions still open their own connection are
strict xfails, to be removed as those functions take the request's session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: name the real extra connections in the request connection xfails

Channel detail: get_channel already uses the request session; the extra connection is
Channel.get_statistics opening a raw cursor (get_db_curs).  Search: count_file_groups opens a
cursor for the total, then handle_file_group_search_results opens a cursor and a session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 15:42:06 -06:00
Roland
d7deea668d
Bump version to 0.29.0-beta
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 11:53:21 -06:00
lrnselfreliance
1c8bbf1f10
deps: cachetools 7 and the current web-vitals API (#771)
cachetools 6 removed cachetools.func.mru_cache; the Zim search estimate
cache was its only user, so it becomes an lru_cache and the pin moves
to 7.2.0 with the Dependabot ignore removed.

reportWebVitals still destructured the web-vitals 2.x names (getCLS,
getFID, ...) which no longer exist, so it silently did nothing.  Use
the on* names, replace FID with INP, return the import promise, and
accept any callable rather than instanceof Function.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 11:04:16 -06:00
lrnselfreliance
c28a9e0078
Revert "build(deps-dev): bump webpack-dev-server from 5.2.6 to 6.0.0 in /app (#769)" (#772)
Cypress component testing resolves the top-level webpack-dev-server
and only accepts major 5, so the bump crashed cypress.config.js on
every run ("Unexpected major version of webpack-dev-server").  The
react-scripts dev server was unaffected because it uses its own
nested 4.x, which is what the pre-merge check looked at.

Pin webpack-dev-server below 6 in dependabot.yml until Cypress
supports it.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 11:00:27 -06:00
lrnselfreliance
f37098cb81
tests: fix the two suites failing on master (#770)
test_handle_reorganize_marks_job_failed_on_exception patched
wrolpi.files.worker.shutil.move, but #719 moved handle_reorganize and
its shutil.move call into wrolpi.files.reorganize_job.

test_file_worker_refresh_inserts_new_files loaded FileGroups into the
shared pytest session between refreshes.  The refresh upserts by raw
SQL, so the modeler then read the stale identity-map object and wrote
its old file list back over the upsert.  Production opens a fresh
session per block; expire the test session before the second refresh.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 10:50:24 -06:00
dependabot[bot]
8610f9c97e
build(deps): bump react-router in /app in the npm-dependencies group (#768)
Bumps the npm-dependencies group in /app with 1 update: [react-router](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router).


Updates `react-router` from 7.18.2 to 7.18.4
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router@7.18.4/packages/react-router/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router@7.18.4/packages/react-router)

---
updated-dependencies:
- dependency-name: react-router
  dependency-version: 7.18.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:44:22 -06:00
dependabot[bot]
6b79323d2c
build(deps-dev): bump webpack-dev-server from 5.2.6 to 6.0.0 in /app (#769)
Bumps [webpack-dev-server](https://github.com/webpack/webpack-dev-server) from 5.2.6 to 6.0.0.
- [Release notes](https://github.com/webpack/webpack-dev-server/releases)
- [Changelog](https://github.com/webpack/webpack-dev-server/blob/main/CHANGELOG.md)
- [Commits](https://github.com/webpack/webpack-dev-server/compare/v5.2.6...v6.0.0)

---
updated-dependencies:
- dependency-name: webpack-dev-server
  dependency-version: 6.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:43:52 -06:00
lrnselfreliance
51d9c07784
dependabot: also hold cypress 16, react-router 8 and testing-library/react majors (#767)
Each regenerated after the last config change and each needs its own
migration: cypress 16 needs Node 22, react-router 8 touches ~40 files,
and @testing-library/react 16 fails 15 menu/popover tests.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 10:34:52 -06:00
dependabot[bot]
9fc9929647
build(deps): bump web-vitals from 5.3.0 to 6.2.2 in /app (#764)
Bumps [web-vitals](https://github.com/GoogleChrome/web-vitals) from 5.3.0 to 6.2.2.
- [Changelog](https://github.com/GoogleChrome/web-vitals/blob/main/CHANGELOG.md)
- [Commits](https://github.com/GoogleChrome/web-vitals/compare/v5.3.0...v6.2.2)

---
updated-dependencies:
- dependency-name: web-vitals
  dependency-version: 6.2.2
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:33:23 -06:00
dependabot[bot]
39cef45c59
build(deps): bump the npm-dependencies group in /app with 3 updates (#761)
Bumps the npm-dependencies group in /app with 3 updates: [react](https://github.com/react/react/tree/HEAD/packages/react), [react-dom](https://github.com/react/react/tree/HEAD/packages/react-dom) and [react-dropzone](https://github.com/react-dropzone/react-dropzone).


Updates `react` from 18.2.0 to 18.3.1
- [Release notes](https://github.com/react/react/releases)
- [Changelog](https://github.com/react/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/react/react/commits/v18.3.1/packages/react)

Updates `react-dom` from 18.2.0 to 18.3.1
- [Release notes](https://github.com/react/react/releases)
- [Changelog](https://github.com/react/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/react/react/commits/v18.3.1/packages/react-dom)

Updates `react-dropzone` from 14.2.3 to 14.4.1
- [Release notes](https://github.com/react-dropzone/react-dropzone/releases)
- [Commits](https://github.com/react-dropzone/react-dropzone/compare/v14.2.3...v14.4.1)

---
updated-dependencies:
- dependency-name: react
  dependency-version: 18.3.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: react-dom
  dependency-version: 18.3.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: react-dropzone
  dependency-version: 14.4.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:33:11 -06:00
dependabot[bot]
920b619bcc
build(deps): bump the python-dependencies group with 12 updates (#763)
Bumps the python-dependencies group with 12 updates:

| Package | From | To |
| --- | --- | --- |
| [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) | `1.3.22` | `1.3.24` |
| [beautifulsoup4](https://www.crummy.com/software/BeautifulSoup/bs4/) | `4.14.3` | `4.15.0` |
| [cachetools](https://github.com/tkem/cachetools) | `5.5.0` | `5.5.2` |
| [cryptography](https://github.com/pyca/cryptography) | `50.0.0` | `50.0.2` |
| [feedparser](https://github.com/kurtmckee/feedparser) | `6.0.12` | `6.0.14` |
| [jc](https://github.com/kellyjonbrazil/jc) | `1.25.6` | `1.26.0` |
| [libzim](https://github.com/openzim/python-libzim) | `3.10.0` | `3.13.0` |
| [pytest](https://github.com/pytest-dev/pytest) | `9.0.3` | `9.1.1` |
| [python-dotenv](https://github.com/theskumar/python-dotenv) | `1.2.2` | `1.2.3` |
| [pytz](https://github.com/stub42/pytz) | `2026.2` | `2026.4` |
| [selenium](https://github.com/SeleniumHQ/Selenium) | `4.44.0` | `4.49.0` |
| [tqdm](https://github.com/tqdm/tqdm) | `4.67.3` | `4.70.1` |


Updates `sqlalchemy` from 1.3.22 to 1.3.24
- [Release notes](https://github.com/sqlalchemy/sqlalchemy/releases)
- [Changelog](https://github.com/sqlalchemy/sqlalchemy/blob/main/CHANGES.rst)
- [Commits](https://github.com/sqlalchemy/sqlalchemy/commits)

Updates `beautifulsoup4` from 4.14.3 to 4.15.0

Updates `cachetools` from 5.5.0 to 5.5.2
- [Changelog](https://github.com/tkem/cachetools/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/tkem/cachetools/compare/v5.5.0...v5.5.2)

Updates `cryptography` from 50.0.0 to 50.0.2
- [Changelog](https://github.com/pyca/cryptography/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pyca/cryptography/compare/50.0.0...50.0.2)

Updates `feedparser` from 6.0.12 to 6.0.14
- [Release notes](https://github.com/kurtmckee/feedparser/releases)
- [Changelog](https://github.com/kurtmckee/feedparser/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/kurtmckee/feedparser/compare/v6.0.12...v6.0.14)

Updates `jc` from 1.25.6 to 1.26.0
- [Release notes](https://github.com/kellyjonbrazil/jc/releases)
- [Changelog](https://github.com/kellyjonbrazil/jc/blob/master/CHANGELOG)
- [Commits](https://github.com/kellyjonbrazil/jc/compare/v1.25.6...v1.26.0)

Updates `libzim` from 3.10.0 to 3.13.0
- [Release notes](https://github.com/openzim/python-libzim/releases)
- [Changelog](https://github.com/openzim/python-libzim/blob/main/CHANGELOG.md)
- [Commits](https://github.com/openzim/python-libzim/compare/v3.10.0...v3.13.0)

Updates `pytest` from 9.0.3 to 9.1.1
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/9.0.3...9.1.1)

Updates `python-dotenv` from 1.2.2 to 1.2.3
- [Release notes](https://github.com/theskumar/python-dotenv/releases)
- [Changelog](https://github.com/theskumar/python-dotenv/blob/main/CHANGELOG.md)
- [Commits](https://github.com/theskumar/python-dotenv/compare/v1.2.2...v1.2.3)

Updates `pytz` from 2026.2 to 2026.4
- [Release notes](https://github.com/stub42/pytz/releases)
- [Commits](https://github.com/stub42/pytz/compare/release_2026.2...release_2026.4)

Updates `selenium` from 4.44.0 to 4.49.0
- [Release notes](https://github.com/SeleniumHQ/Selenium/releases)
- [Commits](https://github.com/SeleniumHQ/Selenium/compare/selenium-4.44.0...selenium-4.49.0)

Updates `tqdm` from 4.67.3 to 4.70.1
- [Release notes](https://github.com/tqdm/tqdm/releases)
- [Commits](https://github.com/tqdm/tqdm/compare/v4.67.3...v4.70.1)

---
updated-dependencies:
- dependency-name: sqlalchemy
  dependency-version: 1.3.24
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: beautifulsoup4
  dependency-version: 4.15.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: cachetools
  dependency-version: 5.5.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: cryptography
  dependency-version: 50.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: feedparser
  dependency-version: 6.0.14
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: jc
  dependency-version: 1.26.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: libzim
  dependency-version: 3.13.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: pytest
  dependency-version: 9.1.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: python-dotenv
  dependency-version: 1.2.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: python-dependencies
- dependency-name: pytz
  dependency-version: '2026.4'
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: selenium
  dependency-version: 4.49.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
- dependency-name: tqdm
  dependency-version: 4.70.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: python-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:33:05 -06:00
dependabot[bot]
a7103002b6
build(deps): bump nanoid from 3.3.16 to 3.3.19 in /app (#759)
Bumps [nanoid](https://github.com/ai/nanoid) from 3.3.16 to 3.3.19.
- [Release notes](https://github.com/ai/nanoid/releases)
- [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ai/nanoid/compare/3.3.16...3.3.19)

---
updated-dependencies:
- dependency-name: nanoid
  dependency-version: 3.3.19
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:22:20 -06:00
dependabot[bot]
5e76914485
build(deps): bump qs and express in /app (#758)
Bumps [qs](https://github.com/ljharb/qs) and [express](https://github.com/expressjs/express). These dependencies needed to be updated together.

Updates `qs` from 6.15.3 to 6.16.0
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.15.3...v6.16.0)

Updates `express` from 4.22.2 to 4.22.3
- [Release notes](https://github.com/expressjs/express/releases)
- [Changelog](https://github.com/expressjs/express/blob/v4.22.3/History.md)
- [Commits](https://github.com/expressjs/express/compare/v4.22.2...v4.22.3)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.16.0
  dependency-type: indirect
- dependency-name: express
  dependency-version: 4.22.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:22:15 -06:00
lrnselfreliance
0d2431c41a
dependabot: move major-version exclusions into the config (#760)
Comment-based ignores did not survive the last config change, and the
SQLAlchemy rule only blocked majors while 1.4 (the 2.0 transition
release) slipped into the python group. Hold SQLAlchemy <1.4, alembic
<1.11, cachetools majors (mru_cache removed in 6), and the npm majors
that each need a migration branch: maplibre-gl 6, react-dropzone 15+,
React 19, TypeScript 6+, Mantine 9.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 10:21:50 -06:00
dependabot[bot]
3d0eb76337
build(deps): update pymupdf requirement from >=1.27.2.3 to >=1.28.2 (#756)
Updates the requirements on [pymupdf](https://github.com/pymupdf/pymupdf) to permit the latest version.
- [Release notes](https://github.com/pymupdf/pymupdf/releases)
- [Changelog](https://github.com/pymupdf/PyMuPDF/blob/main/changes.txt)
- [Commits](https://github.com/pymupdf/pymupdf/compare/1.27.2.3...1.28.2)

---
updated-dependencies:
- dependency-name: pymupdf
  dependency-version: 1.28.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:21:14 -06:00
dependabot[bot]
3800f4d332
build(deps): update fastapi requirement in /controller (#748)
Updates the requirements on [fastapi](https://github.com/fastapi/fastapi) to permit the latest version.
- [Release notes](https://github.com/fastapi/fastapi/releases)
- [Commits](https://github.com/fastapi/fastapi/compare/0.141.1...0.142.2)

---
updated-dependencies:
- dependency-name: fastapi
  dependency-version: 0.142.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:19:52 -06:00
dependabot[bot]
323b7e66df
build(deps): bump fast-uri from 3.1.7 to 3.1.8 in /app (#746)
Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.7 to 3.1.8.
- [Release notes](https://github.com/fastify/fast-uri/releases)
- [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.8)

---
updated-dependencies:
- dependency-name: fast-uri
  dependency-version: 3.1.8
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:19:48 -06:00
dependabot[bot]
9eb56967e4
build(deps): bump brace-expansion in /app (#745)
Bumps  and [brace-expansion](https://github.com/juliangruber/brace-expansion). These dependencies needed to be updated together.

Updates `brace-expansion` from 1.1.18 to 1.1.21
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.18...v1.1.21)

Updates `brace-expansion` from 2.1.4 to 2.1.7
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.18...v1.1.21)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.21
  dependency-type: indirect
- dependency-name: brace-expansion
  dependency-version: 2.1.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:19:43 -06:00
lrnselfreliance
ecd8ce64be
dependabot: hold alembic below 1.11 while SQLAlchemy stays on 1.3 (#747)
alembic 1.20 requires SQLAlchemy>=2.0, so every grouped python
update that included it failed to install (ResolutionImpossible).
Ignore alembic >=1.11 and SQLAlchemy major bumps until the
SQLAlchemy 2 migration is done.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 10:11:08 -06:00
dependabot[bot]
71287c9a23
build(deps): bump the npm-dependencies group in /app with 7 updates (#741)
Bumps the npm-dependencies group in /app with 7 updates:

| Package | From | To |
| --- | --- | --- |
| [@tabler/icons-react](https://github.com/tabler/tabler-icons/tree/HEAD/packages/icons-react) | `3.46.0` | `3.48.0` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.6` | `14.6.7` |
| [esptool-js](https://github.com/espressif/esptool-js) | `0.6.1` | `0.7.0` |
| [react-colorful](https://github.com/omgovich/react-colorful) | `5.8.0` | `5.8.1` |
| [three](https://github.com/mrdoob/three.js) | `0.185.1` | `0.186.1` |
| [@testing-library/dom](https://github.com/testing-library/dom-testing-library) | `10.4.1` | `10.4.2` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.4.0` | `26.6.3` |


Updates `@tabler/icons-react` from 3.46.0 to 3.48.0
- [Release notes](https://github.com/tabler/tabler-icons/releases)
- [Commits](https://github.com/tabler/tabler-icons/commits/v3.48.0/packages/icons-react)

Updates `@testing-library/user-event` from 14.6.6 to 14.6.7
- [Release notes](https://github.com/testing-library/user-event/releases)
- [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/user-event/compare/v14.6.6...v14.6.7)

Updates `esptool-js` from 0.6.1 to 0.7.0
- [Release notes](https://github.com/espressif/esptool-js/releases)
- [Changelog](https://github.com/espressif/esptool-js/blob/main/CHANGELOG.md)
- [Commits](https://github.com/espressif/esptool-js/compare/v0.6.1...v0.7.0)

Updates `react-colorful` from 5.8.0 to 5.8.1
- [Release notes](https://github.com/omgovich/react-colorful/releases)
- [Changelog](https://github.com/omgovich/react-colorful/blob/master/CHANGELOG.md)
- [Commits](https://github.com/omgovich/react-colorful/commits)

Updates `three` from 0.185.1 to 0.186.1
- [Release notes](https://github.com/mrdoob/three.js/releases)
- [Commits](https://github.com/mrdoob/three.js/commits)

Updates `@testing-library/dom` from 10.4.1 to 10.4.2
- [Release notes](https://github.com/testing-library/dom-testing-library/releases)
- [Changelog](https://github.com/testing-library/dom-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/dom-testing-library/compare/v10.4.1...v10.4.2)

Updates `@types/node` from 26.4.0 to 26.6.3
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@tabler/icons-react"
  dependency-version: 3.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: "@testing-library/user-event"
  dependency-version: 14.6.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: esptool-js
  dependency-version: 0.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: react-colorful
  dependency-version: 5.8.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: three
  dependency-version: 0.186.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: "@testing-library/dom"
  dependency-version: 10.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@types/node"
  dependency-version: 26.6.3
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:08:32 -06:00
dependabot[bot]
0837330bd7
build(deps): bump colord from 2.9.3 to 2.10.0 in /app (#703)
Bumps [colord](https://github.com/omgovich/colord) from 2.9.3 to 2.10.0.
- [Release notes](https://github.com/omgovich/colord/releases)
- [Changelog](https://github.com/omgovich/colord/blob/master/CHANGELOG.md)
- [Commits](https://github.com/omgovich/colord/commits/v2.10)

---
updated-dependencies:
- dependency-name: colord
  dependency-version: 2.10.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:07:26 -06:00
dependabot[bot]
5439fff871
build(deps): bump js-yaml in /app (#705)
Bumps  and [js-yaml](https://github.com/nodeca/js-yaml). These dependencies needed to be updated together.

Updates `js-yaml` from 3.15.0 to 3.15.2
- [Changelog](https://github.com/nodeca/js-yaml/blob/3.15.2/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/3.15.0...3.15.2)

Updates `js-yaml` from 4.3.0 to 4.3.2
- [Changelog](https://github.com/nodeca/js-yaml/blob/3.15.2/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/3.15.0...3.15.2)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 3.15.2
  dependency-type: indirect
- dependency-name: js-yaml
  dependency-version: 4.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:07:22 -06:00
dependabot[bot]
c973a4106f
build(deps): bump sanic from 24.12.0 to 24.12.1 in /docker/archive (#714)
Bumps [sanic](https://github.com/sanic-org/sanic) from 24.12.0 to 24.12.1.
- [Release notes](https://github.com/sanic-org/sanic/releases)
- [Commits](https://github.com/sanic-org/sanic/compare/v24.12.0...v24.12.1)

---
updated-dependencies:
- dependency-name: sanic
  dependency-version: 24.12.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:07:17 -06:00
dependabot[bot]
dd7269d1ca
build(deps): update uvicorn requirement in /controller (#742)
Updates the requirements on [uvicorn](https://github.com/Kludex/uvicorn) to permit the latest version.
- [Release notes](https://github.com/Kludex/uvicorn/releases)
- [Changelog](https://github.com/Kludex/uvicorn/blob/main/docs/release-notes.md)
- [Commits](https://github.com/Kludex/uvicorn/compare/0.52.4...0.54.0)

---
updated-dependencies:
- dependency-name: uvicorn
  dependency-version: 0.54.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-03 10:07:13 -06:00
lrnselfreliance
57e647c5b4
docker: web container reaps zombies; zim and help healthchecks can pass (#744)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
Caddy is PID 1 in the web container and reaps nothing.  The healthcheck's
busybox `wget --spider https://...` forks an `ssl_client` helper that is
orphaned to caddy and stays a zombie, one per check.  `init: true` runs
tini as PID 1 so they are reaped.

The zim healthcheck calls curl, which the debian:13 kiwix image does not
install, so every check exited 127.  The help healthcheck probed port
8086, which is Caddy's HTTPS proxy on the web container; mkdocs serves
on port 80 inside its own container.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 15:49:34 -06:00
lrnselfreliance
8d6f5b5cad
api: forked workers die on SIGTERM before Sanic installs their handlers (#743)
A Sanic worker is forked from the manager and carries the manager's
Python SIGTERM/SIGINT handlers until `_setup_system_signals` installs its
own, which happens after the startup listeners (about two seconds with
sixteen workers starting at once).  When auto-reload fires a second time
inside that window the manager terminates the half-started generation,
each child runs `WorkerManager.shutdown_signal` instead of exiting, marks
itself TERMINATED, and then finishes starting.  The manager has already
spawned replacements, so the old generation lives on: untracked, holding
the listening socket, serving stale code, and holding ~220 MB each.

Register an at-fork hook in the main process that resets both signals to
their default action in the child.  The perpetual process already did
this by hand for itself; server workers now get the same treatment.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 15:49:06 -06:00
lrnselfreliance
5c78aa332d
collections: listing answers channel and download queries from covering indexes (#740)
Some checks failed
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled
The listing still read every channel row (for the summary columns) and every download
row of the listed Collections (for the minimum frequency). Both tables store yt-dlp
info_json, so rows are tens of KB and each sits on its own scattered page; selecting
fewer columns did not help because the seek per row is the cost. From a cold disk
cache that was 5 s per table, 10+ s total, on a large library.

Two covering indexes, channel (collection_id, video_count, total_size) and
download (collection_id, frequency), answer both queries without touching a row. The
listing no longer loads Download objects at all; it computes min_download_frequency
with one grouped query and drops the unused `downloads` array from listing rows (the
detail endpoints keep it; the list views only read min_download_frequency).

Adds a models-vs-migrations test (alembic check) so an index or column added to a
model without a migration, or vice versa, fails the suite.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 12:53:40 -06:00
lrnselfreliance
20be5dfc27
collections: channel and domain listings read trigger-maintained summary columns (#739)
* collections: channel listing reads trigger columns and batch-loads tag/downloads

Listing channel collections summed FileGroup sizes through a video join, which reads a
random page of the file_group table per video, and lazy-loaded every collection's tag
and downloads one query at a time. On a large library with a cold disk cache the
listing took over two minutes, past the browser's 60 s timeout, so the Channels page
showed an error.

channel.video_count and channel.total_size are already maintained by triggers
(wrolpi/schema_ddl.py), so read those. Tag and downloads are selectin-loaded, so the
query count no longer grows with the number of collections.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* collections: domain listing reads trigger-maintained summary columns

Domain Collections summed file_group.size through an archive join on every listing,
one random page read per archive (about 9 s from a cold disk cache on a large
library). New triggers keep collection.item_count and collection.total_size current
for Domain Collections, as the channel triggers already do for Channels, and the
listing reads those columns. A migration installs the triggers and backfills
existing Domain Collections.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 11:36:08 -06:00
lrnselfreliance
4fea50943b
map: clicking a POI shows its kind, detail, elevation and coordinates (#738)
The Protomaps basemap keeps a few attributes per POI beyond the name the
map already labels: kind, kind_detail and elevation.  Clicking a POI now
opens a popup with those, plus the feature's coordinates (or the click
location when the feature has no point).  The same POI appears at several
min_zoom levels within one tile, so features are deduped by name and kind.

Map popups (this one and the existing pin popup) now follow the active
theme's tokens instead of MapLibre's fixed white, covering light, dark,
night and amber.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-27 08:23:03 -06:00
lrnselfreliance
15d3792b0e
videos: transcode can remove the audio stream (silent video) (#737)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
A video's audio stream can be dropped the same way its video stream could
already be: a new REMOVE_AUDIO audio target maps only the video stream with
-an, needs a video container, and is refused for audio files.  Output
verification insists the result has no audio stream.

Removing both streams is refused by the validator, the API, resolve_output,
and the modal: choosing Remove for one stream resets the other to Keep and
withdraws the other's Remove option.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 17:49:14 -06:00
lrnselfreliance
63ddad69e8
app: api helpers report failure instead of returning an empty value (#736)
Six helpers turned a non-OK response into an empty value, so their
consumers rendered a server error as "nothing here":

* getConfigBackups -> {dates: []}: "No backups available for this
  config."  A thrown request also left "Loading backups..." forever.
* getInventoryBackups -> []: "No backups yet."
* getDownloaders -> {downloaders: []} on a throw, the error body on a
  non-OK response (which then crashed the .map): the RSS form's
  Downloader select sat empty.
* searchMap -> {results: []}: "No map locations found".
* getMapSearchStatus -> {indexed: [], missing: []}: "No maps are
  installed".
* flasherSearch -> [null, null], then `|| []`: "No .bin firmware
  found".

Invariants now enforced and tested:
* On a non-OK response each helper returns undefined; an empty value
  only ever comes from the server.
* Each consumer shows an error for a failed or thrown fetch and keeps
  its "none" message for a confirmed empty result.  The Downloader
  select is disabled and says it is loading or could not fetch.  A
  failed map status is unknown, never "no maps are installed".
* The map search tab loads from the first render, and a query shorter
  than the two characters the request needs now says so instead of
  "No map locations found".

Archive browsers and recent tags are left as they are: a failed fetch
there hides an optional picker or suggestion list without claiming
anything.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 17:47:32 -06:00
lrnselfreliance
20541d7184
app: number fields no longer throw "e.preventDefault is not a function" (#735)
`useForm`'s input handlers called `e.preventDefault()` unconditionally, but the
Mantine-backed `NumberField` (Sleep between requests, Depth, Maximum Pages)
hands them a bare `{target}` object because NumberInput emits a value, not an
event.  Every keystroke in those fields threw.

`handleInputEvent` now only calls `preventDefault` when the argument actually
has one, and `getInputProps`' wrapper no longer repeats the call.  Audited every
other `preventDefault` call site: all are bound to real DOM/React events or a
guarded no-argument call.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 17:41:52 -06:00
lrnselfreliance
eead78007d
app: status and settings contexts say whether their first poll landed (#734)
Both contexts start as {} and nothing distinguished that from a
server that reported nothing, so for up to one poll interval after a
page load consumers rendered the negative case as fact: the Settings
form appeared with blank values and an "undefined/config/wrolpi.yaml"
path (the ready check `settings ? true : undefined` was always true),
the Downloads toggle was clickable and read "Downloading Disabled",
the upgrade panel said "up to date, vundefined", and the five hardware
toggles on the Controller page claimed "not supported on this server".

Invariants now enforced and tested:
* StatusContext.loaded is true once a poll returned a real status;
  the API being down does not count.  SettingsContext.loaded is true
  once settings were fetched, and `failed` when a fetch returned
  nothing before that; a failed refresh after a load keeps the last
  known values and `loaded`.
* The Settings page shows its loader until loaded and its error only
  when failed.  The upgrade panel shows a loader until status loaded.
  The Downloads toggle is disabled with a neutral label until then.
* A subsystem toggle is disabled without claiming "unsupported" while
  status is unknown (undefined); "unsupported" (null) is reserved for
  a loaded status that lacks the field.  A call in flight is unknown,
  not unsupported.

The context fixtures declare loaded so existing specs render as
before.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 17:25:46 -06:00
lrnselfreliance
306386e801
app: Flasher saved configs and Statistics distinguish pending from empty (#733)
The Flasher's saved configurations started as [] with no loading
flag, and the Saved Firmwares tab is the default tab, so every load
painted "No saved configurations yet." until the fetch returned.  The
api helper returned [] on a non-OK response too, so a failed fetch
read as an empty list.

useStatistics used useState() with no initial value, so the
Statistics page's first render saw undefined and flashed "Failed to
fetch statistics" for one frame before the effect set {} and the
spinner appeared.

Invariants now enforced and tested:
* null = pending, undefined = fetch failed, [] / object = loaded.  The
  api helper returns undefined (and toasts) on a non-OK response.
* The Saved Firmwares tab shows a placeholder while pending, an error
  on failure, and "No saved configurations yet." only once the server
  confirmed there are none.  Only the newest configs request may write
  state, since save and delete refetch.
* The Statistics page shows its loader while pending and its error
  only for a failed fetch.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 17:05:02 -06:00
lrnselfreliance
6e251a009a
app: map pins and subscriptions tables distinguish pending from empty (#732)
* app: map pins and subscriptions tables distinguish pending from empty

Both lists were initialised to [], which SortableTable renders as
"loaded and empty".  The Pins tab therefore showed "No pins.
Right-click on the map to add one." until the pins arrived, and the
Manage tab's subscriptions table showed "No results" until the catalog
did.  A non-OK response (the api helpers return undefined) or a thrown
request left the same messages up permanently.

Invariants now enforced and tested:
* null = pending, undefined = fetch failed, [] = confirmed empty, so
  SortableTable shows its placeholder while pending and each empty
  message appears only once the server confirmed the list is empty.
* A failed fetch renders an error in place of the table.
* Only the newest request for each list may write state, since edits,
  deletes, subscribes and unsubscribes refetch while the mount request
  may still be in flight.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* app: the regions preview waits for the catalog

"View All Regions" stayed enabled while the catalog was pending or
failed, and the modal received a fresh `catalog || []` on every
render.  Its map effect depends on that array, and ManageMap
re-renders on every status poll, so an open preview tore its WebGL
map down and rebuilt it every three seconds, and a failed catalog was
previewed as zero regions over the error message.

The button is disabled until the catalog is an array, and the modal
is mounted only then, so it receives the state array itself.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 16:55:58 -06:00
lrnselfreliance
ae745f1a18
app: search dropdown offers "Channels: No results" only after a search (#730)
useSuggestions started with channels: [] and reset to that on every
keystroke, and the normalizer treats an empty list as "the server
found none".  So the global search dropdown showed a "Channels: No
results" row on focus before anything was typed, and on every
keystroke through the debounce and the request.  Because that row
counts as a result, the SearchBox's own "Searching…" state never
appeared.

The channel, domain, author and subject groups now start as null,
meaning not fetched; an empty list only ever comes from the server.
The count summary tolerates the null.  Tests render the hook and
check no Channels group exists before a search or while the request
is pending, and that the "No results" row and real rows still appear
after the response.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 15:07:00 -06:00
lrnselfreliance
5dda94492e
videos: hide the transcoder's temporary output from the file refresh (#731)
ffmpeg wrote `<stem>.transcode.<container>` next to the source.  A refresh
that overlapped the transcode discovered that file, probed the half-written
output (errors in the log), and created a FileGroup and Video for a path the
final rename removed moments later.

The temporary file is now `.<stem>.transcode.<container>`: every discovery
path already skips hidden files, and staying in the same directory keeps
the rename over the final path atomic.  `transcode_tmp_path` is the single
place the name is built.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 14:59:51 -06:00
lrnselfreliance
86d4bbab98
Bookmarks: a nav menu of user links, stored in bookmarks.yaml (#729)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* bookmarks: user bookmarks in the navigation bar, stored in bookmarks.yaml

A "Bookmarks" tab between Calculators and Flasher opens on hover or click and
lists the user's bookmarks, with directories as flyout submenus (Menu.Sub).
The mobile hamburger shows directories as labelled groups instead.  The tab
always shows, with an "Edit bookmarks" item, so the feature can be found
before any bookmark exists.

Bookmarks live in a new config-only bookmarks.yaml: a nested tree where a
node with `children` is a directory and a node with `url` is a bookmark.
Every node carries an integer id so the API can rename, move and delete
without relying on names.  A URL may be a path on this WROLPi, a port on this
host (`:8096/` or `http://:8096/`, resolved against whatever hostname the
browser used, so it works over LAN IP, mDNS and the hotspot alike), or an
absolute URL.  Each bookmark chooses whether to open in a new tab.

The editor at /more/bookmarks follows the playlist items table: numbered rows,
up/down/edit/delete, and inline "Add a bookmark" / "Add a directory" forms
with a Location picker.  Deleting a directory asks first, since its contents
go with it.  The menu and the editor are in the component gallery.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* bookmarks: mark More current when the editor is folded inside it; rem indents in the mobile menu

Found on the QA Pi at a width where Bookmarks overflows into More: the More
button carried no mark on /more/bookmarks, because the bookmarks link has no
`to` for isLinkActive to match.  isLinkActive now knows the bookmarks link owns
its editor page, and the Bookmarks tab uses the same rule.

The mobile menu's directory labels sat a few pixels left of the labels around
them: the indent was in em, and a Menu.Label is set smaller than a Menu.Item.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* bookmarks: parse URLs instead of matching a prefix; validate the whole tree on every write

The URL contract was checked by prefix on both sides, and a prefix is not a
form: `//evil.com` starts like a path and `:8096@evil.com` starts like a port,
and a browser takes both off this host.  A path is now a single leading slash
that resolves to this origin, a port form is an optional scheme, `:`, digits
and then only a path, query or fragment (no `@`, no backslash, no control
characters), and anything else must parse as http(s).  The same rules live in
wrolpi/bookmarks.py and BookmarksContext.js, with the same bypass strings in
both test suites.

The config's dataclass validator only saw that `bookmarks` was a list, so a
hand-edited file or the generic config API could store a `javascript:` URL
that the bookmarks API would refuse, and the nav rendered it.  The config now
validates the tree itself on every write and import: URL forms, exactly one of
url/children, unique integer ids, boolean new_tab, and no cycles (a YAML
anchor can build one).  An invalid file is not imported and, since it was never
successfully imported, is never overwritten.

On the page, a stored URL that does not resolve is rendered as text, never as
an href.  A refused add keeps what was typed instead of clearing the form, and
an edit whose move is refused still refreshes the nav (the rename was
committed) and keeps the modal open.  An IPv6 host is bracketed before a port.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* help: document Bookmarks

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 13:11:36 -06:00
lrnselfreliance
9caa140fb6
app: search Other tab distinguishes pending channels from none (#728)
* app: search Other tab distinguishes pending channels from none

useSearchChannels initialised channels to [] and loading to false, and
only set loading inside its mount effect, so the Other tab's first
render painted "No Channels" with a count of 0 before the search had
run.  A failed search was rendered the same way, since the hook had no
catch and the API helper returns undefined on a non-OK response.

Invariants now enforced and tested:
* null = pending, undefined = fetch failed, [] = no channels; loading
  is true from the first render because the search starts on mount.
* Changing tags resets to pending, and only the newest request may
  write state, so a slow response for previous tags is dropped.
* The tab shows a loader while pending, an error on failure, and
  "No Channels" only once the server confirmed there are none.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* app: useSearchChannels follows its caller's tags

The hook read its tag argument only as the initial state, so the
Other tab never refetched when the filter modal changed the URL's tags
while the tab stayed mounted; the list, including a stale "No
Channels", was whatever the mount fetched.

The internal tag state now follows the argument's contents, keyed on
the serialized list because the caller builds a new array every
render.  Tests change the hook argument after a loaded result and
expect a second search and a reset to pending, check that a new array
with the same tags does not refetch, and keep the slow-response drop.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 12:01:37 -06:00
lrnselfreliance
811793d767
perpetual: clear in-progress flags after a crash, downloads only in the perpetual process, KillMode=mixed (#726)
* perpetual: clear in-progress flags after a crash; downloads only in the perpetual process

Found by a kill -9 stress test on a device:

A SIGKILL inside `with flags.file_worker_counting` (or any of the file
worker's progress flags) left the shared flag set, so every later refresh
raised "flag is already set" until the whole API was restarted.
reconcile_after_predecessor now clears the perpetual process's in-progress
flags (file_worker_*, global_refresh_active) and reports it.

create_downloads started a dispatch in whatever process called it, so an
API worker executed downloads (and could take transcode_lock) despite the
single-process design.  It now dispatches only inside the perpetual
process (or under pytest); the download loop picks new rows up within
seconds otherwise.

The shared restart cooldown drops from 60 s to 15 s: it only has to
outlast the manager acting on a request, and a replacement that dies
right away was left dead for the rest of the minute.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* systemd: KillMode=mixed for the API so main shuts its own children down

With control-group kill, SIGTERM reaches the multiprocessing Manager at
the same moment as Sanic's main process; main's cleanup then writes
worker state to a dead Manager (broken pipe) and exits 1, so a plain
`systemctl stop` is recorded as a failure whenever a child takes a
moment to stop (a transcode being killed, for instance).  Signal only
main; it stops the workers and the perpetual process itself.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* perpetual: clear an in-progress flag only when its holder is dead

`with flag:` now records the holder pid in shared_ctx.flag_holders and
drops it on exit.  The reconcile step clears the flags only the perpetual
process ever enters (file_worker_counting, file_worker_discovery,
global_refresh_active) whenever they are set, and the flags API workers
also enter (file_worker_modeling / indexing / cleanup via refresh_sync,
map_search_building via the map rebuild endpoints) only when the
recorded holder is dead.  file_worker_busy is no longer touched: a
collection move in an API worker holds it as a mutex, and
process_queue drops a stale one itself.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 11:22:58 -06:00
lrnselfreliance
83362a65c1
app: video comments and description distinguish pending from empty (#727)
* app: video comments and description distinguish pending from empty

useVideoExtras initialised both values to null and the page treated
null the same as "none", so every video open (and every prev/next)
showed "No comments have been downloaded. Refresh the video?" with a
live Refresh button until the comments arrived.  The Description tab
showed "No description available." the same way.  A failed fetch was
also rendered as "none", and the previous video's data lingered until
the next video's responses arrived.

Invariants now enforced and tested:
* null = pending, undefined = fetch failed, [] / '' = loaded and empty.
  The API serialises a missing info_json field as null, so the hook
  normalises that to empty; consumers never see null for "none".
* Switching video resets both to pending, and a slow response for the
  previous video is dropped.
* The page renders a placeholder while pending, an error message on
  failure, and offers Refresh only once the server confirmed there are
  no comments.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* app: useVideoExtras drops any request that is not the newest

Matching on the video id let a stale request land when the user left
and returned to the same video, or saved an edit while the page's
first description request was still in flight.  Each fetch now takes a
generation number and only the newest generation may write state,
per value, so a description refetch never invalidates a comments
request.

The edit dialog adopts a description that arrives while it is open
only if the user has not typed, so a draft written over the
placeholder is not wiped by the empty or failed value that follows.

Tests: 7 -> none -> 8 -> 7 with the first request rejecting last; a
save refetch beating the initial request; the draft surviving; the
pending placeholder asserted; the console spy restored in finally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-26 11:22:37 -06:00
lrnselfreliance
25e00f75fd
app: useLatestRequest reports loading before the debounce (#725)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
`loading` only became true once the debounce timer fired, so for the
first 300-500ms after every sendRequest the hook reported
data=null, loading=false.  Consumers branch on `loading` to choose
between a spinner and an empty state, so the global search dropdown,
the Zim search tab, and the map search rendered "No results" (or
"No Zims have been indexed") for a search that had not run yet.

Invariants now enforced and tested:
* loading is true from sendRequest until the latest request settles.
* The latest-request id is claimed synchronously in sendRequest, so a
  fetch already in flight is stale the moment a newer request is sent
  and cannot write data or clear loading during the new debounce.
* A stale request that rejects late no longer nulls newer data.
* A pending debounce is cancelled on unmount, and any in-flight fetch
  is treated as stale.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-25 14:05:08 -06:00
lrnselfreliance
bcd12c9b96
startup: run database config imports off the worker event loop (#723)
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run
* startup: run database config imports off the worker event loop

import_all_db_configs runs in a Sanic worker's after_server_start
listener, after that worker's socket is already accepting connections.
Every import in it was a synchronous call on the event loop, so a large
tags/channels/domains/downloads config froze that worker for the whole
import and every request the kernel routed to it hung. With the default
worker count equal to CPU count, a one- or two-core host lost all or
half of the API for minutes on startup, and the frontend's 60s request
limit turned that into repeated silent retries.

Each synchronous import now runs in asyncio.to_thread. The SQLite engine
already allows cross-thread connections (check_same_thread off, NullPool)
and other startup work already uses to_thread. Imports still run one at
a time in the documented order; only the loop is no longer blocked.

Test: a ticker task must keep ticking while two deliberately slow
synchronous imports run. It scored zero ticks before this change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* startup: thread the downloads import too; test covers every import

import_downloads_config is async but never awaited anything: its body
called the synchronous DownloadManagerConfig.import_config on the event
loop, so a large download_manager.yaml still froze the worker. The
db_up check stays on the loop and only the import moves to a thread.

The responsiveness test now patches every import the startup path
performs, including that sync downloads import, with the same blocking
sleep, and requires ~90% of the total sleep budget in ticks so any one
import returning to the loop fails it. The ticker is awaited after
cancel so the task does not outlive the loop. Docstring trimmed to the
one constraint not visible at the call site.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 18:22:52 -06:00
lrnselfreliance
92fa3f785f
files: shared modeler batch loop for video, doc, zim, archive (#722)
* files: shared modeler batch loop for video, doc, zim, archive

Paging, skip-ids, progress, and cancel yields live in
wrolpi.files.modeler.run_modeler_loop.  Each module still owns select /
prepare / apply and its transaction style: video probes outside the write
lock, docs use one write per file with lock retries, zim and archive use
one write per page.  Archive HTML that is not a SingleFile raises
SkipModeler so apply_indexers can claim it.

* files: quieter batch-modeler errors; drop unused imports

Break out of a batch page on InvalidRequestError after a flush failure
so the rest of the page does not each log the same poisoned session.
Re-raise PYTEST apply failures without a misleading commit-failure
message.  Remove asyncio/List/OperationalError/PYTEST/Iterable leftovers
from docs, archive, and zim.
2026-09-24 16:47:46 -06:00
lrnselfreliance
2d0f433450
files: split FileWorker move and reorganize into mixins (#719)
FileWorker stays the queue, status, and refresh apply path.  Move planning
and execute/revert live in wrolpi.files.move; collection reorganize jobs
live in wrolpi.files.reorganize_job.  Perpetual-process dispatch is
unchanged.

Existing `from wrolpi.files.worker import build_move_plan_bulk` still works.
2026-09-24 14:17:42 -06:00
1395 changed files with 101453 additions and 7514 deletions

View file

@ -1,253 +0,0 @@
# Use the latest 2.1 version of CircleCI pipeline process engine.
# See: https://circleci.com/docs/2.0/configuration-reference
version: 2.1
# Define a job to be invoked later in a workflow.
# See: https://circleci.com/docs/2.0/configuration-reference/#jobs
jobs:
api-tests:
docker:
- image: cimg/python:3.13
# `large` (4 vCPU, 8 GB) so pytest-xdist's `-nauto` has room to scale.
resource_class: large
steps:
- checkout
- run: sudo apt-get update
- run: sudo apt-get install -y ffmpeg catdoc
- restore_cache:
key: deps-3.13-{{ checksum "requirements.txt" }}-6
- run:
name: Install Requirements
command: |
# A restored venv points at the exact interpreter that built it. CircleCI's
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
# which broke every Python job. Rebuild when it cannot run: that costs a
# reinstall only on the first run after a bump.
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
- save_cache:
key: deps-3.13-{{ checksum "requirements.txt" }}-6
paths:
- "venv"
# `-nauto` parallelizes across all available cores via pytest-xdist.
# `-svv` was dumping the full test stdout to CircleCI logs on every run,
# which inflated wall time and produced multi-MB log artifacts; dropped.
- run:
command: './venv/bin/pytest -nauto --junitxml=test-results.xml'
- store_test_results:
path: test-results.xml
# Do the API and the frontend's test fixtures still agree?
#
# `api-tests` runs these too, as part of the whole suite. This job exists for the
# signal: fixture drift is silent by nature -- the frontend suite passes against a body the
# API stopped sending -- so it is worth a check whose name says what broke, failing in under a
# minute rather than somewhere inside seventeen hundred results.
#
# It needs no ffmpeg or catdoc (verified), and shares the dependency cache key with the other
# Python jobs, so it costs a venv restore and one test file.
api-contract-tests:
docker:
- image: cimg/python:3.13
resource_class: medium
steps:
- checkout
- restore_cache:
key: deps-3.13-{{ checksum "requirements.txt" }}-6
- run:
name: Install Requirements
command: |
# A restored venv points at the exact interpreter that built it. CircleCI's
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
# which broke every Python job. Rebuild when it cannot run: that costs a
# reinstall only on the first run after a bump.
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
- run:
name: Fixtures match the OpenAPI spec, and the spec matches the handlers
command: './venv/bin/pytest wrolpi/test/test_api_fixtures.py -v'
api-alembic-migrations:
docker:
- image: cimg/python:3.13
resource_class: medium
steps:
- checkout
- restore_cache:
key: deps-3.13-{{ checksum "requirements.txt" }}-6
- run:
name: Install Requirements
command: |
# A restored venv points at the exact interpreter that built it. CircleCI's
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
# which broke every Python job. Rebuild when it cannot run: that costs a
# reinstall only on the first run after a bump.
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
- run:
name: Create Media Directory
command: mkdir -p /tmp/wrolpi-media/config
- run:
name: Run Alembic Migrations
command: MEDIA_DIRECTORY=/tmp/wrolpi-media ./venv/bin/python ./main.py db upgrade
- run:
name: Check for Missing Migrations
command: MEDIA_DIRECTORY=/tmp/wrolpi-media ./venv/bin/python ./main.py db check
sanic-api-start:
docker:
- image: cimg/python:3.13
steps:
- checkout
- restore_cache:
key: deps-3.13-{{ checksum "requirements.txt" }}-6
- run:
name: Install dependencies
command: |
# A restored venv points at the exact interpreter that built it. CircleCI's
# cimg/python:3.13 gets patch bumps, and this cache key does not name the
# patch, so a venv cached before a bump has a dangling bin/python3 -- and
# `python3 -m venv` over it fails with `[Errno 2]` instead of repairing it,
# which broke every Python job. Rebuild when it cannot run: that costs a
# reinstall only on the first run after a bump.
if ! ./venv/bin/python3 --version >/dev/null 2>&1; then rm -rf venv; fi
python -m venv venv
. venv/bin/activate
pip install -r requirements.txt
sudo mkdir -p /media/wrolpi
- run:
name: Start Sanic API
command: |
. venv/bin/activate
sanic main:api_app -H 0.0.0.0 -p 8081
background: true
- run:
name: Test Sanic API
command: |
sleep 20
curl http://0.0.0.0:8081/api/echo
- run:
name: Stop Sanic API
command: pkill -f sanic
react-app-start:
docker:
- image: cimg/node:20.19
resource_class: large
steps:
- checkout
- restore_cache:
key: app-{{ checksum "app/package-lock.json" }}
- run: cd app && npm install
- save_cache:
key: app-{{ checksum "app/package-lock.json" }}
paths:
- ./app/node_modules
- run:
name: Build React App
command: cd app && DISABLE_ESLINT_PLUGIN=true npm run build
- run:
name: Start React App
command: cd app && DISABLE_ESLINT_PLUGIN=true npm run start
background: true
- run:
name: Test React App
command: |
sleep 20
curl http://0.0.0.0:3000/manifest.json
- run:
name: Stop React App
command: pkill -f npm
# Jest tests moved to GitHub Actions (.github/workflows/jest-tests.yml)
# Component specs live under `src/`, so they need `cypress run --component`; the e2e job's
# `cypress run` will not match them. Cypress starts its own dev server, so no `npm start`.
cypress-component-tests:
docker:
- image: cimg/node:20.19-browsers
resource_class: large
steps:
- checkout
- restore_cache:
key: app-browsers-{{ checksum "app/package-lock.json" }}
- run:
name: Install Dependencies
command: cd app && npm install
- run:
name: Install Cypress Binary
command: cd app && npx cypress install
- run:
name: Run Cypress Component Tests
command: cd app && CI=true npx cypress run --component
- store_artifacts:
path: app/cypress/screenshots
cypress-e2e-tests:
docker:
- image: cimg/node:20.19-browsers
resource_class: large
steps:
- checkout
- restore_cache:
key: app-browsers-{{ checksum "app/package-lock.json" }}
- run:
name: Install Dependencies
command: cd app && npm install
# The Cypress binary lives outside node_modules, so caching only
# node_modules lets the two drift apart: a restored cache satisfies npm,
# npm skips the postinstall download, and the binary for the new version
# is never fetched. Cache both, and install explicitly (a no-op when the
# binary is already present).
- run:
name: Install Cypress Binary
command: cd app && npx cypress install
- save_cache:
key: app-browsers-{{ checksum "app/package-lock.json" }}
paths:
- ./app/node_modules
- ~/.cache/Cypress
- run:
name: Start React App in Background
command: cd app && DISABLE_ESLINT_PLUGIN=true npm start
background: true
- run:
name: Wait for React App
command: |
for i in {1..60}; do
if curl -s http://localhost:3000 > /dev/null; then
echo "React app is ready!"
exit 0
fi
echo "Waiting for React app... ($i/60)"
sleep 2
done
echo "React app failed to start"
exit 1
- run:
name: Run Cypress Tests
command: cd app && CI=true npx cypress run
- store_artifacts:
path: app/cypress/videos
- store_artifacts:
path: app/cypress/screenshots
workflows:
wrolpi-api-tests:
jobs:
- sanic-api-start
- api-tests
- api-contract-tests
- api-alembic-migrations
wrolpi-app-test:
jobs:
- react-app-start
# jest-tests moved to GitHub Actions
- cypress-e2e-tests
- cypress-component-tests

View file

@ -7,6 +7,11 @@ updates:
interval: "monthly" interval: "monthly"
target-branch: "master" target-branch: "master"
open-pull-requests-limit: 5 open-pull-requests-limit: 5
ignore:
# SQLAlchemy 2.1 is a minor release with its own deprecations; upgrade it
# deliberately rather than by an automatic bump.
- dependency-name: "SQLAlchemy"
versions: [">=2.1"]
groups: groups:
python-dependencies: python-dependencies:
patterns: patterns:
@ -37,6 +42,42 @@ updates:
interval: "monthly" interval: "monthly"
target-branch: "master" target-branch: "master"
open-pull-requests-limit: 5 open-pull-requests-limit: 5
ignore:
# Major upgrades below need their own migration branch, not a bump PR.
# maplibre-gl 6: /map build depends on pinned babel/terser handling.
- dependency-name: "maplibre-gl"
versions: [">=6"]
# react-dropzone 15+ changed the accept API; 20 requires Node >=22.
- dependency-name: "react-dropzone"
versions: [">=15"]
# React 19: @react-three/fiber 8 pins react <19.
- dependency-name: "react"
update-types: ["version-update:semver-major"]
- dependency-name: "react-dom"
update-types: ["version-update:semver-major"]
- dependency-name: "@types/react"
update-types: ["version-update:semver-major"]
- dependency-name: "@types/react-dom"
update-types: ["version-update:semver-major"]
# TypeScript 6+/7 breaks the react-scripts toolchain.
- dependency-name: "typescript"
versions: [">=6"]
# Mantine 9: all @mantine packages move together with app code changes.
- dependency-name: "@mantine/*"
update-types: ["version-update:semver-major"]
# Cypress 16 requires Node >=22; CI and the app image run Node 20.
- dependency-name: "cypress"
versions: [">=16"]
# react-router 8 is a routing migration across ~40 files.
- dependency-name: "react-router"
update-types: ["version-update:semver-major"]
# @testing-library/react 14+ async act semantics break menu/popover tests.
- dependency-name: "@testing-library/react"
update-types: ["version-update:semver-major"]
# Cypress component testing resolves the top-level webpack-dev-server and only
# accepts major 5; 6 crashes cypress.config.js ("Unexpected major version").
- dependency-name: "webpack-dev-server"
versions: [">=6"]
groups: groups:
npm-dependencies: npm-dependencies:
patterns: patterns:

146
.github/workflows/backend.yml vendored Normal file
View file

@ -0,0 +1,146 @@
name: Backend Tests
# Same triggers as jest-tests.yml: `pull_request` is unfiltered so pull requests into feature
# branches are checked too, not only those into master.
on:
push:
branches: [master, feature/*]
pull_request:
# A new push to a pull request makes the run for the previous push worthless; cancel it so it
# does not hold runners (the free plan allows 20 concurrent jobs). Runs on master always finish.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# The suite is split by directory so it finishes in a few minutes, and so a check's name says
# which area broke. The groups are balanced by test time; `rest` runs everything the others do
# not, so a new directory is tested before anyone assigns it. A path added to any other group
# must also be added to `rest` as an --ignore, or its tests run twice.
api-tests:
name: api-tests (${{ matrix.name }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- name: core
paths: wrolpi/test
- name: media
paths: modules/videos modules/zim modules/docs modules/map modules/inventory modules/flasher tiles
- name: files
paths: wrolpi/files wrolpi/collections
- name: rest
paths: >-
--ignore=wrolpi/test
--ignore=modules/videos --ignore=modules/zim --ignore=modules/docs --ignore=modules/map
--ignore=modules/inventory --ignore=modules/flasher --ignore=tiles
--ignore=wrolpi/files --ignore=wrolpi/collections
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install system packages
# Mesa's EGL and GL drivers: the map tile service (tiles/) draws with them.
run: sudo apt-get update && sudo apt-get install -y ffmpeg catdoc libegl1 libegl-mesa0 libgl1-mesa-dri libgles2
- name: Setup Python
uses: actions/setup-python@v5
with:
# Trixie ships 3.13.
python-version: '3.13'
cache: 'pip'
cache-dependency-path: requirements.lock
- name: Install dependencies
run: scripts/install_python_requirements.sh pip requirements.txt
# `logical`, not `auto`: with psutil installed, `auto` counts physical cores, which is two on
# the four-vCPU runner. No `-v`: the full test output inflates wall time and logs.
- name: Run pytest
env:
PATHS: ${{ matrix.paths }}
run: pytest -n logical $PATHS --junitxml=test-results.xml
- name: Upload test results
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v4
with:
name: api-test-results-${{ matrix.name }}
path: test-results.xml
retention-days: 30
# Do the API and the frontend's test fixtures still agree?
#
# `api-tests` runs these too, as part of the whole suite. This job exists for the signal:
# fixture drift is silent by nature -- the frontend suite passes against a body the API stopped
# sending -- so it is worth a check whose name says what broke, failing in under a minute rather
# than somewhere inside seventeen hundred results. It needs no ffmpeg or catdoc.
api-contract-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
cache: 'pip'
cache-dependency-path: requirements.lock
- name: Install dependencies
run: scripts/install_python_requirements.sh pip requirements.txt
- name: Fixtures match the OpenAPI spec, and the spec matches the handlers
run: pytest wrolpi/test/test_api_fixtures.py -v
# The migrations apply to an empty database, the models match them, and the API starts.
api-migrations-and-start:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
cache: 'pip'
cache-dependency-path: requirements.lock
- name: Install dependencies
run: scripts/install_python_requirements.sh pip requirements.txt
- name: Run Alembic migrations
env:
MEDIA_DIRECTORY: ${{ runner.temp }}/wrolpi-media
run: |
mkdir -p "$MEDIA_DIRECTORY/config"
python ./main.py db upgrade
- name: Check for missing migrations
env:
MEDIA_DIRECTORY: ${{ runner.temp }}/wrolpi-media
run: python ./main.py db check
- name: Start Sanic API
run: |
sudo mkdir -p /media/wrolpi
nohup sanic main:api_app -H 0.0.0.0 -p 8081 > sanic.log 2>&1 &
for i in $(seq 1 60); do
if curl -sf http://localhost:8081/api/echo; then
echo
echo "Sanic API is up"
exit 0
fi
sleep 2
done
echo "Sanic API failed to start"
cat sanic.log
exit 1
- name: Stop Sanic API
if: ${{ always() }}
run: pkill -f sanic || true

View file

@ -27,10 +27,10 @@ jobs:
# Trixie ships 3.13, and docker/controller/Dockerfile is python:3.13-slim-trixie. # Trixie ships 3.13, and docker/controller/Dockerfile is python:3.13-slim-trixie.
python-version: '3.13' python-version: '3.13'
cache: 'pip' cache: 'pip'
cache-dependency-path: controller/requirements.txt cache-dependency-path: controller/requirements.lock
- name: Install dependencies - name: Install dependencies
run: pip install -r requirements.txt run: ../scripts/install_python_requirements.sh pip requirements.txt
- name: Run pytest - name: Run pytest
run: python -m pytest test/ -v --tb=short --confcutdir=$(pwd) run: python -m pytest test/ -v --tb=short --confcutdir=$(pwd)

121
.github/workflows/cypress.yml vendored Normal file
View file

@ -0,0 +1,121 @@
name: Cypress Tests
on:
push:
branches: [master, feature/*]
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Component specs live under `src/`, so they need `cypress run --component`; the e2e job's
# `cypress run` will not match them. Cypress starts its own dev server, so no `npm start`.
cypress-component-tests:
runs-on: ubuntu-latest
defaults:
run:
working-directory: app
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.19'
cache: 'npm'
cache-dependency-path: app/package-lock.json
# The Cypress binary lives outside node_modules, and setup-node only caches ~/.npm. Key it
# on the lockfile so a Cypress bump fetches the matching binary.
- name: Cache Cypress binary
uses: actions/cache@v4
with:
path: ~/.cache/Cypress
key: cypress-${{ runner.os }}-${{ hashFiles('app/package-lock.json') }}
- name: Install dependencies
run: npm install
# A no-op when the cached binary matches.
- name: Install Cypress binary
run: npx cypress install
- name: Run Cypress component tests
run: npx cypress run --component
- name: Upload screenshots
if: ${{ failure() }}
uses: actions/upload-artifact@v4
with:
name: cypress-component-screenshots
path: app/cypress/screenshots
retention-days: 14
# Waiting for `npm start` to serve the app also checks that the dev server starts.
cypress-e2e-tests:
runs-on: ubuntu-latest
defaults:
run:
working-directory: app
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.19'
cache: 'npm'
cache-dependency-path: app/package-lock.json
- name: Cache Cypress binary
uses: actions/cache@v4
with:
path: ~/.cache/Cypress
key: cypress-${{ runner.os }}-${{ hashFiles('app/package-lock.json') }}
- name: Install dependencies
run: npm install
- name: Install Cypress binary
run: npx cypress install
# GitHub Actions sets `CI=true`, which makes cypress.config.js use http://localhost:3000 as
# the base URL.
- name: Start React app
env:
DISABLE_ESLINT_PLUGIN: 'true'
BROWSER: none
run: |
nohup npm start > react.log 2>&1 &
for i in $(seq 1 90); do
if curl -sf http://localhost:3000/manifest.json > /dev/null; then
echo "React app is ready"
exit 0
fi
sleep 2
done
echo "React app failed to start"
cat react.log
exit 1
- name: Run Cypress e2e tests
run: npx cypress run
- name: Upload videos and screenshots
if: ${{ failure() }}
uses: actions/upload-artifact@v4
with:
name: cypress-e2e-media
path: |
app/cypress/videos
app/cypress/screenshots
retention-days: 14
if-no-files-found: ignore

34
.github/workflows/dead-code.yml vendored Normal file
View file

@ -0,0 +1,34 @@
name: Dead Code
# Same triggers as backend.yml: `pull_request` is unfiltered so pull requests into feature branches
# are checked too, not only those into master.
on:
push:
branches: [master, feature/*]
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Fails when vulture finds dead code that is not in scripts/vulture_baseline.txt. vulture only
# parses the source, so WROLPi's requirements are not installed.
vulture:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
# Trixie ships 3.13.
python-version: '3.13'
# Pinned: a new vulture release can report findings the baseline does not know about.
- name: Install vulture
run: pip install vulture==2.16
- name: Check for new dead code
run: python scripts/check_dead_code.py

4
.gitignore vendored
View file

@ -118,6 +118,7 @@ test/config
modules/node_modules/ modules/node_modules/
docker/archive/node_modules/ docker/archive/node_modules/
npm-tools/node_modules/
docker/archive/package-lock.json docker/archive/package-lock.json
# open street map files # open street map files
@ -150,3 +151,6 @@ app/cypress/videos
release/latest.json release/latest.json
perf_results/ perf_results/
scripts/api_perf_hosts.json scripts/api_perf_hosts.json
# Tile cache for scripts/build_solar_climatology.py
/scripts/.solar_climatology_cache/

View file

@ -3,8 +3,10 @@
There are several ways to run WROLPi. Pick the one that matches your hardware: There are several ways to run WROLPi. Pick the one that matches your hardware:
* [WROLPi Portable (Live USB)](#wrolpi-portable-live-usb) — boot a full WROLPi from a USB stick on any x86 PC or laptop, no installation required. * [WROLPi Portable (Live USB)](#wrolpi-portable-live-usb) — boot a full WROLPi from a USB stick on any x86 PC or laptop, no installation required.
* [Debian 12 Install](#debian-12-install) — install WROLPi onto an x86 PC or laptop. * [Debian 13 Install](#debian-13-install) — install WROLPi onto an x86 PC or laptop.
* [Raspberry Pi Install](#raspberry-pi-install) — install WROLPi onto a Raspberry Pi with an external drive. * [Raspberry Pi Install](#raspberry-pi-install) — install WROLPi onto a Raspberry Pi with an external drive.
After installing, follow [First Boot](#first-boot) to set up your drive.
* [Docker](docker/README.md) — run the WROLPi containers on an existing Linux host (best for trying it out or development). * [Docker](docker/README.md) — run the WROLPi containers on an existing Linux host (best for trying it out or development).
See [UPGRADE.md](UPGRADE.md) for upgrading an existing WROLPi. See [UPGRADE.md](UPGRADE.md) for upgrading an existing WROLPi.
@ -36,6 +38,7 @@ Steps:
minute or two; progress is shown on screen. minute or two; progress is shown on screen.
5. Once the desktop loads, browse to https://wrolpi.local or the IP address of 5. Once the desktop loads, browse to https://wrolpi.local or the IP address of
your WROLPi. Wi-Fi hotspot and all other features work as usual. your WROLPi. Wi-Fi hotspot and all other features work as usual.
6. To use a terminal remotely: `ssh user@wrolpi.local`, password `live`.
Notes: Notes:
@ -52,30 +55,50 @@ Notes:
* **Upgrading.** See [Upgrading a WROLPi Portable USB](UPGRADE.md#upgrading-a-wrolpi-portable-usb) * **Upgrading.** See [Upgrading a WROLPi Portable USB](UPGRADE.md#upgrading-a-wrolpi-portable-usb)
to move to a newer ISO without losing your library. to move to a newer ISO without losing your library.
## Debian 12 Install ## Debian 13 Install
Steps necessary to initialize your WROLPi after installing the Debian image from wrolpi.org Install WROLPi onto the internal disk of an x86 PC or laptop. This uses the same
`WROLPi-v*-amd64.iso` as WROLPi Portable.
1. Download and copy a pre-built Debian image from https://wrolpi.org onto a USB thumb-drive (USB 2 recommended). 1. Download the latest `WROLPi-v*-amd64.iso` from [wrolpi.org](https://wrolpi.org) and flash it to a USB drive
2. Insert the thumb-drive into the laptop, boot to the thumb-drive. (see [WROLPi Portable](#wrolpi-portable-live-usb) step 2).
1. Select "Start Installer". 2. Boot the PC from the USB drive. At the boot menu, choose **Install** or **Graphical Install**.
2. Install Debian 12 as you would like. 3. Install Debian 13 as you would like.
1. It is recommended to use the hostname **wrolpi**. 1. It is recommended to use the hostname **wrolpi**.
2. (WROLPi will be installed during the installation without your intervention.) 2. WROLPi is installed along with Debian; there is nothing extra to select.
3. Unplug the thumb-drive after the installation has completed. 4. Unplug the USB drive after the installation has completed, and reboot.
4. Login as the user _you_ created during installation. 5. Continue with [First Boot](#first-boot).
5. Initialize the WROLPi databases using the repair script: `/opt/wrolpi/repair.sh`
6. Reboot: `reboot`
7. Browse to https://wrolpi.local or the IP address of your WROLPi!
## Raspberry Pi Install ## Raspberry Pi Install
Steps necessary to initialize your WROLPi after installing the Raspberry Pi image from wrolpi.org Install WROLPi onto a Raspberry Pi. An external drive is recommended for your library.
1. Download and copy a pre-built image from https://wrolpi.org onto an SD card. 1. Download the latest `WROLPi-v*-aarch64-desktop.img.xz` from [wrolpi.org](https://wrolpi.org).
2. Boot the Raspberry Pi, login with username pi and password wrolpi. 2. Flash it to an SD card using Raspberry Pi Imager.
3. Modify fstab to mount your external drive to /media/wrolpi (modify this command to match your system). 3. Plug in your external drive, insert the SD card, and boot the Raspberry Pi.
* `echo '/dev/sda1 /media/wrolpi auto defaults,nofail 0 0' | sudo tee -a /etc/fstab` 4. On the first boot, Raspberry Pi OS asks you to create your own user.
4. Initialize the WROLPi databases using the repair script: `sudo /opt/wrolpi/repair.sh` 5. Continue with [First Boot](#first-boot).
5. Reboot `sudo reboot`
6. Join the Hotspot or browse to https://wrolpi.local or the IP address of your WROLPi! ## First Boot
These steps are the same for every install.
1. Join the WROLPi hotspot (network **WROLPi**, password **wrolpi hotspot**; it starts on every boot), or connect
your WROLPi to your network, then browse to https://wrolpi.local (or the IP address of your WROLPi).
2. **Choose your drive.**
* **Raspberry Pi and Debian:** until a drive is set up, you will see the **Controller** with a *Welcome to WROLPi*
wizard (also at http://wrolpi.local). Select the drive which will hold your library; WROLPi mounts it
at `/media/wrolpi`, adds it to `/etc/fstab`, and runs the repair script for you. If the drive already holds a
WROLPi library (from another WROLPi, or a backup), its configuration is used. No external drive? Choose **Run
repair without external drive** to keep your library on the internal disk or SD card.
* **WROLPi Portable:** nothing to do; your library lives in the persistence partition on the USB drive.
3. **Trust the certificate.** Your browser will warn about the HTTPS certificate because it was made by your WROLPi,
not by a public authority. Download https://wrolpi.local/ca.crt and trust it on each device you use; see
*Help > Certificates* on your WROLPi for per-device instructions.
4. **Wait for the first refresh.** WROLPi refreshes all your files when it first starts so it can find anything already
on the drive. Your library looks empty, and Download and Upload are disabled, until the refresh completes.
5. Start adding content: download a video channel, archive a web page, or add a Zim (Wikipedia) file. The *Help* page
on your WROLPi explains each module.
You do not need to edit `/etc/fstab` or run `repair.sh` by hand. `sudo /opt/wrolpi/repair.sh` is still available if
your WROLPi ever needs repairing.

View file

@ -1,6 +1,6 @@
# WROLPi # WROLPi
[![Build Status](https://img.shields.io/circleci/build/github/lrnselfreliance/wrolpi/release?label=release%20build)](https://app.circleci.com/pipelines/github/lrnselfreliance/wrolpi?branch=release&filter=all) [![Backend Tests](https://github.com/lrnselfreliance/wrolpi/actions/workflows/backend.yml/badge.svg?branch=master)](https://github.com/lrnselfreliance/wrolpi/actions/workflows/backend.yml?query=branch%3Amaster)
[![License: GPL v3](https://img.shields.io/github/license/lrnselfreliance/wrolpi?style=flat-square)](https://github.com/lrnselfreliance/wrolpi/blob/master/LICENSE) [![License: GPL v3](https://img.shields.io/github/license/lrnselfreliance/wrolpi?style=flat-square)](https://github.com/lrnselfreliance/wrolpi/blob/master/LICENSE)
[![Discord](https://img.shields.io/discord/900430987987681330?label=Discord&logo=discord)](https://discord.gg/HrwFk7nqA2) [![Discord](https://img.shields.io/discord/900430987987681330?label=Discord&logo=discord)](https://discord.gg/HrwFk7nqA2)
[![Gitpod](https://img.shields.io/badge/Contribute%20with-Gitpod-908a85?logo=gitpod)](https://gitpod.io/#https://github.com/lrnselfreliance/wrolpi) [![Gitpod](https://img.shields.io/badge/Contribute%20with-Gitpod-908a85?logo=gitpod)](https://gitpod.io/#https://github.com/lrnselfreliance/wrolpi)
@ -40,8 +40,8 @@ network so that any user with a laptop/tablet/phone can connect and use the libr
- [x] Universal search - [x] Universal search
- [x] Food Inventory management - [x] Food Inventory management
- [x] One-Time pad generator, encrypter/decrypter - [x] One-Time pad generator, encrypter/decrypter
- [ ] Synchronizer/duplicator - [x] Sync to a second WROLPi, and backup to a second drive
- [ ] Food storage calculator - [x] Food storage calculator
## Module features matrix ## Module features matrix
@ -93,7 +93,7 @@ More Docker documentation is available in [docker/README.md](docker/README.md)
Full installation instructions are in [INSTALL.md](INSTALL.md). Pick the option that matches your hardware: Full installation instructions are in [INSTALL.md](INSTALL.md). Pick the option that matches your hardware:
* **[WROLPi Portable (Live USB)](INSTALL.md#wrolpi-portable-live-usb)** — boot a complete WROLPi from a USB stick on any x86 PC or laptop. Nothing is installed to the computer; the first boot creates a persistence partition on the USB so your library, database, and configuration survive reboots. * **[WROLPi Portable (Live USB)](INSTALL.md#wrolpi-portable-live-usb)** — boot a complete WROLPi from a USB stick on any x86 PC or laptop. Nothing is installed to the computer; the first boot creates a persistence partition on the USB so your library, database, and configuration survive reboots.
* **[Debian 12](INSTALL.md#debian-12-install)** — install WROLPi onto an x86 PC or laptop. * **[Debian 13](INSTALL.md#debian-13-install)** — install WROLPi onto an x86 PC or laptop.
* **[Raspberry Pi](INSTALL.md#raspberry-pi-install)** — install WROLPi onto a Raspberry Pi with an external drive. * **[Raspberry Pi](INSTALL.md#raspberry-pi-install)** — install WROLPi onto a Raspberry Pi with an external drive.
* **[Docker](docker/README.md)** — run the WROLPi containers on an existing Linux host. * **[Docker](docker/README.md)** — run the WROLPi containers on an existing Linux host.

View file

@ -3,7 +3,7 @@
# Table of Contents # Table of Contents
* [Upgrading Docker containers](#upgrading-docker-containers) * [Upgrading Docker containers](#upgrading-docker-containers)
* [Upgrading Raspberry Pi or Debian 12 Installation](#upgrading-raspberry-pi-or-debian-12-installation) * [Upgrading Raspberry Pi or Debian Installation](#upgrading-raspberry-pi-or-debian-installation)
* [Upgrading a WROLPi Portable USB](#upgrading-a-wrolpi-portable-usb) * [Upgrading a WROLPi Portable USB](#upgrading-a-wrolpi-portable-usb)
## Upgrading Docker containers ## Upgrading Docker containers
@ -14,6 +14,8 @@
* `git pull origin master --ff` * `git pull origin master --ff`
3. Build all docker containers 3. Build all docker containers
* `docker-compose build --parallel` * `docker-compose build --parallel`
* Rebuild the VPN container without its cache, so it gets the latest qBittorrent (it faces the Internet
through the VPN): `docker compose build --pull --no-cache vpn`
4. Create the map volumes 4. Create the map volumes
* `docker volume create --name=openstreetmap-data` * `docker volume create --name=openstreetmap-data`
* `docker volume create --name=openstreetmap-rendered-tiles` * `docker volume create --name=openstreetmap-rendered-tiles`
@ -24,11 +26,15 @@
7. Start all docker containers 7. Start all docker containers
* `docker-compose up -d` * `docker-compose up -d`
## Upgrading Raspberry Pi or Debian 12 Installation ## Upgrading Raspberry Pi or Debian Installation
A Debian 12 (bookworm) WROLPi stays on the final version for Debian 12; reinstall on Debian 13 to get newer versions.
1. Run the upgrade script 1. Run the upgrade script
* `sudo /bin/bash /opt/wrolpi/upgrade.sh` * `sudo /bin/bash /opt/wrolpi/upgrade.sh`
* (If the upgrade script does not exist, run the installation script: `sudo /bin/bash /opt/wrolpi/install.sh`) * (If the upgrade script does not exist, run the installation script: `sudo /bin/bash /opt/wrolpi/install.sh`)
* The upgrade refuses to move back to an older commit of the branch you are on. To downgrade on purpose,
run `sudo /bin/bash /opt/wrolpi/upgrade.sh -d`.
## Upgrading a WROLPi Portable USB ## Upgrading a WROLPi Portable USB

View file

@ -6,8 +6,9 @@ from alembic import context
# access to the values within the .ini file in use. # access to the values within the .ini file in use.
config = context.config config = context.config
# Interpret the config file for Python logging. # Configure logging only for the alembic command line. WROLPi also migrates in-process at startup
# This line sets up loggers basically. # (db_bootstrap), where fileConfig would replace the API's handlers and disable its existing loggers.
if config.cmd_opts is not None:
fileConfig(config.config_file_name) fileConfig(config.config_file_name)
# add your model's MetaData object here # add your model's MetaData object here
@ -23,6 +24,7 @@ from wrolpi.collections.models import Collection, CollectionItem # noqa: F401
from modules.videos.models import Video, Channel # noqa: F401 from modules.videos.models import Video, Channel # noqa: F401
from modules.archive.models import Archive # noqa: F401 from modules.archive.models import Archive # noqa: F401
from modules.zim.models import Zim, TagZimEntry, ZimSubscription # noqa: F401 from modules.zim.models import Zim, TagZimEntry, ZimSubscription # noqa: F401
from modules.repos.models import Repository # noqa: F401
target_metadata = Base.metadata target_metadata = Base.metadata
@ -96,7 +98,10 @@ def run_migrations_online():
connectable = create_wrolpi_engine(get_url()) connectable = create_wrolpi_engine(get_url())
with connectable.connect() as connection: # Autocommit: each migration statement is its own transaction. A migration may call WROLPi
# functions which write on their own connection; a migration connection holding an open read
# transaction could not then upgrade to a writer ("database is locked").
with connectable.connect().execution_options(isolation_level='AUTOCOMMIT') as connection:
context.configure( context.configure(
connection=connection, connection=connection,
target_metadata=target_metadata, target_metadata=target_metadata,

View file

@ -0,0 +1,45 @@
"""Maintain collection.item_count/total_size for Domain Collections with triggers.
Listing Domain Collections summed file_group.size through an archive join on every request,
one random page read per archive. The new triggers keep the summary columns current
(as the channel triggers already do for Channels); this migration installs them and
backfills existing Domain Collections.
Revision ID: 2026_09_27_1200
Revises: 2026_09_20_1200
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_09_27_1200'
down_revision = '2026_09_20_1200'
branch_labels = None
depends_on = None
TRIGGERS = (
'archive_insert_collection_summary',
'archive_delete_collection_summary',
'archive_update_collection_summary',
'file_group_size_collection_summary',
)
def upgrade():
from wrolpi.schema_ddl import install_raw_ddl
# Idempotent: only the new triggers are created.
install_raw_ddl(op.get_bind())
op.execute('''
UPDATE collection SET
item_count = (SELECT COUNT(*) FROM archive WHERE collection_id = collection.id),
total_size = (SELECT COALESCE(SUM(fg.size), 0) FROM archive a
LEFT JOIN file_group fg ON a.file_group_id = fg.id
WHERE a.collection_id = collection.id)
WHERE kind = 'domain'
''')
def downgrade():
for name in TRIGGERS:
op.execute(f'DROP TRIGGER IF EXISTS {name}')

View file

@ -0,0 +1,29 @@
"""Covering indexes for the Collection listing.
Listing Collections read every channel row (for video_count/total_size) and every download
row of those Collections (for the minimum frequency). Both tables store yt-dlp info_json,
so their rows are tens of KB and each sits on its own scattered page; from a cold disk cache
that was 10+ seconds. These indexes answer both queries without touching a row.
Revision ID: 2026_09_28_1200
Revises: 2026_09_27_1200
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_09_28_1200'
down_revision = '2026_09_27_1200'
branch_labels = None
depends_on = None
def upgrade():
op.execute('CREATE INDEX IF NOT EXISTS channel_collection_summary_idx'
' ON channel (collection_id, video_count, total_size)')
op.execute('CREATE INDEX IF NOT EXISTS download_collection_frequency_idx'
' ON download (collection_id, frequency)')
def downgrade():
op.execute('DROP INDEX IF EXISTS channel_collection_summary_idx')
op.execute('DROP INDEX IF EXISTS download_collection_frequency_idx')

View file

@ -0,0 +1,31 @@
"""Retag existing markdown file groups as text/markdown.
A refresh skips a group whose files have not changed, so markdown indexed before text/markdown
existed would keep the type libmagic gave it (text/plain, or a programming language when the file
holds code) and the indexer that type chose. Marking the rows unindexed lets apply_indexers
re-index them with TextIndexer. SQLite's LIKE is case-insensitive for ASCII, so `.MD` matches.
Revision ID: 2026_10_05_1200
Revises: 2026_09_28_1200
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_05_1200'
down_revision = '2026_09_28_1200'
branch_labels = None
depends_on = None
def upgrade():
op.execute("""
UPDATE file_group SET mimetype = 'text/markdown', "indexed" = 0
WHERE (primary_path LIKE '%.md' OR primary_path LIKE '%.markdown')
AND mimetype LIKE 'text/%'
AND mimetype != 'text/markdown'
""")
def downgrade():
# The original types are not recorded; text/plain is what libmagic reports for most markdown.
op.execute("""UPDATE file_group SET mimetype = 'text/plain', "indexed" = 0 WHERE mimetype = 'text/markdown'""")

View file

@ -0,0 +1,43 @@
"""Add the repository table for git Repos (Collections with kind='repo').
Revision ID: 2026_10_06_1200
Revises: 2026_10_05_1200
"""
import sqlalchemy as sa
from alembic import op
import wrolpi.dates
# revision identifiers, used by Alembic.
revision = '2026_10_06_1200'
down_revision = '2026_10_05_1200'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'repository',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('url', sa.String(), nullable=False),
sa.Column('host', sa.String(), nullable=True),
sa.Column('owner', sa.String(), nullable=True),
sa.Column('mode', sa.String(), nullable=False),
sa.Column('branch', sa.String(), nullable=True),
sa.Column('default_branch', sa.String(), nullable=True),
sa.Column('head_sha', sa.String(), nullable=True),
sa.Column('head_date', wrolpi.dates.TZDateTime(), nullable=True),
sa.Column('head_message', sa.Text(), nullable=True),
sa.Column('last_fetch', wrolpi.dates.TZDateTime(), nullable=True),
sa.Column('size', sa.BigInteger(), nullable=True),
sa.Column('readme_path', sa.String(), nullable=True),
sa.Column('collection_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('collection_id'),
sa.UniqueConstraint('url'),
)
def downgrade():
op.drop_table('repository')

View file

@ -0,0 +1,39 @@
"""Search git Repos by name and README: repository.search_name/readme_text and repository_fts.
Revision ID: 2026_10_06_1300
Revises: 2026_10_06_1200
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_06_1300'
down_revision = '2026_10_06_1200'
branch_labels = None
depends_on = None
def upgrade():
from wrolpi.schema_ddl import install_raw_ddl
op.add_column('repository', sa.Column('search_name', sa.String(), nullable=True))
op.add_column('repository', sa.Column('readme_text', sa.Text(), nullable=True))
op.execute('''
UPDATE repository SET search_name = TRIM(
COALESCE((SELECT name FROM collection WHERE collection.id = repository.collection_id), '')
|| ' ' || COALESCE(owner, ''))
''')
# Creates repository_fts and its triggers now that the columns exist. The README text is filled by the next
# update of each Repo.
install_raw_ddl(op.get_bind())
op.execute("INSERT INTO repository_fts(repository_fts) VALUES('rebuild')")
def downgrade():
for name in ('repository_fts_ai', 'repository_fts_ad', 'repository_fts_au'):
op.execute(f'DROP TRIGGER IF EXISTS {name}')
op.execute('DROP TABLE IF EXISTS repository_fts')
with op.batch_alter_table('repository') as batch_op:
batch_op.drop_column('readme_text')
batch_op.drop_column('search_name')

View file

@ -0,0 +1,22 @@
"""A git Repo can also download its submodules: repository.submodules.
Revision ID: 2026_10_06_1400
Revises: 2026_10_06_1300
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_06_1400'
down_revision = '2026_10_06_1300'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('repository', sa.Column('submodules', sa.Boolean(), server_default=sa.false(), nullable=False))
def downgrade():
with op.batch_alter_table('repository') as batch_op:
batch_op.drop_column('submodules')

View file

@ -0,0 +1,22 @@
"""A git Repo's clone holds a random token: repository.clone_token.
Revision ID: 2026_10_06_1500
Revises: 2026_10_06_1400
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_06_1500'
down_revision = '2026_10_06_1400'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('repository', sa.Column('clone_token', sa.String(), nullable=True))
def downgrade():
with op.batch_alter_table('repository') as batch_op:
batch_op.drop_column('clone_token')

View file

@ -0,0 +1,24 @@
"""A FileGroup records how far the user is through it: file_group.progress and file_group.position.
Revision ID: 2026_10_08_1200
Revises: 2026_10_06_1500
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_08_1200'
down_revision = '2026_10_06_1500'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('file_group', sa.Column('progress', sa.Float(), nullable=True))
op.add_column('file_group', sa.Column('position', sa.JSON(), nullable=True))
def downgrade():
# Not batch_alter_table: rebuilding file_group drops its FTS triggers (see 2026_09_20_1200).
op.execute('ALTER TABLE file_group DROP COLUMN position')
op.execute('ALTER TABLE file_group DROP COLUMN progress')

View file

@ -0,0 +1,27 @@
"""Each database config's version, so an import can tell whether the database or the file is newer
(see wrolpi.config_version).
Revision ID: 2026_10_24_1200
Revises: 2026_10_08_1200
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_24_1200'
down_revision = '2026_10_08_1200'
branch_labels = None
depends_on = None
def upgrade():
# No rows: a config's next import (without deletes) records its version.
op.create_table(
'config_version',
sa.Column('name', sa.String(), primary_key=True),
sa.Column('version', sa.Integer(), nullable=False),
)
def downgrade():
op.drop_table('config_version')

View file

@ -0,0 +1,175 @@
"""Tag names have no leading or trailing whitespace.
A Tag whose name had whitespace is renamed. Tags whose names are the same once stripped are merged into one: it
keeps every tagged file, Zim entry and Collection, and the first color (by Tag id) of the merged Tags. Downloads
and the config files that name Tags are rewritten the same way, so the next import finds them in step with the
database (an import of the old names would create the padded Tags again, or delete the stripped ones).
Revision ID: 2026_10_25_1200
Revises: 2026_10_24_1200
"""
import json
import logging
import yaml
from alembic import op
from wrolpi.common import get_media_directory, write_config_data
# revision identifiers, used by Alembic.
revision = '2026_10_25_1200'
down_revision = '2026_10_24_1200'
branch_labels = None
depends_on = None
logger = logging.getLogger(__name__)
# The configs which name Tags.
CONFIG_FILES = ('tags.yaml', 'download_manager.yaml', 'channels.yaml', 'domains.yaml', 'playlists.yaml',
'repos.yaml', 'videos_downloader.yaml', 'archives_downloader.yaml')
def _strip(name):
"""A Tag name without its whitespace; a name that would be empty is kept (it cannot be renamed)."""
if isinstance(name, str) and name.strip():
return name.strip()
return name
def _strip_names(names: list) -> list:
stripped = list()
for name in map(_strip, names):
if name not in stripped:
stripped.append(name)
return stripped
def _strip_nested(data):
"""Strip the Tag names in a config's (or a Download's settings') `tag_name`, `tag_names` and
`channel_tag_name` values, at any depth."""
if isinstance(data, list):
return [_strip_nested(i) for i in data]
if not isinstance(data, dict):
return data
result = dict()
for key, value in data.items():
if key == 'tag_name':
value = _strip(value)
elif key in ('tag_names', 'channel_tag_name') and isinstance(value, list):
value = _strip_names(value)
else:
value = _strip_nested(value)
result[key] = value
return result
def _strip_rows(rows: list, key_length: int) -> list:
"""tags.yaml's tag_files or tag_zims, each row keyed by its first `key_length` values (the Tag name first)."""
result, seen = list(), set()
for row in rows:
if isinstance(row, list) and row:
row = [_strip(row[0]), *row[1:]]
key = json.dumps(row[:key_length], default=str)
if key in seen:
continue
seen.add(key)
result.append(row)
return result
def _strip_tags_config(config: dict, colors: dict) -> dict:
"""`colors`: each renamed Tag's color in the database, which the file must match (an import copies the file's
color into the database)."""
config = dict(config)
if isinstance(config.get('tags'), dict):
tags = dict()
for name, attrs in config['tags'].items():
stripped = _strip(name)
if stripped not in tags:
tags[stripped] = attrs
elif isinstance(attrs, dict) and attrs.get('color') and not (tags[stripped] or dict()).get('color'):
# The first color of the merged Tags.
tags[stripped] = {**(tags[stripped] or dict()), 'color': attrs['color']}
for name in tags.keys() & colors.keys():
tags[name] = {**(tags[name] or dict()), 'color': colors[name]}
config['tags'] = tags
if isinstance(config.get('tag_files'), list):
config['tag_files'] = _strip_rows(config['tag_files'], 2)
if isinstance(config.get('tag_zims'), list):
config['tag_zims'] = _strip_rows(config['tag_zims'], 3)
return config
def strip_tag_names_in_configs(colors: dict):
config_directory = get_media_directory() / 'config'
for file_name in CONFIG_FILES:
file = config_directory / file_name
if not file.is_file():
continue
try:
with file.open('rt') as fh:
config = yaml.load(fh, Loader=yaml.CSafeLoader)
except Exception as e:
logger.error(f'Cannot strip Tag names of invalid config: {file}', exc_info=e)
continue
if not isinstance(config, dict):
continue
stripped = _strip_tags_config(config, colors) if file_name == 'tags.yaml' else config
stripped = _strip_nested(stripped)
if stripped != config:
logger.warning(f'Stripping whitespace from Tag names in {file}')
write_config_data(stripped, file, width=500 if file_name == 'tags.yaml' else 90)
def strip_tag_names_in_db(connection) -> dict:
"""Returns the color of each renamed Tag, by its new name."""
groups, colors = dict(), dict()
for id_, name, color in connection.exec_driver_sql('SELECT id, name, color FROM tag ORDER BY id').fetchall():
groups.setdefault(_strip(name), list()).append((id_, name, color))
for stripped, tags in groups.items():
if all(name == stripped for _, name, _ in tags):
continue
# Keep the Tag already named this, if any, otherwise the oldest.
survivor_id = next((id_ for id_, name, _ in tags if name == stripped), tags[0][0])
color = colors[stripped] = next((color for _, _, color in tags if color), None)
for id_, name, _ in tags:
if id_ == survivor_id:
continue
logger.warning(f'Merging Tag {name!r} into {stripped!r}')
connection.exec_driver_sql(
'INSERT OR IGNORE INTO tag_file (tag_id, file_group_id, created_at)'
' SELECT ?, file_group_id, created_at FROM tag_file WHERE tag_id = ?', (survivor_id, id_))
connection.exec_driver_sql(
'INSERT OR IGNORE INTO tag_zim (tag_id, zim_id, zim_entry, created_at)'
' SELECT ?, zim_id, zim_entry, created_at FROM tag_zim WHERE tag_id = ?', (survivor_id, id_))
connection.exec_driver_sql('DELETE FROM tag_file WHERE tag_id = ?', (id_,))
connection.exec_driver_sql('DELETE FROM tag_zim WHERE tag_id = ?', (id_,))
connection.exec_driver_sql('UPDATE collection SET tag_id = ? WHERE tag_id = ?', (survivor_id, id_))
connection.exec_driver_sql('DELETE FROM tag WHERE id = ?', (id_,))
logger.warning(f'Renaming Tag to {stripped!r}')
connection.exec_driver_sql('UPDATE tag SET name = ?, color = ? WHERE id = ?', (stripped, color, survivor_id))
# The Downloads which apply them (download_manager.yaml is stripped the same way).
downloads = connection.exec_driver_sql(
'SELECT id, tag_names, settings FROM download WHERE tag_names IS NOT NULL OR settings IS NOT NULL').fetchall()
for id_, tag_names, settings in downloads:
tag_names, settings = json.loads(tag_names) if tag_names else None, json.loads(settings) if settings else None
new_tag_names = _strip_names(tag_names) if isinstance(tag_names, list) else tag_names
new_settings = _strip_nested(settings)
if new_tag_names != tag_names or new_settings != settings:
connection.exec_driver_sql(
'UPDATE download SET tag_names = ?, settings = ? WHERE id = ?',
(json.dumps(new_tag_names) if new_tag_names is not None else None,
json.dumps(new_settings) if new_settings is not None else None, id_))
return colors
def upgrade():
colors = strip_tag_names_in_db(op.get_bind())
strip_tag_names_in_configs(colors)
def downgrade():
# Whitespace that was stripped is not restored.
pass

View file

@ -0,0 +1,24 @@
"""A partial index of the unindexed FileGroups.
The modelers and indexers look up `file_group WHERE indexed != 1` (and count it for progress) on every
refresh. SQLite cannot use an index on `indexed` for `!=`, so each lookup read every file_group row; on a
large library from a cold disk cache that was close to a minute. This index holds only the unindexed rows.
Revision ID: 2026_10_30_1200
Revises: 2026_10_25_1200
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '2026_10_30_1200'
down_revision = '2026_10_25_1200'
branch_labels = None
depends_on = None
def upgrade():
op.execute('CREATE INDEX IF NOT EXISTS file_group_unindexed_idx ON file_group (id) WHERE "indexed" != 1')
def downgrade():
op.execute('DROP INDEX IF EXISTS file_group_unindexed_idx')

View file

@ -22,9 +22,14 @@ function sandboxPath(relativePath) {
return resolved; return resolved;
} }
function fileContent(content) {
return content && content.base64 !== undefined ? Buffer.from(content.base64, "base64") : (content ?? "");
}
const fileBrowserTasks = { const fileBrowserTasks = {
// Wipe the sandbox (including leftovers from a crashed run) and create the given files. // Wipe the sandbox (including leftovers from a crashed run) and create the given files.
// `files` maps sandbox-relative paths to file content; a trailing '/' makes a bare directory. // `files` maps sandbox-relative paths to file content; a trailing '/' makes a bare directory.
// Content is text, or `{base64: '...'}` for a binary file.
"fb:reset": ({ files }) => { "fb:reset": ({ files }) => {
fs.rmSync(SANDBOX_DIR, { recursive: true, force: true }); fs.rmSync(SANDBOX_DIR, { recursive: true, force: true });
fs.mkdirSync(SANDBOX_DIR, { recursive: true }); fs.mkdirSync(SANDBOX_DIR, { recursive: true });
@ -34,7 +39,7 @@ const fileBrowserTasks = {
} else { } else {
const filePath = sandboxPath(relativePath); const filePath = sandboxPath(relativePath);
fs.mkdirSync(path.dirname(filePath), { recursive: true }); fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content ?? ""); fs.writeFileSync(filePath, fileContent(content));
} }
} }
return SANDBOX_NAME; return SANDBOX_NAME;
@ -69,10 +74,57 @@ const fileBrowserTasks = {
}, },
}; };
/*
* Real map files for the standalone map viewer's e2e test, jailed to one directory inside the
* media directory's map directory.
*/
const zlib = require("zlib");
const MAP_SANDBOX_NAME = "cypress-map";
const MAP_SANDBOX_DIR = path.join(MEDIA_DIR, "map", MAP_SANDBOX_NAME);
// A PMTiles version 3 file with a header, metadata and an empty tile directory: enough for the
// map to list and add it, with no tiles to draw.
function pmtilesFile(metadata) {
const directory = zlib.gzipSync(Buffer.from([0]));
const meta = zlib.gzipSync(Buffer.from(JSON.stringify(metadata)));
const header = Buffer.alloc(127);
header.write("PMTiles", 0, "latin1");
header[7] = 3;
header.writeBigUInt64LE(127n, 8);
header.writeBigUInt64LE(BigInt(directory.length), 16);
header.writeBigUInt64LE(BigInt(127 + directory.length), 24);
header.writeBigUInt64LE(BigInt(meta.length), 32);
// Clustered, internal compression gzip, tile compression gzip, tile type mvt, zoom 0-8.
Buffer.from([1, 2, 2, 1, 0, 8]).copy(header, 96);
header.writeInt32LE(-1800000000, 102);
header.writeInt32LE(-850000000, 106);
header.writeInt32LE(1800000000, 110);
header.writeInt32LE(850000000, 114);
return Buffer.concat([header, directory, meta]);
}
const mapTasks = {
// Wipe the sandbox and create an overlay file there, with a style beside it if given.
"map:seed-overlay": ({ name, metadata, style }) => {
if (!/^[a-z-]+$/.test(name)) throw new Error(`Refusing the map file name: ${name}`);
fs.rmSync(MAP_SANDBOX_DIR, { recursive: true, force: true });
fs.mkdirSync(MAP_SANDBOX_DIR, { recursive: true });
fs.writeFileSync(path.join(MAP_SANDBOX_DIR, `${name}.pmtiles`), pmtilesFile(metadata));
if (style) fs.writeFileSync(path.join(MAP_SANDBOX_DIR, `${name}.style.json`), JSON.stringify(style));
return `${MAP_SANDBOX_NAME}/${name}.pmtiles`;
},
"map:cleanup": () => {
fs.rmSync(MAP_SANDBOX_DIR, { recursive: true, force: true });
return true;
},
};
module.exports = defineConfig({ module.exports = defineConfig({
e2e: { e2e: {
setupNodeEvents(on) { setupNodeEvents(on) {
on("task", fileBrowserTasks); on("task", fileBrowserTasks);
on("task", mapTasks);
}, },
// Use HTTP for CI, HTTPS for local development // Use HTTP for CI, HTTPS for local development
baseUrl: process.env.CI ? 'http://localhost:3000' : 'https://localhost:8443', baseUrl: process.env.CI ? 'http://localhost:3000' : 'https://localhost:8443',

View file

@ -108,16 +108,24 @@ import {
selectRow('fb-alpha'); selectRow('fb-alpha');
footerButton('Rename').click(); footerButton('Rename').click();
drainQueuedRefresh(() => { // A directory rename is a file-worker move job; the request returns once it is queued, and the job
// reports when it is done. No refresh is queued.
cy.serverNow().then((since) => {
dialog().within(() => { dialog().within(() => {
cy.get('input').clear().type('fb-alpha-renamed'); cy.get('input').clear().type('fb-alpha-renamed');
cy.contains('button', 'Rename').click(); cy.contains('button', 'Rename').click();
}); });
dialog().should('not.exist');
cy.waitForEvent({
since,
event: 'file_move_completed',
message: 'Renamed fb-alpha to fb-alpha-renamed',
failureEvent: 'file_move_failed',
});
});
// A directory rename runs as a file-worker move job; the modal stays open until // The table is fetched again once the file worker is idle.
// the job finishes, which takes longer than the default timeout. cy.contains('tr', 'fb-alpha-renamed', {timeout: 10000}).should('be.visible');
cy.get('[role="dialog"]', {timeout: 30000}).should('not.exist');
row('fb-alpha-renamed').should('be.visible');
// The folder row's text is just the name, so anchoring excludes 'fb-alpha-renamed'. // The folder row's text is just the name, so anchoring excludes 'fb-alpha-renamed'.
cy.contains('tr', /fb-alpha$/).should('not.exist'); cy.contains('tr', /fb-alpha$/).should('not.exist');
@ -126,4 +134,3 @@ import {
cy.task('fb:exists', 'fb-alpha').should('be.false'); cy.task('fb:exists', 'fb-alpha').should('be.false');
}); });
}); });
});

View file

@ -0,0 +1,89 @@
/*
* Previewing STL files, exercised against the live stack in a real browser (WebGL).
*
* An STL is either ASCII text or binary. Both must load in the preview: the dimensions line
* is only shown after the model has been parsed and framed, and a load failure is shown as an
* error (or thrown, which fails the test).
*/
import {assertWROLModeOff, SANDBOX, teardownFileBrowser} from '../../support/file-browser';
// One right triangle, legs of 2 along X and 1 along Y.
const ASCII_STL = `solid ASCII
facet normal 0 0 1
outer loop
vertex 0 0 0
vertex 2 0 0
vertex 0 1 0
endloop
endfacet
endsolid
`;
function binaryStlBase64() {
// 80-byte header, uint32 triangle count, then one 50-byte triangle: normal, three vertices.
const buffer = new ArrayBuffer(84 + 50);
const view = new DataView(buffer);
view.setUint32(80, 1, true);
const floats = [0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0];
floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true));
return Cypress.Buffer.from(buffer).toString('base64');
}
// Requires the full stack (API + real media directory); CI runs only the React dev server.
(Cypress.env('CI') ? describe.skip : describe)('STL preview', () => {
before(() => {
assertWROLModeOff();
cy.task('fb:reset', {
files: {
'ascii.stl': ASCII_STL,
'binary.stl': {base64: binaryStlBase64()},
},
});
cy.refreshFiles([SANDBOX]);
});
after(() => {
teardownFileBrowser();
});
const openPreview = (name) => {
const params = new URLSearchParams({folders: `${SANDBOX}/`, preview: `${SANDBOX}/${name}`});
cy.visit(`/files?${params}`);
cy.get('[role="dialog"]').should('contain', name);
};
const expectTriangleDimensions = () => {
// The triangle is 2 wide along X, which only a parsed model can report. Which axis
// reads as Height or Length depends on how the viewer orients the model, so only
// Width is asserted.
cy.get('[role="dialog"]').contains('Width:', {timeout: 20000}).parent()
.should('contain', 'Width: 2.00');
cy.get('[role="dialog"]').should('not.contain', 'Failed to');
};
it('previews an ASCII STL file', () => {
openPreview('ascii.stl');
expectTriangleDimensions();
});
it('previews a binary STL file', () => {
openPreview('binary.stl');
expectTriangleDimensions();
});
it('shows the action buttons without scrolling the preview', () => {
cy.viewport(1280, 720);
openPreview('binary.stl');
// The dimensions line is the last thing the preview adds, so the layout is final.
expectTriangleDimensions();
cy.get('.mantine-Modal-content').should(([content]) => {
expect(content.scrollHeight, 'preview modal content scrolls')
.to.be.at.most(content.clientHeight);
});
cy.get('.wrolpi-modal-actions').should(([actions]) => {
expect(actions.getBoundingClientRect().bottom, 'action buttons bottom edge')
.to.be.at.most(actions.ownerDocument.defaultView.innerHeight);
});
});
});

View file

@ -0,0 +1,136 @@
/*
* The standalone map viewer (port 8084) and overlays: map files which are not a basemap.
*
* The standalone viewer is plain HTML with no build step; it loads copies of the map viewer's
* overlay modules. This runs against the live stack with a real map file: the map:* tasks write
* a small overlay (no tiles) and a style beside it into the media directory's map directory.
*/
const VIEWER = 'https://localhost:8084/';
const LABEL = 'Cypress Overlay';
const METADATA = {
name: LABEL,
description: 'An overlay for the standalone viewer test',
type: 'overlay',
vector_layers: [
{id: 'towers', fields: {name: 'String'}, minzoom: 0, maxzoom: 8},
{id: 'power_lines', fields: {}, minzoom: 0, maxzoom: 8},
{id: 'parks', fields: {}, minzoom: 0, maxzoom: 8},
],
tilestats: {
layers: [
{layer: 'towers', geometry: 'Point', count: 1},
{layer: 'power_lines', geometry: 'LineString', count: 1},
{layer: 'parks', geometry: 'Polygon', count: 1},
],
},
};
// Written for some other map: its own source name and URL, and one layer MapLibre cannot draw.
const STYLE = {
version: 8,
sources: {features: {type: 'vector', url: 'https://example.com/features.json'}},
layers: [
{id: 'background', type: 'background'},
{id: 'lines', type: 'line', source: 'features', 'source-layer': 'power_lines', paint: {'line-color': '#c60'}},
{id: 'bad', type: 'line', source: 'features', 'source-layer': 'parks', paint: {'line-width': 'wide'}},
{
id: 'towers', type: 'symbol', source: 'features', 'source-layer': 'towers',
layout: {'text-field': ['get', 'name'], 'text-font': ['Roboto Bold']},
},
],
};
const overlayRow = () => cy.contains('.overlay-file', LABEL);
const overlayBox = () => overlayRow().find('input[type=checkbox]');
const layerBox = (name) => cy.contains('.overlay-layer', name).find('input[type=checkbox]');
const openPanel = () => cy.get('#overlay-section', {timeout: 20000}).should('be.visible');
// Requires the full stack (API, Caddy on 8084, real media directory); CI runs only the React dev server.
(Cypress.env('CI') ? describe.skip : describe)('Standalone map viewer: overlays', () => {
afterEach(() => {
cy.task('map:cleanup');
});
it('offers an overlay by its own name, hidden, with a checkbox per layer', () => {
cy.task('map:seed-overlay', {name: 'generic', metadata: METADATA});
cy.visit(VIEWER);
openPanel();
overlayBox().should('not.be.checked');
overlayRow().find('.overlay-zooms').should('have.text', 'z0\u20138');
overlayRow().find('.overlay-expand').click();
// Every layer of the file, each with the color it is drawn in.
cy.get('.overlay-layer').should('have.length', 3);
cy.get('.overlay-swatch').should('have.length', 3);
// The layers cannot be chosen while the file is off.
layerBox('towers').should('be.disabled');
overlayBox().check();
layerBox('towers').should('be.enabled').and('be.checked');
layerBox('towers').uncheck();
cy.contains('.overlay-all-none button', 'None').click();
layerBox('power_lines').should('not.be.checked');
cy.contains('.overlay-all-none button', 'All').click();
layerBox('power_lines').should('be.checked');
layerBox('towers').should('be.checked');
});
it('remembers what was turned on', () => {
cy.task('map:seed-overlay', {name: 'remembered', metadata: METADATA});
cy.visit(VIEWER);
openPanel();
overlayBox().check();
overlayRow().find('.overlay-expand').click();
layerBox('parks').uncheck();
cy.reload();
openPanel();
overlayBox().should('be.checked');
overlayRow().find('.overlay-expand').click();
layerBox('parks').should('not.be.checked');
layerBox('towers').should('be.checked');
});
it('draws an overlay with the style beside it, without the layer MapLibre refuses', () => {
cy.intercept('GET', '**/data/cypress-map/styled.style.json').as('style');
cy.intercept('GET', '**/sprites/overlay-icons*.json').as('icons');
cy.task('map:seed-overlay', {name: 'styled', metadata: METADATA, style: STYLE});
cy.visit(VIEWER);
// The style is fetched from the map directory this viewer is served.
cy.wait('@style').its('response.statusCode').should('eq', 200);
openPanel();
overlayRow().find('.overlay-expand').click();
// Only the layers the style draws, and no generic colors.
cy.get('.overlay-layer').should('have.length', 3);
cy.get('.overlay-swatch').should('have.length', 0);
// This viewer cannot check a layer before MapLibre does: the bad one is refused there.
cy.contains('.overlay-note', '1 style layer skipped');
// The panel is rebuilt by a change, so the checkbox is found again.
overlayBox().check();
overlayBox().should('be.checked');
// A style names icons: the map's own, a sprite of this viewer's. Its index has a name a
// style may use for an icon, beside the icon's own.
cy.wait('@icons').then(({response}) => {
expect(response.statusCode).to.eq(200);
expect(response.body).to.have.property('ham_radio');
expect(response.body.ham_radio).to.deep.eq(response.body.antenna);
expect(response.body.hospital.sdf).to.eq(true);
});
});
it('does not offer an ignored file', () => {
cy.task('map:seed-overlay', {name: 'ignored', metadata: METADATA}).then((mapPath) => {
cy.request('POST', 'https://localhost:8084/api/map/files/visible', {map_path: mapPath, visible: false});
cy.visit(VIEWER);
cy.get('#layer-content', {timeout: 20000}).contains('Labels');
cy.contains('.overlay-file', LABEL).should('not.exist');
// Deleting the file forgets that it was ignored.
cy.request('DELETE', `https://localhost:8084/api/map/files/${mapPath}`);
});
});
});

View file

@ -1,5 +1,5 @@
/* /*
* The five Special Directories fields on /admin/settings. * The six Special Directories fields on /admin/settings.
* *
* These are the fields that shipped printing their own prefix over their own value, and the * These are the fields that shipped printing their own prefix over their own value, and the
* ones whose visible labels were never associated with their inputs. Both faults were * ones whose visible labels were never associated with their inputs. Both faults were
@ -19,6 +19,7 @@ describe('Special Directories settings', () => {
['Map Directory', 'map'], ['Map Directory', 'map'],
['Zims Directory', 'zims'], ['Zims Directory', 'zims'],
['Playlists Directory', 'playlists'], ['Playlists Directory', 'playlists'],
['Repos Directory', 'repos/%(repo_tag)s/%(repo_name)s'],
]; ];
beforeEach(() => { beforeEach(() => {
@ -38,8 +39,8 @@ describe('Special Directories settings', () => {
it('names every directory field, so they can be told apart', () => { it('names every directory field, so they can be told apart', () => {
/* /*
* All five fields sit in one grid, hold similar-looking relative paths, and share the * All six fields sit in one grid, hold similar-looking relative paths, and share the
* same prefix. Without a name attached to the input, a screen reader user hears five * same prefix. Without a name attached to the input, a screen reader user hears six
* fields described only as "/media/wrolpi/" and cannot tell which one saves videos. * fields described only as "/media/wrolpi/" and cannot tell which one saves videos.
*/ */
directories.forEach(([label, value]) => { directories.forEach(([label, value]) => {

View file

@ -41,7 +41,7 @@ import React from "react";
Cypress.on('uncaught:exception', (err, runnable) => { Cypress.on('uncaught:exception', (err, runnable) => {
if (err.message.includes('ChunkLoadError')) { if (err.message.includes('ChunkLoadError')) {
return false; // Ignore this error which happens after CircleCI tests. return false; // Ignore this error which happens after CI tests.
} }
// Otherwise, fail like normal // Otherwise, fail like normal
return true; return true;

View file

@ -0,0 +1,30 @@
'use strict';
// Replaces CRA's JS transform so Jest can load three.js. three ships ES modules
// with static class blocks, which babel-preset-react-app's class-properties plugin rejects at our
// pinned Babel version. Those files only need their imports converted to CommonJS; every other
// file goes through CRA's transform unchanged.
const babelJest = require('babel-jest').default;
const craTransform = require('react-scripts/config/jest/babelTransform');
const threeTransform = babelJest.createTransformer({
babelrc: false,
configFile: false,
plugins: [require.resolve('@babel/plugin-transform-modules-commonjs')],
});
const THREE_PATH = /[\\/]node_modules[\\/]three[\\/]/;
function pick(sourcePath) {
return THREE_PATH.test(sourcePath) ? threeTransform : craTransform;
}
module.exports = {
canInstrument: true,
getCacheKey(sourceText, sourcePath, options) {
return pick(sourcePath).getCacheKey(sourceText, sourcePath, options);
},
process(sourceText, sourcePath, options) {
return pick(sourcePath).process(sourceText, sourcePath, options);
},
};

1402
app/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -9,35 +9,40 @@
"@mantine/core": "^8.3.18", "@mantine/core": "^8.3.18",
"@mantine/hooks": "^8.3.18", "@mantine/hooks": "^8.3.18",
"@mantine/notifications": "^8.3.18", "@mantine/notifications": "^8.3.18",
"@tabler/icons-react": "^3.46.0", "@mapbox/vector-tile": "^2.0.4",
"@maplibre/maplibre-gl-style-spec": "^24.8.5",
"@tabler/icons-react": "^3.50.0",
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.6.6", "@testing-library/user-event": "^14.6.8",
"cypress": "^15.21.1", "cypress": "^15.21.1",
"esptool-js": "^0.6.1", "dompurify": "^3.4.17",
"esptool-js": "^0.7.0",
"lodash": "^4.18.1", "lodash": "^4.18.1",
"maplibre-gl": "^5.24.0", "maplibre-gl": "^5.24.0",
"markdown-it": "^15.0.3",
"mathjs": "^15.2.0", "mathjs": "^15.2.0",
"pbf": "^4.0.1",
"pmtiles": "^4.5.0", "pmtiles": "^4.5.0",
"protomaps-themes-base": "^4.5.0", "protomaps-themes-base": "^4.5.0",
"query-string": "^9.5.1", "query-string": "^10.0.0",
"react": "^18.2.0", "react": "^18.3.1",
"react-colorful": "^5.8.0", "react-colorful": "^5.8.1",
"react-dom": "^18.2.0", "react-dom": "^18.3.1",
"react-dropzone": "^14.2.3", "react-dropzone": "^14.4.1",
"react-hotkeys-hook": "^5.3.3", "react-hotkeys-hook": "^5.3.3",
"react-qr-code": "^2.2.0", "react-qr-code": "^2.2.0",
"react-router": "^7.18.2", "react-router": "^7.18.5",
"react-scripts": "5.0.1", "react-scripts": "5.0.1",
"react-stl-viewer": "^2.5.0", "three": "^0.186",
"three": "^0.185", "web-vitals": "^6.2.3"
"web-vitals": "^5.3.0"
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "start": "react-scripts start",
"build": "BROWSERSLIST_IGNORE_OLD_DATA=true react-scripts build", "build": "BROWSERSLIST_IGNORE_OLD_DATA=true react-scripts build",
"test": "react-scripts test", "test": "TZ=America/New_York react-scripts test",
"eject": "react-scripts eject", "eject": "react-scripts eject",
"cy:run": "cypress run", "cy:run": "cypress run",
"sync:map-shared": "mkdir -p ../modules/map/static/js && cp src/map-shared/overlays.js src/map-shared/overlayStyle.js src/map-shared/terrain.js ../modules/map/static/js/",
"cy:open": "cypress open" "cy:open": "cypress open"
}, },
"eslintConfig": { "eslintConfig": {
@ -58,19 +63,25 @@
] ]
}, },
"devDependencies": { "devDependencies": {
"@testing-library/dom": "^10.4.1", "@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^7.0.1", "@testing-library/jest-dom": "^7.0.1",
"@types/lodash": "^4.17.25", "@types/lodash": "^4.17.27",
"@types/node": "^26.4.0", "@types/node": "^26.6.6",
"@types/react": "^18.3.17", "@types/react": "^18.3.17",
"@types/react-dom": "^18.3.5", "@types/react-dom": "^18.3.5",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"webpack-dev-server": "^5.2.6" "webpack-dev-server": "^5.2.7"
}, },
"jest": { "jest": {
"transform": {
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/jest/babelTransform.js"
},
"transformIgnorePatterns": [ "transformIgnorePatterns": [
"node_modules/(?!(react-hotkeys-hook)/)" "node_modules/(?!(react-hotkeys-hook|three|@mapbox/vector-tile|@mapbox/point-geometry|pbf)/)"
] ],
"moduleNameMapper": {
"^(.*)/falloutWorker(\\.js)?$": "$1/falloutWorker.stub.js"
}
}, },
"overrides": { "overrides": {
"@babel/code-frame": "7.29.0", "@babel/code-frame": "7.29.0",
@ -89,9 +100,9 @@
"@babel/template": "7.28.6", "@babel/template": "7.28.6",
"@babel/traverse": "7.29.0", "@babel/traverse": "7.29.0",
"@babel/types": "7.29.0", "@babel/types": "7.29.0",
"fork-ts-checker-webpack-plugin": "^6.5.3",
"react-scripts": { "react-scripts": {
"typescript": "$typescript" "typescript": "$typescript"
}, }
"fork-ts-checker-webpack-plugin": "^6.5.3"
} }
} }

View file

@ -0,0 +1,11 @@
Solar climatology for the WROLPi Solar calculator
Source: NASA POWER, https://power.larc.nasa.gov/
Data: 2001-2020 monthly climatology of ALLSKY_SFC_SW_DWN, ALLSKY_SFC_SW_DIFF, ALLSKY_SRF_ALB, T2M, on a 1° grid.
The data was obtained from the POWER Project's POWER Climatology API v2.10.0 version on 2026/10/04.
The data was obtained from National Aeronautics and Space Administration (NASA) Langley Research Center's Prediction Of Worldwide Energy Resources (POWER) project funded through the NASA Earth Science Division.
License: Creative Commons Attribution 4.0 International (CC BY 4.0), https://creativecommons.org/licenses/by/4.0/
Changes: WROLPi modified the data: values are rounded to fit one byte each (0.04 kWh/m²/day for irradiance, 0.004 for albedo, 0.5 °C for temperature), temperatures are averaged from NASA's 0.5° x 0.625° grid into 1° cells, and the calculator interpolates between cells.

Binary file not shown.

View file

@ -242,6 +242,8 @@ either expressed or implied, of the FreeBSD Project. -->
// Optional search term passed in from a search-result deep link. If present we'll // Optional search term passed in from a search-result deep link. If present we'll
// search the spine item at `loc` and jump to + highlight the first match. // search the spine item at `loc` and jump to + highlight the first match.
let searchQuery = (params && params.get("q")) ? params.get("q") : null; let searchQuery = (params && params.get("q")) ? params.get("q") : null;
// Where the reader left off (an EPUB CFI). A search result's `loc` wins over it.
let startCfi = (params && params.get("cfi")) ? params.get("cfi") : null;
let book = ePub(url); let book = ePub(url);
let rendition = book.renderTo("viewer", { let rendition = book.renderTo("viewer", {
@ -250,7 +252,33 @@ either expressed or implied, of the FreeBSD Project. -->
height: "100%" height: "100%"
}); });
rendition.display(currentSectionIndex); rendition.display(currentSectionIndex !== undefined ? currentSectionIndex : (startCfi || undefined));
// How far through the book `location` is, from its chapter and its page within that chapter. Cheaper
// than `book.locations.generate()`, which stalls a Raspberry Pi on a large book.
function readingProgress(location) {
if (location.atEnd) {
return 1;
}
const start = location.start;
const sections = book.spine.length || 1;
const displayed = start.displayed || {page: 1, total: 1};
const withinSection = (displayed.page - 1) / Math.max(displayed.total, 1);
return Math.min((start.index + withinSection) / sections, 1);
}
// Tell the WROLPi page that embeds this viewer where the reader is, so it can save their place. Nothing is
// posted at the start of the book: that is where a finished book opens, and saving it would un-finish it.
function postLocation(location) {
if (window.parent === window || !location || !location.start || location.atStart) {
return;
}
window.parent.postMessage({
type: "wrolpi:epub-location",
cfi: location.start.cfi,
progress: readingProgress(location),
}, window.location.origin);
}
// --- In-book search --------------------------------------------------- // --- In-book search ---------------------------------------------------
// State is module-level so the toolbar buttons can drive it. `hits` is the // State is module-level so the toolbar buttons can drive it. `hits` is the
@ -516,6 +544,7 @@ either expressed or implied, of the FreeBSD Project. -->
prev.style.visibility = "visible"; prev.style.visibility = "visible";
} }
postLocation(location);
}); });
rendition.on("layout", function (layout) { rendition.on("layout", function (layout) {

View file

@ -293,9 +293,8 @@ pre.wrap-text {
} }
} }
/* Caps preview content to fit inside the file-preview Modal. /* Caps preview content to fit inside a Modal (e.g. the Zim entry preview): 18.75rem is a guess at
300px reserves room for pathContent <pre>, Modal.Header, Modal.Actions row, everything else in the modal. The file-preview Modal does not guess; see below.
inner content (e.g. STL dimensions banner), and modal padding.
Use 100dvh so mobile browser chrome (URL bar) is accounted for. */ Use 100dvh so mobile browser chrome (URL bar) is accounted for. */
.preview-fit { .preview-fit {
width: 100%; width: 100%;
@ -309,6 +308,36 @@ pre.wrap-text {
justify-content: center; justify-content: center;
} }
/* In the file-preview Modal, a .preview-fit takes whatever height the rest of the modal leaves
(path, header, a 3D model's dimensions line, the action buttons however they wrap) rather
than reserving a fixed amount, so the buttons are always on screen without scrolling.
The modal fills Mantine's maximum height only when it frames a .preview-fit; other previews
keep the height of their content. */
.file-preview-modal-content:has(.preview-fit) {
height: calc(100dvh - var(--modal-y-offset) * 2);
display: flex;
flex-direction: column;
}
.file-preview-modal-content:has(.preview-fit) > .mantine-Modal-header {
flex: none;
}
.file-preview-modal-content:has(.preview-fit) > .mantine-Modal-body {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
/* The .preview-fit (a direct child of the body: MediaGate renders fragments) takes the leftover
height. The other children keep theirs: a flex item never shrinks below its content. */
.file-preview-modal-content .preview-fit {
flex: 1 1 0;
height: auto;
max-height: none;
}
/* Fresnel (Media) wraps iframes in a div which would otherwise shrink to the /* Fresnel (Media) wraps iframes in a div which would otherwise shrink to the
default iframe size; make it fill the preview so the iframe's 100% works. */ default iframe size; make it fill the preview so the iframe's 100% works. */
.preview-fit .fresnel-container { .preview-fit .fresnel-container {
@ -316,6 +345,90 @@ pre.wrap-text {
height: 100%; height: 100%;
} }
/* A markdown file preview, formatted or raw. Scrolls rather than fitting like .preview-fit, because
it is a document to read, not media to frame. Colors come from the theme tokens. */
.markdown-preview {
height: calc(100dvh - 21rem);
min-height: 15rem;
overflow: auto;
margin-top: 0.5em;
padding: 0 0.25em;
}
/* A repo's README is part of its page, not a modal; it grows with its content. */
.repo-readme .markdown-preview {
height: auto;
min-height: 0;
overflow: visible;
}
.markdown-raw {
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.markdown-body {
max-width: 50rem;
line-height: 1.6;
overflow-wrap: break-word;
}
.markdown-body > :first-child {
margin-top: 0;
}
.markdown-body h1, .markdown-body h2 {
padding-bottom: 0.25em;
border-bottom: 1px solid var(--table-line);
}
.markdown-body img {
max-width: 100%;
}
.markdown-body blockquote {
margin: 0 0 1em;
padding: 0 1em;
color: var(--muted);
border-left: 0.25em solid var(--border);
}
.markdown-body code {
padding: 0.1em 0.3em;
border-radius: 0.25em;
background-color: var(--head);
}
.markdown-body pre {
padding: 0.75em 1em;
overflow-x: auto;
border-radius: 0.25em;
background-color: var(--head);
}
.markdown-body pre code {
padding: 0;
background-color: transparent;
}
.markdown-body table {
display: block;
max-width: 100%;
overflow-x: auto;
border-collapse: collapse;
}
.markdown-body th, .markdown-body td {
padding: 0.3em 0.75em;
border: 1px solid var(--table-line);
}
.markdown-body hr {
border: none;
border-top: 1px solid var(--border);
}
td.file-path { td.file-path {
cursor: pointer; cursor: pointer;
} }
@ -725,3 +838,35 @@ tr.drag-deselecting td {
display: block; display: block;
} }
} }
/* Map popups (POI details and pins) follow the active theme's tokens. */
/* Scoped under .maplibregl-popup to outrank maplibre-gl.css, which loads after this file. */
.maplibregl-popup .maplibregl-popup-content {
background: var(--panel);
color: var(--text);
border: 1px solid var(--border);
border-radius: 0.25rem;
}
.maplibregl-popup .maplibregl-popup-close-button {
color: var(--muted);
}
.maplibregl-popup .maplibregl-popup-close-button:hover {
background: var(--head);
color: var(--text);
}
.maplibregl-popup.maplibregl-popup-anchor-top .maplibregl-popup-tip,
.maplibregl-popup.maplibregl-popup-anchor-top-left .maplibregl-popup-tip,
.maplibregl-popup.maplibregl-popup-anchor-top-right .maplibregl-popup-tip {
border-bottom-color: var(--panel);
}
.maplibregl-popup.maplibregl-popup-anchor-bottom .maplibregl-popup-tip,
.maplibregl-popup.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip,
.maplibregl-popup.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip {
border-top-color: var(--panel);
}
.maplibregl-popup.maplibregl-popup-anchor-left .maplibregl-popup-tip {
border-right-color: var(--panel);
}
.maplibregl-popup.maplibregl-popup-anchor-right .maplibregl-popup-tip {
border-left-color: var(--panel);
}

View file

@ -4,6 +4,7 @@ import {NavBar} from "./components/Nav";
import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router"; import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router";
import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos"; import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos";
import AdminRoute from "./components/admin/AdminRoute"; import AdminRoute from "./components/admin/AdminRoute";
import {ExtensionRoute} from "./components/admin/ExtensionPage";
import {Box, Header} from "./components/ui"; import {Box, Header} from "./components/ui";
import '@mantine/core/styles.css'; import '@mantine/core/styles.css';
import '@mantine/notifications/styles.css'; import '@mantine/notifications/styles.css';
@ -15,8 +16,10 @@ import {MoreRoute} from "./components/Apps";
import {InventoryRoute} from "./components/inventory/InventoryRoute"; import {InventoryRoute} from "./components/inventory/InventoryRoute";
import {ArchiveRoute} from "./components/Archive"; import {ArchiveRoute} from "./components/Archive";
import {FilesRoute} from "./components/Files"; import {FilesRoute} from "./components/Files";
import {SyncingOverlay} from "./components/admin/Sync";
import {QueryProvider, StatusProvider} from "./hooks/customHooks"; import {QueryProvider, StatusProvider} from "./hooks/customHooks";
import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext"; import {FileWorkerStatusProvider} from "./contexts/FileWorkerStatusContext";
import {BookmarksProvider} from "./contexts/BookmarksContext";
import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels"; import {ChannelEditPage, ChannelNewPage, ChannelsPage} from "./components/Channels";
import {MapRoute} from "./components/Map"; import {MapRoute} from "./components/Map";
import {MediaContextProvider, mediaStyles, StatusContext} from "./contexts/contexts"; import {MediaContextProvider, mediaStyles, StatusContext} from "./contexts/contexts";
@ -29,6 +32,7 @@ import {FilePreviewProvider} from "./components/FilePreview";
import {TagsProvider} from "./Tags"; import {TagsProvider} from "./Tags";
import {ZimRoute} from "./components/Zim"; import {ZimRoute} from "./components/Zim";
import {PlaylistsRoute} from "./components/Playlists"; import {PlaylistsRoute} from "./components/Playlists";
import {ReposRoute} from "./components/Repos";
import {DocsRoute} from "./components/Docs"; import {DocsRoute} from "./components/Docs";
import {FlasherRoute} from "./components/Flasher"; import {FlasherRoute} from "./components/Flasher";
import ErrorBoundary from "./components/ErrorBoundary"; import ErrorBoundary from "./components/ErrorBoundary";
@ -69,13 +73,16 @@ function Root() {
<TagsProvider> <TagsProvider>
<KeyboardShortcutsProvider> <KeyboardShortcutsProvider>
<FilePreviewProvider> <FilePreviewProvider>
<BookmarksProvider>
<header> <header>
<NavBar/> <NavBar/>
</header> </header>
<SyncingOverlay/>
<ErrorBoundary> <ErrorBoundary>
<Outlet/> <Outlet/>
</ErrorBoundary> </ErrorBoundary>
<Footer/> <Footer/>
</BookmarksProvider>
</FilePreviewProvider> </FilePreviewProvider>
</KeyboardShortcutsProvider> </KeyboardShortcutsProvider>
</TagsProvider> </TagsProvider>
@ -83,10 +90,12 @@ function Root() {
</QueryProvider> </QueryProvider>
} }
const router = createBrowserRouter(createRoutesFromElements(<Route export const routes = createRoutesFromElements(<Route
path='/' path='/'
element={<Root/>} element={<Root/>}
errorElement={<PageNotFound/>} // Root (and its ThemeProvider) is not rendered when Root itself fails, so the error page
// brings its own theme; Mantine components cannot render without one.
errorElement={<ThemeProvider><PageNotFound/></ThemeProvider>}
> >
<Route index element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/> <Route index element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
<Route path='search/*' element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/> <Route path='search/*' element={<ErrorBoundary><DashboardPage/></ErrorBoundary>}/>
@ -114,9 +123,15 @@ const router = createBrowserRouter(createRoutesFromElements(<Route
<Route path='map/*' element={<ErrorBoundary><MapRoute/></ErrorBoundary>}/> <Route path='map/*' element={<ErrorBoundary><MapRoute/></ErrorBoundary>}/>
<Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/> <Route path='zim/*' element={<ErrorBoundary><ZimRoute/></ErrorBoundary>}/>
<Route path='playlists/*' element={<ErrorBoundary><PlaylistsRoute/></ErrorBoundary>}/> <Route path='playlists/*' element={<ErrorBoundary><PlaylistsRoute/></ErrorBoundary>}/>
<Route path='repos/*' element={<ErrorBoundary><ReposRoute/></ErrorBoundary>}/>
<Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/> <Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/>
<Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/> <Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/>
</Route>)); <Route path='extension' element={<ErrorBoundary><ExtensionRoute/></ErrorBoundary>}/>
{/* Unknown URLs render inside Root, with the navigation bar and theme. */}
<Route path='*' element={<PageNotFound/>}/>
</Route>);
const router = createBrowserRouter(routes);
export default function App() { export default function App() {
useEventsInterval(); useEventsInterval();

52
app/src/App.test.js Normal file
View file

@ -0,0 +1,52 @@
import React from 'react';
import {render, screen} from '@testing-library/react';
import {createMemoryRouter, RouterProvider} from 'react-router';
import {routes} from './App';
import {StatusProvider} from './hooks/customHooks';
import {FileWorkerStatusProvider} from './contexts/FileWorkerStatusContext';
import {MediaContextProvider} from './contexts/contexts';
// Jest does not transform CSS inside node_modules (see transformIgnorePatterns).
jest.mock('@mantine/core/styles.css', () => ({}));
jest.mock('@mantine/notifications/styles.css', () => ({}));
// Routes this test does not visit, whose libraries jsdom/Jest cannot load (maplibre needs
// browser APIs; esptool-js is ESM-only).
jest.mock('./components/Map', () => ({MapRoute: () => null}));
jest.mock('./components/Flasher', () => ({FlasherRoute: () => null}));
describe('unknown routes', () => {
beforeEach(() => {
// resetMocks clears setupTests' implementation; the theme and media providers read it.
window.matchMedia.mockImplementation(query => ({
matches: false,
media: query,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
}));
global.fetch = jest.fn(() => Promise.resolve({
ok: true,
status: 200,
headers: {get: () => 'application/json'},
json: () => Promise.resolve({tags: []}),
text: () => Promise.resolve('{}'),
}));
});
it('renders Page Not Found inside the app layout', async () => {
const router = createMemoryRouter(routes, {initialEntries: ['/no-such-page']});
// The providers App wraps around the router.
render(<StatusProvider>
<FileWorkerStatusProvider>
<MediaContextProvider>
<RouterProvider router={router}/>
</MediaContextProvider>
</FileWorkerStatusProvider>
</StatusProvider>);
expect(await screen.findByText('Page Not Found!')).toBeInTheDocument();
// Rendered inside Root's layout (the footer comes from Root), not as a bare error page.
expect(screen.getByText('Donate')).toBeInTheDocument();
});
});

View file

@ -5,8 +5,10 @@ import {
PageContainer, PageContainer,
RefreshHeader, RefreshHeader,
SearchResultsInput, SearchResultsInput,
useLocalStorage,
useTitle useTitle
} from "./components/Common"; } from "./components/Common";
import {SecondaryRoleMessage} from "./components/admin/Sync";
import React, {useContext, useState} from "react"; import React, {useContext, useState} from "react";
import {useHotkeys} from "react-hotkeys-hook"; import {useHotkeys} from "react-hotkeys-hook";
import {Media, SettingsContext, StatusContext} from "./contexts/contexts"; import {Media, SettingsContext, StatusContext} from "./contexts/contexts";
@ -14,6 +16,7 @@ import {DownloadMenu} from "./components/Download";
import { import {
ActionInput, ActionInput,
Button, Button,
ButtonGroup,
Divider, Divider,
Header, Header,
Icon, Icon,
@ -250,6 +253,8 @@ export function Getters() {
</div> </div>
<span className='wrolpi-or-label'>Or</span> <span className='wrolpi-or-label'>Or</span>
</div> </div>
{status?.flags && gettersDisabled &&
<p>Download and Upload are available after your files are refreshed.</p>}
</Panel>; </Panel>;
let getterModal; let getterModal;
@ -351,7 +356,14 @@ export function DashboardStatus() {
} }
function DashboardRecentFiles() { function DashboardRecentFiles() {
const {searchFiles, loading, fetchFiles} = useSearchRecentFiles(); // Show only the files the user is part way through.
const [continueOnly, setContinueOnly] = useLocalStorage('dashboard_recent_continue', false);
const {searchFiles, loading, fetchFiles} = useSearchRecentFiles(continueOnly);
let files = <FileCards files={searchFiles} loading={loading}/>;
if (continueOnly && searchFiles && searchFiles.length === 0) {
files = <p>Nothing in progress. A video, audio file, ebook or comic you stop part way through will be here.</p>;
}
return <Panel> return <Panel>
<RefreshHeader <RefreshHeader
@ -359,7 +371,15 @@ function DashboardRecentFiles() {
popupContents='Fetch the most recent files again' popupContents='Fetch the most recent files again'
onRefresh={fetchFiles} onRefresh={fetchFiles}
/> />
<FileCards files={searchFiles} loading={loading}/> <ButtonGroup>
<Button size='small' variant={continueOnly ? 'default' : 'filled'} onClick={() => setContinueOnly(false)}>
All
</Button>
<Button size='small' variant={continueOnly ? 'filled' : 'default'} onClick={() => setContinueOnly(true)}>
Continue
</Button>
</ButtonGroup>
<div style={{marginTop: '1em'}}>{files}</div>
</Panel> </Panel>
} }
@ -412,18 +432,21 @@ export function DashboardPage() {
} else if (activeTags && activeTags.length > 1) { } else if (activeTags && activeTags.length > 1) {
const tagNames = activeTags.join(' & '); const tagNames = activeTags.join(' & ');
title = `Tags: ${tagNames} - Dashboard`; title = `Tags: ${tagNames} - Dashboard`;
} else if (anyTag) {
title = 'Any Tag - Dashboard';
} }
useTitle(title); useTitle(title);
// Only show dashboard parts if not searching. // Only show dashboard parts if not searching.
let body = <React.Fragment> let body = <React.Fragment>
<SecondaryRoleMessage/>
<Getters/> <Getters/>
<TagsDashboard/> <TagsDashboard/>
<DashboardStatus/> <DashboardStatus/>
<DashboardCalculators/> <DashboardCalculators/>
<DashboardRecentFiles/> <DashboardRecentFiles/>
</React.Fragment>; </React.Fragment>;
if (searchStr || (activeTags && activeTags.length > 0)) { if (searchStr || (activeTags && activeTags.length > 0) || anyTag) {
// User has submitted and wants full search. // User has submitted and wants full search.
body = <SearchView suggestions={suggestions} suggestionsSums={suggestionsSums} loading={loading}/>; body = <SearchView suggestions={suggestions} suggestionsSums={suggestionsSums} loading={loading}/>;
} }

View file

@ -21,11 +21,11 @@ jest.mock('./hooks/customHooks', () => ({
useWROLMode: () => false, useWROLMode: () => false,
})); }));
function renderAtUrl(url) { function renderAtUrl(url, flags = {refresh_complete: true}) {
// test-utils' render() wraps content in a BrowserRouter (not MemoryRouter), // test-utils' render() wraps content in a BrowserRouter (not MemoryRouter),
// so point the jsdom location at the desired URL before rendering. // so point the jsdom location at the desired URL before rendering.
window.history.pushState({}, '', url); window.history.pushState({}, '', url);
const status = {flags: {refresh_complete: true}}; const status = {flags};
return render( return render(
<StatusContext.Provider value={{status}}> <StatusContext.Provider value={{status}}>
<Getters/> <Getters/>
@ -67,6 +67,25 @@ describe('DashboardPage Getters deep-link', () => {
}); });
}); });
describe('DashboardPage Getters before the first refresh', () => {
const note = /available after your files are refreshed/i;
it('explains why Download and Upload are disabled', () => {
renderAtUrl('/', {refresh_complete: false});
expect(screen.getByText(note)).toBeInTheDocument();
});
it('says nothing once the refresh has completed', () => {
renderAtUrl('/');
expect(screen.queryByText(note)).toBeNull();
});
it('says nothing before the status has loaded', () => {
renderAtUrl('/', null);
expect(screen.queryByText(note)).toBeNull();
});
});
// The DownloadMenu's seed-object construction (joining initialUrls with // The DownloadMenu's seed-object construction (joining initialUrls with
// newlines into the `download` prop's `urls` field) is exercised in the // newlines into the `download` prop's `urls` field) is exercised in the
// browser via manual verification, not unit-tested here — reaching into the // browser via manual verification, not unit-tested here — reaching into the

View file

@ -9,7 +9,7 @@ function eventToast(title, description, type = 'info', time = 5000, onClick = nu
toast({type: type, title: title, description: description, time: time, onClick: onClick}); toast({type: type, title: title, description: description, time: time, onClick: onClick});
} }
function handleEvents(events) { export function handleEvents(events) {
const newestEvents = {}; const newestEvents = {};
events.forEach(e => { events.forEach(e => {
@ -46,6 +46,22 @@ function handleEvents(events) {
eventToast('Downloads Disabled', message); eventToast('Downloads Disabled', message);
} }
if (event === 'backup_completed') {
eventToast('Backup Completed', message, 'success');
}
if (event === 'backup_failed') {
eventToast('Backup Failed', message, 'error');
}
if (event === 'sync_completed') {
eventToast('Sync Completed', message, 'success');
}
if (event === 'sync_failed') {
eventToast('Sync Failed', message, 'error');
}
if (event === 'map_import_complete') { if (event === 'map_import_complete') {
eventToast('Map import completed', message, 'success'); eventToast('Map import completed', message, 'success');
} }
@ -63,13 +79,17 @@ function handleEvents(events) {
} }
if (event === 'user_notify_message') { if (event === 'user_notify_message') {
console.log(message, url); // Only a shared page carries a URL; other notifications (jobs, transcodes) are text.
if (url) {
eventToast( eventToast(
message, message,
'Click here to view the shared page', 'Click here to view the shared page',
'info', 'info',
10_000, 10_000,
() => window.open(url, '_self')); () => window.open(url, '_self'));
} else {
eventToast(message, null, 'info', 10_000);
}
} }
if (event === 'deleted') { if (event === 'deleted') {

33
app/src/Events.test.js Normal file
View file

@ -0,0 +1,33 @@
import {handleEvents} from './Events';
import {toast} from './components/ui';
jest.mock('./components/ui', () => ({toast: jest.fn()}));
const notify = (url) => ({event: 'user_notify_message', message: 'Transcoding video.mp4', dt: '2026-10-12', url});
afterEach(() => {
toast.mockClear();
});
describe('user_notify_message', () => {
it('a notification without a URL is plain text, not a link', () => {
handleEvents([notify(null)]);
expect(toast).toHaveBeenCalledTimes(1);
const options = toast.mock.calls[0][0];
expect(options.title).toBe('Transcoding video.mp4');
expect(options.description).toBeFalsy();
expect(options.onClick).toBeFalsy();
});
it('a shared page opens its URL when clicked', () => {
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
handleEvents([notify('/archive/1')]);
const options = toast.mock.calls[0][0];
expect(options.description).toBe('Click here to view the shared page');
options.onClick();
expect(open).toHaveBeenCalledWith('/archive/1', '_self');
open.mockRestore();
});
});

View file

@ -0,0 +1,84 @@
import {
flasherSearch, getConfigBackups, getDownloaders, getInventoryBackups, getMapSearchStatus, searchMap,
} from './api';
// A helper that fails must say so. These used to turn a non-OK response into an empty value
// ([], {dates: []}, {results: []}, ...), so every consumer rendered "nothing here" for a server
// error. They now return undefined; an empty value only ever comes from the server.
jest.mock('./components/ui', () => ({
...jest.requireActual('./components/ui'),
toast: jest.fn(),
}));
const response = (ok, body = {}) => {
const r = {
ok,
status: ok ? 200 : 500,
json: async () => body,
text: async () => JSON.stringify(body),
};
r.clone = () => r;
return r;
};
let originalFetch;
beforeEach(() => {
originalFetch = global.fetch;
});
afterEach(() => {
global.fetch = originalFetch;
});
const failWith = () => {
global.fetch = jest.fn(() => Promise.resolve(response(false, {error: 'boom'})));
};
const succeedWith = (body) => {
global.fetch = jest.fn(() => Promise.resolve(response(true, body)));
};
describe('on a non-OK response, the helper returns undefined', () => {
test.each([
['getConfigBackups', () => getConfigBackups('wrolpi.yaml')],
['getInventoryBackups', () => getInventoryBackups('food')],
['getDownloaders', () => getDownloaders()],
['searchMap', () => searchMap('camp')],
['getMapSearchStatus', () => getMapSearchStatus()],
['flasherSearch', () => flasherSearch(null, null)],
])('%s', async (_name, call) => {
failWith();
expect(await call()).toBeUndefined();
});
});
describe('a confirmed empty result is still empty', () => {
test('getConfigBackups', async () => {
succeedWith({dates: []});
expect(await getConfigBackups('wrolpi.yaml')).toEqual({dates: []});
});
test('getInventoryBackups', async () => {
succeedWith({dates: []});
expect(await getInventoryBackups('food')).toEqual([]);
});
test('getDownloaders', async () => {
succeedWith({downloaders: []});
expect(await getDownloaders()).toEqual({downloaders: []});
});
test('searchMap', async () => {
succeedWith({results: [], total: 0});
expect(await searchMap('camp')).toEqual({results: [], total: 0});
});
test('getMapSearchStatus', async () => {
succeedWith({indexed: [], missing: []});
expect(await getMapSearchStatus()).toEqual({indexed: [], missing: []});
});
test('flasherSearch', async () => {
succeedWith({file_groups: [], totals: {file_groups: 0}});
expect(await flasherSearch(null, null)).toEqual([[], 0]);
});
});

View file

@ -0,0 +1,262 @@
import {ExportCancelled, exportMapPdf} from './api';
const MAP = {
width: 60, height: 90, dpi: 300, title: 'A quadrangle', bounds: [-150, 61.125, -149.875, 61.25],
sheet: {name: 'A quadrangle', credits: [], date: '2026-11-15'},
layers: [{name: 'Background', blob: new Blob(['background'])}, {name: 'Water', blob: new Blob(['water'])}],
};
const reply = (status, body) => ({
ok: status >= 200 && status < 300,
status,
json: () => Promise.resolve(body),
blob: () => Promise.resolve(body),
clone() {
return this;
},
});
// A server whose Job says each of `jobs` in turn, and then the last of them.
function fakeServer(jobs, {pdf = new Blob(['%PDF-']), replies = {}} = {}) {
const calls = [];
let asked = 0;
global.fetch = jest.fn(async (url, init = {}) => {
const path = String(url).replace(/^.*\/api/, '');
const method = init.method || 'GET';
calls.push(`${method} ${path}`);
if (replies[`${method} ${path}`]) return replies[`${method} ${path}`]();
if (path === '/map/export') return reply(201, {export_id: 'abc'});
if (path.startsWith('/map/export/abc/layer/')) return reply(204, null);
if (path === '/map/export/abc/start') return reply(202, {job_id: 'job-1'});
if (path === '/map/export/abc' && method === 'DELETE') return reply(204, null);
if (path === '/jobs/job-1') return reply(200, {job: jobs[Math.min(asked++, jobs.length - 1)]});
if (path === '/map/export/abc/pdf') return reply(200, pdf);
return reply(404, {error: 'Not found'});
});
return calls;
}
describe('exportMapPdf', () => {
afterEach(() => {
delete global.fetch;
});
test('describes the map, sends each layer, watches the Job, and fetches the PDF', async () => {
const pdf = new Blob(['%PDF-']);
const calls = fakeServer([
{status: 'pending'}, {status: 'running', progress: 12.4}, {status: 'running', progress: 75},
{status: 'complete'},
], {pdf});
const statuses = [];
const result = await exportMapPdf(MAP, {onStatus: text => statuses.push(text), pollMs: 0});
expect(result).toBe(pdf);
expect(calls).toEqual([
'POST /map/export',
'POST /map/export/abc/layer/0',
'POST /map/export/abc/layer/1',
'POST /map/export/abc/start',
'GET /jobs/job-1', 'GET /jobs/job-1', 'GET /jobs/job-1', 'GET /jobs/job-1',
'GET /map/export/abc/pdf',
// With the PDF in hand, the server need keep nothing of the export.
'DELETE /map/export/abc',
]);
expect(statuses).toEqual([
'Sending the map…',
'Sending Background (1 of 2)…',
'Sending Water (2 of 2)…',
'Starting the PDF…',
'Making the PDF (12%)…',
'Making the PDF (75%)…',
'Fetching the PDF…',
]);
// The map is described without its images, and each image is sent as it is.
const [, described] = global.fetch.mock.calls[0];
expect(JSON.parse(described.body)).toEqual({
width: 60, height: 90, dpi: 300, title: 'A quadrangle', bounds: MAP.bounds, sheet: MAP.sheet,
layers: ['Background', 'Water'],
});
expect(global.fetch.mock.calls[2][1].body).toBe(MAP.layers[1].blob);
});
test('says it is waiting when another job is in the way', async () => {
fakeServer([...Array(5).fill({status: 'pending'}), {status: 'complete'}]);
const statuses = [];
await exportMapPdf(MAP, {onStatus: text => statuses.push(text), pollMs: 0});
expect(statuses.slice(3)).toEqual([
'Starting the PDF…', 'Starting the PDF…', 'Starting the PDF…',
'Waiting for another job to finish…', 'Waiting for another job to finish…',
'Fetching the PDF…',
]);
});
test('says why the map was refused', async () => {
fakeServer([], {replies: {'POST /map/export': () => reply(400, {error: 'A map of 0x0 pixels can not be exported'})}});
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('A map of 0x0 pixels can not be exported');
});
test('gives the PDF without waiting for the server to remove the export', async () => {
const pdf = new Blob(['%PDF-']);
const calls = fakeServer([{status: 'complete'}], {
// The server never answers.
pdf, replies: {'DELETE /map/export/abc': () => new Promise(() => undefined)},
});
expect(await exportMapPdf(MAP, {pollMs: 0})).toBe(pdf);
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
});
test('has the server remove what was sent when the export fails', async () => {
const calls = fakeServer([{status: 'complete'}], {
replies: {'POST /map/export/abc/layer/1': () => Promise.reject(new Error('network'))},
});
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('Could not reach the server');
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
});
test('says why the Job failed', async () => {
const calls = fakeServer([{status: 'running', progress: 0}, {status: 'failed', error: 'The layer is 10x10'}]);
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('The layer is 10x10');
expect(calls).not.toContain('GET /map/export/abc/pdf');
});
test('stops before anything is sent when it was already cancelled', async () => {
const calls = fakeServer([{status: 'complete'}]);
await expect(exportMapPdf(MAP, {isCancelled: () => true})).rejects.toBeInstanceOf(ExportCancelled);
expect(calls).toEqual([]);
});
test('has the server remove what was sent when it is stopped while layers are sent', async () => {
const calls = fakeServer([{status: 'complete'}]);
// Stopped once the first layer has been sent.
const rejected = exportMapPdf(MAP, {pollMs: 0, isCancelled: () => calls.includes('POST /map/export/abc/layer/0')});
await expect(rejected).rejects.toBeInstanceOf(ExportCancelled);
expect(calls).toEqual(['POST /map/export', 'POST /map/export/abc/layer/0', 'DELETE /map/export/abc']);
});
test('has the server stop the export when it is stopped while the PDF is made', async () => {
const calls = fakeServer([{status: 'running', progress: 10}]);
let polls = 0;
const rejected = exportMapPdf(MAP, {
pollMs: 0,
// Stopped once the Job has been asked about twice.
isCancelled: () => calls.includes('GET /jobs/job-1') && ++polls > 2,
});
await expect(rejected).rejects.toMatchObject({cancelled: true});
// The server cancels the Job of an export which is removed.
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
expect(calls).not.toContain('GET /map/export/abc/pdf');
});
test('is stopped all the same when the server can not be told', async () => {
const calls = fakeServer([{status: 'running', progress: 10}], {
replies: {'DELETE /map/export/abc': () => Promise.reject(new Error('network'))},
});
const rejected = exportMapPdf(MAP, {pollMs: 0, isCancelled: () => calls.includes('GET /jobs/job-1')});
await expect(rejected).rejects.toBeInstanceOf(ExportCancelled);
});
test('is stopped in the middle of a request, which the server may never answer', async () => {
const abort = new AbortController();
let signals = [];
const calls = fakeServer([{status: 'complete'}], {
replies: {
// A layer which is never taken: the request ends when it is stopped, as fetch's does.
'POST /map/export/abc/layer/1': () => new Promise((resolve, reject) => {
signals = global.fetch.mock.calls.map(([, init]) => init?.signal);
abort.signal.addEventListener(
'abort', () => reject(Object.assign(new Error('aborted'), {name: 'AbortError'})));
abort.abort();
}),
},
});
const rejected = exportMapPdf(MAP, {pollMs: 0, signal: abort.signal});
await expect(rejected).rejects.toBeInstanceOf(ExportCancelled);
// Every request of the export could be stopped; the one which removes it can not.
expect(signals).toEqual([abort.signal, abort.signal, abort.signal]);
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
expect(global.fetch.mock.calls.at(-1)[1].signal).toBeUndefined();
});
test.each([
['the Job is asked after', 'GET /jobs/job-1'],
['the PDF is fetched', 'GET /map/export/abc/pdf'],
])('is stopped in the middle of a request while %s', async (_, request) => {
const abort = new AbortController();
const calls = fakeServer([{status: 'complete'}], {
replies: {
[request]: () => new Promise((resolve, reject) => {
abort.signal.addEventListener(
'abort', () => reject(Object.assign(new Error('aborted'), {name: 'AbortError'})));
abort.abort();
}),
},
});
await expect(exportMapPdf(MAP, {pollMs: 0, signal: abort.signal})).rejects.toBeInstanceOf(ExportCancelled);
// Every request up to the one which was stopped, and that one, could be stopped.
const stoppable = global.fetch.mock.calls.slice(0, -1).map(([, init]) => init?.signal);
expect(stoppable).toHaveLength(calls.indexOf(request) + 1);
expect(stoppable.every(signal => signal === abort.signal)).toBe(true);
// It is not asked again once it is stopped; the server is only told to remove the export.
expect(calls.filter(call => call === request)).toHaveLength(1);
expect(calls.at(-1)).toBe('DELETE /map/export/abc');
});
test('a Job which someone else cancelled is a cancelled export', async () => {
fakeServer([{status: 'cancelled'}]);
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toBeInstanceOf(ExportCancelled);
});
test('keeps asking when the server does not answer for a moment', async () => {
let failures = 3;
const calls = fakeServer([{status: 'complete'}], {
replies: {
'GET /jobs/job-1': () => {
if (failures-- > 0) return Promise.reject(new Error('network'));
return reply(200, {job: {status: 'complete'}});
},
},
});
await exportMapPdf(MAP, {pollMs: 0});
expect(calls.filter(i => i === 'GET /jobs/job-1')).toHaveLength(4);
});
test('asks for the PDF again when the request is lost, and not when it is refused', async () => {
const pdf = new Blob(['%PDF-']);
let lost = 3;
let calls = fakeServer([{status: 'complete'}], {
replies: {
'GET /map/export/abc/pdf': () => {
if (lost === 3) { lost--; return Promise.reject(new Error('network')); }
if (lost-- > 0) return reply(502, {error: 'Bad gateway'});
return reply(200, pdf);
},
},
});
expect(await exportMapPdf(MAP, {pollMs: 0})).toBe(pdf);
expect(calls.filter(i => i === 'GET /map/export/abc/pdf')).toHaveLength(4);
// The map was drawn, sent and made into a PDF once.
expect(calls.filter(i => i === 'POST /map/export/abc/start')).toHaveLength(1);
calls = fakeServer([{status: 'complete'}], {
replies: {'GET /map/export/abc/pdf': () => reply(409, {error: 'The PDF is gone'})},
});
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('The PDF is gone');
expect(calls.filter(i => i === 'GET /map/export/abc/pdf')).toHaveLength(1);
calls = fakeServer([{status: 'complete'}], {
replies: {'GET /map/export/abc/pdf': () => Promise.reject(new Error('network'))},
});
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('Could not fetch the PDF');
expect(calls.filter(i => i === 'GET /map/export/abc/pdf')).toHaveLength(10);
});
test('gives up when the server stops answering, or has forgotten the Job', async () => {
fakeServer([], {replies: {'GET /jobs/job-1': () => Promise.reject(new Error('network'))}});
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('Could not reach the server');
expect(global.fetch.mock.calls.filter(([url]) => String(url).endsWith('/jobs/job-1'))).toHaveLength(10);
fakeServer([], {replies: {'GET /jobs/job-1': () => reply(404, {error: 'unknown'})}});
await expect(exportMapPdf(MAP, {pollMs: 0})).rejects.toThrow('The server forgot the export');
});
});

View file

@ -0,0 +1,32 @@
import {getSettings} from './api';
import {settingsFixture} from './test-fixtures';
describe('getSettings', () => {
afterEach(() => {
delete global.fetch;
});
it('keeps every setting the API sends', async () => {
// getSettings copies each field by name, so a field the API added but nobody listed here vanished
// silently (the Sync tab showed no backup drive while one was configured).
const sent = settingsFixture({
backup_directory: '/media/wrolpi_backup', backup_device_uuid: 'uuid-backup',
role: 'secondary', sync_primary_url: 'https://10.0.0.5', sync_window_start: '01:00',
sync_window_end: '05:00',
});
global.fetch = jest.fn(() => Promise.resolve({
ok: true, status: 200,
json: () => Promise.resolve(sent),
clone() {
return this;
},
}));
const settings = await getSettings();
const dropped = Object.keys(sent).filter(key => !(key in settings));
expect(dropped).toEqual([]);
expect(settings.backup_directory).toBe('/media/wrolpi_backup');
expect(settings.backup_device_uuid).toBe('uuid-backup');
});
});

View file

@ -7,6 +7,7 @@ import {
COLLECTIONS_API, COLLECTIONS_API,
DEFAULT_LIMIT, DEFAULT_LIMIT,
Downloaders, Downloaders,
REPOS_API,
VIDEOS_API, VIDEOS_API,
ZIM_API ZIM_API
} from "./components/Vars"; } from "./components/Vars";
@ -57,8 +58,8 @@ async function apiCall(url, method, body, ms = 60_000) {
// Request encountered an error. // Request encountered an error.
let copy = response.clone(); let copy = response.clone();
const content = await copy.json(); const content = await copy.json();
console.error('API error response json', content);
const code = content['code']; const code = content['code'];
console.error('API error response json', content);
if (response.status === 403 && code === 'WROL_MODE_ENABLED') { if (response.status === 403 && code === 'WROL_MODE_ENABLED') {
toast({ toast({
type: 'error', type: 'error',
@ -187,7 +188,7 @@ export async function tagChannelInfo(channelId, tagName) {
}); });
} }
export async function searchVideos(offset, limit, channelId, searchStr, order_by, tagNames, headline, censored, deep) { export async function searchVideos(offset, limit, channelId, searchStr, order_by, tagNames, headline, censored, deep, anyTag) {
// Build a search query to retrieve a list of videos from the API // Build a search query to retrieve a list of videos from the API
offset = parseInt(offset || 0); offset = parseInt(offset || 0);
limit = parseInt(limit || DEFAULT_LIMIT); limit = parseInt(limit || DEFAULT_LIMIT);
@ -211,6 +212,9 @@ export async function searchVideos(offset, limit, channelId, searchStr, order_by
if (deep) { if (deep) {
body['deep'] = true; body['deep'] = true;
} }
if (anyTag) {
body['any_tag'] = true;
}
console.debug('searching videos', body); console.debug('searching videos', body);
@ -383,6 +387,12 @@ export async function getSettings() {
const content = await response.json(); const content = await response.json();
return { return {
archive_destination: content.archive_destination, archive_destination: content.archive_destination,
backup_delete_after_days: content.backup_delete_after_days,
backup_device_uuid: content.backup_device_uuid,
backup_directory: content.backup_directory,
backup_excluded_directories: content.backup_excluded_directories,
backup_window_end: content.backup_window_end,
backup_window_start: content.backup_window_start,
download_manager_disabled: content.download_manager_disabled, download_manager_disabled: content.download_manager_disabled,
download_manager_stopped: content.download_manager_stopped, download_manager_stopped: content.download_manager_stopped,
download_daily_limit_global: content.download_daily_limit_global, download_daily_limit_global: content.download_daily_limit_global,
@ -406,13 +416,21 @@ export async function getSettings() {
nav_color: content.nav_color, nav_color: content.nav_color,
media_directory: content.media_directory, media_directory: content.media_directory,
playlists_destination: content.playlists_destination, playlists_destination: content.playlists_destination,
repos_destination: content.repos_destination,
require_cookies_unlocked: content.require_cookies_unlocked, require_cookies_unlocked: content.require_cookies_unlocked,
require_media_mounted: content.require_media_mounted, require_media_mounted: content.require_media_mounted,
role: content.role,
save_ffprobe_json: content.save_ffprobe_json, save_ffprobe_json: content.save_ffprobe_json,
sync_delete_after_days: content.sync_delete_after_days,
sync_excluded_directories: content.sync_excluded_directories,
sync_primary_url: content.sync_primary_url,
sync_window_end: content.sync_window_end,
sync_window_start: content.sync_window_start,
tags_directory: content.tags_directory, tags_directory: content.tags_directory,
throttle_on_startup: content.throttle_on_startup, throttle_on_startup: content.throttle_on_startup,
throttle_status: content.throttle_status, throttle_status: content.throttle_status,
timezone: content.timezone, timezone: content.timezone,
version: content.version,
videos_destination: content.videos_destination, videos_destination: content.videos_destination,
wrol_mode: content.wrol_mode, wrol_mode: content.wrol_mode,
zims_destination: content.zims_destination, zims_destination: content.zims_destination,
@ -428,6 +446,57 @@ export async function getSettings() {
} }
} }
// Sync: a secondary WROLPi copies its library from its primary.
export async function saveSyncSettings(settings) {
const response = await apiPut(`${API_URI}/sync/settings`, settings);
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not save sync settings.');
toast({type: 'error', title: 'Saving Sync Settings Failed', description: message, time: 5000});
}
return response;
}
export class PrimaryUnreachableError extends Error {
}
/** The folders directly inside `path`; `source` is 'local' (this WROLPi) or 'primary' (its primary). */
export async function getSyncDirectories(path, source) {
const response = await apiPost(`${API_URI}/sync/directories`, {path: path || '', source});
if (response.ok) {
const {directories} = await response.json();
return directories;
}
if (response.status === 502) {
const {error} = await response.json();
throw new PrimaryUnreachableError(error || 'The primary did not answer');
}
const message = await getErrorMessage(response, 'Could not list the folders.');
throw new Error(message);
}
export async function runBackup() {
const response = await apiPost(`${API_URI}/sync/backup/run`);
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not start the backup.');
toast({type: 'error', title: 'Backup Failed', description: message, time: 5000});
}
return response;
}
export async function cancelBackup() {
return await apiPost(`${API_URI}/sync/backup/cancel`);
}
export async function testSync() {
const response = await apiGet(`${API_URI}/sync/test`);
if (response.ok) {
return await response.json();
}
const message = await getErrorMessage(response, 'Could not reach the primary.');
return {ok: false, error: message};
}
export async function saveSettings(settings) { export async function saveSettings(settings) {
const response = await apiPatch(`${API_URI}/settings`, settings); const response = await apiPatch(`${API_URI}/settings`, settings);
if (!response.ok) { if (!response.ok) {
@ -522,7 +591,7 @@ export async function getConfigBackups(fileName) {
if (response.ok) { if (response.ok) {
return await response.json(); return await response.json();
} }
return {dates: []}; // Undefined, not {dates: []}, so the modal can tell a failed fetch from having no backups.
} }
export async function postConfigBackupPreview(fileName, backupDate, mode) { export async function postConfigBackupPreview(fileName, backupDate, mode) {
@ -720,7 +789,7 @@ export async function getInventoryBackups(slug) {
if (response.ok) { if (response.ok) {
return (await response.json())['dates']; return (await response.json())['dates'];
} }
return []; // Undefined, not [], so the modal can tell a failed fetch from having no backups.
} }
export async function postInventoryRestorePreview(slug, backupDate, mode) { export async function postInventoryRestorePreview(slug, backupDate, mode) {
@ -767,7 +836,7 @@ export async function saveCatalog(items) {
} }
export async function searchArchives(offset, limit, domain, searchStr, order, tagNames, headline, deep) { export async function searchArchives(offset, limit, domain, searchStr, order, tagNames, headline, deep, anyTag) {
// Build a search query to retrieve a list of videos from the API // Build a search query to retrieve a list of videos from the API
offset = parseInt(offset || 0); offset = parseInt(offset || 0);
limit = parseInt(limit || DEFAULT_LIMIT); limit = parseInt(limit || DEFAULT_LIMIT);
@ -790,6 +859,9 @@ export async function searchArchives(offset, limit, domain, searchStr, order, ta
if (deep) { if (deep) {
body['deep'] = true; body['deep'] = true;
} }
if (anyTag) {
body['any_tag'] = true;
}
console.debug('searching archives', body); console.debug('searching archives', body);
const response = await apiPost(`${ARCHIVES_API}/search`, body); const response = await apiPost(`${ARCHIVES_API}/search`, body);
@ -927,6 +999,21 @@ export async function getCollectionTagInfo(collectionId, tagName) {
} }
} }
// Tag any Collection (and optionally move its directory).
export async function tagCollection(collectionId, tagName, directory) {
const body = {tag_name: tagName};
if (directory) {
body['directory'] = directory;
}
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/tag`, body);
if (response.ok) {
return await response.json();
}
const message = await getErrorMessage(response, 'Unable to tag. See server logs.');
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
throw new Error(message);
}
export async function tagDomain(domainId, tagName, directory) { export async function tagDomain(domainId, tagName, directory) {
const body = { const body = {
tag_name: tagName, tag_name: tagName,
@ -1259,12 +1346,15 @@ export async function startDownloads() {
} }
export async function getDownloaders() { export async function getDownloaders() {
// Not toasting because this will happen often. Undefined on any failure, not an empty list, so
// the form can say the downloaders could not be fetched.
try { try {
const response = await apiGet(`${API_URI}/downloaders`); const response = await apiGet(`${API_URI}/downloaders`);
// Not toasting because this will happen often. if (response.ok) {
return await response.json(); return await response.json();
}
} catch (e) { } catch (e) {
return {downloaders: []}; // The API is down; reported as undefined below.
} }
} }
@ -1285,7 +1375,7 @@ export async function deleteDownload(downloadId) {
} }
} }
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order, suffix, path, deep) { export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order, suffix, path, deep, inProgress) {
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit), any_tag: anyTag}; const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit), any_tag: anyTag};
if (suffix) { if (suffix) {
body['suffix'] = suffix; body['suffix'] = suffix;
@ -1320,6 +1410,9 @@ export async function filesSearch(offset, limit, searchStr, mimetypes, model, ta
if (deep) { if (deep) {
body['deep'] = true; body['deep'] = true;
} }
if (inProgress) {
body['in_progress'] = true;
}
console.info('searching files', body); console.info('searching files', body);
const response = await apiPost(`${API_URI}/files/search`, body); const response = await apiPost(`${API_URI}/files/search`, body);
@ -1351,7 +1444,7 @@ export async function flasherSearch(chip, path) {
} }
const message = await getErrorMessage(response, 'Cannot search firmware. See server logs.'); const message = await getErrorMessage(response, 'Cannot search firmware. See server logs.');
toast({type: 'error', title: 'Unable to search firmware', description: message, time: 5000}); toast({type: 'error', title: 'Unable to search firmware', description: message, time: 5000});
return [null, null]; // Undefined, not [null, null], so the picker can tell a failed search from finding nothing.
} }
export async function getFlasherConfigs() { export async function getFlasherConfigs() {
@ -1361,7 +1454,9 @@ export async function getFlasherConfigs() {
const data = await response.json(); const data = await response.json();
return data['configurations'] || []; return data['configurations'] || [];
} }
return []; // Undefined, not [], so the page can tell a failed fetch from an empty list.
const message = await getErrorMessage(response, 'Could not get saved firmware configurations');
toast({type: 'error', title: 'Flasher Error', description: message, time: 5000});
} }
export async function saveFlasherConfig(name, files, eraseAll) { export async function saveFlasherConfig(name, files, eraseAll) {
@ -1565,14 +1660,28 @@ export async function getMapFiles() {
} }
} }
export async function deleteMapFile(filename) { // A map file is named by its path within the map directory; it may be in a sub-directory.
const response = await apiDelete(`${API_URI}/map/files/${encodeURIComponent(filename)}`); function encodeMapPath(mapPath) {
return String(mapPath).split('/').map(encodeURIComponent).join('/');
}
export async function deleteMapFile(mapPath) {
const response = await apiDelete(`${API_URI}/map/files/${encodeMapPath(mapPath)}`);
if (!response.ok) { if (!response.ok) {
const message = await getErrorMessage(response, 'Could not delete map file'); const message = await getErrorMessage(response, 'Could not delete map file');
toast({type: 'error', title: 'Map Error', description: message, time: 5000}); toast({type: 'error', title: 'Map Error', description: message, time: 5000});
} }
} }
// Show a map file on the map, or ignore it.
export async function setMapFileVisible(mapPath, visible) {
const response = await apiPost(`${API_URI}/map/files/visible`, {map_path: mapPath, visible});
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not change the map file');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
}
}
export async function fetchMapSubscriptions() { export async function fetchMapSubscriptions() {
const response = await apiGet(`${API_URI}/map/subscribe`); const response = await apiGet(`${API_URI}/map/subscribe`);
if (response.ok) { if (response.ok) {
@ -1603,6 +1712,88 @@ export async function mapUnsubscribe(region) {
} }
} }
// Which months of the fallout climatology are kept: {version, months, missing, published}, or null.
export async function getFalloutClimatology() {
const response = await apiGet(`${API_URI}/map/fallout/climatology`);
return response.ok ? await response.json() : null;
}
// One month of the fallout climatology, as kept (gzip bytes), or null.
export async function getFalloutClimatologyMonth(month) {
const response = await apiGet(`${API_URI}/map/fallout/climatology/${month}`);
return response.ok ? await response.arrayBuffer() : null;
}
// The field of forecast winds aloft fetched most recently (the fallout simulator), or null.
export async function getLatestFalloutWinds() {
const response = await apiGet(`${API_URI}/map/fallout/winds/latest`);
if (response.ok) {
return (await response.json()).winds;
}
return null;
}
// The saved nuclear targets ([{id, lat, lon, label, created, weapon, yield_kt?, fission_fraction?}]), or
// undefined when they could not be fetched.
export async function getMapTargets() {
const response = await apiGet(`${API_URI}/map/nuclear/targets`);
if (response.ok) {
return (await response.json()).targets;
}
}
export async function deleteMapTarget(targetId) {
const response = await apiDelete(`${API_URI}/map/nuclear/targets/${targetId}`);
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not delete the target');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
}
return response.ok;
}
// Save `targets` ([{lat, lon, label, weapon, yield_kt?, fission_fraction?, id?}]) in place of the
// saved targets, which are those of `loadedIds` (refused if they are not): the saved targets, or null.
export async function saveMapTargets(targets, loadedIds) {
const response = await apiPut(`${API_URI}/map/nuclear/targets`, {targets, loaded_ids: loadedIds});
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not save the targets');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
return null;
}
return (await response.json()).targets;
}
// The weather subscription (a forecast around the nuclear targets, downloaded every day): {enabled,
// download, targets, spacing, points, seconds, field}, or undefined when it could not be fetched.
export async function getWeather() {
const response = await apiGet(`${API_URI}/map/weather`);
if (response.ok) {
return await response.json();
}
}
// Subscribe to the weather, or not: the subscription as it is then, or null.
export async function setWeatherSubscription(enabled) {
const response = await apiPut(`${API_URI}/map/weather`, {enabled});
if (response.ok) {
return await response.json();
}
const message = await getErrorMessage(response, 'Could not change the weather download');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
return null;
}
// Download the weather now, rather than when it is next due: the subscription as it is then, or null.
export async function downloadWeatherNow() {
const response = await apiPost(`${API_URI}/map/weather/download`);
if (response.ok) {
return await response.json();
}
const message = await getErrorMessage(response, 'Could not download the weather');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
return null;
}
export async function getMapPins() { export async function getMapPins() {
const response = await apiGet(`${API_URI}/map/pins`); const response = await apiGet(`${API_URI}/map/pins`);
if (response.ok) { if (response.ok) {
@ -1649,6 +1840,158 @@ export async function setMapDefaultLocation(lat, lon, zoom) {
} }
} }
// Make a PDF of a map from the images of its layers ({name, blob}, from the bottom up). Returns the
// PDF (a Blob); throws an Error which says what went wrong.
// `bounds` is the west, south, east and north edges of the images, in degrees.
// What exportMapPdf throws when the person exporting stopped it: not a failure to be told of.
export class ExportCancelled extends Error {
constructor() {
super('The export was cancelled');
this.name = 'ExportCancelled';
this.cancelled = true;
}
}
// How many times in a row the server may not answer, while the PDF of an export is made or fetched,
// before the export is given up on: the API is busy while it makes a PDF, and a Raspberry Pi more so.
const EXPORT_POLL_FAILURES = 10;
// Make the PDF of a map from the images of its layers (see modules/map/export_job.py). The PDF is a
// minute or two of work on a Raspberry Pi, so it is a Job: the map is described, the image of each
// layer is sent, the Job is started and watched, and the PDF is fetched when the Job is done.
//
// onStatus(text): told how far along it is. isCancelled(): asked, between steps, whether to stop;
// signal: an AbortSignal which stops it at once, in the middle of a request (an image of a layer
// is tens of megabytes, and a request to a server which has stopped answering never ends);
// the server is then told to stop the export and remove what was sent. Rejects with
// ExportCancelled when it was stopped.
//
// However it ends, the server is told to remove what it has of the export: the images are a hundred
// megabytes and the PDF tens, on a disk which may be an SD card.
export async function exportMapPdf(
{width, height, dpi, title, bounds, layers, sheet},
{onStatus = () => undefined, isCancelled = () => false, signal = undefined, pollMs = 1000} = {},
) {
const exports = `${API_URI}/map/export`;
let exportId = null;
// Best effort: the server removes old exports itself, later. An export which is stopped while
// it is being described has no id yet to remove it by: what the server made of it is one small
// file, which it removes with the old ones.
const remove = async () => {
if (exportId) await fetch(`${exports}/${exportId}`, {method: 'DELETE'}).catch(() => undefined);
};
try {
return await sendAndFetch();
} catch (e) {
// A request which was stopped because the export was is not a failure to be told of.
throw signal?.aborted ? new ExportCancelled() : e;
} finally {
// Not waited for: a server which is slow to answer is not to keep a PDF from who made it.
remove();
}
async function sendAndFetch() {
const send = async (url, init, fallback) => {
let response;
try {
response = await fetch(url, {...init, signal});
} catch (e) {
throw new Error('Could not reach the server');
}
if (!response.ok) throw new Error(await getErrorMessage(response, fallback));
return response;
};
const pause = () => new Promise(resolve => setTimeout(resolve, pollMs));
// Stopped by the person exporting: removing the export cancels its Job.
const stopIfCancelled = async () => {
if (isCancelled() || signal?.aborted) throw new ExportCancelled();
};
await stopIfCancelled();
onStatus('Sending the map…');
const created = await send(exports, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({width, height, dpi, title, bounds, sheet, layers: layers.map(i => i.name)}),
}, 'Could not export the map');
exportId = (await created.json()).export_id;
// One layer a request: together they are more than a request may be, and more than a slow
// connection sends in the time a request is given.
for (const [index, layer] of layers.entries()) {
await stopIfCancelled();
onStatus(`Sending ${layer.name} (${index + 1} of ${layers.length})…`);
await send(`${exports}/${exportId}/layer/${index}`, {method: 'POST', body: layer.blob},
`Could not send ${layer.name}`);
}
await stopIfCancelled();
const started = await send(`${exports}/${exportId}/start`, {method: 'POST'}, 'Could not make the PDF');
const {job_id: jobId} = await started.json();
let failures = 0;
let waited = 0;
while (true) {
await stopIfCancelled();
let job;
try {
const response = await fetch(`${API_URI}/jobs/${jobId}`, {signal});
if (response.status === 404) throw Object.assign(new Error('The server forgot the export'), {final: true});
if (!response.ok) throw new Error('Could not ask how the PDF is coming');
job = (await response.json()).job;
failures = 0;
} catch (e) {
if (e.final || ++failures >= EXPORT_POLL_FAILURES) {
throw e.final ? e : new Error('Could not reach the server');
}
}
if (job?.status === 'complete') break;
if (job?.status === 'failed') throw new Error(job.error || 'The PDF could not be made');
if (job?.status === 'cancelled') throw new ExportCancelled();
if (job?.status === 'pending') {
// A Job is taken up within a moment, unless another (a video being transcoded) is in its way.
onStatus(++waited > 3 ? 'Waiting for another job to finish…' : 'Starting the PDF…');
} else if (job) {
onStatus(`Making the PDF (${Math.round(job.progress || 0)}%)…`);
}
await pause();
}
// The PDF is made, and kept for an hour. A request which is lost now is asked again: not to be
// the reason all of it is done again.
onStatus('Fetching the PDF…');
for (failures = 0; ; ) {
await stopIfCancelled();
let response;
try {
response = await fetch(`${exports}/${exportId}/pdf`, {signal});
} catch (e) {
response = null;
}
if (response?.ok) return await response.blob();
// What the server refuses, it will refuse again.
if (response && response.status < 500) {
throw new Error(await getErrorMessage(response, 'Could not fetch the PDF'));
}
if (++failures >= EXPORT_POLL_FAILURES) throw new Error('Could not fetch the PDF');
await pause();
}
}
}
// What the USGS calls a quadrangle: {name, state, exact}, or null where it has no name (most of the
// world), and when it can not be asked. A map is exported without its name as well as with it.
export async function getMapQuadName({west, south, east, north}) {
try {
const response = await apiGet(
`${API_URI}/map/quad?west=${west}&south=${south}&east=${east}&north=${north}`);
if (!response.ok) return null;
return (await response.json()).quad || null;
} catch (e) {
return null;
}
}
export async function searchMap(query, limit = 12, offset = 0, lat = null, lon = null) { export async function searchMap(query, limit = 12, offset = 0, lat = null, lon = null) {
let url = `${API_URI}/map/search?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}`; let url = `${API_URI}/map/search?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}`;
if (lat !== null && lon !== null) { if (lat !== null && lon !== null) {
@ -1656,7 +1999,8 @@ export async function searchMap(query, limit = 12, offset = 0, lat = null, lon =
} }
const response = await apiGet(url); const response = await apiGet(url);
if (!response.ok) { if (!response.ok) {
return {results: [], total: 0}; // Undefined, not {results: []}, so a failed search is not shown as finding nothing.
return undefined;
} }
return await response.json(); return await response.json();
} }
@ -1664,7 +2008,8 @@ export async function searchMap(query, limit = 12, offset = 0, lat = null, lon =
export async function getMapSearchStatus() { export async function getMapSearchStatus() {
const response = await apiGet(`${API_URI}/map/search/status`); const response = await apiGet(`${API_URI}/map/search/status`);
if (!response.ok) { if (!response.ok) {
return {indexed: [], missing: []}; // Undefined, not {indexed: [], missing: []}, which read as "no maps are installed".
return undefined;
} }
return await response.json(); return await response.json();
} }
@ -1677,8 +2022,8 @@ export async function searchEstimateMap(search_str) {
return {mapPlaces: data.map_places || 0}; return {mapPlaces: data.map_places || 0};
} }
export async function rebuildMapSearchIndex(filename) { export async function rebuildMapSearchIndex(mapPath) {
const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeURIComponent(filename)}`); const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeMapPath(mapPath)}`);
if (!response.ok) { if (!response.ok) {
const message = await getErrorMessage(response, 'Could not rebuild search index'); const message = await getErrorMessage(response, 'Could not rebuild search index');
toast({type: 'error', title: 'Map Error', description: message, time: 5000}); toast({type: 'error', title: 'Map Error', description: message, time: 5000});
@ -1900,13 +2245,31 @@ export async function searchDirectories(path) {
} }
} }
/**
* Returns the file worker job id of a queued rename (a directory), or null when the rename is already done.
*/
export async function renamePath(path, newName) { export async function renamePath(path, newName) {
const body = {path, new_name: newName}; const body = {path, new_name: newName};
const response = await apiPost(`${API_URI}/files/rename`, body); const response = await apiPost(`${API_URI}/files/rename`, body);
if (!response.ok) { if (!response.ok) {
const message = await getErrorMessage(response, 'Failed to rename!'); const message = await getErrorMessage(response, 'Failed to rename!');
toast({type: 'error', title: 'Error', description: message, time: 5000}); toast({type: 'error', title: 'Error', description: message, time: 5000});
return null;
} }
const json = await response.json();
return json['job_id'] || null;
}
/**
* Returns a file worker job's status ('pending', 'complete', or 'failed'), or null if it is unknown.
*/
export async function fetchFileWorkerJobStatus(jobId) {
const response = await apiGet(`${API_URI}/files/jobs/${encodeURIComponent(jobId)}`);
if (!response.ok) {
return null;
}
const json = await response.json();
return json['status'];
} }
export async function movePaths(destination, paths) { export async function movePaths(destination, paths) {
@ -2044,6 +2407,7 @@ export async function searchSuggestions(search_str) {
domains: content.domains, domains: content.domains,
authors: content.authors || [], authors: content.authors || [],
subjects: content.subjects || [], subjects: content.subjects || [],
repos: content.repos || [],
} }
} else { } else {
console.error('Failed to get file search suggestions!'); console.error('Failed to get file search suggestions!');
@ -2082,8 +2446,8 @@ export async function searchEstimateZims(search_str, tagNames) {
} }
} }
export async function searchEstimateOthers(tagNames) { export async function searchEstimateOthers(tagNames, searchStr) {
const body = {tag_names: tagNames}; const body = {tag_names: tagNames, search_str: searchStr || null};
const response = await apiPost(`${API_URI}/search_other_estimates`, body); const response = await apiPost(`${API_URI}/search_other_estimates`, body);
if (response.ok) { if (response.ok) {
const content = await response.json(); const content = await response.json();
@ -2093,8 +2457,8 @@ export async function searchEstimateOthers(tagNames) {
} }
} }
export async function searchChannels(tagNames) { export async function searchChannels(tagNames, searchStr) {
const body = {tag_names: tagNames}; const body = {tag_names: tagNames, search_str: searchStr};
const response = await apiPost(`${API_URI}/videos/channels/search`, body); const response = await apiPost(`${API_URI}/videos/channels/search`, body);
if (response.ok) { if (response.ok) {
const content = await response.json(); const content = await response.json();
@ -2104,6 +2468,16 @@ export async function searchChannels(tagNames) {
} }
} }
// Collections of `kind` whose name matches `searchStr` and/or which have any of the tags.
export async function searchCollections(kind, tagNames, searchStr) {
const body = {kind, tag_names: tagNames, search_str: searchStr};
const response = await apiPost(`${COLLECTIONS_API}/search`, body);
if (response.ok) {
const content = await response.json();
return {collections: content.collections};
}
}
export async function getOutdatedZims() { export async function getOutdatedZims() {
const response = await apiGet(`${API_URI}/zim/outdated`); const response = await apiGet(`${API_URI}/zim/outdated`);
if (response.status === 200) { if (response.status === 200) {
@ -2170,8 +2544,10 @@ export async function checkUpgrade(force = false) {
return null; return null;
} }
export async function triggerUpgrade() { // `branch` upgrades from that branch; without it the current branch is upgraded.
const response = await apiPost(`${API_URI}/upgrade/start`); export async function triggerUpgrade(branch = null) {
const body = branch ? {branch} : undefined;
const response = await apiPost(`${API_URI}/upgrade/start`, body);
if (!response.ok) { if (!response.ok) {
const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.'); const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.');
toast({ toast({
@ -2297,7 +2673,7 @@ export async function getDoc(fileGroupId) {
} }
export async function searchDocs(offset, limit, searchStr, order, tagNames, author, subject, mimetype, deep) { export async function searchDocs(offset, limit, searchStr, order, tagNames, author, subject, mimetype, deep, anyTag) {
offset = parseInt(offset || 0); offset = parseInt(offset || 0);
limit = parseInt(limit || DEFAULT_LIMIT); limit = parseInt(limit || DEFAULT_LIMIT);
let body = {offset, limit}; let body = {offset, limit};
@ -2322,6 +2698,9 @@ export async function searchDocs(offset, limit, searchStr, order, tagNames, auth
if (deep) { if (deep) {
body['deep'] = true; body['deep'] = true;
} }
if (anyTag) {
body['any_tag'] = true;
}
console.debug('searching docs', body); console.debug('searching docs', body);
const response = await apiPost(`${DOCS_API}/search`, body); const response = await apiPost(`${DOCS_API}/search`, body);
@ -2438,3 +2817,215 @@ export async function setPlaylistTag(playlistId, tagName, directory) {
toast({type: 'error', title: 'Error', description: message, time: 5000}); toast({type: 'error', title: 'Error', description: message, time: 5000});
throw Error(message); throw Error(message);
} }
// Bookmarks: a tree of nodes, a node with `children` being a directory.
export async function getBookmarks() {
const response = await apiGet(`${API_URI}/bookmarks`);
if (response.ok) {
return (await response.json())['bookmarks'];
}
throw new Error('Could not fetch bookmarks');
}
async function bookmarksModify(request, fallbackMessage) {
const response = await request;
if (response.ok) {
return response.status === 204 ? null : await response.json();
}
const message = await getErrorMessage(response, fallbackMessage);
toast({type: 'error', title: 'Bookmarks Error', description: message, time: 5000});
throw new Error(message);
}
export async function addBookmark({name, url, new_tab = false, parent_id = null, position = null}) {
const body = {name, url, new_tab, parent_id, position};
return await bookmarksModify(apiPost(`${API_URI}/bookmarks`, body), 'Could not add bookmark');
}
export async function addBookmarkDirectory({name, parent_id = null, position = null}) {
const body = {name, parent_id, position};
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/directory`, body), 'Could not add directory');
}
export async function updateBookmark(nodeId, {name, url, new_tab}) {
const body = {name, url, new_tab};
return await bookmarksModify(apiPut(`${API_URI}/bookmarks/${nodeId}`, body), 'Could not update bookmark');
}
export async function moveBookmark(nodeId, parent_id, position = null) {
const body = {parent_id, position};
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/${nodeId}/move`, body), 'Could not move bookmark');
}
export async function deleteBookmark(nodeId) {
return await bookmarksModify(apiDelete(`${API_URI}/bookmarks/${nodeId}`), 'Could not delete bookmark');
}
async function reposError(response, fallbackMessage) {
const message = await getErrorMessage(response, fallbackMessage);
toast({type: 'error', title: 'Repos Error', description: message, time: 5000});
throw Error(message);
}
export async function fetchRepos() {
const response = await apiGet(REPOS_API);
if (response.ok) {
return (await response.json())['repos'];
}
await reposError(response, 'Failed to fetch repos.');
}
export async function getRepo(repoId) {
const response = await apiGet(`${REPOS_API}/${repoId}`);
if (response.ok) {
return (await response.json())['repo'];
}
await reposError(response, 'Failed to fetch repo.');
}
// `repo`: {url, directory?, name?, tag_name?, frequency?, mode?, branch?, description?}
export async function createRepo(repo) {
const response = await apiPost(REPOS_API, repo);
if (response.ok) {
return (await response.json())['repo'];
}
await reposError(response, 'Failed to add repo.');
}
// `changes`: {description?, frequency?, mode?, branch?}. An empty branch follows the remote's default branch.
export async function updateRepo(repoId, changes) {
const response = await apiPut(`${REPOS_API}/${repoId}`, changes);
if (response.ok) {
return (await response.json())['repo'];
}
await reposError(response, 'Failed to update repo.');
}
export async function deleteRepo(repoId, deleteFiles = false) {
const response = await apiDelete(`${REPOS_API}/${repoId}?delete_files=${deleteFiles ? 'true' : 'false'}`);
if (!response.ok) {
await reposError(response, 'Failed to delete repo.');
}
}
// Download the repo's updates now.
export async function updateRepoNow(repoId) {
const response = await apiPost(`${REPOS_API}/${repoId}/update`);
if (!response.ok) {
await reposError(response, 'Failed to start the repo update.');
}
}
// One directory of a repo's files: {path, entries: [{name, path, is_dir, size}], readme_path}.
export async function getRepoTree(repoId, path) {
const query = path ? `?path=${encodeURIComponent(path)}` : '';
const response = await apiGet(`${REPOS_API}/${repoId}/tree${query}`);
if (response.ok) {
return await response.json();
}
await reposError(response, 'Failed to list the repo files.');
}
// Repos matching the search (name and README) and/or the tags. Each has an escaped `readme_headline`.
export async function searchRepos(searchStr, tagNames) {
const body = {search_str: searchStr || null, tag_names: tagNames || []};
const response = await apiPost(`${REPOS_API}/search`, body);
if (response.ok) {
const content = await response.json();
return {repos: content.repos, total: content.totals.repos};
}
await reposError(response, 'Failed to search repos.');
}
// The commits of a repo's checked out branch, newest first: {commits: [{sha, author, date, message}], total}.
export async function getRepoLog(repoId, offset = 0, limit = 50) {
const response = await apiGet(`${REPOS_API}/${repoId}/log?limit=${limit}&offset=${offset}`);
if (response.ok) {
return await response.json();
}
await reposError(response, 'Failed to fetch the repo history.');
}
// A ZIP of a repo's checked out files; the browser downloads it.
export function repoArchiveURL(repoId) {
return `${REPOS_API}/${repoId}/archive.zip`;
}
// What importing the git clone in `directory` (relative to the media directory) would do. Changes nothing.
export async function inspectRepoImport(directory, name, tagName, url) {
const body = {directory, name: name || null, tag_name: tagName || null, url: url || null};
const response = await apiPost(`${REPOS_API}/import/inspect`, body);
if (response.ok) {
return {inspection: (await response.json())['inspection']};
}
return {error: await getErrorMessage(response, 'Cannot import this directory.')};
}
// Import an existing git clone as a Repo; it stays where it is. `repo`: {directory, confirm, url?, name?, ...}
export async function importRepo(repo) {
const response = await apiPost(`${REPOS_API}/import`, repo);
if (response.ok) {
return (await response.json())['repo'];
}
await reposError(response, 'Failed to import the repo.');
}
// --- Torrents (they reach the Internet only through the VPN) ---
const TORRENTS_API = `${API_URI}/torrents`;
async function torrentsRequest(response, fallbackMessage) {
if (!response.ok) {
throw new Error(await getErrorMessage(response, fallbackMessage));
}
return response.status === 204 ? null : response;
}
export async function getTorrents() {
const response = await torrentsRequest(await apiGet(`${TORRENTS_API}/`), 'Failed to get torrents');
return await response.json();
}
export async function uploadTorrent(file, destination) {
const form = new FormData();
form.append('torrent', file);
if (destination) {
form.append('destination', destination);
}
const response = await torrentsRequest(await fetch(`${TORRENTS_API}/upload`, {method: 'POST', body: form}),
'Failed to add the .torrent file');
return await response.json();
}
export async function pauseTorrent(hash) {
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/pause`), 'Failed to pause the torrent');
}
export async function resumeTorrent(hash) {
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/resume`), 'Failed to resume the torrent');
}
export async function removeTorrent(hash, deleteFiles = false) {
await torrentsRequest(await apiDelete(`${TORRENTS_API}/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`),
'Failed to remove the torrent');
}
export async function setTorrentShareLimits(hash, seedRatioLimit, seedTimeLimit) {
await torrentsRequest(await apiPut(`${TORRENTS_API}/${hash}/limits`,
{seed_ratio_limit: seedRatioLimit, seed_time_limit: seedTimeLimit}), 'Failed to save the limits');
}
export async function setTorrentSpeedLimits(upload, download) {
await torrentsRequest(await apiPut(`${TORRENTS_API}/limits`, {upload, download}),
'Failed to save the speed limits');
}
export function torrentFileUrl(hash) {
return `${TORRENTS_API}/${hash}/torrent`;
}
export async function shareTorrent(path, trackers, webSeeds, rememberTrackers = false) {
const response = await torrentsRequest(await apiPost(`${TORRENTS_API}/share`,
{path, trackers, web_seeds: webSeeds, remember_trackers: rememberTrackers}), 'Failed to share as a torrent');
return (await response.json()).job_id;
}

View file

@ -279,3 +279,44 @@ export async function healthCheck() {
export async function getControllerInfo() { export async function getControllerInfo() {
return controllerFetch('/info'); return controllerFetch('/info');
} }
// --- Sync (a secondary WROLPi copying its primary; the Controller runs it, because the API is stopped) ---
export async function getSyncStatus() {
return controllerFetch('/sync/status');
}
/** Start a sync now. Throws with the reason a sync cannot start. */
export async function runSync() {
return controllerFetch('/sync/run', {method: 'POST'});
}
export async function cancelSync() {
return controllerFetch('/sync/cancel', {method: 'POST'});
}
// --- VPN (torrents reach the Internet only through it) ---
export async function getVpnStatus() {
return controllerFetch('/vpn/status');
}
export async function getVpnSettings() {
return controllerFetch('/vpn/settings');
}
export async function updateVpnSettings(settings) {
return controllerFetch('/vpn/settings', {method: 'POST', body: JSON.stringify(settings)});
}
export async function uploadVpnConfig(filename, content) {
return controllerFetch('/vpn/config', {method: 'POST', body: JSON.stringify({filename, content})});
}
export async function deleteVpnConfig() {
return controllerFetch('/vpn/config', {method: 'DELETE'});
}
export async function saveVpnAuth(username, password) {
return controllerFetch('/vpn/auth', {method: 'POST', body: JSON.stringify({username, password})});
}

View file

@ -12,8 +12,10 @@ import {
import {Header, Loading, Panel, Statistic, StatisticGroup} from "./ui"; import {Header, Loading, Panel, Statistic, StatisticGroup} from "./ui";
import {useStatistics} from "../hooks/customHooks"; import {useStatistics} from "../hooks/customHooks";
import {CalculatorsPage} from "./Calculators"; import {CalculatorsPage} from "./Calculators";
import {BookmarksPage} from "./Bookmarks";
function StatisticsPage() { // `statistics` follows useStatistics: null = pending, undefined = fetch failed.
export function StatisticsPage() {
useTitle('Statistics'); useTitle('Statistics');
const {statistics} = useStatistics(); const {statistics} = useStatistics();
@ -25,7 +27,7 @@ function StatisticsPage() {
</> </>
} }
if (statistics['global_statistics']) { if (statistics && statistics['global_statistics']) {
let {global_statistics, file_statistics} = statistics; let {global_statistics, file_statistics} = statistics;
const { const {
archive_count, archive_count,
@ -104,6 +106,7 @@ export function MoreRoute(props) {
<Routes> <Routes>
<Route path='calculators' element={<CalculatorsPage/>}/> <Route path='calculators' element={<CalculatorsPage/>}/>
<Route path='statistics' exact element={<StatisticsPage/>}/> <Route path='statistics' exact element={<StatisticsPage/>}/>
<Route path='bookmarks' element={<BookmarksPage/>}/>
</Routes> </Routes>
</PageContainer> </PageContainer>
} }

View file

@ -0,0 +1,453 @@
import React, {useState} from 'react';
import {Link} from 'react-router';
import {IconBookmark} from '@tabler/icons-react';
import {Button, Group, Header, Icon, Menu, Message, Modal, Panel, Select, Table, Text, TextInput, Toggle} from './ui';
import {APIButton, PageContainer, useTitle} from './Common';
import {isBookmarkDirectory, resolveBookmarkUrl, useBookmarks} from '../contexts/BookmarksContext';
import {addBookmark, addBookmarkDirectory, deleteBookmark, moveBookmark, updateBookmark} from '../api';
export const EDIT_BOOKMARKS_PATH = '/more/bookmarks';
/**
* The props that make a Menu.Item open a bookmark: an in-app Link for a path, a plain
* anchor for everything else, and a new tab when the bookmark asks for one. A URL that
* does not resolve (see resolveBookmarkUrl) gets a disabled item, never a raw href.
*/
function bookmarkItemProps(node) {
const {internal, href} = resolveBookmarkUrl(node.url);
if (!href) {
return {disabled: true};
}
const target = node.new_tab ? {target: '_blank', rel: 'noopener noreferrer'} : {};
if (internal) {
return {component: Link, to: href, ...target};
}
return {component: 'a', href, ...target};
}
/**
* The items of a bookmarks menu.
*
* `nested` draws a directory as a flyout (Menu.Sub), which opens beside the menu on hover.
* Without it a directory is a labelled, indented run of items instead: the mobile
* hamburger is the one place bookmarks are shown where a flyout cannot be hovered. The
* indent is in rem: a label is set smaller than an item, so an em indent would put a
* directory's label a few pixels left of the items beside it.
*/
export function BookmarkMenuItems({nodes, nested = true, depth = 0}) {
if (!nodes || nodes.length === 0) {
return null;
}
return nodes.map(node => {
if (isBookmarkDirectory(node)) {
if (nested) {
return <Menu.Sub key={node.id}>
<Menu.Sub.Target>
<Menu.Sub.Item leftSection={<Icon name='folder' size='small'/>}>{node.name}</Menu.Sub.Item>
</Menu.Sub.Target>
<Menu.Sub.Dropdown>
{node.children.length > 0
? <BookmarkMenuItems nodes={node.children} nested={nested}/>
: <Menu.Item disabled>Empty</Menu.Item>}
</Menu.Sub.Dropdown>
</Menu.Sub>;
}
return <React.Fragment key={node.id}>
<Menu.Label style={{paddingLeft: `${0.75 + depth}rem`}}>{node.name}</Menu.Label>
<BookmarkMenuItems nodes={node.children} nested={false} depth={depth + 1}/>
</React.Fragment>;
}
return <Menu.Item
key={node.id}
{...bookmarkItemProps(node)}
style={nested ? undefined : {paddingLeft: `${0.75 + depth}rem`}}
rightSection={node.new_tab ? <Icon name='external' size='small'/> : undefined}
>
{node.name}
</Menu.Item>;
});
}
/**
* Everything inside a bookmarks dropdown: the bookmarks, then the link to edit them. The
* edit link is always there, so a user with no bookmarks yet can find where to add one.
*/
export function BookmarksMenuContents({nested = true}) {
const {bookmarks} = useBookmarks();
const nodes = bookmarks || [];
return <>
<BookmarkMenuItems nodes={nodes} nested={nested}/>
{nodes.length > 0 && <Menu.Divider/>}
<Menu.Item component={Link} to={EDIT_BOOKMARKS_PATH} leftSection={<Icon name='edit' size='small'/>}>
Edit bookmarks
</Menu.Item>
</>;
}
/** Every directory in the tree with its full path, for the "Location" picker. */
export function directoryOptions(nodes, prefix = '') {
const options = [];
for (const node of nodes || []) {
if (isBookmarkDirectory(node)) {
const label = `${prefix}${node.name}`;
options.push({value: String(node.id), label, id: node.id});
options.push(...directoryOptions(node.children, `${label} / `));
}
}
return options;
}
/** The ids of `node` and everything beneath it. */
const subtreeIds = (node) => {
const ids = [node.id];
if (isBookmarkDirectory(node)) {
node.children.forEach(child => ids.push(...subtreeIds(child)));
}
return ids;
};
const ROOT = 'root';
/** The places a node may live: the top level, and every directory not inside `node`. */
export function locationOptions(nodes, node = null) {
// A directory cannot be moved into itself or its own children.
const excluded = node ? new Set(subtreeIds(node)) : new Set();
return [
{value: ROOT, label: 'Top level'},
...directoryOptions(nodes).filter(i => !excluded.has(i.id)).map(({value, label}) => ({value, label})),
];
}
/**
* The form for one node. `node` is null when adding; `directory` says which kind.
* `parentId` is where a new node goes, or where an edited one currently lives.
*/
export function BookmarkNodeModal({open, node, directory, parentId, nodes, onSave, onClose}) {
const [name, setName] = useState(node?.name || '');
const [url, setUrl] = useState(node?.url || '');
const [newTab, setNewTab] = useState(Boolean(node?.new_tab));
const [location, setLocation] = useState(parentId === null || parentId === undefined ? ROOT : String(parentId));
const [saving, setSaving] = useState(false);
const locations = locationOptions(nodes, node);
const valid = name.trim() && (directory || url.trim());
const title = node ? (directory ? 'Edit directory' : 'Edit bookmark') : (directory ? 'New directory' : 'New bookmark');
const handleSave = async () => {
if (!valid) return;
setSaving(true);
try {
await onSave({
name: name.trim(),
url: url.trim(),
new_tab: newTab,
parent_id: location === ROOT ? null : Number(location),
});
} finally {
setSaving(false);
}
};
return <Modal open={open} onClose={onClose} size='tiny'>
<Modal.Header>{title}</Modal.Header>
<Modal.Content>
<form onSubmit={e => {
e.preventDefault();
handleSave();
}}>
<TextInput
autoFocus
label='Name'
value={name}
onChange={e => setName(e.currentTarget.value)}
/>
{!directory && <TextInput
label='URL'
style={{marginTop: '1em'}}
value={url}
onChange={e => setUrl(e.currentTarget.value)}
placeholder='/videos, :8096/, or https://example.com'
description='A path on this WROLPi (/videos), a port on this host (:8096/ or http://:8096/), or a full URL.'
/>}
<Select
label='Location'
style={{marginTop: '1em'}}
data={locations}
value={location}
onChange={value => setLocation(value || ROOT)}
allowDeselect={false}
/>
{!directory && <Toggle
style={{marginTop: '1em'}}
label='Open in a new tab'
checked={newTab}
onChange={e => setNewTab(e.currentTarget.checked)}
/>}
</form>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='save' disabled={!valid || saving} onClick={handleSave}>Save</Button>
</Modal.Actions>
</Modal>;
}
/** The rows of the editor, one per node, children beneath their directory and indented. */
function BookmarkTableRows({nodes, parentId, depth, editable, actions}) {
return nodes.map((node, index) => {
const directory = isBookmarkDirectory(node);
const {href} = directory ? {} : resolveBookmarkUrl(node.url);
return <React.Fragment key={node.id}>
<Table.Row>
<Table.Cell>{String(index + 1).padStart(2, '0')}</Table.Cell>
<Table.Cell style={{width: '90px', textAlign: 'center'}}>
{directory
? <Icon name='folder' size='large'/>
: <Icon name={node.new_tab ? 'external' : 'linkify'} size='large'/>}
</Table.Cell>
<Table.Cell style={{paddingLeft: depth ? `calc(0.75em + ${depth * 1.5}em)` : undefined}}>
{directory && <b>{node.name}</b>}
{!directory && (href
? <a href={href} target={node.new_tab ? '_blank' : undefined} rel='noopener noreferrer'>
{node.name}
</a>
: <span>{node.name}</span>)}
{!directory && <Text size='xs' c='dimmed' truncate='end'>{node.url}</Text>}
</Table.Cell>
{editable && <Table.Cell>
<div className='wrolpi-button-row' style={{justifyContent: 'flex-end'}}>
<Button icon='arrow up' size='xs' aria-label={`Move ${node.name} up`} disabled={index === 0}
onClick={() => actions.move(node, parentId, index - 1)}/>
<Button icon='arrow down' size='xs' aria-label={`Move ${node.name} down`}
disabled={index === nodes.length - 1}
onClick={() => actions.move(node, parentId, index + 1)}/>
<Button icon='edit' size='xs' aria-label={`Edit ${node.name}`}
onClick={() => actions.edit(node, parentId)}/>
{directory
? <APIButton
role='danger' icon='trash' size='xs' aria-label={`Delete ${node.name}`}
confirmContent={`Delete the directory "${node.name}" and everything in it?`}
confirmButton='Delete'
onClick={() => actions.remove(node)}/>
: <Button role='danger' icon='trash' size='xs' aria-label={`Delete ${node.name}`}
onClick={() => actions.remove(node)}/>}
</div>
</Table.Cell>}
</Table.Row>
{directory && <BookmarkTableRows nodes={node.children} parentId={node.id} depth={depth + 1}
editable={editable} actions={actions}/>}
</React.Fragment>;
});
}
/**
* The bookmarks table, in the shape of the playlist items table. `actions` carries
* edit/move/remove so the gallery can render it with none of them wired.
*/
export function BookmarkTable({nodes, editable = true, actions}) {
return <Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>#</Table.HeaderCell>
<Table.HeaderCell>Kind</Table.HeaderCell>
<Table.HeaderCell>Bookmark</Table.HeaderCell>
{editable && <Table.HeaderCell/>}
</Table.Row>
</Table.Header>
<Table.Body>
<BookmarkTableRows nodes={nodes} parentId={null} depth={0} editable={editable} actions={actions}/>
</Table.Body>
</Table>;
}
/** The "Add a bookmark" and "Add a directory" forms beneath the table. */
export function BookmarkAddForms({nodes, onAddBookmark, onAddDirectory}) {
const [url, setUrl] = useState('');
const [name, setName] = useState('');
const [newTab, setNewTab] = useState(false);
const [location, setLocation] = useState(ROOT);
const [directoryName, setDirectoryName] = useState('');
const [directoryLocation, setDirectoryLocation] = useState(ROOT);
const locations = locationOptions(nodes);
const parentOf = (value) => value === ROOT ? null : Number(value);
// The form is cleared only once the server has accepted the node. A refused add has
// already shown its toast; the typed URL stays so the user can correct it.
const handleAddBookmark = async () => {
if (!url.trim() || !name.trim()) return;
try {
await onAddBookmark({name: name.trim(), url: url.trim(), new_tab: newTab, parent_id: parentOf(location)});
} catch (e) {
return;
}
setUrl('');
setName('');
};
const handleAddDirectory = async () => {
if (!directoryName.trim()) return;
try {
await onAddDirectory({name: directoryName.trim(), parent_id: parentOf(directoryLocation)});
} catch (e) {
return;
}
setDirectoryName('');
};
return <>
<Header as='h4'>Add a bookmark</Header>
<form onSubmit={e => {
e.preventDefault();
handleAddBookmark();
}}>
<Group align='flex-end' wrap='wrap'>
<TextInput
style={{flex: '2 1 300px'}}
aria-label='Bookmark URL'
placeholder='URL (e.g. /videos, :8096/, or https://example.com)'
value={url}
onChange={e => setUrl(e.currentTarget.value)}/>
<TextInput
style={{flex: '1 1 200px'}}
aria-label='Bookmark name'
placeholder='Name'
value={name}
onChange={e => setName(e.currentTarget.value)}/>
<Select
style={{flex: '1 1 160px'}}
aria-label='Bookmark location'
data={locations}
value={location}
onChange={value => setLocation(value || ROOT)}
allowDeselect={false}/>
<Toggle
label='New tab'
checked={newTab}
onChange={e => setNewTab(e.currentTarget.checked)}/>
<Button role='primary' type='submit' disabled={!url.trim() || !name.trim()}>Add</Button>
</Group>
</form>
<p style={{marginTop: '0.5em'}}>
<Text size='xs' c='dimmed' component='span'>
A URL is a path on this WROLPi (/videos), a port on this host (:8096/ or http://:8096/) that
works whichever address you reach it by, or a full URL.
</Text>
</p>
<Header as='h4'>Add a directory</Header>
<form onSubmit={e => {
e.preventDefault();
handleAddDirectory();
}}>
<Group align='flex-end' wrap='wrap'>
<TextInput
style={{flex: '2 1 300px'}}
aria-label='Directory name'
placeholder='Directory name'
value={directoryName}
onChange={e => setDirectoryName(e.currentTarget.value)}/>
<Select
style={{flex: '1 1 160px'}}
aria-label='Directory location'
data={locations}
value={directoryLocation}
onChange={value => setDirectoryLocation(value || ROOT)}
allowDeselect={false}/>
<Button role='primary' type='submit' disabled={!directoryName.trim()}>Add</Button>
</Group>
</form>
</>;
}
export function BookmarksPage() {
useTitle('Bookmarks');
const {bookmarks, refresh} = useBookmarks();
// {node, directory, parentId} while the edit modal is open; a `key` remounts the form fresh.
const [modal, setModal] = useState(null);
const [modalKey, setModalKey] = useState(0);
const nodes = bookmarks || [];
const actions = {
edit: (node, parentId) => {
setModalKey(k => k + 1);
setModal({node, directory: isBookmarkDirectory(node), parentId});
},
move: async (node, parentId, position) => {
try {
await moveBookmark(node.id, parentId, position);
await refresh();
} catch (e) {
// Error toast already shown by the API client.
}
},
remove: async (node) => {
try {
await deleteBookmark(node.id);
await refresh();
} catch (e) {
}
},
};
// These reject on failure (the API client has already shown the toast) so the add
// forms know to keep what was typed.
const handleAddBookmark = async (bookmark) => {
await addBookmark(bookmark);
await refresh();
};
const handleAddDirectory = async (directory) => {
await addBookmarkDirectory(directory);
await refresh();
};
const handleEditSave = async ({name, url, new_tab, parent_id}) => {
const {node, directory, parentId} = modal;
try {
await updateBookmark(node.id, directory ? {name} : {name, url, new_tab});
} catch (e) {
return; // Nothing changed; the modal stays open with the toast beside it.
}
// The rename is committed even if the move is refused, so the nav must show it
// either way; only a fully successful edit closes the modal.
let moved = true;
if (parent_id !== parentId) {
try {
await moveBookmark(node.id, parent_id);
} catch (e) {
moved = false;
}
}
await refresh();
if (moved) {
setModal(null);
}
};
return <PageContainer>
<Panel>
<Header as='h1' icon={IconBookmark}>Bookmarks</Header>
<p>
Bookmarks appear in the Bookmarks menu of the navigation bar. They can point at pages on this
WROLPi, at other services running beside it, or anywhere on the web.
</p>
{nodes.length === 0
? <Message title='There are no bookmarks yet'>Add a bookmark below.</Message>
: <BookmarkTable nodes={nodes} actions={actions}/>}
<BookmarkAddForms nodes={nodes} onAddBookmark={handleAddBookmark} onAddDirectory={handleAddDirectory}/>
</Panel>
{modal && <BookmarkNodeModal
key={modalKey}
open
node={modal.node}
directory={modal.directory}
parentId={modal.parentId}
nodes={nodes}
onSave={handleEditSave}
onClose={() => setModal(null)}
/>}
</PageContainer>;
}

View file

@ -0,0 +1,199 @@
import React from 'react';
import {screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {render} from '../test-utils';
import {BookmarkAddForms, BookmarkNodeModal, BookmarkTable, directoryOptions, locationOptions} from './Bookmarks';
import {resolveBookmarkUrl} from '../contexts/BookmarksContext';
const tree = [
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
{
id: 2, name: 'Services', children: [
{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true},
{id: 4, name: 'Radio', children: []},
]
},
];
describe('resolveBookmarkUrl', () => {
const location = {protocol: 'https:', hostname: '10.0.0.2', host: '10.0.0.2'};
it.each([
['/videos', {internal: true, href: '/videos'}],
[' /videos/channel/3 ', {internal: true, href: '/videos/channel/3'}],
// A port on this host takes the page's scheme, or its own when it names one.
[':8096/web', {internal: false, href: 'https://10.0.0.2:8096/web'}],
[':8096', {internal: false, href: 'https://10.0.0.2:8096'}],
['http://:8096/web', {internal: false, href: 'http://10.0.0.2:8096/web'}],
['HTTPS://:8085', {internal: false, href: 'https://10.0.0.2:8085'}],
['https://example.com/a?b=c', {internal: false, href: 'https://example.com/a?b=c'}],
])('resolves %s', (url, expected) => {
expect(resolveBookmarkUrl(url, location)).toEqual(expected);
});
it.each([
// Paths a browser takes off this host: network paths, backslashes, and control
// characters a URL parser strips before deciding.
'//evil.com', '///evil.com', '/\\evil.com', '/\\@evil.com', '/\t/evil.com', '/\n/evil.com',
// Port forms where the host would become credentials.
':8096@evil.com', 'http://:8096@evil.com', ':8096\t@evil.com', ':8096/x@evil.com', ':8096\\evil.com',
// Not http(s).
'javascript:alert(1)', 'data:text/html,hi', 'ftp://example.com', 'videos', '',
])('refuses %j rather than guessing', (url) => {
expect(resolveBookmarkUrl(url, location)).toEqual({internal: false, href: null});
});
it('brackets an IPv6 host for a port bookmark', () => {
// The browser reports an IPv6 hostname bracketed already.
const v6 = {protocol: 'https:', hostname: '[::1]', host: '[::1]'};
expect(resolveBookmarkUrl(':8096/web', v6)).toEqual({internal: false, href: 'https://[::1]:8096/web'});
expect(resolveBookmarkUrl(':8096', {protocol: 'http:', hostname: '::1', host: '[::1]'}))
.toEqual({internal: false, href: 'http://[::1]:8096'});
});
});
describe('directoryOptions', () => {
it('lists every directory with its path, and no bookmarks', () => {
expect(directoryOptions(tree)).toEqual([
{value: '2', label: 'Services', id: 2},
{value: '4', label: 'Services / Radio', id: 4},
]);
});
});
describe('BookmarkTable', () => {
const actions = () => ({edit: jest.fn(), move: jest.fn(), remove: jest.fn()});
it('renders the tree with resolved links, numbered within each directory', () => {
render(<BookmarkTable nodes={tree} actions={actions()}/>);
const channels = screen.getByRole('link', {name: 'Channels'});
expect(channels).toHaveAttribute('href', '/videos/channel');
expect(channels).not.toHaveAttribute('target');
const jellyfin = screen.getByRole('link', {name: 'Jellyfin'});
expect(jellyfin).toHaveAttribute('href', `${window.location.protocol}//${window.location.hostname}:8096/`);
expect(jellyfin).toHaveAttribute('target', '_blank');
expect(screen.getByText('Radio')).toBeInTheDocument();
// Channels, Services, then Services' two children.
const numbers = screen.getAllByRole('row').slice(1).map(row => row.firstChild.textContent);
expect(numbers).toEqual(['01', '02', '01', '02']);
});
it('moves a node among its siblings and only within bounds', async () => {
const a = actions();
render(<BookmarkTable nodes={tree} actions={a}/>);
// The first top-level node cannot move up; the last cannot move down.
expect(screen.getByRole('button', {name: 'Move Channels up'})).toBeDisabled();
expect(screen.getByRole('button', {name: 'Move Services down'})).toBeDisabled();
await userEvent.click(screen.getByRole('button', {name: 'Move Channels down'}));
expect(a.move).toHaveBeenCalledWith(tree[0], null, 1);
// A child moves within its directory: parent 2, from index 1 to 0.
await userEvent.click(screen.getByRole('button', {name: 'Move Radio up'}));
expect(a.move).toHaveBeenCalledWith(tree[1].children[1], 2, 0);
});
it('shows a bookmark whose URL does not resolve as text, not a link', () => {
const nodes = [{id: 1, name: 'Bad', url: '//evil.com', new_tab: false}];
render(<BookmarkTable nodes={nodes} actions={actions()}/>);
expect(screen.queryByRole('link', {name: 'Bad'})).not.toBeInTheDocument();
expect(screen.getByText('Bad')).toBeInTheDocument();
});
it('edits with the parent the node lives in, and deletes a bookmark without asking', async () => {
const a = actions();
render(<BookmarkTable nodes={tree} actions={a}/>);
await userEvent.click(screen.getByRole('button', {name: 'Edit Jellyfin'}));
expect(a.edit).toHaveBeenCalledWith(tree[1].children[0], 2);
await userEvent.click(screen.getByRole('button', {name: 'Delete Channels'}));
expect(a.remove).toHaveBeenCalledWith(tree[0]);
});
it('asks before deleting a directory, since its contents go with it', async () => {
const a = actions();
render(<BookmarkTable nodes={tree} actions={a}/>);
await userEvent.click(screen.getByRole('button', {name: 'Delete Services'}));
expect(a.remove).not.toHaveBeenCalled();
await userEvent.click(await screen.findByRole('button', {name: 'Delete'}));
expect(a.remove).toHaveBeenCalledWith(tree[1]);
});
});
describe('BookmarkAddForms', () => {
it('adds a bookmark at the top level and clears the form', async () => {
const onAddBookmark = jest.fn();
render(<BookmarkAddForms nodes={tree} onAddBookmark={onAddBookmark} onAddDirectory={jest.fn()}/>);
const adds = screen.getAllByRole('button', {name: 'Add'});
expect(adds[0]).toBeDisabled();
await userEvent.type(screen.getByLabelText('Bookmark URL'), ':8123/');
expect(adds[0]).toBeDisabled();
await userEvent.type(screen.getByLabelText('Bookmark name'), 'Home Assistant');
await userEvent.click(screen.getByLabelText('New tab'));
await userEvent.click(adds[0]);
expect(onAddBookmark).toHaveBeenCalledWith({name: 'Home Assistant', url: ':8123/', new_tab: true, parent_id: null});
expect(screen.getByLabelText('Bookmark URL')).toHaveValue('');
});
it('keeps what was typed when the server refuses the bookmark', async () => {
const onAddBookmark = jest.fn().mockRejectedValue(new Error('refused'));
render(<BookmarkAddForms nodes={tree} onAddBookmark={onAddBookmark} onAddDirectory={jest.fn()}/>);
await userEvent.type(screen.getByLabelText('Bookmark URL'), '//evil.com');
await userEvent.type(screen.getByLabelText('Bookmark name'), 'Oops');
await userEvent.click(screen.getAllByRole('button', {name: 'Add'})[0]);
expect(onAddBookmark).toHaveBeenCalled();
expect(screen.getByLabelText('Bookmark URL')).toHaveValue('//evil.com');
expect(screen.getByLabelText('Bookmark name')).toHaveValue('Oops');
});
it('adds a directory', async () => {
const onAddDirectory = jest.fn();
render(<BookmarkAddForms nodes={tree} onAddBookmark={jest.fn()} onAddDirectory={onAddDirectory}/>);
await userEvent.type(screen.getByLabelText('Directory name'), 'Tools');
await userEvent.click(screen.getAllByRole('button', {name: 'Add'})[1]);
expect(onAddDirectory).toHaveBeenCalledWith({name: 'Tools', parent_id: null});
});
});
describe('BookmarkNodeModal', () => {
// Mantine's Select scrolls the highlighted option into view; jsdom has no layout.
beforeAll(() => {
Element.prototype.scrollIntoView = jest.fn();
});
it('saves a new bookmark with its location and new-tab choice', async () => {
const onSave = jest.fn();
render(<BookmarkNodeModal open node={null} directory={false} parentId={2} nodes={tree}
onSave={onSave} onClose={jest.fn()}/>);
const save = screen.getByRole('button', {name: 'Save'});
expect(save).toBeDisabled();
await userEvent.type(screen.getByLabelText('Name'), 'Home Assistant');
expect(save).toBeDisabled();
await userEvent.type(screen.getByLabelText('URL'), ':8123/');
await userEvent.click(screen.getByLabelText('Open in a new tab'));
await userEvent.click(save);
expect(onSave).toHaveBeenCalledWith({name: 'Home Assistant', url: ':8123/', new_tab: true, parent_id: 2});
});
it('a directory has no URL or new-tab choice', () => {
render(<BookmarkNodeModal open node={tree[1]} directory parentId={null} nodes={tree}
onSave={jest.fn()} onClose={jest.fn()}/>);
expect(screen.getByLabelText('Name')).toHaveValue('Services');
expect(screen.queryByLabelText('URL')).not.toBeInTheDocument();
expect(screen.queryByLabelText('Open in a new tab')).not.toBeInTheDocument();
});
});
describe('locationOptions', () => {
it('offers the top level and every directory to a new node', () => {
expect(locationOptions(tree).map(o => o.label)).toEqual(['Top level', 'Services', 'Services / Radio']);
});
it('never offers a directory itself, or its children', () => {
expect(locationOptions(tree, tree[1]).map(o => o.label)).toEqual(['Top level']);
expect(locationOptions(tree, tree[1].children[1]).map(o => o.label)).toEqual(['Top level', 'Services']);
});
});

View file

@ -2,7 +2,6 @@ import React from "react";
import {Breadcrumbs, useTitle} from "./Common"; import {Breadcrumbs, useTitle} from "./Common";
import {Button, Header, Icon} from "./ui"; import {Button, Header, Icon} from "./ui";
import {useCalcQuery} from "../hooks/customHooks"; import {useCalcQuery} from "../hooks/customHooks";
import {TemperatureCalculator} from "./calculators/TemperatureCalculator";
import {ElectricalCalculators} from "./calculators/ElectricalCalculators"; import {ElectricalCalculators} from "./calculators/ElectricalCalculators";
import {DipoleAntennaCalculator} from "./calculators/HamCalculators"; import {DipoleAntennaCalculator} from "./calculators/HamCalculators";
import {Link} from "react-router"; import {Link} from "react-router";
@ -14,6 +13,7 @@ import {FoodStorageCalculator} from "./calculators/FoodStorageCalculator";
import {OneTimePadCalculator} from "./calculators/OneTimePadCalculator"; import {OneTimePadCalculator} from "./calculators/OneTimePadCalculator";
import {VinDecoderCalculator} from "./calculators/VinDecoderCalculator"; import {VinDecoderCalculator} from "./calculators/VinDecoderCalculator";
import {SpeedTestCalculator} from "./calculators/SpeedTestCalculator"; import {SpeedTestCalculator} from "./calculators/SpeedTestCalculator";
import {SolarCalculator} from "./calculators/SolarCalculator";
// Calculators are shown in these titled groups, in this order. Each calculator carries a // Calculators are shown in these titled groups, in this order. Each calculator carries a
// `group` matching one of these names; any calculator whose group is missing/unknown falls // `group` matching one of these names; any calculator whose group is missing/unknown falls
@ -35,10 +35,10 @@ export const useCalculators = () => {
{key: 'ratio', icon: 'th large', button: 'Ratio', group: 'Engineering', contents: <RatioCalculators/>}, {key: 'ratio', icon: 'th large', button: 'Ratio', group: 'Engineering', contents: <RatioCalculators/>},
{key: 'electrical', icon: 'lightning', button: 'Electrical', group: 'Engineering', contents: <ElectricalCalculators/>}, {key: 'electrical', icon: 'lightning', button: 'Electrical', group: 'Engineering', contents: <ElectricalCalculators/>},
{key: 'drive', icon: 'cogs', button: 'Drive Ratio', group: 'Engineering', contents: <DriveCalculator/>}, {key: 'drive', icon: 'cogs', button: 'Drive Ratio', group: 'Engineering', contents: <DriveCalculator/>},
{key: 'solar', icon: 'sun', button: 'Solar', group: 'Engineering', contents: <SolarCalculator/>},
{key: 'water', icon: 'tint', button: 'Water Storage', group: 'Preparedness & Storage', contents: <WaterCalculator/>}, {key: 'water', icon: 'tint', button: 'Water Storage', group: 'Preparedness & Storage', contents: <WaterCalculator/>},
{key: 'ration', icon: 'food', button: 'Food Storage', group: 'Preparedness & Storage', contents: <FoodStorageCalculator/>}, {key: 'ration', icon: 'food', button: 'Food Storage', group: 'Preparedness & Storage', contents: <FoodStorageCalculator/>},
{key: 'antenna', icon: 'signal', button: 'Antenna', group: 'Radio & Communications', contents: <DipoleAntennaCalculator/>}, {key: 'antenna', icon: 'signal', button: 'Antenna', group: 'Radio & Communications', contents: <DipoleAntennaCalculator/>},
{key: 'temperature', icon: 'thermometer', button: 'Temperature', group: 'Tools & Reference', contents: <TemperatureCalculator/>},
{key: 'qrCode', icon: 'qrcode', button: 'QR Code', group: 'Tools & Reference', contents: <QRCodeCalculator/>}, {key: 'qrCode', icon: 'qrcode', button: 'QR Code', group: 'Tools & Reference', contents: <QRCodeCalculator/>},
{key: 'otp', icon: 'lock', button: 'One Time Pad', title: 'One Time Pad', group: 'Radio & Communications', contents: <OneTimePadCalculator/>}, {key: 'otp', icon: 'lock', button: 'One Time Pad', title: 'One Time Pad', group: 'Radio & Communications', contents: <OneTimePadCalculator/>},
{key: 'vin', icon: 'car', button: 'VIN Decoder', title: 'VIN Decoder', group: 'Tools & Reference', contents: <VinDecoderCalculator/>}, {key: 'vin', icon: 'car', button: 'VIN Decoder', title: 'VIN Decoder', group: 'Tools & Reference', contents: <VinDecoderCalculator/>},

View file

@ -3,6 +3,7 @@ import {IconArrowLeft, IconArrowRight} from '@tabler/icons-react';
import {getArchiveContents, getArchiveMemberUrl} from '../api'; import {getArchiveContents, getArchiveMemberUrl} from '../api';
import {IconButton, Label, Loading, Message} from './ui'; import {IconButton, Label, Loading, Message} from './ui';
import {useLocalStorage} from './Common'; import {useLocalStorage} from './Common';
import {usePageProgress} from '../hooks/useFileProgress';
const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|bmp|tiff?)$/i; const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|bmp|tiff?)$/i;
@ -22,9 +23,20 @@ function flattenEntries(entries, prefix = '') {
return paths; return paths;
} }
export function CbzViewer({path}) { /**
* @param path The comic book file.
* @param progressPath The FileGroup's primary path, to resume and save the reader's page; omit to not track it.
* @param fileGroup The FileGroup JSON, which holds the saved page.
*/
export function CbzViewer({path, progressPath = null, fileGroup = null}) {
const [pages, setPages] = useState(null); const [pages, setPages] = useState(null);
const [currentPage, setCurrentPage] = useState(0); const [currentPage, setCurrentPage] = useState(0);
const {initialPage, onPageChange} = usePageProgress(progressPath, fileGroup, {enabled: !!progressPath});
// Read when the pages load; a later save must not move the reader.
const initialPageRef = useRef(initialPage);
initialPageRef.current = initialPage;
// The page shown on opening is where the reader already is (or the cover of a finished comic); it is not saved.
const justOpenedRef = useRef(true);
const [rtl, setRtl] = useLocalStorage('cbzViewerRtl', false); const [rtl, setRtl] = useLocalStorage('cbzViewerRtl', false);
const [fullscreen, setFullscreen] = useState(false); const [fullscreen, setFullscreen] = useState(false);
const [error, setError] = useState(null); const [error, setError] = useState(null);
@ -41,8 +53,9 @@ export function CbzViewer({path}) {
.filter(name => IMAGE_EXTENSIONS.test(name)) .filter(name => IMAGE_EXTENSIONS.test(name))
.sort(); .sort();
const urls = images.map(member => getArchiveMemberUrl(path, member)); const urls = images.map(member => getArchiveMemberUrl(path, member));
justOpenedRef.current = true;
setPages(urls); setPages(urls);
setCurrentPage(0); setCurrentPage(Math.min(initialPageRef.current, Math.max(urls.length - 1, 0)));
} catch (e) { } catch (e) {
setError(e.message || 'Could not read archive contents.'); setError(e.message || 'Could not read archive contents.');
} }
@ -50,6 +63,17 @@ export function CbzViewer({path}) {
load(); load();
}, [path]); }, [path]);
useEffect(() => {
if (!pages || pages.length === 0) {
return;
}
if (justOpenedRef.current) {
justOpenedRef.current = false;
return;
}
onPageChange(currentPage, pages.length);
}, [currentPage, pages, onPageChange]);
const goNext = useCallback(() => { const goNext = useCallback(() => {
setCurrentPage(p => Math.min(p + 1, (pages?.length || 1) - 1)); setCurrentPage(p => Math.min(p + 1, (pages?.length || 1) - 1));
}, [pages]); }, [pages]);

View file

@ -0,0 +1,84 @@
import React from 'react';
import {act, fireEvent, screen} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {CbzViewer} from './CbzViewer';
import {getArchiveContents} from '../api';
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getArchiveContents: jest.fn(),
getArchiveMemberUrl: (path, member) => `/member/${member}`,
}));
const PATH = 'comics/issue.cbz';
const PAGES = ['01.jpg', '02.jpg', '03.jpg', '04.jpg'];
const {fetch: realFetch} = global;
const realSendBeacon = navigator.sendBeacon;
beforeEach(() => {
window.sessionStorage.clear();
getArchiveContents.mockResolvedValue({entries: PAGES.map(name => ({name, path: name, is_dir: false}))});
navigator.sendBeacon = jest.fn(() => false);
global.fetch = jest.fn(() => Promise.resolve({ok: true}));
});
afterEach(() => {
global.fetch = realFetch;
navigator.sendBeacon = realSendBeacon;
});
const saves = () => global.fetch.mock.calls.map(([, init]) => JSON.parse(init.body));
describe('CbzViewer progress', () => {
test('opens at the saved page, and saves the page the reader leaves on', async () => {
const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}};
const {unmount} = renderWithProviders(
<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
expect(await screen.findByText('3 / 4')).toBeInTheDocument();
expect(screen.getByAltText('Page 3')).toHaveAttribute('src', '/member/03.jpg');
fireEvent.click(screen.getByLabelText('Next page'));
expect(screen.getByText('4 / 4')).toBeInTheDocument();
unmount();
expect(saves()).toEqual([expect.objectContaining({
file: PATH, progress: 1, final: true, position: expect.objectContaining({kind: 'page', page: 3}),
})]);
});
test('a saved page past the end opens the last page', async () => {
const fileGroup = {progress: 0.5, position: {kind: 'page', page: 40, updated_at: 1000}};
renderWithProviders(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
expect(await screen.findByText('4 / 4')).toBeInTheDocument();
});
test('without a progress path it opens at the first page and saves nothing', async () => {
const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}};
const {unmount} = renderWithProviders(<CbzViewer path={PATH} fileGroup={fileGroup}/>);
expect(await screen.findByText('1 / 4')).toBeInTheDocument();
await act(async () => fireEvent.click(screen.getByLabelText('Next page')));
unmount();
expect(saves()).toEqual([]);
});
test('opening a comic saves nothing, so a finished comic stays finished', async () => {
const fileGroup = {progress: 1, position: null, viewed: new Date(9000).toISOString()};
const {unmount} = renderWithProviders(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
expect(await screen.findByText('1 / 4')).toBeInTheDocument();
unmount();
expect(saves()).toEqual([]);
});
test('peeking at the cover keeps the reader\'s place', async () => {
const fileGroup = {progress: 0.75, position: {kind: 'page', page: 2, updated_at: 1000}};
const {unmount} = renderWithProviders(<CbzViewer path={PATH} progressPath={PATH} fileGroup={fileGroup}/>);
expect(await screen.findByText('3 / 4')).toBeInTheDocument();
fireEvent.click(screen.getByLabelText('Previous page'));
fireEvent.click(screen.getByLabelText('Previous page'));
expect(screen.getByText('1 / 4')).toBeInTheDocument();
unmount();
expect(saves()).toEqual([expect.objectContaining({position: expect.objectContaining({page: 1})})]);
});
});

View file

@ -49,7 +49,7 @@ describe('Channels Page', () => {
{initialEntries: ['/videos/channel/1/edit']} {initialEntries: ['/videos/channel/1/edit']}
); );
cy.wait('@channelFetch'); cy.wait('@channelFetch');
cy.wait('@searchDirectories'); // Needed for CircleCi. cy.wait('@searchDirectories'); // Needed in CI.
cy.wait(500); cy.wait(500);
cy.get('input[name="name"]').should('be.visible'); cy.get('input[name="name"]').should('be.visible');
cy.get('input[name="name"]').should('have.value', 'Editing Channel'); cy.get('input[name="name"]').should('have.value', 'Editing Channel');

View file

@ -757,6 +757,18 @@ export function findPosterPath(file) {
} }
} }
/** How far the user is through a file, as a bar along the bottom of its poster. A full bar is finished. */
export function ViewProgress({progress}) {
if (!(progress > 0)) {
return null;
}
const percent = Math.round(Math.min(progress, 1) * 100);
return <div className='wrolpi-view-progress' role='progressbar' aria-label='Viewing progress'
aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent}>
<div className='wrolpi-view-progress-bar' style={{width: `${percent}%`}}/>
</div>
}
export function CardPoster({to, file, overlay}) { export function CardPoster({to, file, overlay}) {
const navigate = useNavigate(); const navigate = useNavigate();
@ -785,6 +797,7 @@ export function CardPoster({to, file, overlay}) {
{imageLabel} {imageLabel}
<img alt='poster' src={posterPath}/> <img alt='poster' src={posterPath}/>
{overlay} {overlay}
<ViewProgress progress={file.progress}/>
</>; </>;
return <div className='wrolpi-card-poster'> return <div className='wrolpi-card-poster'>
@ -802,6 +815,7 @@ export function CardPoster({to, file, overlay}) {
<div className='wrolpi-card-icon'> <div className='wrolpi-card-icon'>
{imageLabel} {imageLabel}
<FileIcon file={file}/> <FileIcon file={file}/>
<ViewProgress progress={file.progress}/>
</div> </div>
</PreviewLink> </PreviewLink>
} else if (!posterPath && to) { } else if (!posterPath && to) {
@ -810,6 +824,7 @@ export function CardPoster({to, file, overlay}) {
<div className='wrolpi-card-icon' onClick={() => navigate(to)}> <div className='wrolpi-card-icon' onClick={() => navigate(to)}>
{imageLabel} {imageLabel}
<FileIcon file={file}/> <FileIcon file={file}/>
<ViewProgress progress={file.progress}/>
</div> </div>
</Link> </Link>
} }
@ -928,7 +943,10 @@ export function HelpHeader({
// why it cannot be used. `confirmStop` asks before switching off. // why it cannot be used. `confirmStop` asks before switching off.
function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null, disabled = null, confirmStop = null}) { function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null, disabled = null, confirmStop = null}) {
const [confirmOpen, setConfirmOpen] = React.useState(false); const [confirmOpen, setConfirmOpen] = React.useState(false);
// null = the status has loaded without this subsystem; undefined = the status has not loaded
// yet (or a call is in flight). Both disable the toggle; only the first claims unsupported.
const unsupported = on === null; const unsupported = on === null;
const unknown = on === undefined;
const handleChange = (checked) => { const handleChange = (checked) => {
if (!checked && confirmStop) { if (!checked && confirmStop) {
@ -961,11 +979,11 @@ function SubsystemToggle({label, on, onChange, unsupportedMessage, info = null,
</Confirm>} </Confirm>}
<Toggle <Toggle
label={label} label={label}
disabled={disabled === null ? unsupported : disabled} disabled={disabled === null ? (unsupported || unknown) : disabled}
checked={on === true} checked={on === true}
onChange={handleChange} onChange={handleChange}
/> />
{popup && <InfoPopup content={popup}/>} {popup && <span data-testid='subsystem-popup'><InfoPopup content={popup}/></span>}
</div>; </div>;
} }
@ -1065,9 +1083,10 @@ export function Toggle({label, checked, disabled, onChange, icon, popupContent =
export function DisableDownloadsToggle() { export function DisableDownloadsToggle() {
const [pending, setPending] = React.useState(false); const [pending, setPending] = React.useState(false);
const {status, fetchStatus} = React.useContext(StatusContext); const {status, fetchStatus, loaded} = React.useContext(StatusContext);
const {downloads} = status ? status : {downloads: null}; // Until the first status poll lands there is no downloads state to show, only a disabled toggle.
const downloads = loaded ? status?.downloads : null;
const wrolModeEnabled = useWROLMode(); const wrolModeEnabled = useWROLMode();
const setDownloads = async (enable) => { const setDownloads = async (enable) => {
@ -1082,8 +1101,9 @@ export function DisableDownloadsToggle() {
} }
const on = downloads && downloads['disabled'] === false && downloads['stopped'] === false; const on = downloads && downloads['disabled'] === false && downloads['stopped'] === false;
const label = downloads === null ? 'Downloading' : on === true ? 'Downloading Enabled' : 'Downloading Disabled';
return <Toggle return <Toggle
label={on === true ? 'Downloading Enabled' : 'Downloading Disabled'} label={label}
disabled={wrolModeEnabled || pending || downloads === null} disabled={wrolModeEnabled || pending || downloads === null}
checked={on === true} checked={on === true}
onChange={setDownloads} onChange={setDownloads}
@ -1160,7 +1180,7 @@ export function mimetypeIconName(mimetype, lowerPath = '') {
return 'file code'; return 'file code';
} else if (mimetype.startsWith('application/pdf')) { } else if (mimetype.startsWith('application/pdf')) {
return 'file pdf'; return 'file pdf';
} else if (mimetype.startsWith('text/plain')) { } else if (mimetype.startsWith('text/plain') || mimetype.startsWith('text/markdown')) {
return 'file text'; return 'file text';
} else if (mimetype.startsWith('image/')) { } else if (mimetype.startsWith('image/')) {
return 'image'; return 'image';

View file

@ -1121,7 +1121,7 @@ describe('a row of buttons', () => {
* the two had been inline before. * the two had been inline before.
* *
* A row fixes it without touching the stack: the row is the stretched child, and it lays * A row fixes it without touching the stack: the row is the stretched child, and it lays
* its buttons out at their own width. Nine sites, so this scan rather than nine * its buttons out at their own width. Thirteen sites, so this scan rather than thirteen
* assertions -- and a scan because a stretched button is still a working button. * assertions -- and a scan because a stretched button is still a working button.
*/ */
const offenders = []; const offenders = [];
@ -1140,8 +1140,8 @@ describe('a row of buttons', () => {
} }
} }
// Nine renders. Common.js declares it, and a declaration is not a `<BackButton`. // Thirteen renders. Common.js declares it, and a declaration is not a `<BackButton`.
expect(found).toBe(9); expect(found).toBe(13);
expect(offenders).toEqual([]); expect(offenders).toEqual([]);
}); });

View file

@ -38,6 +38,7 @@ import {toast} from "./ui";
import {CollectionTable} from "./collections/CollectionTable"; import {CollectionTable} from "./collections/CollectionTable";
import {AddToPlaylistButton} from "./AddToPlaylist"; import {AddToPlaylistButton} from "./AddToPlaylist";
import {CbzViewer} from "./CbzViewer"; import {CbzViewer} from "./CbzViewer";
import {useEpubProgress} from "../hooks/useFileProgress";
import _ from "lodash"; import _ from "lodash";
function DocsPage() { function DocsPage() {
@ -165,6 +166,23 @@ function DocsPage() {
</>; </>;
} }
/**
* The embedded viewer (the EPUB viewer, or the browser's PDF viewer). An EPUB opens where the user left off,
* unless a search result says where (`deepLinked`), and saves their place as they read.
*
* @param epubProgressPath The FileGroup's primary path when an EPUB is shown and tracked, otherwise null.
*/
function DocViewerFrame({url, epubProgressPath, fileGroup, deepLinked, title}) {
const {iframeRef, resumeCfi} = useEpubProgress(epubProgressPath, fileGroup, {enabled: !!epubProgressPath});
const src = resumeCfi && !deepLinked ? `${url}&cfi=${encodeURIComponent(resumeCfi)}` : url;
return <iframe
ref={iframeRef}
src={src}
title={title}
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
/>
}
function DocPage() { function DocPage() {
const {fileGroupId} = useParams(); const {fileGroupId} = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
@ -245,6 +263,8 @@ function DocPage() {
? `/media/${encodeMediaPath(activePath)}${pageParam ? `#page=${encodeURIComponent(pageParam)}` : ''}` ? `/media/${encodeMediaPath(activePath)}${pageParam ? `#page=${encodeURIComponent(pageParam)}` : ''}`
: null; : null;
const embedUrl = isEpub ? viewerUrl : pdfSrc; const embedUrl = isEpub ? viewerUrl : pdfSrc;
// Progress belongs to the FileGroup; another format of the same book (a PDF beside the EPUB) is not tracked.
const trackedPath = String(activePath) === String(docFile.primary_path) ? docFile.primary_path : null;
const handleDelete = async (force = false) => { const handleDelete = async (force = false) => {
if (doc && doc.id) { if (doc && doc.id) {
@ -354,7 +374,7 @@ function DocPage() {
return <> return <>
<div className='wrolpi-button-row'><BackButton/></div> <div className='wrolpi-button-row'><BackButton/></div>
{isCbz && activePath && <CbzViewer path={activePath}/>} {isCbz && activePath && <CbzViewer path={activePath} progressPath={trackedPath} fileGroup={docFile}/>}
{canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}> {canEmbed && embedUrl && !isCbz && <div style={{marginBottom: '1em'}}>
{/* {/*
@ -364,11 +384,8 @@ function DocPage() {
* re-gates rather than inheriting the last one's reveal. * re-gates rather than inheriting the last one's reveal.
*/} */}
<MediaGate key={activePath} gated={isPdf && mediaFilterEnabled}> <MediaGate key={activePath} gated={isPdf && mediaFilterEnabled}>
<iframe <DocViewerFrame url={embedUrl} epubProgressPath={isEpub ? trackedPath : null} fileGroup={docFile}
src={embedUrl} deepLinked={!!locParam} title={docFile.title || docFile.name}/>
title={docFile.title || docFile.name}
style={{width: '100%', height: '80vh', border: '1px solid var(--border)'}}
/>
</MediaGate> </MediaGate>
</div>} </div>}

View file

@ -19,10 +19,15 @@ const source = fs.readFileSync(path.join(__dirname, 'Docs.js'), 'utf8');
describe('DocPage embed gating (source contract)', () => { describe('DocPage embed gating (source contract)', () => {
it('wraps the embedded viewer in a MediaGate', () => { it('wraps the embedded viewer in a MediaGate', () => {
// The iframe must not be reachable without passing through the gate. // The iframe must not be reachable without passing through the gate. The gate's only child is the
const embed = source.match(/<MediaGate[^>]*>\s*<iframe/); // viewer frame, and the frame is just the iframe.
const embed = source.match(/<MediaGate[^>]*>\s*<DocViewerFrame/);
expect(embed).not.toBeNull(); expect(embed).not.toBeNull();
const frame = source.match(/function DocViewerFrame[\s\S]*?\n}\n/);
expect(frame).not.toBeNull();
expect(frame[0]).toMatch(/return <iframe/);
expect(source.match(/<iframe/g)).toHaveLength(1);
}); });
it('gates on the live filter state, not on the theme name', () => { it('gates on the live filter state, not on the theme name', () => {

View file

@ -1,7 +1,7 @@
import React, {useState} from "react"; import React from "react";
import {PageContainer, useTitle} from "./Common"; import {PageContainer, useTitle} from "./Common";
import {Button, Header, IconButton, Modal, Panel, Table} from "./ui"; import {Button, Header, Panel, Table} from "./ui";
import QRCode from "react-qr-code"; import {QRCodeButton} from "./QRCode";
const bitcoinAddress = '1mi1ddLSd6LmkuwJd1ttZsKuED724vYjS'; const bitcoinAddress = '1mi1ddLSd6LmkuwJd1ttZsKuED724vYjS';
const bitcoinContent = `bitcoin:${bitcoinAddress}`; const bitcoinContent = `bitcoin:${bitcoinAddress}`;
@ -13,27 +13,8 @@ const moneroAddress = '87jv2NpGb5sbUwk7zYYwEY5RAoh1jRfTo4d1BAewVdJJFKg2bDF2UXtLf
const moneroContent = `monero:${moneroAddress};` const moneroContent = `monero:${moneroAddress};`
function CoinQRButton({qrCodeValue, header, buttonColor}) { function CoinQRButton({qrCodeValue, header, buttonColor}) {
const [open, setOpen] = useState(false); return <QRCodeButton value={qrCodeValue} label={`Show ${header} QR code`} header={header}
color={buttonColor}/>;
return <>
<IconButton icon='qrcode' label={`Show ${header} QR code`} color={buttonColor}
onClick={() => setOpen(true)}/>
<Modal size='small' closeIcon
open={open}
onClose={() => setOpen(false)}
onOpen={() => setOpen(true)}
>
<Modal.Header>{header}</Modal.Header>
<Modal.Content>
{/* `media`: the white field a scanner needs is filtered as a unit by night mode,
rather than sitting on screen as a lit panel. */}
<div className='media'
style={{backgroundColor: '#FFFFFF', display: 'inline-block', padding: '1em'}}>
<QRCode value={qrCodeValue} size={300}/>
</div>
</Modal.Content>
</Modal>
</>
} }
function CoinRow({header, qrCodeValue, address, buttonColor}) { function CoinRow({header, qrCodeValue, address, buttonColor}) {

View file

@ -127,6 +127,15 @@ describe('<ChannelDownloadForm/>', () => {
shouldBeInvalid('#url_input'); shouldBeInvalid('#url_input');
}); });
it('can be submitted with a frequency of Once', () => {
cy.get('#url_input').type('https://example.com/playlist').wait(500);
cy.get('#frequency_select').click();
cy.contains('[role="option"]:visible', 'Once').should('be.visible').click({force: true});
cy.get('#frequency_select').should('have.value', 'Once');
cy.get('#download_form_download_button').should('not.be.disabled');
});
it('can choose different options', () => { it('can choose different options', () => {
/* /*
* `#download_frequency_selector` and `.item` named the old dropdown and its menu rows. * `#download_frequency_selector` and `.item` named the old dropdown and its menu rows.

View file

@ -1,5 +1,5 @@
import React, {useState} from "react"; import React, {useState} from "react";
import {fetchVideoDownloadDefaults, getDownloaders, postDownload, putDownload} from "../api"; import {fetchVideoDownloadDefaults, getDownloaders, getTorrents, postDownload, putDownload, uploadTorrent} from "../api";
import { import {
APIButton, APIButton,
DirectorySearch, DirectorySearch,
@ -13,8 +13,22 @@ import {
validURL, validURL,
validURLs, validURLs,
} from "./Common"; } from "./Common";
import {Button, Group, Header, Icon, Message, MultiSelect, NumberInput, Select, Stack, TextInput, Textarea} from "./ui"; import {
Button,
Group,
Header,
Icon,
Message,
MultiSelect,
NumberInput,
Select,
Stack,
TextInput,
Textarea,
toast,
} from "./ui";
import {Link} from "react-router"; import {Link} from "react-router";
import {VPN_SETTINGS_PATH, VpnStateUnknown} from "./admin/VpnSection";
import {TagsSelector} from "../Tags"; import {TagsSelector} from "../Tags";
import { import {
commaSeparatedValidator, commaSeparatedValidator,
@ -247,28 +261,38 @@ export function DownloadFrequencySelector({
} }
export function DownloaderSelector({form, name = 'sub_downloader', path = 'sub_downloader'}) { export function DownloaderSelector({form, name = 'sub_downloader', path = 'sub_downloader'}) {
const [downloaders, setDownloaders] = React.useState([]); // null = pending, undefined = could not be fetched, a list = loaded. Until loaded, the select is
// disabled and says why, rather than sitting empty as though there were no downloaders.
const [downloaders, setDownloaders] = React.useState(null);
const fetchDownloaders = async () => { const fetchDownloaders = async () => {
let {downloaders: downloaders_} = await getDownloaders(); const result = await getDownloaders();
downloaders_ = downloaders_.map((i) => { if (!result || !Array.isArray(result.downloaders)) {
setDownloaders(undefined);
return;
}
setDownloaders(result.downloaders.map((i) => {
return {key: i.name, text: i.pretty_name || i.name, value: i.name} return {key: i.name, text: i.pretty_name || i.name, value: i.name}
}) }));
setDownloaders(downloaders_);
} }
React.useEffect(() => { React.useEffect(() => {
fetchDownloaders(); fetchDownloaders();
}, []); }, []);
const placeholder = downloaders === null ? 'Loading downloaders…'
: downloaders === undefined ? 'Could not fetch downloaders'
: 'Select a downloader';
return <SelectField return <SelectField
form={form} form={form}
name={name} name={name}
path={path} path={path}
required required
label='Downloader' label='Downloader'
placeholder='Select a downloader' placeholder={placeholder}
options={downloaders} options={downloaders || []}
disabled={!Array.isArray(downloaders)}
/> />
} }
@ -1496,6 +1520,116 @@ export function FilesDownloadForm({
</form> </form>
} }
// One magnet link or .torrent URL per line.
export const validTorrentUrls = (value) => {
const lines = (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
return lines.length > 0 && lines.every(i => /^magnet:\?/i.test(i) || /^https?:\/\/\S+$/i.test(i));
};
// The URLs are optional (a .torrent file may be chosen instead); a stable function, as the form registers it.
const optionalTorrentUrls = (value) => !(value || '').trim() || validTorrentUrls(value);
function TorrentVpnStatus() {
const [status, setStatus] = React.useState(null);
const [failed, setFailed] = React.useState(false);
React.useEffect(() => {
let cancelled = false;
getTorrents()
.then(s => !cancelled && setStatus(s))
.catch(e => {
console.error('Failed to get torrents', e);
if (!cancelled) {
setFailed(true);
}
});
return () => {
cancelled = true;
};
}, []);
if (failed) {
return <VpnStateUnknown/>;
}
if (!status) {
return null;
}
const vpn = status.vpn || {};
if (vpn.state === 'connected') {
return <Message kind='success'>
VPN connected{vpn.public_ip ? <> · peers see <b>{vpn.public_ip}</b></> : null}
</Message>;
}
return <Message kind='warning' title='The VPN is not connected'>
Torrents only use the VPN. This torrent will start once the VPN connects.{' '}
<Link to={VPN_SETTINGS_PATH}>Set up the VPN</Link>
</Message>;
}
export function TorrentDownloadForm({download, onCancel, actions = DownloadFormButtons}) {
const [showMessage, setShowMessage] = React.useState(false);
const [file, setFile] = React.useState(null);
const fileInput = React.useRef(null);
const submitter = async (formData) => {
const urls = (formData.urls || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
if (!file && !urls.length) {
throw new Error('Enter a magnet link or .torrent URL, or choose a .torrent file');
}
if (file) {
try {
await uploadTorrent(file, formData.destination);
} catch (e) {
// The Download button only changes its icon; say why (postDownload toasts its own failures).
toast({type: 'error', title: 'Could not add the .torrent file', description: e.message, time: 6000});
throw e;
}
setFile(null);
}
if (urls.length) {
await postDownload({downloader: Downloaders.Torrent, destination: formData.destination, urls});
}
};
const emptyFormData = {destination: null, urls: ''};
const form = useForm({
submitter,
defaultFormData: mergeDeep(emptyFormData, download),
emptyFormData,
clearPathsOnSuccess: URL_PATHS,
onSuccess: async () => setShowMessage(true),
});
return <form onSubmit={(e) => e.preventDefault()}>
<Header as='h3' icon='share'>Torrent</Header>
<p>Download (and share) torrents of open data. Torrents only use the VPN, so peers never see this WROLPi's own
address. Saved in the "torrents" directory unless you choose another.</p>
<Stack gap='md'>
<TorrentVpnStatus/>
{/* Optional: a .torrent file may be chosen instead (or as well). */}
<UrlsField form={form} label='Magnet links or .torrent URLs' placeholder='magnet:?xt=urn:btih:...'
valid={optionalTorrentUrls}/>
<div>
<input ref={fileInput} type='file' accept='.torrent,application/x-bittorrent'
style={{display: 'none'}} data-testid='torrent-file'
onChange={e => setFile((e.target.files && e.target.files[0]) || null)}/>
<Group gap='sm'>
<Button type='button' role='cancel' icon='file' disabled={form.disabled}
onClick={() => fileInput.current && fileInput.current.click()}>
{file ? 'Choose another .torrent file' : 'Or choose a .torrent file'}
</Button>
{file && <span>{file.name}</span>}
</Group>
</div>
<DestinationForm form={form}/>
{showMessage && <SuccessfulDownloadSubmitMessage/>}
{/* Download waits for something to download: a URL or a chosen file. */}
{actions({onCancel, form: {...form, ready: form.ready && (!!file || !!(form.formData.urls || '').trim())}})}
</Stack>
</form>
}
const suffixValidator = (value) => { const suffixValidator = (value) => {
const error = commaSeparatedValidator(value); const error = commaSeparatedValidator(value);
if (error) { if (error) {
@ -1649,11 +1783,12 @@ function UrlField({form, required = true, name = 'url', path = 'url', disabled =
} }
/** Multiline URLs field: one URL per line. */ /** Multiline URLs field: one URL per line. */
function UrlsField({name = 'urls', required, form}) { function UrlsField({name = 'urls', required, form, label = 'URLs', placeholder = 'Enter one URL per line',
valid = validURLs}) {
required = required !== undefined; required = required !== undefined;
const validator = (value) => { const validator = (value) => {
if (!validURLs(value)) { if (!valid(value)) {
return 'Invalid URLs'; return 'Invalid URLs';
} }
}; };
@ -1677,10 +1812,10 @@ function UrlsField({name = 'urls', required, form}) {
}; };
return <div> return <div>
<FieldLabel htmlFor='urls_textarea' label='URLs' required={required}/> <FieldLabel htmlFor='urls_textarea' label={label} required={required}/>
<Textarea <Textarea
id='urls_textarea' id='urls_textarea'
placeholder='Enter one URL per line' placeholder={placeholder}
name='urls' name='urls'
minRows={4} minRows={4}
autosize autosize
@ -1714,6 +1849,7 @@ export function DownloadMenu({onOpen, disabled, initialDownloader, initialUrls})
<Button color='blue' disabled={disabled} onClick={() => localOnOpen('video_channel')}>Channel/Playlist</Button> <Button color='blue' disabled={disabled} onClick={() => localOnOpen('video_channel')}>Channel/Playlist</Button>
<Button disabled={disabled} onClick={() => localOnOpen('rss')}>RSS Feed</Button> <Button disabled={disabled} onClick={() => localOnOpen('rss')}>RSS Feed</Button>
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('file')}>Files</Button> <Button color='grey' disabled={disabled} onClick={() => localOnOpen('file')}>Files</Button>
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('torrent')}>Torrent</Button>
<Button role='danger' disabled={disabled} onClick={() => localOnOpen('scrape')}>Scrape</Button> <Button role='danger' disabled={disabled} onClick={() => localOnOpen('scrape')}>Scrape</Button>
</Stack>); </Stack>);
@ -1736,6 +1872,7 @@ export function DownloadMenu({onOpen, disabled, initialDownloader, initialUrls})
video_channel: <ChannelDownloadForm onCancel={clearSelected} download={seed}/>, video_channel: <ChannelDownloadForm onCancel={clearSelected} download={seed}/>,
rss: <RSSDownloadForm onCancel={clearSelected} download={seed}/>, rss: <RSSDownloadForm onCancel={clearSelected} download={seed}/>,
file: <FilesDownloadForm onCancel={clearSelected} download={seed}/>, file: <FilesDownloadForm onCancel={clearSelected} download={seed}/>,
torrent: <TorrentDownloadForm onCancel={clearSelected} download={seed}/>,
scrape: <ScrapeFilesDownloadForm onCancel={clearSelected} download={seed}/> scrape: <ScrapeFilesDownloadForm onCancel={clearSelected} download={seed}/>
}; };

View file

@ -1,8 +1,9 @@
import React from 'react'; import React from 'react';
import {render, screen, waitFor} from '@testing-library/react'; import {render, screen, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import {DestinationForm} from './Download'; import {DepthInputForm, DestinationForm} from './Download';
import {createTestForm} from '../test-utils'; import {useForm} from '../hooks/useForm';
import {createTestForm, renderWithProviders} from '../test-utils';
// Mock DirectorySearch component - simplified to avoid useState/useEffect warnings // Mock DirectorySearch component - simplified to avoid useState/useEffect warnings
jest.mock('./Common', () => { jest.mock('./Common', () => {
@ -251,3 +252,26 @@ describe('DestinationForm', () => {
}); });
}); });
}); });
describe('NumberField', () => {
// Renders a NumberField against a real useForm: the Mantine NumberInput passes a value (not an
// event) to onChange, which used to reach `e.preventDefault()` and throw while typing.
function DepthHarness({onData}) {
const form = useForm({defaultFormData: {settings: {depth: ''}}, submitter: jest.fn()});
onData(form.formData);
return <DepthInputForm form={form}/>;
}
it('typing into a NumberField updates the form without throwing', async () => {
let latest = null;
renderWithProviders(<DepthHarness onData={(d) => latest = d}/>);
const input = screen.getByRole('textbox', {name: /Depth/});
await userEvent.type(input, '3');
await waitFor(() => {
expect(latest.settings.depth).toBe(3);
});
expect(input).toHaveValue('3');
});
});

View file

@ -0,0 +1,43 @@
import React from 'react';
import {act, render, screen} from '../test-utils';
import {createTestForm} from '../test-utils';
import {DownloaderSelector} from './Download';
import {getDownloaders} from '../api';
// The RSS form's Downloader select is filled from the API. Until the list arrives, or if it could
// not be fetched, the select must say so rather than sit empty as though there were no downloaders.
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getDownloaders: jest.fn(),
}));
const makeForm = () => createTestForm({}, {
overrides: {getSelectionProps: () => [{value: null, onChange: jest.fn(), disabled: false, error: null}]},
});
beforeEach(() => getDownloaders.mockReset());
test('pending: the select says it is loading and is disabled', () => {
getDownloaders.mockReturnValue(new Promise(() => {
}));
render(<DownloaderSelector form={makeForm()}/>);
const input = screen.getByPlaceholderText('Loading downloaders…');
expect(input).toBeDisabled();
});
test('failed: the select says the downloaders could not be fetched', async () => {
getDownloaders.mockResolvedValue(undefined);
render(<DownloaderSelector form={makeForm()}/>);
await act(async () => {
});
expect(screen.getByPlaceholderText('Could not fetch downloaders')).toBeDisabled();
});
test('loaded: the select offers the downloaders', async () => {
getDownloaders.mockResolvedValue({downloaders: [{name: 'video', pretty_name: 'Videos'}]});
render(<DownloaderSelector form={makeForm()}/>);
await act(async () => {
});
expect(screen.getByPlaceholderText('Select a downloader')).toBeEnabled();
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,746 @@
import {WEAPON_CHOICES} from './FalloutPanel';
import {serveFallout} from '../map-shared/fallout/work.js';
import {loadTerrainGrid} from './falloutTerrain';
// No terrain files under Jest, until a test gives a grid.
jest.mock('./falloutTerrain', () => ({loadTerrainGrid: jest.fn(async () => null)}));
// No forecast (unless a test gives one), past days or fetches under Jest.
let mockLatestWinds = null;
let mockWeather = {enabled: true, download: {status: 'complete'}, targets: 1, spacing: 1, points: 160, seconds: 61,
field: null};
const mockWeatherSet = [];
jest.mock('../api', () => ({
getFalloutClimatology: async () => null,
getFalloutClimatologyMonth: async () => null,
getWeather: async () => mockWeather,
setWeatherSubscription: (enabled) => {
mockWeatherSet.push(enabled);
return Promise.resolve({...mockWeather, enabled});
},
downloadWeatherNow: async () => mockWeather,
getLatestFalloutWinds: async () => mockLatestWinds,
}));
// Fallout workers serving their tasks (as fallout.worker.js does) here, as a browser's would on
// another thread: messages arrive later, copied. `made` are those made since it was emptied.
const made = [];
const copy = (v) => {
if (v instanceof ArrayBuffer) return v.slice(0);
if (ArrayBuffer.isView(v)) return v.slice();
if (Array.isArray(v)) return v.map(copy);
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, copy(x)]));
return v;
};
function worker({fail = false} = {}) {
const scope = {postMessage: (data) => setTimeout(() => !w.terminated && w.onmessage?.({data}), 0)};
serveFallout(scope);
const w = {
terminated: false, onmessage: null, onerror: null, given: [], kind: null,
postMessage(data) {
if (data.type === 'start') {
w.kind = data.kind;
w.start = data;
}
if (data.type === 'task') w.given.push(data.k);
const copied = copy(data);
setTimeout(() => {
if (w.terminated) return;
if (fail && data.type === 'task') w.onerror?.({message: 'No such script'});
else scope.onmessage({data: copied});
}, 0);
},
terminate() {
w.terminated = true;
},
};
made.push(w);
return w;
}
describe('the fallout panel\'s weapons', () => {
test('are grouped by country, then a yield of one\'s own', () => {
const groups = WEAPON_CHOICES.map((g) => g.group);
expect(groups[0]).toBe('United States');
expect(groups).toContain('Russia');
expect(groups).toContain('Improvised nuclear device');
expect(groups[groups.length - 1]).toBe('Other');
expect(WEAPON_CHOICES[groups.length - 1].items.map((i) => i.value)).toEqual(['custom']);
});
test('each read differently, by name and yield', () => {
const labels = WEAPON_CHOICES.flatMap((g) => g.items.map((i) => i.label));
expect(new Set(labels).size).toBe(labels.length);
expect(labels).toContain('B61-12 bomb, 0.3 kt, half fission');
});
test('say their yield', () => {
const w88 = WEAPON_CHOICES[0].items.find((i) => i.value === 'w88');
expect(w88.label).toBe('W88 (Trident II D5), 455 kt, half fission');
});
});
describe('the fallout panel\'s winds', () => {
const {windProfile, hourLabel} = require('./FalloutPanel');
test('fall back to one wind at every height until there is a forecast', () => {
const profile = windProfile({direction: 270, speed: 10});
expect(profile).toHaveLength(1);
expect(profile[0][1]).toBeGreaterThan(0);
});
test('mark the hour nearest now', () => {
expect(hourLabel('2026-11-22T00:00Z', true)).toMatch(/\(now\)$/);
expect(hourLabel('2026-11-22T00:00Z', false)).not.toMatch(/now/);
});
});
describe('the fallout of several bursts', () => {
const {simulateBursts} = require('./FalloutPanel');
const {prepareField} = require('../map-shared/fallout/winds.js');
const winds = {profile: [[0, 10, 0]]};
const bursts = [
{lat: 40, lon: -105, yieldKt: 10, fissionFraction: 0.5},
{lat: 40.5, lon: -104, yieldKt: 100, fissionFraction: 0.5},
];
// A forecast over 39-42 N, 106-103 W, every degree, whose wind turns from the west to the
// south-west over the hours, on ground rising to the east.
const HOURS = ['2026-11-22T00:00Z', '2026-11-22T01:00Z', '2026-11-22T02:00Z'];
function forecast() {
const points = [];
for (const lat of [39, 40, 41, 42]) for (const lon of [-106, -105, -104, -103]) points.push({lat, lon, elevation: 1500 + (lon + 106) * 100});
return {
source: 'Open-Meteo', fetched_at: '2026-11-22T00:30:00+00:00', spacing: 1, points, hours: HOURS,
winds: points.map(() => HOURS.map((_, h) => [[10, 12, 270 - 20 * h], [20000, 30, 260 - 20 * h]])),
rain: points.map(() => HOURS.map(() => 0)),
};
}
const fieldWinds = () => ({prepared: prepareField(forecast()), startMs: Date.parse(HOURS[0])});
test('carries each burst by the winds where it is, from the ground there', async () => {
const ran = await simulateBursts(bursts, {winds: fieldWinds(), useTerrain: false});
expect(ran.grid.values.some((v) => v > 0)).toBe(true);
// Not as one wind would carry them.
const one = await simulateBursts(bursts, {winds, useTerrain: false});
expect(ran.grid.values.length === one.grid.values.length
&& ran.grid.values.every((v, i) => v === one.grid.values[i])).toBe(false);
});
test('is drawn on one grid around the first burst', async () => {
const one = await simulateBursts(bursts.slice(0, 1), {winds, useTerrain: false});
const both = await simulateBursts(bursts, {winds, useTerrain: false});
expect(both.origin).toBe(bursts[0]);
const sum = (g) => g.values.reduce((a, v) => a + v, 0) * g.cell ** 2;
expect(sum(both.grid)).toBeGreaterThan(sum(one.grid) * 5);
expect(both.terrainStatus).toMatch(/terrain is off/);
});
test('stops when it is no longer wanted', async () => {
expect(await simulateBursts(bursts, {winds, useTerrain: false, cancelled: () => true})).toBeNull();
});
const MANY = Array.from({length: 7}, (_, i) => ({lat: 40 + 0.2 * i, lon: -105 + 0.3 * i, yieldKt: 5 * (i + 1), fissionFraction: 0.5}));
// Whether two results have the same grid (said quickly: Jest's diff of such arrays takes minutes).
const same = (a, b) => a.grid.cell === b.grid.cell && a.grid.values.length === b.grid.values.length
&& a.grid.values.every((v, i) => v === b.grid.values[i]);
test('spreads the bursts over workers, as the page calculates them', async () => {
for (const w of [winds, fieldWinds()]) {
made.length = 0;
const here = await simulateBursts(MANY, {winds: w, useTerrain: false});
const heard = [];
const spread = await simulateBursts(MANY, {winds: w, useTerrain: false, workers: 3, makeWorker: () => worker(),
onProgress: (done, total) => heard.push([done, total])});
// The bursts by three workers, then the grid's parts by three more.
const burstWorkers = made.filter((x) => x.kind === 'bursts');
const gridWorkers = made.filter((x) => x.kind === 'grid');
expect(burstWorkers).toHaveLength(3);
expect(gridWorkers).toHaveLength(3);
expect(burstWorkers.flatMap((x) => x.given).sort()).toEqual([0, 1, 2, 3, 4, 5, 6]);
expect(gridWorkers.flatMap((x) => x.given).length).toBeGreaterThan(3);
expect(made.every((x) => x.given.length > 0 && x.terminated)).toBe(true);
expect(heard[heard.length - 1]).toEqual([7, 7]);
expect(same(spread, here)).toBe(true);
expect(JSON.stringify(spread.spots) === JSON.stringify(here.spots)).toBe(true);
// Given the forecast's arrays, not the forecast as fetched.
if (w.prepared) {
const {prepared} = burstWorkers[0].start;
expect(prepared.u).toBeInstanceOf(Float32Array);
expect(prepared.field.winds).toBeUndefined();
expect(prepared.field.points).toHaveLength(16);
}
}
});
test('shows its progress every so often, and when all is done', () => {
const {everySoOften} = require('./FalloutPanel');
jest.useFakeTimers();
try {
const heard = [];
const report = everySoOften((done, total) => heard.push(done));
for (let done = 1; done <= 10; done++) {
report(done, 10);
jest.advanceTimersByTime(30);
}
// The first, one in every four after it (30 ms apart), and the last.
expect(heard).toEqual([1, 5, 9, 10]);
} finally {
jest.useRealTimers();
}
});
test('gives its workers the terrain, when it is read', async () => {
// Ground rising to the north-east of the bursts.
const nx = 81, ny = 81, step = 0.05;
const grid = {west: -107, south: 38, step, nx, ny, values: new Float32Array(nx * ny)};
for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) grid.values[j * nx + i] = 1500 + 40 * (i + j);
loadTerrainGrid.mockImplementation(async () => ({grid, zoom: 9, coverage: 1}));
try {
const flat = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: false});
const here = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true});
made.length = 0;
const heard = [];
const spread = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true, workers: 2,
makeWorker: () => worker(), onProgress: (done, total) => heard.push([done, total])});
expect(here.terrainStatus).toMatch(/Follows the terrain/);
expect(same(here, flat)).toBe(false);
expect(same(spread, here)).toBe(true);
// A pass on flat ground, then another over the terrain, each by its own workers.
expect(made.map((x) => x.kind)).toEqual(['bursts', 'bursts', 'grid', 'grid', 'bursts', 'bursts', 'grid', 'grid']);
expect(heard[heard.length - 1]).toEqual([14, 14]);
} finally {
loadTerrainGrid.mockImplementation(async () => null);
}
});
test('stops its workers at once when cancelled', async () => {
made.length = 0;
const controller = new AbortController();
const running = simulateBursts(MANY, {winds, useTerrain: false, workers: 3, makeWorker: () => worker(),
signal: controller.signal});
controller.abort();
expect(await running).toBeNull();
expect(made).toHaveLength(3);
expect(made.every((x) => x.terminated)).toBe(true);
});
test('calculates on the page when its workers fail, or there are none', async () => {
made.length = 0;
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
const here = await simulateBursts(MANY, {winds, useTerrain: false});
const ran = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => worker({fail: true})});
expect(error).toHaveBeenCalled();
error.mockRestore();
expect(made.every((x) => x.terminated)).toBe(true);
expect(same(ran, here)).toBe(true);
const none = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => null});
expect(same(none, here)).toBe(true);
});
});
describe('the fallout image', () => {
const {imageRows} = require('./FalloutPanel');
test('takes each row from the grid row at its own latitude', () => {
// A grid from 20 to 80 degrees north, around 40: a tenth of a degree a row.
const grid = {y0: -20 * 111320, cell: 11132, ny: 600, nx: 1};
const rows = imageRows(grid, 40, 600);
// The top row is the grid's northernmost, the bottom its southernmost.
expect(rows[0]).toBe(599);
expect(rows[599]).toBe(0);
// Halfway down the image, in Web Mercator, is well north of halfway in latitude (50 degrees).
expect(rows[300]).toBeGreaterThan(330);
for (let r = 1; r < 600; r++) expect(rows[r]).toBeLessThanOrEqual(rows[r - 1]);
});
test('is the plain grid over a small area', () => {
const grid = {y0: -5000, cell: 100, ny: 100, nx: 1};
const rows = imageRows(grid, 40, 100);
expect(rows[0]).toBe(99);
expect(Math.abs(rows[50] - 49)).toBeLessThanOrEqual(1);
});
});
describe('the fallout timeline', () => {
const {screen, fireEvent} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const {Timeline, HOURS, afterLabel, weakerThanH1} = require('./FalloutPanel');
test('runs from the first hour to two weeks, in longer steps as it goes', () => {
expect(HOURS[0]).toBe(1);
expect(HOURS[HOURS.length - 1]).toBe(336);
for (let k = 1; k < HOURS.length; k++) expect(HOURS[k]).toBeGreaterThan(HOURS[k - 1]);
expect(HOURS.map(afterLabel)).toEqual(['1 hour', '2 hours', '3 hours', '6 hours', '12 hours', '1 day',
'2 days', '3 days', '5 days', '1 week', '2 weeks']);
});
test('says how much the fallout has weakened since H+1', () => {
// t^-1.2: about 10 times weaker for every 7 times longer.
expect(weakerThanH1(7)).toBe('10');
expect(weakerThanH1(3)).toBe('3.7');
expect(weakerThanH1(48)).toBe('100');
expect(weakerThanH1(336)).toBe('1,100');
});
test('says what it shows, and moves and plays the hours', () => {
const onAfter = jest.fn(), onPlaying = jest.fn();
const {unmount} = renderWithProviders(<Timeline after={1} onAfter={onAfter} playing={false}
onPlaying={onPlaying} startMs={null}/>);
expect(screen.getByText(/^H\+1: the fallout landed by then\.$/)).toBeTruthy();
// Each step of the slider is one of the hours.
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: String(HOURS.indexOf(48))}});
expect(onAfter).toHaveBeenCalledWith(48);
fireEvent.click(screen.getByLabelText('Play'));
expect(onPlaying).toHaveBeenCalledWith(true);
unmount();
renderWithProviders(<Timeline after={6} onAfter={onAfter} playing={true} onPlaying={onPlaying}
startMs={Date.parse('2026-11-22T00:00Z')}/>);
expect(screen.getByText(/^H\+6, .*: the fallout landed by then, about 8\.6 times weaker than at H\+1\.$/)).toBeTruthy();
expect(screen.getByLabelText('Time after the bursts').getAttribute('aria-valuetext')).toBe('6 hours');
fireEvent.click(screen.getByLabelText('Pause'));
expect(onPlaying).toHaveBeenLastCalledWith(false);
});
});
describe('the total dose view', () => {
const {TOTAL_BANDS, DOSE_BANDS, legendHeading, legendText} = require('./FalloutPanel');
test('has its own bands, each saying what it does to a person', () => {
expect(TOTAL_BANDS.map((b) => b.rate)).toEqual([1000, 450, 100, 25, 5]);
for (const b of TOTAL_BANDS) expect(b.meaning.length).toBeGreaterThan(5);
// The same colors, highest first.
expect(TOTAL_BANDS.map((b) => b.color)).toEqual(DOSE_BANDS.map((b) => b.color));
});
test('says what is shown, by the hour', () => {
expect(legendHeading('total', 6)).toBe('Total dose outdoors in the first two weeks');
expect(legendHeading('rate', 1)).toBe('Dose rate 1 hour after the bursts');
expect(legendHeading('rate', 120)).toBe('Dose rate 5 days after the bursts');
expect(legendText('total')).toMatch(/outdoors the whole time/);
expect(legendText('rate')).toMatch(/landed by then/);
expect(legendText('rate')).toMatch(/weakens/);
});
});
describe('the forecast\'s warning', () => {
const {forecastShortText} = require('./FalloutPanel');
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const of = (from, count) => ({hours: Array.from({length: count}, (_, h) => new Date(hourMs + (from + h) * 3600000).toISOString())});
test('says when it is out of date, or ends before the fallout is down, and else nothing', () => {
expect(forecastShortText(null, 0)).toBeNull();
expect(forecastShortText(of(-30, 10), 9)).toMatch(/out of date.*last hour's winds are held for the whole simulation/);
expect(forecastShortText(of(-1, 30), 1)).toMatch(/ends at .*, before all the fallout is down/);
expect(forecastShortText(of(-1, 96), 1)).toBeNull();
});
test('says the last hour is held only from when it is, for the hour chosen', () => {
// Out of date, but its first hour still has 48 hours of winds after it: none is held.
const old = of(-200, 96);
expect(forecastShortText(old, 0)).toMatch(/out of date/);
expect(forecastShortText(old, 0)).not.toMatch(/held/);
expect(forecastShortText(old, 60)).toMatch(/held from then on/);
expect(forecastShortText(old, 60)).not.toMatch(/whole simulation/);
expect(forecastShortText(old, 95)).toMatch(/held for the whole simulation/);
});
});
describe('the targets simulated', () => {
const {withSavedTargets, targetsUnsaved, withWeapon} = require('./FalloutPanel');
const saved = [{id: 1, label: 'A', lat: 1, lon: 1, kind: 'target', weapon: 'yars'},
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'custom', yield_kt: 20, fission_fraction: 1}];
const tried = {key: 'new-1', label: 'C', lat: 3, lon: 3, weapon: 'w88'};
test('are the saved ones once loaded, then those tried out', () => {
const loaded = withSavedTargets(saved, [tried]);
expect(loaded.map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
// Loading again keeps the tried ones once, and the saved ones as saved.
expect(withSavedTargets(saved, loaded).map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
});
test('are unsaved when they differ from the saved ones', () => {
expect(targetsUnsaved([], saved, false)).toBe(false);
expect(targetsUnsaved([tried], saved, false)).toBe(true);
const loaded = withSavedTargets(saved, []);
expect(targetsUnsaved(loaded, saved, true)).toBe(false);
expect(targetsUnsaved(loaded.slice(1), saved, true)).toBe(true);
expect(targetsUnsaved([withWeapon(loaded[0], {weapon: 'w88'}), loaded[1]], saved, true)).toBe(true);
expect(targetsUnsaved([...loaded, tried], saved, true)).toBe(true);
});
test('take a new weapon in place of the old', () => {
expect(withWeapon(saved[1], {weapon: 'w88', fission_fraction: 0.5})).toEqual(
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'w88', fission_fraction: 0.5});
});
});
describe('the fallout panel\'s steps', () => {
const {screen, fireEvent, waitFor, act, cleanup} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const FalloutPanel = require('./FalloutPanel').default;
// A map which keeps the one image source and layer the panel draws.
function fakeMap() {
const map = {
source: null, layer: false, added: 0,
getSource: () => map.source,
addSource: (id, s) => {
map.added++;
map.source = {...s, updateImage: (i) => Object.assign(map.source, i)};
},
addLayer: () => {
map.layer = true;
},
getLayer: () => map.layer,
removeLayer: () => {
map.layer = false;
},
removeSource: () => {
map.source = null;
},
on: () => null, off: () => null,
getCenter: () => ({lat: 40, lng: -100}),
};
return map;
}
const target = {key: 'saved-1', id: 1, label: 'Somewhere', lat: 40, lon: -100, weapon: 'w88'};
let getContext, toDataURL;
beforeEach(() => {
loadTerrainGrid.mockClear();
// jsdom draws no canvas: an image of the right size is all the map is given.
getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => ({
createImageData: (w, h) => ({data: new Uint8ClampedArray(w * h * 4)}),
putImageData: () => null,
}));
toDataURL = jest.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockImplementation(() => 'data:');
});
afterEach(() => {
cleanup();
getContext.mockRestore();
toDataURL.mockRestore();
});
test('ask for targets first, and calculate nothing until there are some', async () => {
const map = fakeMap();
renderWithProviders(<FalloutPanel map={map} targets={[]} onClose={() => null}/>);
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
expect(screen.getByText('No targets yet')).toBeTruthy();
expect(screen.getByText(/Right-clicking the map adds one too/)).toBeTruthy();
expect(screen.getByRole('button', {name: 'Next: the wind'}).disabled).toBe(true);
// The wind is a step of its own.
expect(screen.queryByRole('textbox', {name: 'Wind'})).toBeNull();
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
});
test('show the targets\' fallout only once the user goes on, hour by hour or in total', async () => {
const map = fakeMap();
renderWithProviders(<FalloutPanel map={map} targets={[target]} onClose={() => null}/>);
expect(screen.getByText('1 target')).toBeTruthy();
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
// Its fields are all shown; the winds a user can choose are the forecast or one wind of their
// own, and no test shots' winds.
expect(screen.getByRole('checkbox', {name: 'Follow the terrain'})).toBeTruthy();
expect(screen.getByRole('textbox', {name: 'Speed (mph)'})).toBeTruthy();
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
const winds = (await screen.findAllByRole('option')).map((o) => o.textContent);
expect(winds).toEqual(['Forecast winds aloft', 'One wind at every height']);
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
expect(screen.getByText('Step 4 of 4: The fallout')).toBeTruthy();
expect(screen.getByRole('button', {name: 'Hour by hour'}).getAttribute('aria-pressed')).toBe('true');
expect(screen.getByText('Dose rate 1 hour after the bursts')).toBeTruthy();
await waitFor(() => expect(loadTerrainGrid).toHaveBeenCalledTimes(1), {timeout: 20000});
await waitFor(() => expect(screen.queryByText(/Calculating/)).toBeNull(), {timeout: 20000});
expect(map.layer).toBe(true);
// A later hour, then the total, which has no timeline.
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: '5'}});
expect(screen.getByText('Dose rate 1 day after the bursts')).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Total dose'}));
expect(screen.getByText('Total dose outdoors in the first two weeks')).toBeTruthy();
expect(screen.queryByLabelText('Time after the bursts')).toBeNull();
// Back to the wind clears the map; on again, with nothing changed, it is not calculated again.
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
expect(map.layer).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
await waitFor(() => expect(map.layer).toBe(true));
expect(screen.queryByText(/Calculating/)).toBeNull();
expect(loadTerrainGrid).toHaveBeenCalledTimes(1);
}, 60000);
test('default to the forecast when it has the winds until the fallout is down, else one wind', async () => {
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
const windShown = async () => {
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
return screen.getByRole('textbox', {name: 'Wind'}).value;
};
// No forecast.
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('One wind at every height');
cleanup();
// A forecast from the hour before now, for 3 days: it has the winds.
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const hours = (count) => Array.from({length: count}, (_, h) => new Date(hourMs + (h - 1) * 3600000).toISOString());
const forecastOf = (count) => ({source: 'Open-Meteo', fetched_at: new Date(hourMs).toISOString(), spacing: 3,
points: [{lat: 40, lon: -100, elevation: 0}], hours: hours(count),
winds: [hours(count).map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours(count).map(() => 0)]});
mockLatestWinds = forecastOf(72);
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('Forecast winds aloft');
cleanup();
// One ending a day from now does not: the fallout is still coming down then.
mockLatestWinds = forecastOf(24);
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('One wind at every height');
} finally {
mockLatestWinds = null;
}
});
test('ask to download the forecast on the wind step, when it is not', async () => {
const before = mockWeather;
mockWeather = {...before, enabled: false, download: null};
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
mockWeatherSet.length = 0;
fireEvent.click(screen.getByRole('button', {name: 'Download the forecast every day'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
expect(mockWeatherSet).toEqual([true]);
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
} finally {
mockWeather = before;
}
cleanup();
// Subscribed: nothing asked.
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
});
test('warn when the forecast chosen runs out before the fallout is down', async () => {
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const hours = Array.from({length: 24}, (_, h) => new Date(hourMs - (100 - h) * 3600000).toISOString());
mockLatestWinds = {source: 'Open-Meteo', fetched_at: new Date(hourMs - 100 * 3600000).toISOString(), spacing: 3,
points: [{lat: 40, lon: -100, elevation: 0}], hours,
winds: [hours.map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours.map(() => 0)]};
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
// Too old: one wind is chosen for the user.
expect(screen.getByRole('textbox', {name: 'Wind'}).value).toBe('One wind at every height');
await act(async () => new Promise((r) => setTimeout(r, 50)));
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
fireEvent.click([...document.querySelectorAll('[role=option]')].find((o) => o.textContent === 'Forecast winds aloft'));
expect(screen.getByText(/This forecast is out of date: .*last hour's winds are held/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
expect(screen.getByText(/This forecast is out of date/)).toBeTruthy();
} finally {
mockLatestWinds = null;
}
});
test('add a target where the map is clicked next, until stopped', () => {
const onPlaceTarget = jest.fn();
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]}
onPlaceTarget={onPlaceTarget}/>);
fireEvent.click(screen.getByRole('button', {name: 'Add a target'}));
expect(onPlaceTarget).toHaveBeenLastCalledWith(true);
rerender(<FalloutPanel map={fakeMap()} targets={[]} placingTarget onPlaceTarget={onPlaceTarget}/>);
expect(screen.getByText('Click the map where the target is.')).toBeTruthy();
expect(screen.queryByRole('button', {name: 'Add a target'})).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
expect(onPlaceTarget).toHaveBeenLastCalledWith(false);
// Going on to the wind stops it too.
onPlaceTarget.mockClear();
rerender(<FalloutPanel map={fakeMap()} targets={[target]} placingTarget onPlaceTarget={onPlaceTarget}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
expect(onPlaceTarget).toHaveBeenCalledWith(false);
});
test('load the saved targets before saving over them', () => {
const onLoad = jest.fn(), onSave = jest.fn();
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={156}
unsaved onLoad={onLoad} onSave={onSave}/>);
// Only the target being tried out is simulated until the saved ones are loaded.
expect(screen.getByText('1 target')).toBeTruthy();
expect(screen.getByText('(not saved)')).toBeTruthy();
expect(screen.getByText('Not saved.')).toBeTruthy();
const save = screen.getByRole('button', {name: 'Save Targets'});
expect(save.disabled).toBe(true);
expect(screen.getByText(/Saving replaces the saved targets: load them first/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Load Saved Targets (156)'}));
expect(onLoad).toHaveBeenCalledTimes(1);
rerender(<FalloutPanel map={fakeMap()} targets={[target, tried]} savedCount={156} loaded unsaved
onLoad={onLoad} onSave={onSave}/>);
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
expect(screen.queryByText(/load them first/)).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Save Targets'}));
expect(onSave).toHaveBeenCalledTimes(1);
});
test('save targets when none are saved, and take one out of the list', () => {
const onRemoveTarget = jest.fn();
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]} savedCount={0}/>);
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(true);
rerender(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={0} unsaved
onRemoveTarget={onRemoveTarget}/>);
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'Remove Tried'}));
expect(onRemoveTarget).toHaveBeenCalledWith(tried);
});
});
describe('the fallout of past days', () => {
const {simulateClimate, CLIMATE_BANDS} = require('./FalloutPanel');
const {parseClimatology} = require('../map-shared/fallout/climatology.js');
// Days on a coarse grid (lat 90..-90 every 30, lon 0..330 every 30), each one wind [east, north].
function climate(days) {
const header = {version: 1, levels_hpa: [1000, 500], lat: [90, -30, 7], lon: [0, 30, 12],
days: days.map((_, k) => `200${k}-05-01`)};
const head = new TextEncoder().encode(JSON.stringify(header));
const size = 2 * 7 * 12;
const bytes = new Uint8Array(10 + head.length + 2 * size + days.length * 2 * size);
bytes.set([87, 70, 67, 76], 0);
const view = new DataView(bytes.buffer);
view.setUint16(4, 1, true);
view.setUint32(6, head.length, true);
bytes.set(head, 10);
let at = 10 + head.length;
for (let c = 0; c < size; c++) view.setInt16(at + 2 * c, c < size / 2 ? 100 : 5500, true);
at += 2 * size;
for (const [e, n] of days) {
for (let c = 0; c < size; c++) view.setInt8(at + c, e);
for (let c = 0; c < size; c++) view.setInt8(at + size + c, n);
at += 2 * size;
}
return parseClimatology(bytes);
}
test('counts the days each place was reached, for all the bursts at once', async () => {
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
const heard = [];
const ran = await simulateClimate(bursts, climate([[10, 0], [10, 0], [0, 10]]),
{rate: 1, onProgress: (done, total) => heard.push([done, total])});
expect(ran.origin).toBe(bursts[0]);
expect(ran.grid.days).toBe(3);
const most = ran.grid.values.reduce((a, v) => Math.max(a, v), 0);
expect(most).toBeGreaterThan(0.3);
expect(most).toBeLessThanOrEqual(1);
expect(heard[heard.length - 1]).toEqual([6, 6]);
// The bands go from most days to any.
expect(CLIMATE_BANDS.map((b) => b.rate)).toEqual([...CLIMATE_BANDS.map((b) => b.rate)].sort((a, b) => b - a));
});
test('stops when cancelled', async () => {
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}];
expect(await simulateClimate(bursts, climate([[10, 0], [0, 10]]), {cancelled: () => true})).toBeNull();
});
const BURSTS = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
const DAYS = [[10, 0], [10, 0], [0, 10], [-8, 4], [3, -9]];
test('spreads the days over workers, and counts them as the page does', async () => {
made.length = 0;
const clim = climate(DAYS);
const here = await simulateClimate(BURSTS, clim, {rate: 1});
const heard = [];
const spread = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker(),
onProgress: (done, total) => heard.push([done, total])});
expect(made).toHaveLength(2);
// Every day given once, to one worker or the other, and both given some.
expect(made.flatMap((w) => w.given).sort()).toEqual([0, 1, 2, 3, 4]);
expect(made.every((w) => w.given.length > 0)).toBe(true);
expect(made.every((w) => w.terminated)).toBe(true);
expect(heard[heard.length - 1]).toEqual([10, 10]);
expect(spread.grid.days).toBe(5);
expect(spread.grid.cell).toBe(here.grid.cell);
expect(Array.from(spread.grid.values)).toEqual(Array.from(here.grid.values));
});
test('stops its workers at once when cancelled', async () => {
made.length = 0;
const controller = new AbortController();
const running = simulateClimate(BURSTS, climate(DAYS), {rate: 1, workers: 3, makeWorker: () => worker(),
signal: controller.signal});
controller.abort();
expect(await running).toBeNull();
expect(made).toHaveLength(3);
expect(made.every((w) => w.terminated)).toBe(true);
});
test('calculates on the page when its workers fail', async () => {
made.length = 0;
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
const clim = climate(DAYS);
const here = await simulateClimate(BURSTS, clim, {rate: 1});
const ran = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker({fail: true})});
expect(error).toHaveBeenCalled();
error.mockRestore();
expect(made.every((w) => w.terminated)).toBe(true);
expect(Array.from(ran.grid.values)).toEqual(Array.from(here.grid.values));
// And where there are none to be had.
const none = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => null});
expect(Array.from(none.grid.values)).toEqual(Array.from(here.grid.values));
});
});
describe('the fallout panel\'s progress', () => {
const {screen} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const {FalloutProgress} = require('./FalloutPanel');
test('is a bar filled as far as the bursts are calculated', () => {
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1170, total: 4680}}/>);
const bar = screen.getByRole('progressbar');
expect(bar.getAttribute('aria-valuenow')).toBe('25');
expect(screen.getByText('Calculating 1,170 of 4,680')).toBeTruthy();
unmount();
});
test('has a button which cancels the calculation', () => {
const {fireEvent} = require('@testing-library/react');
const onCancel = jest.fn();
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1, total: 2}} onCancel={onCancel}/>);
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
expect(onCancel).toHaveBeenCalledTimes(1);
unmount();
});
test('moves without a count until there is one, and is gone when done', () => {
const {rerender, unmount} = renderWithProviders(<FalloutProgress busy={true} progress={null}/>);
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBeNull();
expect(screen.getByText('Calculating…')).toBeTruthy();
rerender(<FalloutProgress busy={false} progress={null}/>);
expect(screen.queryByRole('progressbar')).toBeNull();
unmount();
});
});

View file

@ -23,7 +23,15 @@ import {
import React, {useContext, useEffect, useState} from "react"; import React, {useContext, useEffect, useState} from "react";
import {IconArrowsMove, IconChevronsUp, IconCursorText, IconTags} from "@tabler/icons-react"; import {IconArrowsMove, IconChevronsUp, IconCursorText, IconTags} from "@tabler/icons-react";
import {useHotkeys} from "react-hotkeys-hook"; import {useHotkeys} from "react-hotkeys-hook";
import {deleteFile, ignoreDirectory, makeDirectory, movePaths, renamePath, unignoreDirectory} from "../api"; import {
deleteFile,
fetchFileWorkerJobStatus,
ignoreDirectory,
makeDirectory,
movePaths,
renamePath,
unignoreDirectory
} from "../api";
import _ from 'lodash'; import _ from 'lodash';
import {SortableTable} from "./SortableTable"; import {SortableTable} from "./SortableTable";
import {useBrowseFiles, useElementWidth, useMediaDirectory, useWROLMode} from "../hooks/customHooks"; import {useBrowseFiles, useElementWidth, useMediaDirectory, useWROLMode} from "../hooks/customHooks";
@ -33,7 +41,9 @@ import {DragSelectionContext, DragSelectionProvider, SettingsContext, ThemeConte
import {BulkTagModal} from "./BulkTagModal"; import {BulkTagModal} from "./BulkTagModal";
import {InlineErrorBoundary} from "./ErrorBoundary"; import {InlineErrorBoundary} from "./ErrorBoundary";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal"; import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
import {ShareTorrentModal} from "./ShareTorrentModal";
import {UploadModal} from "./Upload"; import {UploadModal} from "./Upload";
import {useFileWorkerStatus} from "../contexts/FileWorkerStatusContext";
function depthIndentation(path) { function depthIndentation(path) {
// Repeated spaces for every folder a path is in. // Repeated spaces for every folder a path is in.
@ -228,11 +238,14 @@ function SkeletonFileRow({depth}) {
// Below this footer width (px) the action buttons are icon-only; at or above it they expand to show labels. // Below this footer width (px) the action buttons are icon-only; at or above it they expand to show labels.
// The eight labeled buttons need ~1020px to fit on a single row; this leaves a small buffer. // The eight labeled buttons need ~1020px to fit on a single row; this leaves a small buffer.
const FOOTER_LABELS_MIN_WIDTH = 1050; const FOOTER_LABELS_MIN_WIDTH = 1050;
// How often a queued rename's job is checked.
const RENAME_JOB_POLL_MS = 500;
export function FileBrowser() { export function FileBrowser() {
const [selectedPaths, setSelectedPaths] = React.useState([]); const [selectedPaths, setSelectedPaths] = React.useState([]);
const [renameOpen, setRenameOpen] = React.useState(false); const [renameOpen, setRenameOpen] = React.useState(false);
const [moveOpen, setMoveOpen] = React.useState(false); const [moveOpen, setMoveOpen] = React.useState(false);
const [shareOpen, setShareOpen] = React.useState(false);
const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false); const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false);
const [ignoreDirectoryOpen, setIgnoreDirectoryOpen] = React.useState(false); const [ignoreDirectoryOpen, setIgnoreDirectoryOpen] = React.useState(false);
const [bulkTagOpen, setBulkTagOpen] = React.useState(false); const [bulkTagOpen, setBulkTagOpen] = React.useState(false);
@ -328,6 +341,46 @@ export function FileBrowser() {
} }
}, [browseFiles]); }, [browseFiles]);
// A move finishes in the file worker after its request returns (the Files page shows its progress), so fetch
// the files again when the file worker is done.
const {status: fileWorkerStatus, setFastPolling} = useFileWorkerStatus();
const fileWorkerBusy = !!fileWorkerStatus && fileWorkerStatus.status !== 'idle';
const fileWorkerWasBusy = React.useRef(false);
useEffect(() => {
if (fileWorkerWasBusy.current && !fileWorkerBusy) {
fetchFiles();
}
fileWorkerWasBusy.current = fileWorkerBusy;
}, [fileWorkerBusy]);
// A queued rename (a directory) returns its job; wait for that job, rather than inferring it from the file
// worker's status (a short job can start and finish between two polls).
const mountedRef = React.useRef(true);
useEffect(() => () => {
mountedRef.current = false;
}, []);
const afterRename = async (jobId) => {
if (!jobId) {
await reset();
return;
}
setSelectedPaths([]);
setFastPolling(true); // Update the progress bar while the rename runs.
try {
while (mountedRef.current) {
await new Promise(resolve => setTimeout(resolve, RENAME_JOB_POLL_MS));
if (await fetchFileWorkerJobStatus(jobId) !== 'pending') {
break;
}
}
} finally {
setFastPolling(false);
}
if (mountedRef.current) {
await reset();
}
}
// Clear loading states when file data updates // Clear loading states when file data updates
useEffect(() => { useEffect(() => {
if (loadingFolders.size > 0) { if (loadingFolders.size > 0) {
@ -413,7 +466,7 @@ export function FileBrowser() {
onClose={() => setRenameOpen(false)} onClose={() => setRenameOpen(false)}
onPending={setPending} onPending={setPending}
path={selectedPaths[0]} path={selectedPaths[0]}
onSubmit={reset} onSubmit={afterRename}
/> : null} /> : null}
<Button icon={IconArrowsMove} <Button icon={IconArrowsMove}
color='teal' color='teal'
@ -426,6 +479,13 @@ export function FileBrowser() {
paths={selectedPaths} paths={selectedPaths}
onSubmit={reset} onSubmit={reset}
/> : null} /> : null}
<Button icon='share'
color='violet'
onClick={() => setShareOpen(true)}
disabled={wrolModeEnabled || selectedPathsCount !== 1}
>{label('Share')}</Button>
{selectedPathsCount === 1 ?
<ShareTorrentModal open={shareOpen} onClose={() => setShareOpen(false)} path={selectedPaths[0]}/> : null}
<Button <Button
color='blue' color='blue'
onClick={() => setMakeDirectoryOpen(true)} onClick={() => setMakeDirectoryOpen(true)}
@ -619,15 +679,16 @@ export function RenameModal({open, onClose, path, onSubmit, onPending}) {
if (e) { if (e) {
e.preventDefault(); e.preventDefault();
} }
let jobId = null;
try { try {
console.log(`Renaming: ${path} to ${value}`); console.log(`Renaming: ${path} to ${value}`);
onPending(true); onPending(true);
await renamePath(path, value); jobId = await renamePath(path, value);
} finally { } finally {
onClose(); onClose();
onPending(false); onPending(false);
if (onSubmit) { if (onSubmit) {
await onSubmit(); await onSubmit(jobId);
} }
} }
} }

View file

@ -6,10 +6,13 @@ import {FileBrowser, filterBrowseFiles} from './FileBrowser';
import {renderWithProviders} from '../test-utils'; import {renderWithProviders} from '../test-utils';
import {SettingsContext} from '../contexts/contexts'; import {SettingsContext} from '../contexts/contexts';
import {FilePreviewContext} from './FilePreview'; import {FilePreviewContext} from './FilePreview';
import {FileWorkerStatusContext} from '../contexts/FileWorkerStatusContext';
import {fileWorkerStatusFixture} from '../test-fixtures';
// Mock the API functions // Mock the API functions
jest.mock('../api', () => ({ jest.mock('../api', () => ({
deleteFile: jest.fn(), deleteFile: jest.fn(),
fetchFileWorkerJobStatus: jest.fn(),
ignoreDirectory: jest.fn(), ignoreDirectory: jest.fn(),
makeDirectory: jest.fn(), makeDirectory: jest.fn(),
movePaths: jest.fn(), movePaths: jest.fn(),
@ -59,8 +62,13 @@ jest.mock('react-dropzone', () => ({
// Import mocked hooks for manipulation // Import mocked hooks for manipulation
import {useBrowseFiles, useElementWidth, useWROLMode} from '../hooks/customHooks'; import {useBrowseFiles, useElementWidth, useWROLMode} from '../hooks/customHooks';
// Set by the wrapper so a test can change the file worker's status, as a poll would.
let setFileWorkerStatus;
// Create wrapper with all required contexts // Create wrapper with all required contexts
const AllContextsWrapper = ({children}) => { const AllContextsWrapper = ({children}) => {
const [fileWorkerStatus, setStatus] = React.useState({status: 'idle'});
setFileWorkerStatus = setStatus;
const settingsValue = { const settingsValue = {
settings: {ignored_directories: []}, settings: {ignored_directories: []},
fetchSettings: jest.fn(), fetchSettings: jest.fn(),
@ -71,11 +79,13 @@ const AllContextsWrapper = ({children}) => {
}; };
return ( return (
<FileWorkerStatusContext.Provider value={fileWorkerStatusFixture({status: fileWorkerStatus})}>
<SettingsContext.Provider value={settingsValue}> <SettingsContext.Provider value={settingsValue}>
<FilePreviewContext.Provider value={filePreviewValue}> <FilePreviewContext.Provider value={filePreviewValue}>
{children} {children}
</FilePreviewContext.Provider> </FilePreviewContext.Provider>
</SettingsContext.Provider> </SettingsContext.Provider>
</FileWorkerStatusContext.Provider>
); );
}; };
@ -399,6 +409,77 @@ describe('FileBrowser', () => {
}); });
}); });
describe('File worker changes', () => {
it('fetches the files again when the file worker finishes', async () => {
const mockFetchFiles = jest.fn();
useBrowseFiles.mockReturnValue({
browseFiles: mockBrowseFiles,
openFolders: [],
setOpenFolders: jest.fn(),
fetchFiles: mockFetchFiles,
});
renderFileBrowser(<FileBrowser/>);
await act(async () => setFileWorkerStatus({status: 'moving', rename_from: '/media/wrolpi/testdir'}));
expect(mockFetchFiles).not.toHaveBeenCalled();
await act(async () => setFileWorkerStatus({status: 'idle'}));
expect(mockFetchFiles).toHaveBeenCalledTimes(1);
});
const renameTestdir = async () => {
// Select testdir/ (the second checkbox) and rename it.
await act(async () => fireEvent.click(screen.getAllByRole('checkbox')[1]));
const renameButton = document.querySelector('.tabler-icon-cursor-text').closest('button');
await act(async () => fireEvent.click(renameButton));
const nameInput = await screen.findByDisplayValue(/^testdir/);
await act(async () => fireEvent.change(nameInput, {target: {value: 'newdir'}}));
await act(async () => fireEvent.click(screen.getByRole('button', {name: 'Rename'})));
};
it('fetches the files once a queued rename job is done, even if no poll saw it running', async () => {
const mockFetchFiles = jest.fn();
const api = require('../api');
api.renamePath.mockResolvedValue('move-1234');
// The job is still queued at the first check, and done at the second.
api.fetchFileWorkerJobStatus.mockResolvedValueOnce('pending').mockResolvedValue('complete');
useBrowseFiles.mockReturnValue({
browseFiles: mockBrowseFiles,
openFolders: [],
setOpenFolders: jest.fn(),
fetchFiles: mockFetchFiles,
});
renderFileBrowser(<FileBrowser/>);
await renameTestdir();
expect(api.renamePath).toHaveBeenCalledWith('testdir/', 'newdir');
// Nothing is fetched while the rename is only queued.
expect(mockFetchFiles).not.toHaveBeenCalled();
// The file worker's status never left idle; the job is what says the rename is done.
await waitFor(() => expect(mockFetchFiles).toHaveBeenCalledTimes(1), {timeout: 3000});
expect(api.fetchFileWorkerJobStatus).toHaveBeenCalledWith('move-1234');
expect(api.fetchFileWorkerJobStatus).toHaveBeenCalledTimes(2);
});
it('fetches the files right away after a rename that was not queued', async () => {
const mockFetchFiles = jest.fn();
const api = require('../api');
api.renamePath.mockResolvedValue(null);
useBrowseFiles.mockReturnValue({
browseFiles: mockBrowseFiles,
openFolders: [],
setOpenFolders: jest.fn(),
fetchFiles: mockFetchFiles,
});
renderFileBrowser(<FileBrowser/>);
await renameTestdir();
expect(mockFetchFiles).toHaveBeenCalledTimes(1);
expect(api.fetchFileWorkerJobStatus).not.toHaveBeenCalled();
});
});
describe('Delete functionality', () => { describe('Delete functionality', () => {
it('removes deleted directory from openFolders', async () => { it('removes deleted directory from openFolders', async () => {
const mockSetOpenFolders = jest.fn(); const mockSetOpenFolders = jest.fn();

View file

@ -5,15 +5,16 @@ import {encodeMediaPath, isSupportedArchive, useLocalStorage} from "./Common";
import {getFile, tagFileGroup, untagFileGroup} from "../api"; import {getFile, tagFileGroup, untagFileGroup} from "../api";
import {ArchivePreviewContent} from "./ArchivePreview"; import {ArchivePreviewContent} from "./ArchivePreview";
import {CbzViewer} from "./CbzViewer"; import {CbzViewer} from "./CbzViewer";
import {StlViewer} from "react-stl-viewer";
import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui"; import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
import {useOneQuery} from "../hooks/customHooks"; import {useOneQuery} from "../hooks/customHooks";
import {useEpubProgress, useMediaProgress} from "../hooks/useFileProgress";
import {ShareButton} from "./Share"; import {ShareButton} from "./Share";
import {AddToPlaylistButton} from "./AddToPlaylist"; import {AddToPlaylistButton} from "./AddToPlaylist";
import {pathDirectory} from "./FileBrowser"; import {pathDirectory} from "./FileBrowser";
import {InlineErrorBoundary} from "./ErrorBoundary"; import {InlineErrorBoundary} from "./ErrorBoundary";
import {useLocation} from "react-router"; import {useLocation} from "react-router";
import {ThemeContext} from "../contexts/contexts"; import {ThemeContext} from "../contexts/contexts";
import {isMarkdownFile, MarkdownPreview} from "./MarkdownPreview";
// Routes where file views should not be tracked // Routes where file views should not be tracked
const EXCLUDED_TRACKING_ROUTES = [ const EXCLUDED_TRACKING_ROUTES = [
@ -100,7 +101,7 @@ function getEpubViewerURL(previewFile) {
* A component rather than part of `getIframePreviewModal` because it reads the theme: the * A component rather than part of `getIframePreviewModal` because it reads the theme: the
* modal builders are plain functions called from an event handler, where hooks cannot run. * modal builders are plain functions called from an event handler, where hooks cannot run.
*/ */
export function IframePreview({url, gatePdf}) { export function IframePreview({url, gatePdf, iframeRef}) {
const {isDark, mediaFilterEnabled} = React.useContext(ThemeContext); const {isDark, mediaFilterEnabled} = React.useContext(ThemeContext);
/* /*
@ -116,7 +117,7 @@ export function IframePreview({url, gatePdf}) {
*/ */
return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}> return <MediaGate key={url} gated={!!gatePdf && !!mediaFilterEnabled}>
<div className='preview-fit'> <div className='preview-fit'>
<iframe title='textModal' src={url} <iframe title='textModal' src={url} ref={iframeRef}
style={{ style={{
height: '100%', width: '100%', border: 'none', height: '100%', width: '100%', border: 'none',
// A same-origin document has no styles of its own; it renders with the // A same-origin document has no styles of its own; it renders with the
@ -137,6 +138,19 @@ function getIframePreviewModal(previewFile, url, {gatePdf = false} = {}) {
</Modal.Content> </Modal.Content>
} }
/** The EPUB viewer, opened where the user left off. */
function EpubPreview({previewFile}) {
const path = previewFile.primary_path ?? previewFile.path;
const {iframeRef, resumeCfi} = useEpubProgress(path, previewFile);
let url = getEpubViewerURL(previewFile);
if (resumeCfi) {
url = `${url}&cfi=${encodeURIComponent(resumeCfi)}`;
}
return <Modal.Content>
<IframePreview url={url} iframeRef={iframeRef}/>
</Modal.Content>
}
function getImagePreviewModal(previewFile) { function getImagePreviewModal(previewFile) {
const path = previewFile.primary_path ?? previewFile.path; const path = previewFile.primary_path ?? previewFile.path;
const url = getMediaPathURL(previewFile); const url = getMediaPathURL(previewFile);
@ -156,6 +170,14 @@ function getImagePreviewModal(previewFile) {
</React.Fragment> </React.Fragment>
} }
/** A <video> or <audio> which resumes where the user left off, and saves how far they got. */
function PreviewMediaPlayer({as: Element, previewFile, path, style, children}) {
const progressHandlers = useMediaProgress(path, previewFile);
return <Element controls autoPlay={true} id="player" playsInline={true} style={style} {...progressHandlers}>
{children}
</Element>
}
function getVideoPreviewModal(previewFile) { function getVideoPreviewModal(previewFile) {
const url = getMediaPathURL(previewFile); const url = getMediaPathURL(previewFile);
const path = previewFile.primary_path ?? previewFile.path; const path = previewFile.primary_path ?? previewFile.path;
@ -167,14 +189,10 @@ function getVideoPreviewModal(previewFile) {
<Modal.Content> <Modal.Content>
<Header as='h5'>{path['path']}</Header> <Header as='h5'>{path['path']}</Header>
<div className='preview-fit'> <div className='preview-fit'>
<video controls <PreviewMediaPlayer as='video' previewFile={previewFile} path={path}
autoPlay={true} style={{maxHeight: '100%', maxWidth: '100%'}}>
id="player"
playsInline={true}
style={{maxHeight: '100%', maxWidth: '100%'}}
>
<source src={url}/> <source src={url}/>
</video> </PreviewMediaPlayer>
</div> </div>
</Modal.Content> </Modal.Content>
</React.Fragment> </React.Fragment>
@ -191,19 +209,44 @@ function getAudioPreviewModal(previewFile) {
{name} {name}
</Modal.Header> </Modal.Header>
<Modal.Content> <Modal.Content>
<audio controls <PreviewMediaPlayer as='audio' previewFile={previewFile} path={path}
autoPlay={true} style={{width: '90%', maxWidth: '95%'}}>
id="player"
playsInline={true}
style={{width: '90%', maxWidth: '95%'}}
>
<source src={url} type={type}/> <source src={url} type={type}/>
</audio> </PreviewMediaPlayer>
</Modal.Content> </Modal.Content>
</React.Fragment> </React.Fragment>
} }
function ThreeMFPreviewModal({previewFile}) { // Each 3D format's loader ships with three, so it always matches the installed three. Every
// format is Z-up.
const MODEL_FORMATS = {
'3mf': {
label: '3MF',
loader: async () => new (await import('three/examples/jsm/loaders/3MFLoader.js')).ThreeMFLoader(),
// A 3MF loads as a group of meshes.
toObject: (THREE, group) => group,
},
stl: {
label: 'STL',
loader: async () => new (await import('three/examples/jsm/loaders/STLLoader.js')).STLLoader(),
// An STL loads as a single geometry.
toObject: (THREE, geometry) => new THREE.Mesh(geometry),
},
};
/**
* How far a camera must stand from a sphere of `radius` for the whole sphere to be in view, with
* `margin` to spare. The narrower of the vertical and horizontal fields of view decides: a tall,
* narrow viewer is limited by its width.
*/
export function modelCameraDistance(radius, verticalFovDegrees, aspect, margin = 1.02) {
const halfVertical = (verticalFovDegrees * Math.PI) / 360;
const halfHorizontal = Math.atan(Math.tan(halfVertical) * aspect);
return (radius / Math.sin(Math.min(halfVertical, halfHorizontal))) * margin;
}
function ModelPreviewModal({previewFile, format}) {
const {label, loader: getLoader, toObject} = MODEL_FORMATS[format];
const containerRef = React.useRef(null); const containerRef = React.useRef(null);
const [dimensions, setDimensions] = React.useState(null); const [dimensions, setDimensions] = React.useState(null);
const [error, setError] = React.useState(null); const [error, setError] = React.useState(null);
@ -212,7 +255,7 @@ function ThreeMFPreviewModal({previewFile}) {
const name = path.replace(/^.*[\\\/]/, ''); const name = path.replace(/^.*[\\\/]/, '');
React.useEffect(() => { React.useEffect(() => {
// Imperative three.js viewer — mirrors react-stl-viewer behavior for .3mf files. // Imperative three.js viewer.
let cancelled = false; let cancelled = false;
const container = containerRef.current; const container = containerRef.current;
if (!container) return; if (!container) return;
@ -224,12 +267,12 @@ function ThreeMFPreviewModal({previewFile}) {
try { try {
THREE = await import('three'); THREE = await import('three');
const {OrbitControls} = await import('three/examples/jsm/controls/OrbitControls.js'); const {OrbitControls} = await import('three/examples/jsm/controls/OrbitControls.js');
const {ThreeMFLoader} = await import('three/examples/jsm/loaders/3MFLoader.js'); const {toCreasedNormals} = await import('three/examples/jsm/utils/BufferGeometryUtils.js');
const loader = await getLoader();
if (cancelled) return; if (cancelled) return;
scene = new THREE.Scene(); scene = new THREE.Scene();
// Transparent background so the modal/theme color shows through, // Transparent background so the modal/theme color shows through.
// matching react-stl-viewer's behavior.
const width = container.clientWidth || 1; const width = container.clientWidth || 1;
const height = container.clientHeight || 1; const height = container.clientHeight || 1;
@ -243,32 +286,40 @@ function ThreeMFPreviewModal({previewFile}) {
renderer.setSize(width, height); renderer.setSize(width, height);
container.appendChild(renderer.domElement); container.appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0xffffff, 0.6)); // Sky above, darker ground below, so top and bottom read differently. The headlight
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8); // follows the camera, so whichever side the user orbits to is lit; it shines from a
dirLight.position.set(1, 1, 1); // little above and left of the camera so faces turned toward the viewer still shade
scene.add(dirLight); // differently.
const dirLight2 = new THREE.DirectionalLight(0xffffff, 0.4); scene.add(new THREE.HemisphereLight(0xffffff, 0x404040, 2));
dirLight2.position.set(-1, -1, -1); const headlight = new THREE.DirectionalLight(0xffffff, 2.5);
scene.add(dirLight2); scene.add(headlight);
const headlightOffset = new THREE.Vector3();
controls = new OrbitControls(camera, renderer.domElement); controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; controls.enableDamping = true;
const loader = new ThreeMFLoader();
loader.load( loader.load(
url, url,
(group) => { (result) => {
if (cancelled) return; if (cancelled) return;
const group = toObject(THREE, result);
loadedGroup = group; loadedGroup = group;
// STL and 3MF are Z-up (the 3D printing convention) and three is Y-up, so
// stand the model upright: model Z reads as Height, model Y as Length.
group.rotation.x = -Math.PI / 2;
// Match react-stl-viewer's violet so 3MFs without authored // One violet for every model, so models without authored materials
// materials are visible against either theme's background. // are visible against either theme's background.
// 3MF geometry often lacks vertex normals — compute them so // Geometry may lack vertex normals (3MF stores none) — compute them so
// MeshPhongMaterial can shade faces instead of rendering flat black. // MeshPhongMaterial can shade faces instead of rendering flat black.
// Creased: curves are smoothed, but an edge sharper than 30 degrees stays
// sharp, so flat faces do not shade into their neighbors.
group.traverse((obj) => { group.traverse((obj) => {
if (obj.isMesh) { if (obj.isMesh) {
if (obj.geometry && !obj.geometry.attributes.normal) { if (obj.geometry && !obj.geometry.attributes.normal) {
obj.geometry.computeVertexNormals(); const creased = toCreasedNormals(obj.geometry, Math.PI / 6);
obj.geometry.dispose();
obj.geometry = creased;
} }
obj.material = new THREE.MeshPhongMaterial({ obj.material = new THREE.MeshPhongMaterial({
color: 0x7353a8, color: 0x7353a8,
@ -279,7 +330,9 @@ function ThreeMFPreviewModal({previewFile}) {
scene.add(group); scene.add(group);
// Frame the model: center it, then pull camera back along Z by bounding radius. // Frame the model: center it, then view it from the front, raised and a little
// to the right, far enough back that its bounding sphere (every point of it)
// fills the viewer.
const box = new THREE.Box3().setFromObject(group); const box = new THREE.Box3().setFromObject(group);
const size = new THREE.Vector3(); const size = new THREE.Vector3();
const center = new THREE.Vector3(); const center = new THREE.Vector3();
@ -287,11 +340,11 @@ function ThreeMFPreviewModal({previewFile}) {
box.getCenter(center); box.getCenter(center);
group.position.sub(center); group.position.sub(center);
const boundingRadius = Math.max(size.x, size.y, size.z) / 2 || 1; const boundingRadius = size.length() / 2 || 1;
const fitDistance = boundingRadius / Math.tan((Math.PI * camera.fov) / 360); const distance = modelCameraDistance(boundingRadius, camera.fov, camera.aspect);
camera.position.set(0, 0, fitDistance * 2.2); camera.position.set(0.6, 0.5, 1).normalize().multiplyScalar(distance);
camera.near = Math.max(0.1, fitDistance / 1000); camera.near = distance / 100;
camera.far = fitDistance * 100; camera.far = distance * 100;
camera.updateProjectionMatrix(); camera.updateProjectionMatrix();
controls.target.set(0, 0, 0); controls.target.set(0, 0, 0);
controls.update(); controls.update();
@ -305,14 +358,17 @@ function ThreeMFPreviewModal({previewFile}) {
}, },
undefined, undefined,
(err) => { (err) => {
console.error('Failed to load 3MF', err); console.error(`Failed to load ${label}`, err);
if (!cancelled) setError('Failed to load 3MF file.'); if (!cancelled) setError(`Failed to load ${label} file.`);
}, },
); );
const animate = () => { const animate = () => {
animationId = requestAnimationFrame(animate); animationId = requestAnimationFrame(animate);
controls.update(); controls.update();
headlightOffset.set(-0.4, 0.6, 0).applyQuaternion(camera.quaternion)
.multiplyScalar(camera.position.length());
headlight.position.copy(camera.position).add(headlightOffset);
renderer.render(scene, camera); renderer.render(scene, camera);
}; };
animate(); animate();
@ -326,8 +382,8 @@ function ThreeMFPreviewModal({previewFile}) {
}); });
resizeObserver.observe(container); resizeObserver.observe(container);
} catch (err) { } catch (err) {
console.error('3MF viewer init failed', err); console.error(`${label} viewer init failed`, err);
if (!cancelled) setError('Failed to initialize 3MF viewer.'); if (!cancelled) setError(`Failed to initialize ${label} viewer.`);
} }
})(); })();
@ -355,7 +411,7 @@ function ThreeMFPreviewModal({previewFile}) {
} }
} }
}; };
}, [url]); }, [url, label, getLoader, toObject]);
return <React.Fragment> return <React.Fragment>
<Modal.Header>{name}</Modal.Header> <Modal.Header>{name}</Modal.Header>
@ -380,35 +436,12 @@ function ThreeMFPreviewModal({previewFile}) {
</React.Fragment> </React.Fragment>
} }
function STLPreviewModal({previewFile}) { export function ThreeMFPreviewModal({previewFile}) {
const [dimensions, setDimensions] = React.useState(null); return <ModelPreviewModal previewFile={previewFile} format='3mf'/>;
const url = getMediaPathURL(previewFile); }
const path = previewFile.primary_path ?? previewFile.path;
const name = path.replace(/^.*[\\\/]/, ''); export function STLPreviewModal({previewFile}) {
return <React.Fragment> return <ModelPreviewModal previewFile={previewFile} format='stl'/>;
<Modal.Header>{name}</Modal.Header>
<Modal.Content>
{dimensions && <div style={{marginBottom: '1em', textAlign: 'center'}}>
<b>Width:</b> {dimensions.width.toFixed(2)}
{' | '}
<b>Height:</b> {dimensions.height.toFixed(2)}
{' | '}
<b>Length:</b> {dimensions.length.toFixed(2)}
{' | '}
<b>Bounding Radius:</b> {dimensions.boundingRadius.toFixed(2)}
</div>}
<InlineErrorBoundary>
<div className='preview-fit'>
<StlViewer orbitControls shadows
url={url}
style={{height: '100%', width: '100%'}}
modelProps={{color: '#7353a8'}}
onFinishLoading={(dims) => setDimensions(dims)}
/>
</div>
</InlineErrorBoundary>
</Modal.Content>
</React.Fragment>
} }
function getGenericPreviewModal(previewFile) { function getGenericPreviewModal(previewFile) {
@ -441,6 +474,9 @@ export function FilePreviewProvider({children}) {
const [previewQuery, setPreviewQuery] = useOneQuery('preview'); const [previewQuery, setPreviewQuery] = useOneQuery('preview');
const [errorModalOpen, setErrorModalOpen] = React.useState(false); const [errorModalOpen, setErrorModalOpen] = React.useState(false);
const location = useLocation(); const location = useLocation();
// The path of the open preview that has been marked viewed. One opening is one view, however
// many times previewFile is replaced while it is open (re-fetching after tagging, for example).
const trackedPathRef = React.useRef(null);
// Determine if tracking should be skipped based on current route // Determine if tracking should be skipped based on current route
const skipTracking = shouldSkipTracking(location.pathname); const skipTracking = shouldSkipTracking(location.pathname);
@ -470,7 +506,8 @@ export function FilePreviewProvider({children}) {
const initPreviewFile = async () => { const initPreviewFile = async () => {
// Get simple information about the file, preview the file. // Get simple information about the file, preview the file.
try { try {
const file = await getFile(previewQuery, skipTracking); // Not a view; the preview effect marks the file viewed once it is displayed.
const file = await getFile(previewQuery, true);
setPreviewFile(file); setPreviewFile(file);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@ -495,7 +532,7 @@ export function FilePreviewProvider({children}) {
// Get the file again with its Tags. // Get the file again with its Tags.
const {path, primary_path} = previewFile; const {path, primary_path} = previewFile;
try { try {
const file = await getFile(primary_path ?? path, skipTracking); const file = await getFile(primary_path ?? path, true);
setPreviewFile(file); setPreviewFile(file);
} finally { } finally {
await handleCallbacks(); await handleCallbacks();
@ -562,6 +599,7 @@ export function FilePreviewProvider({children}) {
setPreviewModal(<Modal size='fullscreen' setPreviewModal(<Modal size='fullscreen'
open={true} open={true}
onClose={e => handleClose(e)} onClose={e => handleClose(e)}
classNames={{content: 'file-preview-modal-content'}}
> >
{pathContent} {pathContent}
<Modal.Actions> <Modal.Actions>
@ -585,6 +623,9 @@ export function FilePreviewProvider({children}) {
React.useEffect(() => { React.useEffect(() => {
setPreviewModal(null); setPreviewModal(null);
if (_.isEmpty(previewFile)) {
trackedPathRef.current = null;
}
if (previewFile && !_.isObject(previewFile)) { if (previewFile && !_.isObject(previewFile)) {
console.error(`Unknown previewFile type: ${typeof previewFile}`); console.error(`Unknown previewFile type: ${typeof previewFile}`);
toast({ toast({
@ -607,6 +648,9 @@ export function FilePreviewProvider({children}) {
if (mimetype.startsWith('text/') && size > MAXIMUM_TEXT_SIZE) { if (mimetype.startsWith('text/') && size > MAXIMUM_TEXT_SIZE) {
// Large text files should be downloaded. // Large text files should be downloaded.
window.open(downloadURL); window.open(downloadURL);
} else if (isMarkdownFile(mimetype, lowerPath)) {
setModalContent(<Modal.Content><MarkdownPreview url={url}/></Modal.Content>, url, downloadURL, path,
taggable);
} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) { } else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {
setModalContent(getIframePreviewModal(previewFile), url, downloadURL, path, taggable); setModalContent(getIframePreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('video/')) { } else if (mimetype.startsWith('video/')) {
@ -615,7 +659,7 @@ export function FilePreviewProvider({children}) {
setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable); setModalContent(getAudioPreviewModal(previewFile), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/epub')) { } else if (mimetype.startsWith('application/epub')) {
const viewerURL = getEpubViewerURL(previewFile); const viewerURL = getEpubViewerURL(previewFile);
setModalContent(getIframePreviewModal(previewFile, viewerURL), viewerURL, downloadURL, path, taggable); setModalContent(<EpubPreview previewFile={previewFile}/>, viewerURL, downloadURL, path, taggable);
} else if (mimetype.startsWith('application/pdf')) { } else if (mimetype.startsWith('application/pdf')) {
setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable); setModalContent(getIframePreviewModal(previewFile, null, {gatePdf: true}), url, downloadURL, path, taggable);
} else if (mimetype.startsWith('image/')) { } else if (mimetype.startsWith('image/')) {
@ -637,7 +681,9 @@ export function FilePreviewProvider({children}) {
<OpenInSlicerButton previewFile={previewFile}/>); <OpenInSlicerButton previewFile={previewFile}/>);
} else if (mimetype.includes('cbz') || mimetype.includes('cbr') || mimetype.includes('comicbook+zip') || mimetype.includes('comicbook-rar') } else if (mimetype.includes('cbz') || mimetype.includes('cbr') || mimetype.includes('comicbook+zip') || mimetype.includes('comicbook-rar')
|| lowerPath.endsWith('.cbz') || lowerPath.endsWith('.cbr') || lowerPath.endsWith('.cbt') || lowerPath.endsWith('.cb7')) { || lowerPath.endsWith('.cbz') || lowerPath.endsWith('.cbr') || lowerPath.endsWith('.cbt') || lowerPath.endsWith('.cb7')) {
setModalContent(<Modal.Content><CbzViewer path={path}/></Modal.Content>, null, downloadURL, path, taggable); setModalContent(<Modal.Content>
<CbzViewer path={path} progressPath={path} fileGroup={previewFile}/>
</Modal.Content>, null, downloadURL, path, taggable);
} else if (isSupportedArchive(mimetype, lowerPath)) { } else if (isSupportedArchive(mimetype, lowerPath)) {
setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable); setModalContent(<ArchivePreviewContent previewFile={previewFile}/>, null, downloadURL, path, taggable);
} else { } else {
@ -646,7 +692,8 @@ export function FilePreviewProvider({children}) {
} }
// Trigger tracking for the file view (unless on an excluded route) // Trigger tracking for the file view (unless on an excluded route)
if (!skipTracking) { if (!skipTracking && trackedPathRef.current !== path) {
trackedPathRef.current = path;
getFile(path).catch(e => { getFile(path).catch(e => {
console.error(e); console.error(e);
console.error('Failed to get file to set FileGroup.viewed'); console.error('Failed to get file to set FileGroup.viewed');

View file

@ -101,6 +101,26 @@ describe('preview gate remounting (source contract)', () => {
}); });
}); });
describe('markdown preview routing (source contract)', () => {
/*
* Markdown is text/*, so the generic text branch would also accept it and show it raw in an
* iframe. The markdown branch has to be tested first for the formatted view to be reachable.
*/
const fs = require('fs');
const path = require('path');
const source = fs.readFileSync(path.join(__dirname, 'FilePreview.js'), 'utf8');
test('markdown is routed to MarkdownPreview before the generic text preview', () => {
const markdownBranch = source.indexOf('} else if (isMarkdownFile(mimetype, lowerPath)) {');
const textBranch = source.indexOf("} else if (mimetype.startsWith('text/') || mimetype.startsWith('application/json')) {");
expect(markdownBranch).toBeGreaterThan(-1);
expect(textBranch).toBeGreaterThan(-1);
expect(markdownBranch).toBeLessThan(textBranch);
expect(source.slice(markdownBranch, textBranch)).toContain('<MarkdownPreview url={url}/>');
});
});
describe('IframePreview color scheme', () => { describe('IframePreview color scheme', () => {
/* /*
* The previewed file is a bare document with no styles of its own, so it renders with the * The previewed file is a bare document with no styles of its own, so it renders with the

View file

@ -0,0 +1,80 @@
import React from 'react';
import {act, waitFor} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {FilePreviewContext, FilePreviewProvider} from './FilePreview';
import {getFile} from '../api';
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getFile: jest.fn(),
tagFileGroup: jest.fn(),
untagFileGroup: jest.fn(),
}));
const imageFile = {primary_path: 'pictures/cat.png', mimetype: 'image/png', size: 100, taggable: true, tags: []};
/** getFile calls that would mark the file viewed (skipTracking not set). */
const trackedCalls = () => getFile.mock.calls.filter(([, skipTracking]) => !skipTracking);
/** Exposes the provider's context so a test can open a preview the way PreviewLink does. */
let context;
const ContextSpy = () => {
context = React.useContext(FilePreviewContext);
return null;
};
const renderProvider = (preview = null) => renderWithProviders(
<FilePreviewProvider><ContextSpy/></FilePreviewProvider>,
{
route: '/files',
query: {searchParams: new URLSearchParams(preview ? {preview} : {}), updateQuery: jest.fn()},
},
);
describe('FilePreview view tracking', () => {
beforeEach(() => {
getFile.mockReset();
getFile.mockResolvedValue(imageFile);
context = null;
});
test('opening a preview from the URL marks the file viewed once', async () => {
renderProvider(imageFile.primary_path);
await waitFor(() => expect(getFile).toHaveBeenCalled());
await waitFor(() => expect(context.previewModal).not.toBeNull());
expect(trackedCalls()).toHaveLength(1);
});
test('opening a preview from a link marks the file viewed once', async () => {
renderProvider();
act(() => context.setPreviewFile(imageFile));
await waitFor(() => expect(trackedCalls()).toHaveLength(1));
expect(getFile).toHaveBeenCalledTimes(1);
});
test('refreshing the open file (after tagging) is not another view', async () => {
renderProvider();
act(() => context.setPreviewFile(imageFile));
await waitFor(() => expect(trackedCalls()).toHaveLength(1));
// localFetchFile replaces previewFile with the re-fetched file after a tag change.
act(() => context.setPreviewFile({...imageFile, tags: ['animals']}));
await waitFor(() => expect(context.previewFile.tags).toEqual(['animals']));
expect(trackedCalls()).toHaveLength(1);
});
test('closing and reopening the same file is another view', async () => {
renderProvider();
act(() => context.setPreviewFile(imageFile));
await waitFor(() => expect(trackedCalls()).toHaveLength(1));
act(() => context.setPreviewFile(null));
act(() => context.setPreviewFile(imageFile));
await waitFor(() => expect(trackedCalls()).toHaveLength(2));
});
});

View file

@ -481,6 +481,9 @@ export function DocSearchFilterButton({size = 'medium'}) {
return <SearchFilter filters={docMimetypeFilterOptions} size={size}/> return <SearchFilter filters={docMimetypeFilterOptions} size={size}/>
} }
// The search relevance sort; see `SearchFilterModal`.
const RANK_ORDER = 'rank';
// The app-wide default page size (matches usePages' fallback); used to reset Results Per Page on Clear All. // The app-wide default page size (matches usePages' fallback); used to reset Results Per Page on Clear All.
const DEFAULT_SEARCH_LIMIT = 24; const DEFAULT_SEARCH_LIMIT = 24;
@ -540,7 +543,8 @@ export function SearchFilterModal(
// Seed the drafts from the URL each time the modal is opened. // Seed the drafts from the URL each time the modal is opened.
React.useEffect(() => { React.useEffect(() => {
if (open) { if (open) {
setDraftSort(sort || null); // Rank has no direction here; an old `-rank` link becomes `rank` when the modal closes.
setDraftSort(sort === `-${RANK_ORDER}` ? RANK_ORDER : (sort || null));
setDraftFilter(filter || null); setDraftFilter(filter || null);
setDraftTags(activeTags || []); setDraftTags(activeTags || []);
setDraftAnyTag(anyTag || false); setDraftAnyTag(anyTag || false);
@ -614,17 +618,19 @@ export function SearchFilterModal(
setDraftDeep(false); setDraftDeep(false);
} }
// Sort section (operates on the draft). // Sort section (operates on the draft). Rank has no direction: `rank` is always the most relevant first
// (`-rank` would be the least relevant first), and a sort chosen after it starts descending.
const sortKey = draftSort ? draftSort.replace(/^-/, '') : (sorts ? sorts[0]['value'] : null); const sortKey = draftSort ? draftSort.replace(/^-/, '') : (sorts ? sorts[0]['value'] : null);
const desc = draftSort ? draftSort.startsWith('-') : true; const isRank = sortKey === RANK_ORDER;
const desc = draftSort && !isRank ? draftSort.startsWith('-') : true;
const sortButtons = sorts && sorts.map(o => const sortButtons = sorts && sorts.map(o =>
<Button key={o['value']} <Button key={o['value']}
color={o['value'] === sortKey ? 'violet' : undefined} color={o['value'] === sortKey ? 'violet' : undefined}
onClick={() => setDraftSort(desc ? `-${o['value']}` : o['value'])} onClick={() => setDraftSort(o['value'] === RANK_ORDER || !desc ? o['value'] : `-${o['value']}`)}
style={{margin: '0.2em'}} style={{margin: '0.2em'}}
>{o['text']}</Button> >{o['text']}</Button>
); );
const directionToggle = <Button icon={desc ? IconSortDescending : IconSortAscending} const directionToggle = isRank ? null : <Button icon={desc ? IconSortDescending : IconSortAscending}
onClick={() => { onClick={() => {
const base = sortKey || sorts[0]['value']; const base = sortKey || sorts[0]['value'];
setDraftSort(desc ? base : `-${base}`); setDraftSort(desc ? base : `-${base}`);
@ -658,7 +664,7 @@ export function SearchFilterModal(
<Stack gap='lg'> <Stack gap='lg'>
{sorts && {sorts &&
<SearchFilterSection header='Sort By'> <SearchFilterSection header='Sort By'>
<div style={{marginBottom: '1em'}}>{directionToggle}</div> {directionToggle && <div style={{marginBottom: '1em'}}>{directionToggle}</div>}
<div>{sortButtons}</div> <div>{sortButtons}</div>
</SearchFilterSection>} </SearchFilterSection>}
@ -915,7 +921,12 @@ export function FilesSearchView({
</> </>
} }
function getPhaseLabel(status) { function getPhaseLabel(status, renameFrom) {
if (renameFrom && (status === 'planning' || status === 'moving')) {
// A directory rename is a move of the directory's contents.
const name = renameFrom.split('/').filter(Boolean).pop();
return `Rename ${name}: ${status === 'planning' ? 'Planning' : 'Moving'}`;
}
switch (status) { switch (status) {
case 'counting': case 'counting':
return 'Counting'; return 'Counting';
@ -1037,8 +1048,8 @@ export function RefreshSteps({progress}) {
</div> </div>
} }
function RefreshProgressBar({status, operation_total, operation_processed, operation_percent, error}) { function RefreshProgressBar({status, operation_total, operation_processed, operation_percent, error, rename_from}) {
const phaseLabel = getPhaseLabel(status); const phaseLabel = getPhaseLabel(status, rename_from);
if (!phaseLabel) { if (!phaseLabel) {
return null; return null;
@ -1064,7 +1075,7 @@ export function FilesRefreshProgress() {
return null; return null;
} }
const {status, operation_total, operation_processed, operation_percent, error} = progress; const {status, operation_total, operation_processed, operation_percent, error, rename_from} = progress;
// Show Steps component AND progress bar for global refresh operations // Show Steps component AND progress bar for global refresh operations
if (isGlobalRefresh(progress)) { if (isGlobalRefresh(progress)) {
@ -1080,13 +1091,14 @@ export function FilesRefreshProgress() {
</>; </>;
} }
// Show just progress bar for other operations (moves, reorganize, targeted refresh) // Show just progress bar for other operations (moves, renames, reorganize, targeted refresh)
return <RefreshProgressBar return <RefreshProgressBar
status={status} status={status}
operation_total={operation_total} operation_total={operation_total}
operation_processed={operation_processed} operation_processed={operation_processed}
operation_percent={operation_percent} operation_percent={operation_percent}
error={error} error={error}
rename_from={rename_from}
/>; />;
} }

View file

@ -0,0 +1,44 @@
import React from 'react';
import {screen} from '@testing-library/react';
import {FilesRefreshProgress} from './Files';
import {renderWithProviders} from '../test-utils';
import {fileWorkerStatusFixture} from '../test-fixtures';
import {FileWorkerStatusContext} from '../contexts/FileWorkerStatusContext';
const renderProgress = (status) => renderWithProviders(
<FileWorkerStatusContext.Provider value={fileWorkerStatusFixture({status})}>
<FilesRefreshProgress/>
</FileWorkerStatusContext.Provider>
);
const moving = {
status: 'moving',
task_type: 'move',
destination: '/media/wrolpi/3d models/Tools',
operation_total: 109,
operation_processed: 40,
operation_percent: 36,
error: null,
};
describe('FilesRefreshProgress', () => {
it('labels a move', () => {
renderProgress({...moving, rename_from: null});
expect(screen.getByText('Move: Moving (40 / 109)')).toBeInTheDocument();
});
it('labels a directory rename with the renamed directory', () => {
renderProgress({...moving, rename_from: '/media/wrolpi/3d models/tools'});
expect(screen.getByText('Rename tools: Moving (40 / 109)')).toBeInTheDocument();
});
it('labels a directory rename that is planning', () => {
renderProgress({...moving, status: 'planning', operation_total: 0, rename_from: '/media/wrolpi/3d models/tools'});
expect(screen.getByText('Rename tools: Planning')).toBeInTheDocument();
});
it('shows nothing while idle', () => {
renderProgress({...moving, status: 'idle'});
expect(screen.queryByText(/Move|Rename/)).not.toBeInTheDocument();
});
});

View file

@ -3,7 +3,7 @@ import {Route, Routes} from "react-router";
import {ESPLoader, Transport} from "esptool-js"; import {ESPLoader, Transport} from "esptool-js";
import {useDropzone} from "react-dropzone"; import {useDropzone} from "react-dropzone";
import _ from "lodash"; import _ from "lodash";
import {encodeMediaPath, humanFileSize, PageContainer, useTitle} from "./Common"; import {encodeMediaPath, ErrorMessage, humanFileSize, PageContainer, useTitle} from "./Common";
import { import {
Button, Button,
Checkbox, Checkbox,
@ -17,6 +17,7 @@ import {
Message, Message,
Modal, Modal,
Panel, Panel,
Placeholder,
Progress, Progress,
Select, Select,
Stack, Stack,
@ -269,7 +270,8 @@ export function FlasherPage() {
// Media-directory firmware picker. // Media-directory firmware picker.
const [mediaFilter, setMediaFilter] = useState(''); const [mediaFilter, setMediaFilter] = useState('');
const [mediaResults, setMediaResults] = useState([]); // null = not searched yet, undefined = the search failed, a list = the server's results.
const [mediaResults, setMediaResults] = useState(null);
const [mediaLoading, setMediaLoading] = useState(false); const [mediaLoading, setMediaLoading] = useState(false);
// When set (e.g. "ESP32-S2"), the picker only shows firmware for that chip (detected from the device). // When set (e.g. "ESP32-S2"), the picker only shows firmware for that chip (detected from the device).
const [deviceChip, setDeviceChip] = useState(null); const [deviceChip, setDeviceChip] = useState(null);
@ -297,8 +299,12 @@ export function FlasherPage() {
// Which firmware-source tab is active (controlled so a file drop can switch to "Add from computer"). // Which firmware-source tab is active (controlled so a file drop can switch to "Add from computer").
const [activeTab, setActiveTab] = useState(TAB_SAVED); const [activeTab, setActiveTab] = useState(TAB_SAVED);
// Saved firmware configurations (flasher.yaml). // Saved firmware configurations (flasher.yaml). null = pending, undefined = fetch failed,
const [savedConfigs, setSavedConfigs] = useState([]); // [] = none saved; the "No saved configurations yet." message is only for the last.
const [savedConfigs, setSavedConfigs] = useState(null);
// Only the newest configs request may write state: a save or delete refetches while the mount
// request may still be in flight.
const savedConfigsGen = useRef(0);
const [saveModalOpen, setSaveModalOpen] = useState(false); const [saveModalOpen, setSaveModalOpen] = useState(false);
const [saveName, setSaveName] = useState(''); const [saveName, setSaveName] = useState('');
@ -388,14 +394,15 @@ export function FlasherPage() {
const fetchMediaFirmware = React.useCallback(async (pathFilter, chip) => { const fetchMediaFirmware = React.useCallback(async (pathFilter, chip) => {
setMediaLoading(true); setMediaLoading(true);
try { try {
const [fileGroups] = await flasherSearch(chip || null, pathFilter || null); const result = await flasherSearch(chip || null, pathFilter || null);
setMediaResults(fileGroups || []); // The api helper returns undefined (and toasts) on a non-OK response.
setMediaResults(result ? result[0] || [] : undefined);
} catch (e) { } catch (e) {
// Surface connectivity errors instead of showing the empty "no firmware found" state, which would // Surface connectivity errors instead of showing the empty "no firmware found" state, which would
// be indistinguishable from genuinely having no firmware. // be indistinguishable from genuinely having no firmware.
setError(e && e.message ? e.message : String(e)); setError(e && e.message ? e.message : String(e));
setBootHint(false); setBootHint(false);
setMediaResults([]); setMediaResults(undefined);
} finally { } finally {
setMediaLoading(false); setMediaLoading(false);
} }
@ -424,7 +431,19 @@ export function FlasherPage() {
// Saved firmware configurations. // Saved firmware configurations.
const fetchSavedConfigs = React.useCallback(async () => { const fetchSavedConfigs = React.useCallback(async () => {
setSavedConfigs(await getFlasherConfigs()); const gen = ++savedConfigsGen.current;
try {
const configs = await getFlasherConfigs();
if (gen === savedConfigsGen.current) {
// The api helper returns undefined on a non-OK response.
setSavedConfigs(configs ?? undefined);
}
} catch (e) {
console.error(e);
if (gen === savedConfigsGen.current) {
setSavedConfigs(undefined);
}
}
}, []); }, []);
useEffect(() => { useEffect(() => {
@ -750,8 +769,10 @@ export function FlasherPage() {
onChange={(e) => handleMediaFilterChange(e.currentTarget.value)} onChange={(e) => handleMediaFilterChange(e.currentTarget.value)}
/> />
<div style={{marginTop: '1em', overflowX: 'auto'}}> <div style={{marginTop: '1em', overflowX: 'auto'}}>
{mediaLoading {mediaLoading || mediaResults === null
? <Loading/> ? <Loading/>
: mediaResults === undefined
? <ErrorMessage>Could not search firmware.</ErrorMessage>
: (mediaResults.length === 0 : (mediaResults.length === 0
? <p style={{opacity: 0.7}}> ? <p style={{opacity: 0.7}}>
No <code>.bin</code> firmware found No <code>.bin</code> firmware found
@ -812,7 +833,9 @@ export function FlasherPage() {
Configure the firmware files and offsets, then save them as a named set to re-flash later Configure the firmware files and offsets, then save them as a named set to re-flash later
(e.g. a Meshtastic T-Deck: firmware at <code>0x0</code>, littlefs at <code>0xc90000</code>). (e.g. a Meshtastic T-Deck: firmware at <code>0x0</code>, littlefs at <code>0xc90000</code>).
</p> </p>
{savedConfigs.length > 0 {savedConfigs === null && <Placeholder lines={2}/>}
{savedConfigs === undefined && <ErrorMessage>Could not fetch saved configurations.</ErrorMessage>}
{Array.isArray(savedConfigs) && (savedConfigs.length > 0
? <Panel style={{padding: 0}}> ? <Panel style={{padding: 0}}>
{savedConfigs.map((configuration, index) => <div {savedConfigs.map((configuration, index) => <div
key={configuration.name} key={configuration.name}
@ -846,7 +869,7 @@ export function FlasherPage() {
onClick={() => handleDeleteConfig(configuration.name)}/> onClick={() => handleDeleteConfig(configuration.name)}/>
</div>)} </div>)}
</Panel> </Panel>
: <p style={{opacity: 0.7}}>No saved configurations yet.</p>} : <p style={{opacity: 0.7}}>No saved configurations yet.</p>)}
</>; </>;
return <div {...getRootProps()}> return <div {...getRootProps()}>

View file

@ -265,6 +265,43 @@ describe('FlasherPage', () => {
} }
}); });
// The Saved Firmwares tab is the default tab. "No saved configurations yet." may only appear once the
// server confirmed there are none; a pending or failed fetch must not read as an empty list.
it('shows a placeholder, not "no saved configurations", while the configs load', () => {
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
getFlasherConfigs.mockReturnValue(new Promise(() => {
}));
const {container} = render(<FlasherPage/>);
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
expect(screen.queryAllByText('No saved configurations yet.')).toHaveLength(0);
});
it('shows an error, not "no saved configurations", when the configs fetch failed', async () => {
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
getFlasherConfigs.mockResolvedValue(undefined);
render(<FlasherPage/>);
expect((await screen.findAllByText(/Could not fetch saved configurations/)).length).toBeGreaterThan(0);
expect(screen.queryAllByText('No saved configurations yet.')).toHaveLength(0);
});
it('shows "no saved configurations" once the server confirmed there are none', async () => {
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
render(<FlasherPage/>);
expect((await screen.findAllByText('No saved configurations yet.')).length).toBeGreaterThan(0);
});
// "No .bin firmware found" may only appear once the server searched and found none.
it('shows an error, not "no firmware found", when the firmware search failed', async () => {
Object.defineProperty(global.navigator, 'serial', {value: {}, configurable: true});
// The api helper returns undefined on a non-OK response.
flasherSearch.mockResolvedValue(undefined);
render(<FlasherPage/>);
await waitFor(() => expect(flasherSearch).toHaveBeenCalled());
switchTab('Choose from your WROLPi');
expect((await screen.findAllByText(/Could not search firmware/)).length).toBeGreaterThan(0);
expect(screen.queryAllByText(/firmware found/)).toHaveLength(0);
});
// PageContainer renders both the mobile and desktop breakpoints (fresnel Media), so each label appears twice. // PageContainer renders both the mobile and desktop breakpoints (fresnel Media), so each label appears twice.
it('warns when Web Serial is unavailable', () => { it('warns when Web Serial is unavailable', () => {
delete global.navigator.serial; delete global.navigator.serial;

View file

@ -1,4 +1,4 @@
import React, {useEffect, useState} from "react"; import React, {useEffect, useRef, useState} from "react";
import { import {
APIButton, APIButton,
ErrorMessage, ErrorMessage,
@ -11,41 +11,46 @@ import {
} from "./Common"; } from "./Common";
import {Route, Routes, useNavigate} from "react-router"; import {Route, Routes, useNavigate} from "react-router";
import { import {
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins, deleteMapFile, deleteMapPin, deleteMapTarget, fetchMapSubscriptions, getMapFiles, getMapPins, getMapTargets,
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, updateMapPin mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, setMapFileVisible, updateMapPin
} from "../api"; } from "../api";
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput} from "./ui"; import {targetWeapon} from "../map-shared/fallout/targets.js";
import {formatYieldAndFission} from "../map-shared/fallout/weapons.js";
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput, Toggle} from "./ui";
import {SortableTable} from "./SortableTable"; import {SortableTable} from "./SortableTable";
import {Media, StatusContext} from "../contexts/contexts"; import {Media, StatusContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars"; import {MAP_VIEWER_URI} from "./Vars";
import MapViewer from "./MapViewer"; import MapViewer from "./MapViewer";
import {WeatherSection} from "./MapWeather";
import {AddToPlaylistButton} from "./AddToPlaylist"; import {AddToPlaylistButton} from "./AddToPlaylist";
import {solarCalculatorPath} from "./calculators/solar";
import maplibregl from "maplibre-gl"; import maplibregl from "maplibre-gl";
import {Protocol} from "pmtiles"; import {Protocol} from "pmtiles";
import layers from "protomaps-themes-base"; import layers from "protomaps-themes-base";
import {planMapFiles, pmtilesUrl} from "./mapOverlays";
import {MapAtak} from "./MapAtak";
// Ensure PMTiles protocol is registered (may already be registered by MapViewer). // Ensure PMTiles protocol is registered (may already be registered by MapViewer).
try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ } try { maplibregl.addProtocol("pmtiles", new Protocol().tile); } catch (e) { /* already registered */ }
const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles"; const MAP_OVERVIEW_URL = "/blobs/map-overview.pmtiles";
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles". // How the map draws a file (the API's `kind`).
function isPlanetFile(name) { const MAP_FILE_KINDS = {
if (name.startsWith("planet-")) return true; basemap: 'Basemap',
return /^\d{8}\.pmtiles$/.test(name); overlay: 'Overlay',
} terrain: 'Terrain',
unknown: 'Unreadable',
};
// Resolve the best available base map source for preview maps. // Resolve the best available base map source for preview maps.
// Checks for a user's planet file first, falls back to the overview blob. // Checks for a user's planet file first, falls back to the overview blob.
async function getPreviewMapSource() { async function getPreviewMapSource() {
try { try {
const data = await getMapFiles(); const data = await getMapFiles();
if (data?.files) { const {planet} = planMapFiles(data?.files);
for (const f of data.files) { if (planet) {
if (isPlanetFile(f.name)) { return {type: 'vector', url: pmtilesUrl(planet.path)};
return {type: 'vector', url: `pmtiles:///media/map/${f.name}`};
}
}
} }
} catch (e) { /* ignore */ } } catch (e) { /* ignore */ }
return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`}; return {type: 'vector', url: `pmtiles://${MAP_OVERVIEW_URL}`};
@ -284,11 +289,15 @@ function MapCatalogRow({item, subscribedRegions, fetchData}) {
function ManageMap() { function ManageMap() {
const [files, setFiles] = useState(null); const [files, setFiles] = useState(null);
const [catalog, setCatalog] = useState([]); // null = pending, undefined = fetch failed, [] = no regions in the catalog.
const [catalog, setCatalog] = useState(null);
const [subscriptions, setSubscriptions] = useState([]); const [subscriptions, setSubscriptions] = useState([]);
const [allRegionsOpen, setAllRegionsOpen] = useState(false); const [allRegionsOpen, setAllRegionsOpen] = useState(false);
const {status} = React.useContext(StatusContext); const {status} = React.useContext(StatusContext);
const searchBuilding = status?.flags?.map_search_building; const searchBuilding = status?.flags?.map_search_building;
// Only the newest subscriptions request may write state: a subscribe or unsubscribe refetches
// while the mount request may still be in flight.
const subscriptionsGen = useRef(0);
const fetchFiles = async () => { const fetchFiles = async () => {
try { try {
@ -303,14 +312,24 @@ function ManageMap() {
}; };
const fetchSubscriptionData = async () => { const fetchSubscriptionData = async () => {
const gen = ++subscriptionsGen.current;
try { try {
const data = await fetchMapSubscriptions(); const data = await fetchMapSubscriptions();
if (gen !== subscriptionsGen.current) {
return;
}
if (data) { if (data) {
setCatalog(data.catalog || []); setCatalog(data.catalog || []);
setSubscriptions(data.subscriptions || []); setSubscriptions(data.subscriptions || []);
} else {
// The api helper already toasted the non-OK response.
setCatalog(undefined);
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
if (gen === subscriptionsGen.current) {
setCatalog(undefined);
}
} }
}; };
@ -328,30 +347,51 @@ function ManageMap() {
// --- Files table --- // --- Files table ---
const fileHeaders = [ const fileHeaders = [
{key: 'name', text: 'File', sortBy: i => i.name.toLowerCase()}, {key: 'name', text: 'File', sortBy: i => i.map_path.toLowerCase()},
{key: 'kind', text: 'Type', sortBy: i => i.kind || ''},
{key: 'size', text: 'Size', sortBy: i => i.size || 0}, {key: 'size', text: 'Size', sortBy: i => i.size || 0},
{key: 'search', text: 'Search', sortBy: null}, {key: 'search', text: 'Search', sortBy: null},
{key: 'actions', text: '', sortBy: null}, {key: 'actions', text: '', sortBy: null},
{key: 'visible', text: 'Visible', sortBy: i => (i.visible === false ? 0 : 1)},
]; ];
const handleBuildSearch = async (filename) => { const handleBuildSearch = async (mapPath) => {
await rebuildMapSearchIndex(filename); await rebuildMapSearchIndex(mapPath);
await fetchFiles(); await fetchFiles();
}; };
const handleVisible = async (file, visible) => {
try {
await setMapFileVisible(file.map_path, visible);
} finally {
await fetchFiles();
}
};
const fileRowFunc = (file) => { const fileRowFunc = (file) => {
return <Table.Row key={file.name}> return <Table.Row key={file.map_path}>
<Table.Cell>{file.name}</Table.Cell> <Table.Cell>
{/* A file in a sub-directory is shown with its directory. */}
{file.map_path}
{file.title && file.title !== file.name.replace(/\.pmtiles$/, '') && <div style={{fontSize: '0.75rem', color: 'var(--muted)'}}
title={file.description || undefined}>{file.title}</div>}
</Table.Cell>
<Table.Cell>
{MAP_FILE_KINDS[file.kind] || ''}
{/* A style beside the file says how it is drawn. */}
{file.kind === 'overlay' && file.style_path ? ' (styled)' : ''}
</Table.Cell>
<Table.Cell>{humanFileSize(file.size)}</Table.Cell> <Table.Cell>{humanFileSize(file.size)}</Table.Cell>
<Table.Cell> <Table.Cell>
{file.name.startsWith('terrain') {/* A search index is built from a basemap's places; other files have none. */}
{file.kind !== 'basemap'
? null ? null
: file.has_search_index : file.has_search_index
? <Button size='xs' icon='check' disabled role='save'>Built</Button> ? <Button size='xs' icon='check' disabled role='save'>Built</Button>
: <APIButton size='xs' icon='search' : <APIButton size='xs' icon='search'
disabled={searchBuilding} disabled={searchBuilding}
loading={searchBuilding} loading={searchBuilding}
onClick={() => handleBuildSearch(file.name)}> onClick={() => handleBuildSearch(file.map_path)}>
{searchBuilding ? 'Building...' : 'Build'} {searchBuilding ? 'Building...' : 'Build'}
</APIButton> </APIButton>
} }
@ -362,16 +402,24 @@ function ManageMap() {
size='xs' size='xs'
confirmContent='Delete this map file?' confirmContent='Delete this map file?'
confirmButton='Delete' confirmButton='Delete'
onClick={() => handleDelete(file.name)} onClick={() => handleDelete(file.map_path)}
> >
Delete Delete
</APIButton> </APIButton>
</Table.Cell> </Table.Cell>
<Table.Cell>
<Toggle
aria-label={`Show ${file.map_path} on the map`}
title='Show this file on the map, or ignore it.'
checked={file.visible !== false}
onChange={(e) => handleVisible(file, e.currentTarget.checked)}
/>
</Table.Cell>
</Table.Row>; </Table.Row>;
}; };
const emptyRow = <Table.Row> const emptyRow = <Table.Row>
<Table.Cell colSpan={4}>No PMTiles map files were found in <b>map/</b></Table.Cell> <Table.Cell colSpan={6}>No PMTiles map files were found in <b>map/</b></Table.Cell>
</Table.Row>; </Table.Row>;
// --- Catalog table --- // --- Catalog table ---
@ -397,6 +445,8 @@ function ManageMap() {
</>; </>;
} }
const catalogLoaded = Array.isArray(catalog);
/* /*
* A fragment, not a `PageContainer`. `MapRoute` already provides the page chrome -- a * A fragment, not a `PageContainer`. `MapRoute` already provides the page chrome -- a
* `wrolpi-stack` wrapper with its own top margin -- so a second one put this page a further * `wrolpi-stack` wrapper with its own top margin -- so a second one put this page a further
@ -410,7 +460,7 @@ function ManageMap() {
tableHeaders={fileHeaders} tableHeaders={fileHeaders}
data={files} data={files}
rowFunc={fileRowFunc} rowFunc={fileRowFunc}
rowKey='name' rowKey='map_path'
defaultSortColumn='name' defaultSortColumn='name'
emptyRow={emptyRow} emptyRow={emptyRow}
/> />
@ -419,18 +469,26 @@ function ManageMap() {
<div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}> <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5em'}}>
<Header as='h3'>Map Subscriptions</Header> <Header as='h3'>Map Subscriptions</Header>
<Button size='xs' icon='globe' onClick={() => setAllRegionsOpen(true)}>View All Regions</Button> {/* A pending or failed catalog is not "zero regions": the preview waits for one. The
modal is mounted only then, so it receives the state array itself and its map is
not rebuilt by a fresh `[]` on every status tick. */}
<Button size='xs' icon='globe' disabled={!catalogLoaded} onClick={() => setAllRegionsOpen(true)}>
View All Regions
</Button>
</div> </div>
<AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen} onClose={() => setAllRegionsOpen(false)}/> {catalogLoaded && <AllRegionsPreviewModal catalog={catalog} open={allRegionsOpen}
onClose={() => setAllRegionsOpen(false)}/>}
<SortableTable {catalog === undefined
? <ErrorMessage>Could not fetch map subscriptions</ErrorMessage>
: <SortableTable
tableHeaders={catalogHeaders} tableHeaders={catalogHeaders}
data={catalog} data={catalog}
rowFunc={catalogRowFunc} rowFunc={catalogRowFunc}
rowKey='region' rowKey='region'
defaultSortColumn='name' defaultSortColumn='name'
/> />}
<InfoMessage storageName='hint_map_subscribe'> <InfoMessage storageName='hint_map_subscribe'>
<div style={{fontWeight: 600, marginBottom: 4}}>How to get map files</div> <div style={{fontWeight: 600, marginBottom: 4}}>How to get map files</div>
@ -447,6 +505,10 @@ function ManageMap() {
</p> </p>
</InfoMessage> </InfoMessage>
<Divider/>
<WeatherSection/>
<HandPointMessage> <HandPointMessage>
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p> <p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage> </HandPointMessage>
@ -497,17 +559,29 @@ function PinEditRow({pin, onSave, onCancel}) {
} }
function MapPins() { function MapPins() {
const [pins, setPins] = useState([]); // null = pending, undefined = fetch failed, [] = no pins. The empty row invites the user to
// add one, so it may only appear for a confirmed empty list.
const [pins, setPins] = useState(null);
const [filter, setFilter] = useState(''); const [filter, setFilter] = useState('');
const [editingId, setEditingId] = useState(null); const [editingId, setEditingId] = useState(null);
const navigate = useNavigate(); const navigate = useNavigate();
// Only the newest pins request may write state: an edit or delete refetches while the mount
// request may still be in flight.
const pinsGen = useRef(0);
const fetchPins = async () => { const fetchPins = async () => {
const gen = ++pinsGen.current;
try { try {
const data = await getMapPins(); const data = await getMapPins();
if (data) setPins(data.pins || []); if (gen === pinsGen.current) {
// The api helper returns undefined on a non-OK response.
setPins(data ? data.pins || [] : undefined);
}
} catch (e) { } catch (e) {
console.error(e); console.error(e);
if (gen === pinsGen.current) {
setPins(undefined);
}
} }
}; };
@ -531,6 +605,9 @@ function MapPins() {
navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`); navigate(`/map?lat=${pin.lat}&lon=${pin.lon}&z=14`);
}; };
const solarButton = (pin) => <Button size='xs' icon='sun' aria-label={`Solar estimate for ${pin.label}`}
onClick={() => navigate(solarCalculatorPath(pin.lat, pin.lon))}/>;
// --- Desktop headers and row --- // --- Desktop headers and row ---
const fullHeaders = [ const fullHeaders = [
{key: 'color', text: '', sortBy: i => i.color}, {key: 'color', text: '', sortBy: i => i.color},
@ -564,10 +641,11 @@ function MapPins() {
</Table.Cell> </Table.Cell>
<Table.Cell>{pin.created}</Table.Cell> <Table.Cell>{pin.created}</Table.Cell>
<Table.Cell> <Table.Cell>
{/* See PinEditRow: a Group so the three controls line up and are spaced. */} {/* See PinEditRow: a Group so the controls line up and are spaced. */}
<Group gap='xs' wrap='nowrap'> <Group gap='xs' wrap='nowrap'>
<Button size='xs' icon='edit' aria-label={`Edit ${pin.label}`} <Button size='xs' icon='edit' aria-label={`Edit ${pin.label}`}
onClick={() => setEditingId(pin.id)}/> onClick={() => setEditingId(pin.id)}/>
{solarButton(pin)}
<AddToPlaylistButton <AddToPlaylistButton
size='xs' size='xs'
icon='list' icon='list'
@ -610,6 +688,8 @@ function MapPins() {
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div> <div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{pin.lat.toFixed(4)}, {pin.lon.toFixed(4)}</div>
</Table.Cell> </Table.Cell>
<Table.Cell> <Table.Cell>
<Group gap='xs' wrap='nowrap'>
{solarButton(pin)}
<APIButton <APIButton
size='xs' size='xs'
role='danger' role='danger'
@ -619,6 +699,7 @@ function MapPins() {
confirmButton='Delete' confirmButton='Delete'
onClick={() => handleDelete(pin.id)} onClick={() => handleDelete(pin.id)}
/> />
</Group>
</Table.Cell> </Table.Cell>
</Table.Row>; </Table.Row>;
}; };
@ -627,8 +708,13 @@ function MapPins() {
<Table.Cell colSpan={5}>No pins. Right-click on the map to add one.</Table.Cell> <Table.Cell colSpan={5}>No pins. Right-click on the map to add one.</Table.Cell>
</Table.Row>; </Table.Row>;
if (pins === undefined) {
return <ErrorMessage>Could not fetch map pins</ErrorMessage>;
}
const lowerFilter = filter.toLowerCase(); const lowerFilter = filter.toLowerCase();
const filteredPins = lowerFilter // Pending (null) passes through so SortableTable shows its placeholder.
const filteredPins = lowerFilter && pins
? pins.filter(p => ? pins.filter(p =>
(p.label || '').toLowerCase().includes(lowerFilter) || (p.label || '').toLowerCase().includes(lowerFilter) ||
`${p.lat.toFixed(4)}, ${p.lon.toFixed(4)}`.includes(lowerFilter) `${p.lat.toFixed(4)}, ${p.lon.toFixed(4)}`.includes(lowerFilter)
@ -665,6 +751,103 @@ function MapPins() {
emptyRow={emptyRow} emptyRow={emptyRow}
/> />
</Media> </Media>
<MapTargets filter={lowerFilter}/>
</>;
}
// The saved nuclear targets (map_nuclear.yaml), apart from the pins: what each is and where, and
// deleting one. `filter` (lower case) matches a name or coordinates.
export function MapTargets({filter = ''}) {
// null = pending, undefined = fetch failed, [] = no targets.
const [targets, setTargets] = useState(null);
const navigate = useNavigate();
const gen = useRef(0);
const fetchTargets = async () => {
const mine = ++gen.current;
const saved = await getMapTargets();
if (mine === gen.current) setTargets(saved);
};
useEffect(() => {
fetchTargets();
}, []);
const handleDelete = async (targetId) => {
await deleteMapTarget(targetId);
await fetchTargets();
};
const weaponOf = (target) => {
const chosen = targetWeapon(target);
return `${chosen.weapon ? chosen.weapon.name : 'A yield of my own'}, `
+ formatYieldAndFission(chosen.yieldKt, chosen.fissionFraction);
};
const place = (target) => {
const to = `/map?lat=${target.lat}&lon=${target.lon}&z=10`;
return <a href={to} onClick={(e) => {
e.preventDefault();
navigate(to);
}}>{target.lat.toFixed(4)}, {target.lon.toFixed(4)}</a>;
};
const deleteButton = (target) => <APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${target.label}`}
confirmContent='Delete this target?'
confirmButton='Delete'
onClick={() => handleDelete(target.id)}
/>;
const fullHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'weapon', text: 'Weapon', sortBy: i => targetWeapon(i).yieldKt},
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
{key: 'created', text: 'Created', sortBy: i => i.created},
{key: 'actions', text: '', sortBy: null},
];
const fullRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell><span aria-hidden>☢ </span>{target.label}</Table.Cell>
<Table.Cell>{weaponOf(target)}</Table.Cell>
<Table.Cell>{place(target)}</Table.Cell>
<Table.Cell>{target.created}</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const mobileHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell>
<span aria-hidden>☢ </span>{target.label}
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{weaponOf(target)}</div>
<div style={{fontSize: '0.6875rem'}}>{place(target)}</div>
</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const emptyRow = <Table.Row>
<Table.Cell colSpan={5}>No targets. Turn on nuclear mode (☢) on the map to add and save some.</Table.Cell>
</Table.Row>;
const shown = filter && targets
? targets.filter(t => (t.label || '').toLowerCase().includes(filter) ||
`${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}`.includes(filter))
: targets;
return <>
<Header as='h3'>Nuclear Targets</Header>
{targets === undefined ? <ErrorMessage>Could not fetch the nuclear targets</ErrorMessage> : <>
<Media at='mobile'>
<SortableTable tableHeaders={mobileHeaders} data={shown} rowFunc={mobileRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
<Media greaterThanOrEqual='tablet'>
<SortableTable tableHeaders={fullHeaders} data={shown} rowFunc={fullRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
</>}
</>; </>;
} }
@ -678,6 +861,8 @@ export function MapRoute() {
const links = [ const links = [
{text: 'Map', to: '/map', key: 'map', end: true}, {text: 'Map', to: '/map', key: 'map', end: true},
{text: 'Pins', to: '/map/pins', key: 'pins'}, {text: 'Pins', to: '/map/pins', key: 'pins'},
// Manage (and Statistics, on pages which have one) are the last tabs.
{text: 'ATAK', to: '/map/atak', key: 'atak'},
{text: 'Manage', to: '/map/manage', key: 'manage'}, {text: 'Manage', to: '/map/manage', key: 'manage'},
]; ];
@ -688,6 +873,7 @@ export function MapRoute() {
<Routes> <Routes>
<Route path='/' exact element={<MapPage/>}/> <Route path='/' exact element={<MapPage/>}/>
<Route path='pins' exact element={<MapPins/>}/> <Route path='pins' exact element={<MapPins/>}/>
<Route path='atak' exact element={<MapAtak/>}/>
<Route path='manage' exact element={<ManageMap/>}/> <Route path='manage' exact element={<ManageMap/>}/>
</Routes> </Routes>
</div> </div>

View file

@ -0,0 +1,229 @@
// The map's ATAK tab: how to use this WROLPi's map in ATAK (Android) and iTAK (iPhone), and what the
// tile service (tiles/, wrolpi-tiles) is doing.
import React, {useCallback, useEffect, useRef, useState} from "react";
import {APIButton, ErrorMessage, humanFileSize, InfoMessage} from "./Common";
import {Group, Header, Panel, Table} from "./ui";
import {QRCodeButton} from "./QRCode";
// How often the status is asked for while the tab is open.
const STATUS_INTERVAL_MS = 5000;
// The map source over plain HTTP: no certificate is needed, so it works on any phone.
export function httpMapSourceUrl(hostname = window.location.hostname) {
return `http://${hostname}:8088/tiles/wrolpi.xml`;
}
// The map source over HTTPS: the phone must trust this WROLPi's certificate authority.
export function httpsMapSourceUrl(origin = window.location.origin) {
return `${origin}/tiles/wrolpi.xml`;
}
// Whether this page was opened on the WROLPi itself (or through Docker's localhost): then the map
// source addresses name this computer, and a phone can not open them.
export function isLoopback(hostname = window.location.hostname) {
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1';
}
// Remove the tiles the tile service keeps; they are drawn again when a phone next asks for them.
export async function clearTileCache() {
const response = await fetch('/tiles/cache/clear', {method: 'POST'});
if (!response.ok) {
throw new Error(`Could not clear the kept tiles: ${response.status}`);
}
return await response.json();
}
// The status of the tile service, and a function which asks for it now. The status is null while
// the first request is pending, undefined when the service did not answer.
//
// Only the newest request may write the status: a slow answer which settles after a newer poll (or
// after the refresh which follows clearing the kept tiles) would put an older status back.
export function useTileStatus(interval = STATUS_INTERVAL_MS) {
const [status, setStatus] = useState(null);
// Each request's number; a request writes only while it is the newest. Unmounting makes every
// request in flight old.
const generation = useRef(0);
const fetchStatus = useCallback(async () => {
const mine = ++generation.current;
let data;
try {
const response = await fetch('/tiles/status');
data = response.ok ? await response.json() : undefined;
} catch (e) {
data = undefined;
}
if (mine === generation.current) setStatus(data);
}, []);
useEffect(() => {
// The counter itself (not a DOM node): on unmount every request in flight becomes old.
const requests = generation;
fetchStatus();
const timer = setInterval(fetchStatus, interval);
return () => {
requests.current++;
clearInterval(timer);
};
}, [interval, fetchStatus]);
return [status, fetchStatus];
}
function MapSourceRow({label, name, url, note}) {
return <Table.Row>
<Table.Cell>
<b>{label}</b>
<div style={{fontSize: '0.8125rem', color: 'var(--muted)'}}>{note} Called <b>{name}</b> in the app.</div>
</Table.Cell>
<Table.Cell style={{wordBreak: 'break-all'}}><a href={url}>{url}</a></Table.Cell>
<Table.Cell>
<Group gap='xs' wrap='nowrap'>
<APIButton icon='copy' aria-label={`Copy ${label} map source address`}
onClick={() => navigator.clipboard.writeText(url)}/>
<QRCodeButton value={url} color='violet' label={`Show ${label} map source QR code`}
header={`Scan with the phone to download the ${label} map source`}>
<p style={{wordBreak: 'break-all'}}>{url}</p>
</QRCodeButton>
</Group>
</Table.Cell>
</Table.Row>;
}
function HowTo() {
return <Panel>
<Header as='h3'>Use this map in ATAK or iTAK</Header>
<p>
ATAK (Android) and iTAK (iPhone) can draw this WROLPi's map while the phone is on this
WROLPi's network, and download an area of it to use when it is not.
</p>
{isLoopback() && <InfoMessage>
This page was opened on this computer ({window.location.hostname}), so these addresses only
work here. On the phone, open this page (or these addresses) with this WROLPi's address on
your network or its hotspot instead.
</InfoMessage>}
<Table>
<Table.Body>
<MapSourceRow label='HTTP' name='WROLPi Map' url={httpMapSourceUrl()}
note='Works on any phone, nothing to install.'/>
<MapSourceRow label='HTTPS' name='WROLPi Map (HTTPS)' url={httpsMapSourceUrl()}
note="Only once the phone trusts this WROLPi's certificate."/>
</Table.Body>
</Table>
<ol>
<li>On the phone, open a map source address above in its browser (or scan its QR code);
it downloads a small file.
</li>
<li>Open that file with ATAK or iTAK (or import it with the app's import tool).</li>
<li>Choose <b>WROLPi Map</b> (or <b>WROLPi Map (HTTPS)</b>) in the app's list of maps.</li>
<li>To use the map away from this WROLPi, download an area of it with the app's map
download tool while still connected.
</li>
</ol>
<p>
For HTTPS, the phone must first install and trust{' '}
<a href='/ca.crt'>this WROLPi's certificate</a>. On an iPhone, after installing it, turn
it on in Settings, General, About, Certificate Trust Settings.
</p>
<p style={{color: 'var(--muted)'}}>
The map is of the map files on the Manage tab. Map data &copy; OpenStreetMap contributors.
</p>
</Panel>;
}
function secondsAgo(timestamp) {
const seconds = Math.max(0, Math.round(Date.now() / 1000 - timestamp));
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.round(seconds / 60)}m ago`;
return `${Math.round(seconds / 3600)}h ago`;
}
function TileServiceStatus({status, refresh}) {
if (status === null) {
return <Panel><Header as='h3'>Tile service</Header><p>Loading...</p></Panel>;
}
if (status === undefined) {
return <Panel>
<Header as='h3'>Tile service</Header>
<ErrorMessage>The tile service is not running. Start <b>wrolpi-tiles</b> on the
Controller page.</ErrorMessage>
</Panel>;
}
const basemaps = status.maps.length;
const cache = status.cache;
return <Panel>
<Header as='h3'>Tile service</Header>
{!status.renderer && <ErrorMessage>The tile service cannot draw tiles: its renderer (mapli) is not
installed.</ErrorMessage>}
{basemaps === 0 && <InfoMessage>There are no map files; download some on the Manage tab.</InfoMessage>}
<Table>
<Table.Body>
<Table.Row>
<Table.Cell>Map files</Table.Cell>
<Table.Cell>{basemaps}</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Tiles sent</Table.Cell>
<Table.Cell>{status.tiles_per_second} per second (last minute)</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Waiting to be drawn</Table.Cell>
<Table.Cell>{status.queued_blocks + status.drawing_blocks} blocks of 16 tiles</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Kept tiles</Table.Cell>
<Table.Cell>
{cache.enabled
? <Group gap='sm'>
<span>{humanFileSize(cache.bytes)} of {humanFileSize(cache.max_bytes)}</span>
<APIButton
size='xs'
role='danger'
icon='trash'
disabled={!cache.bytes}
confirmHeader='Clear kept tiles?'
confirmContent={'The tiles this WROLPi keeps are removed, and drawn again when a ' +
'phone next asks for them. Maps already downloaded to phones are not ' +
'changed: a phone keeps its own copy.'}
confirmButton='Clear'
onClick={async () => {
await clearTileCache();
await refresh();
}}
>Clear</APIButton>
</Group>
: 'Not kept'}
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Header as='h4'>Phones (last day)</Header>
{status.clients.length === 0
? <p>No phone has asked for tiles.</p>
: <Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Address</Table.HeaderCell>
<Table.HeaderCell>Tiles</Table.HeaderCell>
<Table.HeaderCell>Last tile</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{status.clients.map(client => <Table.Row key={client.client}>
<Table.Cell>{client.client}</Table.Cell>
<Table.Cell>{client.tiles}</Table.Cell>
<Table.Cell>{secondsAgo(client.last_seen)}</Table.Cell>
</Table.Row>)}
</Table.Body>
</Table>}
</Panel>;
}
export function MapAtak() {
const [status, refresh] = useTileStatus();
return <>
<HowTo/>
<TileServiceStatus status={status} refresh={refresh}/>
</>;
}

View file

@ -0,0 +1,188 @@
import React from 'react';
import {act, fireEvent, renderHook, screen, waitFor, within} from '@testing-library/react';
import {mockFetch, renderWithProviders} from '../test-utils';
import {humanFileSize} from './Common';
import {clearTileCache, httpMapSourceUrl, httpsMapSourceUrl, isLoopback, MapAtak, useTileStatus} from './MapAtak';
const STATUS = {
renderer: true,
processes: 2,
max_zoom: 17,
maps: ['/opt/wrolpi-blobs/map-overview.pmtiles', '/media/wrolpi/map/mexico.pmtiles'],
style_id: 'abc',
queued_blocks: 3,
drawing_blocks: 2,
tiles_per_second: 31.5,
block_ms: 310,
cache: {enabled: true, bytes: 25 * 1024 * 1024, max_bytes: 1024 * 1024 * 1024},
stats: {},
clients: [{client: '192.0.2.34', tiles: 578, first_seen: 0, last_seen: Date.now() / 1000 - 30, queued_blocks: 0}],
};
describe('MapAtak', () => {
const realFetch = global.fetch;
afterEach(() => {
global.fetch = realFetch;
});
it('builds the map source addresses from how the browser reached this WROLPi', () => {
expect(httpMapSourceUrl('192.0.2.8')).toBe('http://192.0.2.8:8088/tiles/wrolpi.xml');
expect(httpsMapSourceUrl('https://wrolpi.local')).toBe('https://wrolpi.local/tiles/wrolpi.xml');
});
it('shows the map sources and what the tile service is doing', async () => {
global.fetch = mockFetch(STATUS);
renderWithProviders(<MapAtak/>);
expect(screen.getByText(httpMapSourceUrl())).toHaveAttribute('href', httpMapSourceUrl());
expect(screen.getByText(httpsMapSourceUrl())).toHaveAttribute('href', httpsMapSourceUrl());
expect(screen.getByText("this WROLPi's certificate")).toHaveAttribute('href', '/ca.crt');
// Both apps take an area offline (tested with iTAK on an iPhone).
expect(screen.getByText(/download an area of it with the app's map download tool/)).toBeInTheDocument();
expect(await screen.findByText('31.5 per second (last minute)')).toBeInTheDocument();
expect(global.fetch).toHaveBeenCalledWith('/tiles/status');
expect(screen.getByText('5 blocks of 16 tiles')).toBeInTheDocument();
expect(screen.getByText(`${humanFileSize(25 * 1024 * 1024)} of ${humanFileSize(1024 * 1024 * 1024)}`))
.toBeInTheDocument();
expect(screen.getByText('192.0.2.34')).toBeInTheDocument();
expect(screen.getByText('578')).toBeInTheDocument();
expect(screen.getByText('30s ago')).toBeInTheDocument();
});
it('shows a QR code of each map source address for the phone to scan', async () => {
global.fetch = mockFetch(STATUS);
renderWithProviders(<MapAtak/>);
await screen.findByText('31.5 per second (last minute)');
for (const [label, url] of [['HTTP', httpMapSourceUrl()], ['HTTPS', httpsMapSourceUrl()]]) {
fireEvent.click(screen.getByRole('button', {name: `Show ${label} map source QR code`}));
const dialog = await screen.findByRole('dialog');
// react-qr-code renders an svg titled with its value.
expect(within(dialog).getByTitle(url)).toBeInTheDocument();
expect(within(dialog).getByText(`Scan with the phone to download the ${label} map source`))
.toBeInTheDocument();
fireEvent.keyDown(dialog, {key: 'Escape'});
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
}
});
it('says when the tile service is not running', async () => {
global.fetch = jest.fn(() => Promise.reject(new Error('connection refused')));
renderWithProviders(<MapAtak/>);
expect(await screen.findByText(/The tile service is not running/)).toBeInTheDocument();
});
it('says when there are no map files', async () => {
global.fetch = mockFetch({...STATUS, maps: [], clients: []});
renderWithProviders(<MapAtak/>);
expect(await screen.findByText(/There are no map files/)).toBeInTheDocument();
expect(screen.getByText('No phone has asked for tiles.')).toBeInTheDocument();
});
it('clears the kept tiles after asking, then shows the new size', async () => {
let bytes = 25 * 1024 * 1024;
global.fetch = jest.fn(async (url, options) => {
if (url === '/tiles/cache/clear') {
expect(options).toEqual({method: 'POST'});
const freed = bytes;
bytes = 0;
return {ok: true, status: 200, json: async () => ({freed_bytes: freed})};
}
return {ok: true, status: 200, json: async () => ({...STATUS, cache: {...STATUS.cache, bytes}})};
});
renderWithProviders(<MapAtak/>);
await screen.findByText('31.5 per second (last minute)');
fireEvent.click(screen.getByRole('button', {name: /Clear/}));
// Nothing is removed until it is confirmed.
expect(await screen.findByText(/a phone keeps its own copy/)).toBeInTheDocument();
expect(global.fetch).not.toHaveBeenCalledWith('/tiles/cache/clear', expect.anything());
const dialog = screen.getByRole('dialog');
fireEvent.click(within(dialog).getByRole('button', {name: 'Clear'}));
await waitFor(() => expect(global.fetch).toHaveBeenCalledWith('/tiles/cache/clear', {method: 'POST'}));
expect(await screen.findByText(`${humanFileSize(0)} of ${humanFileSize(1024 * 1024 * 1024)}`))
.toBeInTheDocument();
});
it('cannot clear when no tiles are kept', async () => {
global.fetch = mockFetch({...STATUS, cache: {...STATUS.cache, bytes: 0}});
renderWithProviders(<MapAtak/>);
await screen.findByText('31.5 per second (last minute)');
expect(screen.getByRole('button', {name: /Clear/})).toBeDisabled();
});
it('clearTileCache fails loudly when the service refuses', async () => {
global.fetch = jest.fn(async () => ({ok: false, status: 502, json: async () => ({})}));
await expect(clearTileCache()).rejects.toThrow('502');
});
it('names each map source as the app will list it', async () => {
global.fetch = mockFetch(STATUS);
renderWithProviders(<MapAtak/>);
await screen.findByText('31.5 per second (last minute)');
// The tile service names the HTTPS source differently (tiles/service.py).
expect(screen.getAllByText('WROLPi Map').length).toBeGreaterThanOrEqual(1);
expect(screen.getAllByText('WROLPi Map (HTTPS)').length).toBeGreaterThanOrEqual(1);
});
it('says when the addresses only work on this computer', async () => {
expect(isLoopback('localhost')).toBe(true);
expect(isLoopback('127.0.0.1')).toBe(true);
expect(isLoopback('[::1]')).toBe(true);
expect(isLoopback('wrolpi.local')).toBe(false);
expect(isLoopback('192.0.2.8')).toBe(false);
// jsdom's page is on localhost.
global.fetch = mockFetch(STATUS);
renderWithProviders(<MapAtak/>);
expect(screen.getByText(/these addresses only\s+work here/)).toBeInTheDocument();
await screen.findByText('31.5 per second (last minute)');
});
it('does not put an older status back over a newer one', async () => {
// The first request is slow and its answer old. A newer one (as Clear's refresh makes) is
// answered first. The old answer settles last, and must not undo the newer.
let answerFirst;
let calls = 0;
global.fetch = jest.fn(() => {
calls++;
if (calls === 1) {
return new Promise(resolve => {
answerFirst = () => resolve({ok: true, status: 200, json: async () => STATUS});
});
}
return Promise.resolve({ok: true, status: 200,
json: async () => ({...STATUS, cache: {...STATUS.cache, bytes: 0}})});
});
const {result} = renderHook(() => useTileStatus(60000));
await waitFor(() => expect(calls).toBe(1));
await act(async () => {
await result.current[1](); // the newer request
});
expect(result.current[0].cache.bytes).toBe(0);
await act(async () => {
answerFirst(); // the older one settles last
});
expect(result.current[0].cache.bytes).toBe(0);
});
it('polls the status while open', async () => {
jest.useFakeTimers();
try {
global.fetch = mockFetch(STATUS);
const {unmount} = renderWithProviders(<MapAtak/>);
await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(1));
jest.advanceTimersByTime(5000);
await waitFor(() => expect(global.fetch).toHaveBeenCalledTimes(2));
unmount();
jest.advanceTimersByTime(20000);
expect(global.fetch).toHaveBeenCalledTimes(2);
} finally {
jest.useRealTimers();
}
});
});

View file

@ -0,0 +1,63 @@
import {poiPopupHtml} from './mapPoiPopup';
// Clicking a POI on the map opens a popup built from attributes already in the pmtiles
// file: the name, its category (kind), sub-category (kind_detail), and elevation.
const feature = (properties) => ({properties});
test('name, kind, detail and elevation are all shown, humanized', () => {
const html = poiPopupHtml([feature({
name: 'Flattop Mountain', kind: 'peak', kind_detail: 'volcano', elevation: 1070,
})]);
expect(html).toContain('Flattop Mountain');
expect(html).toContain('Peak');
expect(html).toContain('Volcano');
expect(html).toContain('1070 m');
expect(html).toContain('3510 ft');
});
test('missing attributes are left out rather than shown as undefined', () => {
const html = poiPopupHtml([feature({name: 'Franz', kind: 'bakery'})]);
expect(html).toContain('Franz');
expect(html).toContain('Bakery');
expect(html).not.toContain('undefined');
expect(html).not.toContain('Elevation');
});
test('kind_detail of "none" is not shown', () => {
const html = poiPopupHtml([feature({name: 'West High', kind: 'school', kind_detail: 'none'})]);
expect(html).not.toContain('none');
expect(html).not.toContain('None');
});
test('the same feature at several min_zoom levels appears once', () => {
const html = poiPopupHtml([
feature({name: 'Westchester Lagoon', kind: 'water', min_zoom: 12}),
feature({name: 'Westchester Lagoon', kind: 'water', min_zoom: 14}),
]);
expect(html.match(/Westchester Lagoon/g)).toHaveLength(1);
});
test('feature properties are HTML escaped', () => {
const html = poiPopupHtml([feature({name: '<img src=x onerror=alert(1)>', kind: 'a&b'})]);
expect(html).not.toContain('<img');
expect(html).toContain('&lt;img');
expect(html).toContain('A&amp;b');
});
test('a point feature shows its own coordinates, lat then lon', () => {
const html = poiPopupHtml([{
properties: {name: 'Peak Two', kind: 'peak'},
geometry: {type: 'Point', coordinates: [-149.67301, 61.08571]},
}], {lng: -149.5, lat: 61.0});
expect(html).toContain('61.08571, -149.67301');
});
test('a feature without a point falls back to the clicked location', () => {
const html = poiPopupHtml([feature({name: 'Lagoon', kind: 'water'})], {lng: -149.5, lat: 61.0});
expect(html).toContain('61.00000, -149.50000');
});
test('no features gives no popup', () => {
expect(poiPopupHtml([])).toBeNull();
});

View file

@ -102,6 +102,7 @@ const CATALOG = [
jest.mock('../api', () => ({ jest.mock('../api', () => ({
...jest.requireActual('../api'), ...jest.requireActual('../api'),
getWeather: async () => ({enabled: false, download: null, targets: 0, field: null}),
getMapFiles: jest.fn(), getMapFiles: jest.fn(),
fetchMapSubscriptions: jest.fn(), fetchMapSubscriptions: jest.fn(),
getMapPins: jest.fn(), getMapPins: jest.fn(),
@ -213,16 +214,47 @@ describe('a single region preview', () => {
describe('the basemap source', () => { describe('the basemap source', () => {
it("uses the user's planet file when they have one", async () => { it("uses the user's planet file when they have one", async () => {
await renderManage({files: [{name: '20260329.pmtiles', size: 134e9}]}); await renderManage({
files: [
{
name: '20260329.pmtiles', path: 'map/planet/20260329.pmtiles',
map_path: 'planet/20260329.pmtiles', kind: 'basemap', visible: true, size: 134e9,
},
],
});
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'})); await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
await waitFor(() => expect(constructed).toHaveLength(1)); await waitFor(() => expect(constructed).toHaveLength(1));
const {sources} = constructed[0].options.style; const {sources} = constructed[0].options.style;
expect(sources.basemap.url).toBe('pmtiles:///media/map/20260329.pmtiles'); // The file is used where it is, here in a sub-directory of the map directory.
expect(sources.basemap.url).toBe('pmtiles:///media/map/planet/20260329.pmtiles');
}); });
it('falls back to the overview blob when there is no planet file', async () => { it('falls back to the overview blob when there is no planet file', async () => {
await renderManage({files: [{name: 'us-west-20260329.pmtiles', size: 5e9}]}); await renderManage({
files: [
{
name: 'us-west-20260329.pmtiles', path: 'map/us-west-20260329.pmtiles',
map_path: 'us-west-20260329.pmtiles', kind: 'basemap', visible: true, size: 5e9,
},
],
});
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
await waitFor(() => expect(constructed).toHaveLength(1));
const {sources} = constructed[0].options.style;
expect(sources.basemap.url).toBe('pmtiles:///blobs/map-overview.pmtiles');
});
it('falls back to the overview blob when the planet file is ignored', async () => {
await renderManage({
files: [
{
name: '20260329.pmtiles', path: 'map/20260329.pmtiles',
map_path: '20260329.pmtiles', kind: 'basemap', visible: false, size: 134e9,
},
],
});
await userEvent.click(screen.getByRole('button', {name: 'View All Regions'})); await userEvent.click(screen.getByRole('button', {name: 'View All Regions'}));
await waitFor(() => expect(constructed).toHaveLength(1)); await waitFor(() => expect(constructed).toHaveLength(1));

View file

@ -0,0 +1,263 @@
import React, {useEffect, useRef, useState} from "react";
import {Button, Checkbox, Group, Radio} from "./ui";
import {EXPORT_DPI, EXPORT_DPIS} from "./mapExport";
import {EXPORT_LOOKS, PRINT_LOOK} from "./mapPrintStyle";
import {
EMPTY_FEATURES,
QUAD_MIN_ZOOM,
quadAt,
quadGridLines,
quadLabel,
quadPolygon,
quadSize,
quadTitle,
} from "./mapQuads";
// What the ids of the picker's layers and sources start with: they are of the app, not of the map.
export const QUAD_LAYER_PREFIX = "quad-";
const GRID_SOURCE = "quad-grid";
const SELECTED_SOURCE = "quad-selected";
// The picker's own layers, in the order they are drawn (all above the map's).
const QUAD_LAYERS = [
{
id: "quad-grid-lines", type: "line", source: GRID_SOURCE,
paint: {"line-color": "#e8590c", "line-width": 1.5, "line-opacity": 0.8},
},
{
id: "quad-selected-fill", type: "fill", source: SELECTED_SOURCE,
paint: {"fill-color": "#e8590c", "fill-opacity": 0.2},
},
{
id: "quad-selected-outline", type: "line", source: SELECTED_SOURCE,
paint: {"line-color": "#e8590c", "line-width": 3.5},
},
];
export function formatDistance(meters, scaleUnit) {
return scaleUnit === "imperial"
? `${(meters / 1609.344).toFixed(1)} mi`
: `${(meters / 1000).toFixed(1)} km`;
}
export function formatSheet(millimeters, scaleUnit) {
return scaleUnit === "imperial"
? `${(millimeters / 25.4).toFixed(1)} in`
: `${(millimeters / 10).toFixed(1)} cm`;
}
function selectedFeatures(quad) {
return quad ? {type: "FeatureCollection", features: [quadPolygon(quad)]} : EMPTY_FEATURES;
}
// Draws the grid of 1:24,000 quadrangles over the map while the user chooses one to export.
//
// The grid and the chosen quadrangle are layers of the map, which a change of its style removes; they
// are put back whenever the style has loaded.
//
// onExport(quad, {sheet, dpi, name}): make the PDF; `sheet` is whether the map is to be on a sheet,
// with a margin, a grid and scale bars, `dpi` is how sharp it is to be, and `name` is what the USGS
// calls the quadrangle ({name, state, exact}), or null.
//
// fetchName(quad): asks for that name; it resolves to null where there is none.
//
// look, onLook(look): the look the map is exported in (see mapPrintStyle.js), and what is told when
// another is chosen. The map is shown in it, so what is seen is what is exported.
//
// While the PDF is being made `status` says how far along it is, and nothing else can be chosen;
// Cancel then stops it (onCancel()) and does not close the picker. `error` says why the last one
// could not be made.
export default function MapQuadPicker({
map, scaleUnit, initialQuad = null, onExport, onCancel, onClose, fetchName, status = null, error = null,
look = null, onLook = null,
}) {
const busy = status !== null;
const busyRef = useRef(busy);
busyRef.current = busy;
const [selected, setSelected] = useState(initialQuad);
const selectedRef = useRef(initialQuad);
// Whether the map is zoomed in far enough for the grid to be drawn.
const [gridShown, setGridShown] = useState(true);
const [sheet, setSheet] = useState(true);
const [dpi, setDpi] = useState(EXPORT_DPI);
// What the chosen quadrangle is called: {id, name} once it is known, for the quadrangle it is of.
const [named, setNamed] = useState(null);
const name = selected && named?.id === selected.id ? named.name : null;
useEffect(() => {
if (!selected || !fetchName) return;
let current = true;
Promise.resolve(fetchName(selected))
.then(found => current && setNamed({id: selected.id, name: found || null}))
.catch(() => current && setNamed({id: selected.id, name: null}));
// An answer for a quadrangle which is no longer the chosen one is not used.
return () => {
current = false;
};
}, [selected, fetchName]);
useEffect(() => {
if (!map) return;
const drawGrid = () => {
const source = map.getSource(GRID_SOURCE);
if (!source) return;
const bounds = map.getBounds();
const grid = map.getZoom() >= QUAD_MIN_ZOOM
? quadGridLines({
west: bounds.getWest(), south: bounds.getSouth(),
east: bounds.getEast(), north: bounds.getNorth(),
})
: null;
source.setData(grid || EMPTY_FEATURES);
setGridShown(grid !== null);
};
const drawSelected = () => {
const source = map.getSource(SELECTED_SOURCE);
if (source) source.setData(selectedFeatures(selectedRef.current));
};
const addLayers = () => {
if (!map.getSource(GRID_SOURCE)) map.addSource(GRID_SOURCE, {type: "geojson", data: EMPTY_FEATURES});
if (!map.getSource(SELECTED_SOURCE)) {
map.addSource(SELECTED_SOURCE, {type: "geojson", data: EMPTY_FEATURES});
}
for (const layer of QUAD_LAYERS) {
if (!map.getLayer(layer.id)) map.addLayer(layer);
}
drawGrid();
drawSelected();
};
const choose = (e) => {
// The quadrangle being exported stays the chosen one.
if (busyRef.current) return;
const quad = quadAt(e.lngLat.lng, e.lngLat.lat);
// Choosing the chosen quadrangle again lets go of it.
const next = quad && selectedRef.current?.id === quad.id ? null : quad;
selectedRef.current = next;
setSelected(next);
drawSelected();
};
addLayers();
map.on("style.load", addLayers);
map.on("moveend", drawGrid);
map.on("click", choose);
return () => {
map.off("style.load", addLayers);
map.off("moveend", drawGrid);
map.off("click", choose);
try {
for (const layer of [...QUAD_LAYERS].reverse()) {
if (map.getLayer(layer.id)) map.removeLayer(layer.id);
}
for (const source of [GRID_SOURCE, SELECTED_SOURCE]) {
if (map.getSource(source)) map.removeSource(source);
}
} catch (e) {
// The map itself is gone, and its layers with it.
}
};
}, [map]);
const size = selected ? quadSize(selected) : null;
// Part of the app's interface over the map, like the layer control: plain, token-colored chrome.
const panelStyle = {
position: "absolute",
bottom: "2.5rem",
left: "50%",
transform: "translateX(-50%)",
zIndex: 1000,
background: "var(--panel)",
border: "1px solid var(--border)",
color: "var(--text)",
padding: "0.625rem 0.75rem",
fontSize: "0.8125rem",
width: "max-content",
maxWidth: "calc(100% - 1.25rem)",
};
return <div style={panelStyle} role="region" aria-label="Export a 1:24,000 map">
<div style={{fontWeight: 600, paddingBottom: "0.25rem"}}>Export a 1:24,000 map</div>
{selected
? <div>
{name && <div data-testid="quad-name" style={{fontWeight: 600}}>{quadTitle(name)}</div>}
<div data-testid="quad-label">{quadLabel(selected)}</div>
<div style={{color: "var(--muted)"}} data-testid="quad-size">
{formatDistance(size.widthMeters, scaleUnit)} × {formatDistance(size.heightMeters, scaleUnit)}
{" on the ground, "}
{formatSheet(size.sheetWidthMm, scaleUnit)} × {formatSheet(size.sheetHeightMm, scaleUnit)}
{" printed"}
</div>
</div>
: <div>
{gridShown
? "Click a quadrangle on the map to choose it."
: "Zoom in to see the quadrangles."}
</div>}
<Checkbox
size="xs"
style={{paddingTop: "0.5rem"}}
label="Margins, grid and scale bars"
checked={sheet}
disabled={busy}
onChange={e => setSheet(e.currentTarget.checked)}
/>
<Radio.Group
size="xs"
style={{paddingTop: "0.5rem"}}
aria-label="Sharpness"
value={String(dpi)}
onChange={value => setDpi(Number(value))}
>
<Group gap="md">
{EXPORT_DPIS.map(value => <Radio
key={value}
size="xs"
value={String(value)}
label={`${value} DPI`}
disabled={busy}
/>)}
</Group>
</Radio.Group>
{look && onLook && <Radio.Group
size="xs"
style={{paddingTop: "0.5rem"}}
aria-label="Colors"
value={look}
onChange={onLook}
>
<Group gap="md">
{EXPORT_LOOKS.map(({value, label}) => <Radio
key={value}
size="xs"
value={value}
label={label}
disabled={busy}
/>)}
</Group>
</Radio.Group>}
{look === PRINT_LOOK && onLook && <div style={{paddingTop: "0.25rem", color: "var(--muted)"}}>
Its colors can be changed under Layers.
</div>}
{status && <div role="status" style={{paddingTop: "0.25rem"}}>{status}</div>}
{error && !status && <div role="alert" style={{paddingTop: "0.25rem", color: "var(--danger, #c92a2a)"}}>
{error}
</div>}
<div style={{display: "flex", gap: "0.5rem", justifyContent: "flex-end", paddingTop: "0.5rem"}}>
<Button role="cancel" size="xs" disabled={busy && !onCancel} onClick={busy ? onCancel : onClose}>
{error && !busy ? "Close" : "Cancel"}
</Button>
<Button
role="primary"
size="xs"
disabled={!selected || !onExport || busy}
loading={busy}
onClick={() => onExport(selected, {sheet, dpi, name})}
>Export PDF</Button>
</div>
</div>;
}

View file

@ -0,0 +1,315 @@
import React from 'react';
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
import {renderUI} from '../test-utils';
import MapQuadPicker, {formatDistance, formatSheet} from './MapQuadPicker';
import {quadAt} from './mapQuads';
// As much of a MapLibre map as the picker uses.
class FakeMap {
constructor({zoom = 12, bounds = {west: -105.175, south: 40.26, east: -104.925, north: 40.4}} = {}) {
this.zoom = zoom;
this.bounds = bounds;
this.sources = {};
this.layers = [];
this.handlers = {};
}
on(event, handler) {
(this.handlers[event] = this.handlers[event] || []).push(handler);
}
off(event, handler) {
this.handlers[event] = (this.handlers[event] || []).filter(i => i !== handler);
}
fire(event, data) {
for (const handler of [...(this.handlers[event] || [])]) handler(data);
}
addSource(id, source) {
this.sources[id] = {data: source.data, setData(data) { this.data = data; }};
}
getSource(id) {
return this.sources[id];
}
removeSource(id) {
delete this.sources[id];
}
addLayer(layer) {
this.layers.push(layer);
}
getLayer(id) {
return this.layers.find(i => i.id === id);
}
removeLayer(id) {
this.layers = this.layers.filter(i => i.id !== id);
}
getZoom() {
return this.zoom;
}
getBounds() {
const {west, south, east, north} = this.bounds;
return {getWest: () => west, getSouth: () => south, getEast: () => east, getNorth: () => north};
}
// What a style change does: every layer and source is gone, then the new style has loaded.
changeStyle() {
this.sources = {};
this.layers = [];
this.fire('style.load');
}
}
const click = (map, lng, lat) => act(() => map.fire('click', {lngLat: {lng, lat}}));
const gridLines = map => map.getSource('quad-grid').data.features[0]?.geometry.coordinates || [];
const selectedIds = map => map.getSource('quad-selected').data.features.map(f => f.properties.id);
const BERTHOUD = quadAt(-105.0595, 40.31);
function renderPicker(map, props = {}) {
const onClose = jest.fn();
const result = renderUI(<MapQuadPicker map={map} scaleUnit="metric" onClose={onClose} {...props}/>);
return {...result, onClose};
}
describe('choosing a quadrangle to export', () => {
test('the grid is drawn over the view, above the layers of the map', () => {
const map = new FakeMap();
map.layers.push({id: 'roads'});
renderPicker(map);
expect(gridLines(map)).toHaveLength(7);
expect(map.layers.map(l => l.id))
.toEqual(['roads', 'quad-grid-lines', 'quad-selected-fill', 'quad-selected-outline']);
expect(screen.getByText('Click a quadrangle on the map to choose it.')).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Export PDF'})).toBeDisabled();
});
test('the grid follows the map', () => {
const map = new FakeMap();
renderPicker(map);
map.bounds = {west: -105.175, south: 40.26, east: -104.925, north: 40.6};
act(() => map.fire('moveend'));
expect(gridLines(map)).toHaveLength(8);
});
test('there is no grid when zoomed out, and the user is told to zoom in', () => {
const map = new FakeMap({zoom: 5});
renderPicker(map);
expect(gridLines(map)).toEqual([]);
expect(screen.getByText('Zoom in to see the quadrangles.')).toBeInTheDocument();
map.zoom = 9;
act(() => map.fire('moveend'));
expect(gridLines(map)).toHaveLength(7);
expect(screen.getByText('Click a quadrangle on the map to choose it.')).toBeInTheDocument();
});
test('a click chooses the quadrangle under it, and says what it is', () => {
const map = new FakeMap();
renderPicker(map);
click(map, -105.0595, 40.31);
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
expect(screen.getByTestId('quad-size'))
.toHaveTextContent('10.6 km × 13.9 km on the ground, 44.3 cm × 57.8 cm printed');
// Another click chooses another; there is one at a time.
click(map, -104.925, 40.4);
expect(selectedIds(map)).toEqual([quadAt(-104.925, 40.4).id]);
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°22′30″N 105°00′W');
});
test('a click on the chosen quadrangle lets go of it', () => {
const map = new FakeMap();
renderPicker(map);
click(map, -105.0595, 40.31);
click(map, -105.075, 40.3);
expect(selectedIds(map)).toEqual([]);
expect(screen.queryByTestId('quad-label')).not.toBeInTheDocument();
});
test('can start with a quadrangle already chosen', () => {
const map = new FakeMap();
renderPicker(map, {initialQuad: BERTHOUD});
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
});
test('the size is in the units of the map', () => {
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, scaleUnit: 'imperial'});
expect(screen.getByTestId('quad-size'))
.toHaveTextContent('6.6 mi × 8.6 mi on the ground, 17.4 in × 22.8 in printed');
expect(formatDistance(1609.344, 'imperial')).toBe('1.0 mi');
expect(formatSheet(254, 'metric')).toBe('25.4 cm');
});
test('the grid and the choice are put back when the style of the map changes', () => {
const map = new FakeMap();
renderPicker(map);
click(map, -105.0595, 40.31);
act(() => map.changeStyle());
expect(map.layers.map(l => l.id)).toEqual(['quad-grid-lines', 'quad-selected-fill', 'quad-selected-outline']);
expect(gridLines(map)).toHaveLength(7);
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
});
test('exports the chosen quadrangle', () => {
const onExport = jest.fn();
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
});
test('while the PDF is being made, Cancel stops it and the picker stays', () => {
const onCancel = jest.fn();
const {onClose} = renderPicker(new FakeMap(), {
initialQuad: BERTHOUD, onExport: jest.fn(), onCancel, status: 'Making the PDF (40%)…',
});
const cancel = screen.getByRole('button', {name: 'Cancel'});
expect(cancel).toBeEnabled();
fireEvent.click(cancel);
expect(onCancel).toHaveBeenCalledTimes(1);
expect(onClose).not.toHaveBeenCalled();
});
test('when nothing is being made, Cancel closes the picker', () => {
const onCancel = jest.fn();
const {onClose} = renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport: jest.fn(), onCancel});
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onCancel).not.toHaveBeenCalled();
});
test('exports the map alone when the sheet is turned off', () => {
const onExport = jest.fn();
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
const sheet = screen.getByRole('checkbox', {name: 'Margins, grid and scale bars'});
expect(sheet).toBeChecked();
fireEvent.click(sheet);
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: false, dpi: 300, name: null});
});
test('exports a sharper map when one is asked for', () => {
const onExport = jest.fn();
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
expect(screen.getByRole('radio', {name: '300 DPI'})).toBeChecked();
fireEvent.click(screen.getByRole('radio', {name: '400 DPI'}));
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 400, name: null});
});
test('the look the map is exported in is chosen, and not while a map is exported', () => {
const onLook = jest.fn();
const {unmount} = renderPicker(new FakeMap(), {initialQuad: BERTHOUD, look: 'print', onLook});
expect(screen.getByRole('radio', {name: 'Print'})).toBeChecked();
fireEvent.click(screen.getByRole('radio', {name: 'Dark'}));
expect(onLook).toHaveBeenCalledWith('dark');
unmount();
renderPicker(new FakeMap(), {
initialQuad: BERTHOUD, look: 'dark', onLook, status: 'Drawing Water (1 of 12)…',
});
expect(screen.getByRole('radio', {name: 'Dark'})).toBeChecked();
expect(screen.getByRole('radio', {name: 'Light'})).toBeDisabled();
});
test('there is no look to choose where none is given', () => {
renderPicker(new FakeMap(), {initialQuad: BERTHOUD});
expect(screen.queryByRole('radio', {name: 'Print'})).toBeNull();
});
test('says what the USGS calls the quadrangle, and exports it by that name', async () => {
const named = {name: 'Berthoud', state: 'Colorado', exact: true};
const fetchName = jest.fn().mockResolvedValue(named);
const onExport = jest.fn();
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, fetchName});
expect(await screen.findByTestId('quad-name')).toHaveTextContent('Berthoud, Colorado');
expect(fetchName).toHaveBeenCalledWith(BERTHOUD);
// Where it is, is still said.
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: named});
});
test('a quadrangle the USGS has no name for goes by where it is', async () => {
const fetchName = jest.fn().mockResolvedValue(null);
const onExport = jest.fn();
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, fetchName});
await waitFor(() => expect(fetchName).toHaveBeenCalled());
expect(screen.queryByTestId('quad-name')).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
});
test('a name which can not be asked for is no name', async () => {
const fetchName = jest.fn().mockRejectedValue(new Error('offline'));
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, fetchName});
await waitFor(() => expect(fetchName).toHaveBeenCalled());
expect(screen.queryByTestId('quad-name')).toBeNull();
expect(screen.getByTestId('quad-label')).toBeInTheDocument();
});
test('the name of one quadrangle is not shown for another', async () => {
let answer;
const fetchName = jest.fn()
.mockImplementationOnce(() => new Promise(resolve => {
answer = resolve;
}))
.mockResolvedValue({name: 'Windsor', state: 'Colorado', exact: true});
const map = new FakeMap();
renderPicker(map, {initialQuad: BERTHOUD, fetchName});
// Another quadrangle is chosen before the first is named.
act(() => map.fire('click', {lngLat: {lng: -104.925, lat: 40.4}}));
expect(await screen.findByTestId('quad-name')).toHaveTextContent('Windsor, Colorado');
await act(async () => answer({name: 'Berthoud', state: 'Colorado', exact: true}));
expect(screen.getByTestId('quad-name')).toHaveTextContent('Windsor, Colorado');
});
test('while the PDF is being made it says how far along it is, and the choice stays', () => {
const map = new FakeMap();
const onExport = jest.fn();
renderPicker(map, {initialQuad: BERTHOUD, onExport, status: 'Drawing Water (2 of 13)…'});
expect(screen.getByRole('status')).toHaveTextContent('Drawing Water (2 of 13)…');
expect(screen.getByRole('button', {name: 'Export PDF'})).toBeDisabled();
// An export which can not be stopped has no way to stop it.
expect(screen.getByRole('button', {name: 'Cancel'})).toBeDisabled();
// A click on the map does not choose another quadrangle.
click(map, -104.925, 40.4);
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
});
test('says why the PDF could not be made, and it can be tried again', () => {
const onExport = jest.fn();
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, error: 'Could not reach the server'});
expect(screen.getByRole('alert')).toHaveTextContent('Could not reach the server');
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
expect(screen.getByRole('button', {name: 'Close'})).toBeEnabled();
});
test('leaves nothing on the map when it is closed', () => {
const map = new FakeMap();
map.layers.push({id: 'roads'});
const {onClose, unmount} = renderPicker(map);
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
expect(onClose).toHaveBeenCalled();
unmount();
expect(map.layers.map(l => l.id)).toEqual(['roads']);
expect(map.sources).toEqual({});
expect(Object.values(map.handlers).flat()).toEqual([]);
});
});

View file

@ -2,7 +2,7 @@ import React, {useEffect, useState} from "react";
import {Link, useNavigate} from "react-router"; import {Link, useNavigate} from "react-router";
import {getMapSearchStatus, searchMap} from "../api"; import {getMapSearchStatus, searchMap} from "../api";
import {Card, CardGroup, Header, Loading, Panel} from "./ui"; import {Card, CardGroup, Header, Loading, Panel} from "./ui";
import {Paginator} from "./Common"; import {ErrorMessage, Paginator} from "./Common";
import {useLatestRequest, usePages} from "../hooks/customHooks"; import {useLatestRequest, usePages} from "../hooks/customHooks";
import {QueryContext} from "../contexts/contexts"; import {QueryContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars"; import {MAP_VIEWER_URI} from "./Vars";
@ -68,17 +68,25 @@ export function MapSearchView() {
const {offset, limit, activePage, setPage, totalPages, setTotal} = usePages(12); const {offset, limit, activePage, setPage, totalPages, setTotal} = usePages(12);
// useLatestRequest discards stale responses and catches errors, so rapid pagination // useLatestRequest discards stale responses and catches errors, so rapid pagination
// can't show out-of-order results and a network failure can't leave the spinner stuck. // can't show out-of-order results and a network failure can't leave the spinner stuck.
const {data, sendRequest, loading} = useLatestRequest(300); // Loading from the first render: a query of two or more characters always sends a request (below),
// so this settles, and the shorter-query branches render before the loading check.
const {data, sendRequest, loading} = useLatestRequest(300, true);
// null = unknown (pending, or the status could not be fetched), otherwise whether any map is
// installed. Only a real status may claim that no maps are installed.
const [hasMaps, setHasMaps] = useState(null); const [hasMaps, setHasMaps] = useState(null);
useEffect(() => { useEffect(() => {
let cancelled = false; let cancelled = false;
(async () => { (async () => {
try {
const status = await getMapSearchStatus(); const status = await getMapSearchStatus();
if (!cancelled) { if (!cancelled && status) {
const installed = (status.indexed || []).length + (status.missing || []).length; const installed = (status.indexed || []).length + (status.missing || []).length;
setHasMaps(installed > 0); setHasMaps(installed > 0);
} }
} catch (e) {
console.error(e);
}
})(); })();
return () => { return () => {
cancelled = true; cancelled = true;
@ -106,12 +114,22 @@ export function MapSearchView() {
</Panel>; </Panel>;
} }
if (!searchStr) {
return <Panel><Header as="h4">Enter a search query to find map locations.</Header></Panel>;
}
if (searchStr.length < 2) {
return <Panel><Header as="h4">Enter at least two characters to find map locations.</Header></Panel>;
}
if (loading) { if (loading) {
return <Panel><Loading/></Panel>; return <Panel><Loading/></Panel>;
} }
if (!searchStr) { // Settled with no data: the request failed (the api helper returns undefined on a non-OK
return <Panel><Header as="h4">Enter a search query to find map locations.</Header></Panel>; // response, and useLatestRequest leaves null when it throws).
if (data == null) {
return <Panel><ErrorMessage>Could not search the map.</ErrorMessage></Panel>;
} }
if (results.length === 0) { if (results.length === 0) {

View file

@ -0,0 +1,61 @@
import React from 'react';
import {render, screen} from '../test-utils';
import {MapSearchView} from './MapSearchView';
import {getMapSearchStatus, searchMap} from '../api';
// The map search tab says "No map locations found" only when the server searched and found none,
// and "No maps are installed" only when the server said so. A failed request is an error.
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getMapSearchStatus: jest.fn(),
searchMap: jest.fn(),
}));
const NOT_FOUND = /No map locations found/;
const NO_MAPS = /No maps are installed/;
const FAILED = /Could not search the map/;
const renderAt = (q) => render(<MapSearchView/>, {query: {searchParams: new URLSearchParams({q})}});
beforeEach(() => {
getMapSearchStatus.mockReset();
searchMap.mockReset();
getMapSearchStatus.mockResolvedValue({indexed: ['utah'], missing: []});
});
test('found nothing: says so', async () => {
searchMap.mockResolvedValue({results: [], total: 0});
renderAt('camp');
expect(await screen.findByText(NOT_FOUND)).toBeInTheDocument();
});
test('a failed search shows an error, not "No map locations found"', async () => {
searchMap.mockResolvedValue(undefined);
renderAt('camp');
expect(await screen.findByText(FAILED)).toBeInTheDocument();
expect(screen.queryByText(NOT_FOUND)).not.toBeInTheDocument();
});
test('a failed status check does not claim no maps are installed', async () => {
getMapSearchStatus.mockResolvedValue(undefined);
searchMap.mockResolvedValue({results: [], total: 0});
renderAt('camp');
expect(await screen.findByText(NOT_FOUND)).toBeInTheDocument();
expect(screen.queryByText(NO_MAPS)).not.toBeInTheDocument();
});
test('a thrown status check does not claim no maps are installed', async () => {
getMapSearchStatus.mockRejectedValue(new Error('down'));
searchMap.mockResolvedValue({results: [], total: 0});
renderAt('camp');
expect(await screen.findByText(NOT_FOUND)).toBeInTheDocument();
expect(screen.queryByText(NO_MAPS)).not.toBeInTheDocument();
});
test('the server saying no maps are installed is shown', async () => {
getMapSearchStatus.mockResolvedValue({indexed: [], missing: []});
searchMap.mockResolvedValue({results: [], total: 0});
renderAt('camp');
expect(await screen.findByText(NO_MAPS)).toBeInTheDocument();
});

View file

@ -0,0 +1,362 @@
import React from 'react';
import {act, fireEvent, screen} from '@testing-library/react';
import {Route, Routes} from 'react-router';
import {renderWithProviders as render} from '../test-utils';
import {MapRoute} from './Map';
// What the map's Pins and Manage tabs show while their lists are still loading, when the
// fetch failed, and when the server confirmed the list is empty. The empty messages invite
// the user to act ("Right-click on the map to add one"), so they may only appear for a
// confirmed empty list.
jest.mock('maplibre-gl', () => ({
__esModule: true,
default: {Map: class {
}, addProtocol: jest.fn(), Marker: class {
}},
}));
jest.mock('pmtiles', () => ({
__esModule: true, Protocol: class {
tile = jest.fn();
},
}));
jest.mock('protomaps-themes-base', () => ({__esModule: true, default: () => []}));
jest.mock('./MapViewer', () => ({__esModule: true, default: () => null}));
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getMapFiles: jest.fn(),
fetchMapSubscriptions: jest.fn(),
getMapPins: jest.fn(),
getMapTargets: jest.fn(),
getWeather: jest.fn(),
setWeatherSubscription: jest.fn(),
downloadWeatherNow: jest.fn(),
deleteMapTarget: jest.fn(),
setMapFileVisible: jest.fn(),
rebuildMapSearchIndex: jest.fn(),
}));
const api = require('../api');
const pending = () => new Promise(() => {
});
const NO_PINS = /No pins\. Right-click/;
const NO_RESULTS = /^No results$/;
const WEATHER_OFF = {enabled: false, download: null, targets: 3, spacing: 1, points: 160, seconds: 61, field: null};
// The pins page renders one table per breakpoint through `Media`, so the real media provider is
// needed; the queries below tolerate either variant being in the tree.
const renderAt = (route) => render(
<Routes><Route path='/map/*' element={<MapRoute/>}/></Routes>,
{route, withMedia: true},
);
beforeEach(() => {
jest.clearAllMocks();
// The media provider reads matchMedia; the global stub's implementation is reset between
// tests, so give it one here. Only the computer breakpoint (1024px) matches, so the
// provider reports a desktop viewport and the pins page renders its desktop table.
window.matchMedia = jest.fn().mockImplementation(query => ({
matches: query.includes('1024'), media: query, onchange: null,
addListener: jest.fn(), removeListener: jest.fn(),
addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(),
}));
api.getMapFiles.mockResolvedValue({files: []});
api.fetchMapSubscriptions.mockResolvedValue({catalog: [], subscriptions: []});
api.getMapPins.mockResolvedValue({pins: []});
api.getMapTargets.mockResolvedValue([]);
api.deleteMapTarget.mockResolvedValue(true);
api.getWeather.mockResolvedValue(WEATHER_OFF);
});
describe('the Pins tab', () => {
test('pending: shows a placeholder, not "No pins"', () => {
api.getMapPins.mockReturnValue(pending());
const {container} = renderAt('/map/pins');
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
});
test('failed: shows an error, not "No pins"', async () => {
// The api helper returns undefined on a non-OK response.
api.getMapPins.mockResolvedValue(undefined);
renderAt('/map/pins');
await act(async () => {
});
expect(screen.getByText(/Could not fetch map pins/)).toBeInTheDocument();
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
});
test('empty: shows "No pins"', async () => {
renderAt('/map/pins');
await act(async () => {
});
expect(screen.getAllByText(NO_PINS).length).toBeGreaterThan(0);
});
test('loaded: lists the pins', async () => {
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.1, lon: -111.2, label: 'Camp', color: '#f00'}]});
renderAt('/map/pins');
await act(async () => {
});
expect(screen.getAllByText('Camp').length).toBeGreaterThan(0);
expect(screen.queryAllByText(NO_PINS)).toHaveLength(0);
});
test('a pin opens the Solar calculator at its location', async () => {
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.12346, lon: -111.2, label: 'Camp', color: '#f00'}]});
renderAt('/map/pins');
await act(async () => {
});
fireEvent.click(screen.getAllByRole('button', {name: 'Solar estimate for Camp'})[0]);
expect(window.location.pathname).toBe('/more/calculators');
expect(window.location.search).toBe('?calc=solar&lat=40.1235&lon=-111.2');
});
});
describe('the Pins tab\'s nuclear targets', () => {
const {within} = require('@testing-library/react');
const targets = [
{id: 1, lat: 40.1, lon: -111.2, label: 'Base', created: '2026-11-24', weapon: 'w88', fission_fraction: 0.5},
{id: 2, lat: 41, lon: -112, label: 'Depot', created: '2026-11-24', weapon: 'custom', yield_kt: 20,
fission_fraction: 1},
];
test('are listed in their own table, apart from the pins', async () => {
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.1, lon: -111.2, label: 'Camp', color: '#f00'}]});
api.getMapTargets.mockResolvedValue(targets);
renderAt('/map/pins');
await act(async () => {
});
const tables = screen.getAllByRole('table');
expect(tables).toHaveLength(2);
const [pinsTable, table] = tables;
expect(within(pinsTable).queryByText('Base')).toBeNull();
expect(within(pinsTable).getByText('Camp')).toBeTruthy();
expect(within(table).queryByText('Camp')).toBeNull();
expect(within(table).getByText('Base')).toBeTruthy();
expect(within(table).getByText(/W88.*455 kt, half fission/)).toBeTruthy();
expect(within(table).getByText(/A yield of my own, 20 kt/)).toBeTruthy();
});
test('says when there are none, and when they could not be fetched', async () => {
const {unmount} = renderAt('/map/pins');
await act(async () => {
});
expect(screen.getAllByText(/No targets\. Turn on nuclear mode/).length).toBeGreaterThan(0);
unmount();
api.getMapTargets.mockResolvedValue(undefined);
renderAt('/map/pins');
await act(async () => {
});
expect(screen.getByText('Could not fetch the nuclear targets')).toBeTruthy();
expect(screen.queryAllByText(/No targets\./)).toHaveLength(0);
});
test('delete one, and are fetched again', async () => {
api.getMapTargets.mockResolvedValueOnce(targets).mockResolvedValueOnce(targets.slice(1));
renderAt('/map/pins');
await act(async () => {
});
fireEvent.click(screen.getAllByRole('button', {name: 'Delete Base'})[0]);
// The delete is confirmed first.
await act(async () => {
fireEvent.click(await screen.findByRole('button', {name: 'Delete'}));
});
expect(api.deleteMapTarget).toHaveBeenCalledWith(1);
expect(api.getMapTargets).toHaveBeenCalledTimes(2);
expect(screen.queryAllByText('Base')).toHaveLength(0);
});
});
describe('the Manage tab subscriptions table', () => {
test('pending: shows a placeholder, not "No results"', async () => {
api.fetchMapSubscriptions.mockReturnValue(pending());
const {container} = renderAt('/map/manage');
await act(async () => {
});
// The files table has loaded (empty); the subscriptions table is still pending.
expect(container.querySelector('.wrolpi-placeholder')).toBeInTheDocument();
expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
});
test('failed: shows an error, not "No results"', async () => {
api.fetchMapSubscriptions.mockResolvedValue(undefined);
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/Could not fetch map subscriptions/)).toBeInTheDocument();
expect(screen.queryByText(NO_RESULTS)).not.toBeInTheDocument();
});
test('empty: shows "No results"', async () => {
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(NO_RESULTS)).toBeInTheDocument();
});
// The "View All Regions" preview draws the catalog; a pending or failed catalog must not be
// previewed as zero regions.
test('pending: the regions preview is disabled', async () => {
api.fetchMapSubscriptions.mockReturnValue(pending());
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByRole('button', {name: 'View All Regions'})).toBeDisabled();
});
test('failed: the regions preview is disabled', async () => {
api.fetchMapSubscriptions.mockResolvedValue(undefined);
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByRole('button', {name: 'View All Regions'})).toBeDisabled();
});
test('loaded: the regions preview is enabled', async () => {
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByRole('button', {name: 'View All Regions'})).toBeEnabled();
});
});
describe('the Manage tab files table', () => {
const mapFile = (map_path, kind, extra = {}) => ({
name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, kind,
size: 1024, visible: true, has_search_index: false, title: null, ...extra,
});
const FILES = [
mapFile('us-west.pmtiles', 'basemap', {title: 'Protomaps Basemap'}),
mapFile('extras/features.pmtiles', 'overlay', {title: 'Topographic Features'}),
mapFile('terrain-planet.pmtiles', 'terrain'),
mapFile('broken.pmtiles', 'unknown'),
];
const rowOf = (text) => screen.getByText(text).closest('tr');
const cellsOf = (text) => [...rowOf(text).querySelectorAll('td')].map(td => td.textContent);
const renderFiles = async (files = FILES) => {
api.getMapFiles.mockResolvedValue({files});
renderAt('/map/manage');
await act(async () => {
});
};
test('a file is listed with its directory, its own name, and how the map draws it', async () => {
await renderFiles();
expect(cellsOf('extras/features.pmtiles').slice(0, 2))
.toEqual(['extras/features.pmtilesTopographic Features', 'Overlay']);
expect(cellsOf('us-west.pmtiles')[1]).toBe('Basemap');
expect(cellsOf('terrain-planet.pmtiles')[1]).toBe('Terrain');
expect(cellsOf('broken.pmtiles')[1]).toBe('Unreadable');
});
test('only a basemap offers a search index', async () => {
await renderFiles();
const builds = screen.getAllByRole('button', {name: 'Build'});
expect(builds).toHaveLength(1);
expect(rowOf('us-west.pmtiles')).toContainElement(builds[0]);
});
test('the search index of a file in a sub-directory is built by its path', async () => {
await renderFiles([mapFile('regions/oregon.pmtiles', 'basemap')]);
await act(async () => {
fireEvent.click(screen.getByRole('button', {name: 'Build'}));
});
expect(api.rebuildMapSearchIndex).toHaveBeenCalledWith('regions/oregon.pmtiles');
});
test('a file is ignored with its toggle, and the list is fetched again', async () => {
await renderFiles();
const toggle = screen.getByRole('switch', {name: 'Show extras/features.pmtiles on the map'});
expect(toggle).toBeChecked();
api.getMapFiles.mockResolvedValue({
files: FILES.map(f => f.kind === 'overlay' ? {...f, visible: false} : f),
});
const before = api.getMapFiles.mock.calls.length;
await act(async () => {
fireEvent.click(toggle);
});
expect(api.setMapFileVisible).toHaveBeenCalledWith('extras/features.pmtiles', false);
expect(api.getMapFiles.mock.calls.length).toBe(before + 1);
// Only the ignored file's toggle is off.
expect(screen.getByRole('switch', {name: 'Show extras/features.pmtiles on the map'})).not.toBeChecked();
expect(screen.getByRole('switch', {name: 'Show us-west.pmtiles on the map'})).toBeChecked();
});
test('an ignored file is shown again with its toggle', async () => {
await renderFiles([mapFile('satellite.pmtiles', 'overlay', {visible: false})]);
const toggle = screen.getByRole('switch', {name: 'Show satellite.pmtiles on the map'});
expect(toggle).not.toBeChecked();
await act(async () => {
fireEvent.click(toggle);
});
expect(api.setMapFileVisible).toHaveBeenCalledWith('satellite.pmtiles', true);
});
});
describe('the Manage tab\'s weather', () => {
const hour = 3600000;
const field = (fromHours, toHours) => ({
fetched_at: new Date().toISOString(), spacing: 1, points: 160, size: 5 * 1024 * 1024,
first_hour: new Date(Date.now() + fromHours * hour).toISOString(),
last_hour: new Date(Date.now() + toHours * hour).toISOString(),
});
test('is turned on with its toggle, and says what it downloads', async () => {
api.setWeatherSubscription.mockResolvedValue({...WEATHER_OFF, enabled: true,
download: {status: 'new', next_download: null, last_successful_download: null}});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText('Weather')).toBeInTheDocument();
expect(screen.getByText(/Around 3 targets: 160 places every 1°, which takes about 2 minutes/)).toBeInTheDocument();
expect(screen.getByText('No forecast has been downloaded.')).toBeInTheDocument();
expect(screen.queryByRole('button', {name: 'Download now'})).toBeNull();
await act(async () => {
fireEvent.click(screen.getByRole('switch', {name: /Download the weather forecast from Open-Meteo/}));
});
expect(api.setWeatherSubscription).toHaveBeenCalledWith(true);
expect(screen.getByText('Downloading the forecast…')).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Download now'})).toBeDisabled();
});
test('shows the forecast kept, and whether it is recent enough for bursts now', async () => {
const done = {status: 'complete', last_successful_download: new Date().toISOString(),
next_download: new Date(Date.now() + 24 * hour).toISOString()};
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true, download: done, field: field(-5, 90)});
api.downloadWeatherNow.mockResolvedValue({...WEATHER_OFF, enabled: true, download: {...done, status: 'new'}});
const {unmount} = renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/Forecast kept: .* 160 places every 1°, 5.0 MB/)).toBeInTheDocument();
expect(screen.getByText(/It has the winds for bursts now/)).toBeInTheDocument();
expect(screen.getByText(/Last downloaded .*\. Next /)).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole('button', {name: 'Download now'}));
});
expect(api.downloadWeatherNow).toHaveBeenCalled();
unmount();
// Ending a day from now: too old for bursts now.
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true,
download: {status: 'failed', error: 'The forecast service answered HTTP 500'}, field: field(-60, 24)});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/It is too old for bursts now/)).toBeInTheDocument();
expect(screen.getByText(/The last download failed: The forecast service answered HTTP 500/)).toBeInTheDocument();
});
test('says when there are no targets to download around', async () => {
api.getWeather.mockResolvedValue({...WEATHER_OFF, targets: 0, spacing: null, points: null});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/No nuclear targets are saved/)).toBeInTheDocument();
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,45 @@
import React from 'react';
import {renderWithProviders as render} from '../test-utils';
import MapViewer from './MapViewer';
// MapLibre needs WebGL, which jsdom lacks; these tests only cover what the viewer does to the URL.
jest.mock('maplibre-gl', () => ({
__esModule: true,
default: {Map: class {
}, addProtocol: jest.fn(), Marker: class {
}, Popup: class {
}},
}));
jest.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
jest.mock('pmtiles', () => ({
__esModule: true, Protocol: class {
tile = jest.fn();
},
}));
jest.mock('protomaps-themes-base', () => ({__esModule: true, default: () => []}));
jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({__esModule: true, default: {}}));
jest.mock('../api', () => ({
...jest.requireActual('../api'),
// Never resolves: the map never initializes, which these tests do not need.
getMapFiles: jest.fn(() => new Promise(() => {
})),
getMapPins: jest.fn(() => new Promise(() => {
})),
}));
describe('the map position in the URL', () => {
test('is removed when the map closes', () => {
const {unmount} = render(<MapViewer/>, {route: '/map?lat=40&lon=-105&z=8&layer=a'});
unmount();
expect(window.location.pathname).toBe('/map');
expect(window.location.search).toBe('?layer=a');
});
test('is not removed from the page the map navigated to', () => {
// "Calculate Solar Performance" navigates to a page whose own lat/lon must survive the map closing.
const {unmount} = render(<MapViewer/>, {route: '/map?lat=40&lon=-105&z=8'});
window.history.pushState({}, '', '/more/calculators?calc=solar&lat=40.0154&lon=-105.2705');
unmount();
expect(window.location.search).toBe('?calc=solar&lat=40.0154&lon=-105.2705');
});
});

View file

@ -0,0 +1,491 @@
import React from 'react';
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
import {renderWithProviders as render} from '../test-utils';
import MapViewer from './MapViewer';
import {STORAGE_KEY_OVERLAYS} from './mapOverlays';
// How the viewer draws the map files it is given: which become the basemap, which are offered as
// overlays in the layer control, and what the control's checkboxes do to the map's layers.
/*
* MapLibre needs WebGL, which jsdom lacks, so it is mocked down to the surface MapViewer uses.
* A constructed map keeps the style it was given, and the visibility of each of its layers as
* `setLayoutProperty` changes it -- the two things these tests read.
*/
const constructed = [];
jest.mock('maplibre-gl', () => {
class FakeMap {
constructor(options) {
this.options = options;
this.style = options.style;
this.center = {lat: 0, lng: 0};
this.moves = [];
this.listeners = [];
this.controls = [];
constructed.push(this);
}
on(event, callback) {
// MapLibre fires `load` asynchronously once the style resolves.
if (event === 'load') setTimeout(() => callback(), 0);
return this;
}
once(event, callback) {
this.listeners.push({event, callback});
return this;
}
off(event, callback) {
this.listeners = this.listeners.filter(i => i.event !== event || i.callback !== callback);
return this;
}
getStyle() {
return this.style;
}
setStyle(style) {
this.style = style;
// MapLibre puts a style which only differs from the one it has in place, and says so,
// before this returns.
const waiting = this.listeners.filter(i => i.event === 'style.load');
this.listeners = this.listeners.filter(i => i.event !== 'style.load');
waiting.forEach(i => i.callback());
}
getLayer(id) {
return this.style.layers.find(l => l.id === id);
}
setLayoutProperty(id, name, value) {
const layer = this.getLayer(id);
layer.layout = {...layer.layout, [name]: value};
}
visibility(id) {
return this.getLayer(id)?.layout?.visibility ?? 'visible';
}
getCanvas() {
return global.document.createElement('canvas');
}
getCenter() {
return this.center;
}
getZoom() {
return 2;
}
setCenter(center) {
this.moves.push(center);
this.center = center;
}
setZoom() {
}
addControl(control) {
// A control of the viewer's own (not one of MapLibre's) is put on the page.
if (typeof control?.onAdd === 'function') {
this.controls.push(global.document.body.appendChild(control.onAdd(this)));
}
return this;
}
removeControl() {
}
remove() {
this.controls.forEach(control => control.remove());
}
}
class Control {
}
return {
__esModule: true,
default: {
Map: FakeMap, addProtocol: jest.fn(), Marker: Control, Popup: Control,
NavigationControl: Control, FullscreenControl: Control, ScaleControl: Control,
GeolocateControl: Control,
},
};
});
jest.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
jest.mock('pmtiles', () => ({
__esModule: true, Protocol: class {
tile = jest.fn();
},
}));
// The basemap theme: a layer of each kind the tests care about, for whichever source asks.
jest.mock('protomaps-themes-base', () => ({
__esModule: true,
default: (source) => [
{id: 'earth', type: 'fill', source},
{id: 'water', type: 'fill', source},
{id: 'places_locality', type: 'symbol', source},
],
// The printed map: the same layers, in colors of its own.
namedTheme: () => ({}),
layersWithCustomTheme: (source) => [
{id: 'earth', type: 'fill', source, paint: {'fill-color': 'print'}},
{id: 'water', type: 'fill', source},
{id: 'places_locality', type: 'symbol', source},
],
}));
// Choosing a quadrangle draws on the map, which is not what is looked at here.
jest.mock('./MapQuadPicker', () => ({onClose}) => <button onClick={onClose}>Close the picker</button>);
// Contours are generated in the browser from the terrain file; only the URL of that source matters here.
jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({
__esModule: true,
default: {
DemSource: class {
setupMaplibre() {
}
contourProtocolUrl() {
return 'dem-contour://{z}/{x}/{y}';
}
},
},
}));
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getMapFiles: jest.fn(),
getMapPins: jest.fn(),
}));
const api = require('../api');
const mapFile = (map_path, kind, extra = {}) => ({
name: map_path.split('/').pop(), map_path, path: `map/${map_path}`, kind,
tile_type: 'mvt', size: 1024, visible: true, vector_layers: [], ...extra,
});
const layer = (id, geometry) => ({id, geometry, minzoom: 0, maxzoom: 8, description: null});
const PLANET = mapFile('20260329.pmtiles', 'basemap', {size: 134e9});
const REGION = mapFile('regions/oregon.pmtiles', 'basemap');
// An overlay with a layer named like one of the basemap's.
const FEATURES = mapFile('extras/features.pmtiles', 'overlay', {
title: 'Topographic Features', description: 'Topographic features', min_zoom: 0, max_zoom: 8,
vector_layers: [layer('water', 'Polygon'), layer('power_lines', 'LineString'), layer('towers', 'Point')],
});
const SATELLITE = mapFile('satellite.pmtiles', 'overlay', {tile_type: 'jpeg'});
const WATER = 'overlay:extras/features.pmtiles:water:fill';
const POWER_LINES = 'overlay:extras/features.pmtiles:power_lines:line';
const TOWERS = 'overlay:extras/features.pmtiles:towers:circle';
const RASTER = 'overlay:satellite.pmtiles:raster';
/** Render the viewer with these map files, and open its layer control. Returns the map. */
const renderViewer = async (files) => {
api.getMapFiles.mockResolvedValue({files});
render(<MapViewer/>, {route: '/map'});
await waitFor(() => expect(constructed).toHaveLength(1));
// The layer control appears once the map has loaded; it starts collapsed.
fireEvent.click(await screen.findByTitle('Layers'));
return constructed[0];
};
const click = async (element) => {
await act(async () => {
fireEvent.click(element);
});
};
beforeEach(() => {
constructed.length = 0;
localStorage.clear();
jest.clearAllMocks();
api.getMapPins.mockResolvedValue({pins: []});
// The layer control asks whether this is a narrow screen; the global stub's implementation is
// reset between tests.
window.matchMedia = jest.fn().mockImplementation(query => ({
matches: false, media: query, onchange: null,
addListener: jest.fn(), removeListener: jest.fn(),
addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(),
}));
// The overview blob is only asked for when there is no planet file.
global.fetch = jest.fn().mockResolvedValue({ok: true});
});
describe('which files the viewer draws', () => {
test('a planet file is the basemap, and an overlay is drawn with it', async () => {
const map = await renderViewer([PLANET, REGION, FEATURES]);
expect(Object.keys(map.style.sources)).toEqual(['20260329.pmtiles', 'overlay:extras/features.pmtiles']);
// The overlay is drawn as itself, not with the basemap theme.
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
.toEqual([WATER, POWER_LINES, TOWERS]);
});
test('files are fetched from where they are, sub-directories included', async () => {
const map = await renderViewer([REGION, FEATURES]);
expect(map.style.sources['regions/oregon.pmtiles'].url).toBe('pmtiles:///media/map/regions/oregon.pmtiles');
expect(map.style.sources['overlay:extras/features.pmtiles'].url)
.toBe('pmtiles:///media/map/extras/features.pmtiles');
});
test('an ignored file is neither drawn nor offered', async () => {
const map = await renderViewer([{...PLANET, visible: false}, REGION, {...FEATURES, visible: false}, SATELLITE]);
// Without the planet file the regional basemap (over the overview) is drawn.
expect(Object.keys(map.style.sources))
.toEqual(['map-overview', 'regions/oregon.pmtiles', 'overlay:satellite.pmtiles']);
expect(screen.queryByLabelText('Topographic Features')).not.toBeInTheDocument();
expect(screen.getByLabelText('satellite')).toBeInTheDocument();
});
test('no overlays, no Overlays section', async () => {
await renderViewer([PLANET]);
expect(screen.queryByText('Overlays')).not.toBeInTheDocument();
});
});
describe('an overlay in the layer control', () => {
test('is named by the file, and starts hidden', async () => {
const map = await renderViewer([PLANET, FEATURES, SATELLITE]);
expect(screen.getByText('Overlays')).toBeInTheDocument();
expect(screen.getByLabelText('Topographic Features')).not.toBeChecked();
expect(screen.getByLabelText('satellite')).not.toBeChecked();
expect([WATER, POWER_LINES, TOWERS, RASTER].map(id => map.visibility(id)))
.toEqual(['none', 'none', 'none', 'none']);
});
test('is drawn when it is turned on, and that is remembered', async () => {
const map = await renderViewer([PLANET, FEATURES, SATELLITE]);
await click(screen.getByLabelText('Topographic Features'));
// The basemap draws water already, so the file's own is left off.
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'visible', 'visible']);
// The other overlay is untouched.
expect(map.visibility(RASTER)).toBe('none');
expect(JSON.parse(localStorage.getItem(STORAGE_KEY_OVERLAYS)))
.toEqual({'extras/features.pmtiles': {enabled: true}});
await click(screen.getByLabelText('Topographic Features'));
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none', 'none']);
});
test('is drawn from the start when it was turned on before', async () => {
localStorage.setItem(STORAGE_KEY_OVERLAYS, JSON.stringify({
'extras/features.pmtiles': {enabled: true, layers: {towers: false}},
}));
const map = await renderViewer([PLANET, FEATURES]);
expect(screen.getByLabelText('Topographic Features')).toBeChecked();
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'visible', 'none']);
});
test('each layer of a vector file has its own checkbox', async () => {
const map = await renderViewer([PLANET, FEATURES]);
await click(screen.getByLabelText('Topographic Features'));
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
// A layer of something the basemap draws starts unchecked, and can be checked.
expect(screen.getByLabelText('water')).not.toBeChecked();
expect(screen.getByLabelText('power_lines')).toBeChecked();
await click(screen.getByLabelText('water'));
expect(screen.getByLabelText('water')).toBeChecked();
await click(screen.getByLabelText('towers'));
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'none']);
await click(screen.getByText('None'));
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none', 'none']);
expect(screen.getByLabelText('power_lines')).not.toBeChecked();
await click(screen.getByText('All'));
expect([WATER, POWER_LINES, TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible', 'visible']);
});
test('a raster file has no layers to choose from', async () => {
const map = await renderViewer([PLANET, SATELLITE]);
expect(screen.queryByRole('button', {name: /layers of satellite/})).not.toBeInTheDocument();
await click(screen.getByLabelText('satellite'));
expect(map.visibility(RASTER)).toBe('visible');
});
});
describe('the basemap layer groups', () => {
test("do not show or hide an overlay's layer of the same name", async () => {
const map = await renderViewer([PLANET, FEATURES]);
await click(screen.getByLabelText('Topographic Features'));
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
await click(screen.getByLabelText('water'));
expect(map.visibility('water')).toBe('visible');
expect(map.visibility(WATER)).toBe('visible');
// Hide the basemap's water: the overlay's `water` layer stays.
await click(screen.getByLabelText('Water'));
expect(map.visibility('water')).toBe('none');
expect(map.visibility(WATER)).toBe('visible');
// Hide the overlay, then show the basemap's water: the overlay's stays hidden.
await click(screen.getByLabelText('Topographic Features'));
await click(screen.getByLabelText('Water'));
expect(map.visibility('water')).toBe('visible');
expect(map.visibility(WATER)).toBe('none');
});
});
describe('an overlay with a style beside it', () => {
const STYLED = {...FEATURES, style_path: 'map/extras/style.json'};
const STYLE = {
version: 8,
sources: {features: {type: 'vector', url: 'https://example.com/features.json'}},
layers: [
{id: 'background', type: 'background'},
{id: 'lines', type: 'line', source: 'features', 'source-layer': 'power_lines'},
{
id: 'towers', type: 'symbol', source: 'features', 'source-layer': 'towers',
layout: {'icon-image': 'tower', 'text-field': ['get', 'name'], 'text-font': ['Roboto Bold']},
},
],
};
const STYLED_LINES = 'overlay:extras/features.pmtiles:power_lines:lines';
const STYLED_TOWERS = 'overlay:extras/features.pmtiles:towers:towers';
// The style is fetched from the media directory; the overview blob is asked for with HEAD.
const serveStyle = (style) => {
global.fetch = jest.fn(async (url) => {
if (String(url).endsWith('style.json')) {
if (!style) return {ok: false};
return {ok: true, json: async () => style};
}
return {ok: true};
});
};
test("is drawn with that style and the map's own icons", async () => {
serveStyle(STYLE);
const map = await renderViewer([PLANET, STYLED]);
expect(global.fetch).toHaveBeenCalledWith('/media/map/extras/style.json');
const overlayLayers = map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles');
expect(overlayLayers.map(l => l.id)).toEqual([STYLED_LINES, STYLED_TOWERS]);
expect(map.getLayer(STYLED_TOWERS).layout['icon-image']).toBe('overlay-icons:tower');
expect(map.getLayer(STYLED_TOWERS).layout['text-font']).toEqual(['Noto Sans Medium']);
// The basemap keeps its sprite; the overlay icons are beside it.
expect(map.style.sprite).toEqual([
{id: 'default', url: `${window.location.origin}/map-assets/sprites/light`},
{id: 'overlay-icons', url: `${window.location.origin}/map-assets/sprites/overlay-icons`},
]);
// Nothing of the style's own sources reaches the map.
expect(JSON.stringify(map.style)).not.toContain('example.com');
});
test('starts hidden, and offers only the layers its style draws', async () => {
serveStyle(STYLE);
const map = await renderViewer([PLANET, STYLED]);
expect([STYLED_LINES, STYLED_TOWERS].map(id => map.visibility(id))).toEqual(['none', 'none']);
await click(screen.getByLabelText('Topographic Features'));
expect([STYLED_LINES, STYLED_TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'visible']);
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
// The style has no layer for the file's `water`.
expect(screen.queryByLabelText('water')).not.toBeInTheDocument();
await click(screen.getByLabelText('towers'));
expect([STYLED_LINES, STYLED_TOWERS].map(id => map.visibility(id))).toEqual(['visible', 'none']);
});
test('says how many layers of the style could not be used', async () => {
serveStyle({
...STYLE,
layers: [...STYLE.layers, {id: 'bad', type: 'line', source: 'features', 'source-layer': 'water', paint: {'line-width': 'wide'}}],
});
const map = await renderViewer([PLANET, STYLED]);
await click(screen.getByRole('button', {name: 'Show layers of Topographic Features'}));
expect(screen.getByText('1 style layer skipped')).toBeInTheDocument();
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
.toEqual([STYLED_LINES, STYLED_TOWERS]);
});
test('is drawn generically when the style cannot be fetched', async () => {
serveStyle(null);
const map = await renderViewer([PLANET, STYLED]);
expect(map.style.layers.filter(l => l.source === 'overlay:extras/features.pmtiles').map(l => l.id))
.toEqual([WATER, POWER_LINES, TOWERS]);
// The overlay icons are only asked for when a style names them.
expect(map.style.sprite).toBe(`${window.location.origin}/map-assets/sprites/light`);
});
});
describe('the text of the map', () => {
// The fonts the map has glyphs for (modules/map/static/fonts).
const FONTS = ['Noto Sans Regular', 'Noto Sans Medium', 'Noto Sans Italic'];
const TERRAIN = mapFile('terrain-planet.pmtiles', 'terrain', {tile_type: 'webp'});
test('contour labels are drawn in a font the map has', async () => {
const map = await renderViewer([PLANET, TERRAIN]);
const labels = map.getLayer('contour-labels');
expect(labels.layout['text-field']).toBeDefined();
// Without a font MapLibre asks for its default, which the map does not have.
expect(labels.layout['text-font']).toBeDefined();
expect(FONTS).toEqual(expect.arrayContaining(labels.layout['text-font']));
});
test('every layer with text names a font the map has', async () => {
const map = await renderViewer([PLANET, TERRAIN, FEATURES]);
const textLayers = map.style.layers.filter(l => l.layout?.['text-field'] !== undefined);
expect(textLayers.map(l => l.id)).toContain('contour-labels');
for (const textLayer of textLayers) {
expect([textLayer.id, textLayer.layout['text-font']]).toEqual([textLayer.id, expect.any(Array)]);
expect(FONTS).toEqual(expect.arrayContaining(textLayer.layout['text-font']));
}
});
});
describe('the look the map is exported in', () => {
const earthColor = map => map.getLayer('earth').paint?.['fill-color'];
test('is how the map is shown while a quadrangle is chosen, where it is and with what is off still off', async () => {
const map = await renderViewer([PLANET]);
await click(screen.getByLabelText('Water'));
expect(map.visibility('water')).toBe('none');
// The map has been moved since it was made.
map.center = {lat: 40.3, lng: -105.06};
await click(screen.getByTitle('Export a 1:24,000 map'));
expect(earthColor(map)).toBe('print');
expect(map.visibility('water')).toBe('none');
// Moved again, while the quadrangle is chosen.
map.center = {lat: 61.2, lng: -149.9};
await click(screen.getByText('Close the picker'));
expect(earthColor(map)).toBeUndefined();
expect(map.visibility('water')).toBe('none');
// Changing the look never moves the map.
expect(map.moves).toEqual([]);
expect(map.center).toEqual({lat: 61.2, lng: -149.9});
});
test('has colors which are chosen where its layers are, while a quadrangle is chosen', async () => {
const map = await renderViewer([PLANET]);
// The map on the screen has no colors to choose.
expect(screen.queryByLabelText('Water: color when printed')).not.toBeInTheDocument();
await click(screen.getByTitle('Export a 1:24,000 map'));
const water = screen.getByLabelText('Water: color when printed');
expect(water).toHaveValue('#a9d4f2');
expect(screen.queryByText('Reset colors')).not.toBeInTheDocument();
await act(async () => {
fireEvent.change(water, {target: {value: '#ff00ff'}});
});
expect(screen.getByLabelText('Water: color when printed')).toHaveValue('#ff00ff');
expect(JSON.parse(localStorage.getItem('wrolpi-map-print-colors'))).toEqual({water: '#ff00ff'});
// The map was drawn again, where it was.
expect(earthColor(map)).toBe('print');
expect(map.moves).toEqual([]);
await click(screen.getByText('Reset colors'));
expect(screen.getByLabelText('Water: color when printed')).toHaveValue('#a9d4f2');
expect(localStorage.getItem('wrolpi-map-print-colors')).toBeNull();
await click(screen.getByText('Close the picker'));
expect(screen.queryByLabelText('Water: color when printed')).not.toBeInTheDocument();
});
});

View file

@ -0,0 +1,112 @@
import React, {useCallback, useEffect, useState} from "react";
import {downloadWeatherNow, getWeather, setWeatherSubscription} from "../api";
import {ErrorMessage, humanFileSize} from "./Common";
import {Button, Header, Toggle} from "./ui";
import {LANDING_HOURS} from "../map-shared/fallout/winds.js";
// The weather subscription: a forecast of the winds aloft around the saved nuclear targets,
// downloaded every day (a recurring Download), for the fallout simulator.
// How often (ms) the subscription is asked again while it downloads.
const REFRESH_MS = 10000;
// Whether a download of the weather is waiting or running.
export const weatherDownloading = (weather) => ['new', 'pending'].includes(weather?.download?.status);
// The weather subscription, asked again while it downloads: {weather (null while pending, undefined
// when it could not be fetched), downloading, setEnabled(enabled), downloadNow()}.
export function useWeather() {
const [weather, setWeather] = useState(null);
const refresh = useCallback(async () => setWeather(await getWeather()), []);
useEffect(() => {
refresh();
}, [refresh]);
const downloading = weatherDownloading(weather);
useEffect(() => {
if (!downloading) return;
const timer = setInterval(refresh, REFRESH_MS);
return () => clearInterval(timer);
}, [downloading, refresh]);
const setEnabled = async (enabled) => {
const changed = await setWeatherSubscription(enabled);
if (changed) setWeather(changed);
};
const downloadNow = async () => {
const changed = await downloadWeatherNow();
if (changed) setWeather(changed);
};
return {weather, downloading, setEnabled, downloadNow};
}
// Whether the forecast kept (`field`, as the subscription tells it) has the winds for bursts now,
// until all their fallout is down.
export function fieldCoversNow(field, when = new Date()) {
if (!field) return false;
const first = Date.parse(field.first_hour), last = Date.parse(field.last_hour);
return first <= when.getTime() + 3600000 && last >= when.getTime() + LANDING_HOURS * 3600000;
}
// About how long a download takes, as the user reads it.
export const downloadTime = (seconds) => !seconds || seconds < 60 ? "about a minute"
: `about ${Math.round(seconds / 60) + 1} minutes`;
const when = (time) => time ? new Date(time).toLocaleString(undefined, {
weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
}) : null;
// The Manage tab's section for the weather subscription: turning it on or off, what it downloads,
// how its downloads have gone, and the forecast kept.
export function WeatherSection() {
const {weather, downloading, setEnabled, downloadNow} = useWeather();
const muted = {color: "var(--muted)", fontSize: "0.875rem"};
const warning = {color: "var(--warning)", fontSize: "0.875rem"};
const header = <Header as='h3'>Weather</Header>;
if (weather === undefined) return <>{header}<ErrorMessage>Could not fetch the weather subscription</ErrorMessage></>;
if (!weather) return header;
const {download, field} = weather;
const failed = download && ['failed', 'deferred'].includes(download.status) && download.error;
return <>
{header}
<Toggle label="Download the weather forecast from Open-Meteo every day" checked={weather.enabled}
onChange={(e) => setEnabled(e.currentTarget.checked)}/>
<div style={muted}>
The winds aloft, hour by hour for four days, around the saved nuclear targets: the fallout simulator
carries fallout by them. Open-Meteo is told only places on whole degrees, never a target.
</div>
{weather.targets === 0
? <div style={warning}>
No nuclear targets are saved, so there is nowhere to download the forecast around. Save some in
nuclear mode (☢) on the map.
</div>
: <div style={muted}>
Around {weather.targets === 1 ? "1 target" : `${weather.targets} targets`}: {weather.points} places
every {weather.spacing}°, which takes {downloadTime(weather.seconds)} to download.
</div>}
{weather.enabled && <div style={{marginTop: "0.5rem"}}>
{downloading && <div>Downloading the forecast…</div>}
{download?.last_successful_download && <div style={muted}>
Last downloaded {when(download.last_successful_download)}.
{download.next_download && !downloading && ` Next ${when(download.next_download)}.`}
</div>}
{failed && <div style={warning}>The last download failed: {download.error}</div>}
<Button size='xs' style={{marginTop: "0.25rem"}} disabled={downloading || weather.targets === 0}
onClick={downloadNow}>Download now</Button>
</div>}
<div style={{marginTop: "0.5rem"}}>
{field
? <>
<div>
Forecast kept: {when(field.first_hour)} to {when(field.last_hour)}, {field.points} places
every {field.spacing}°, {humanFileSize(field.size)}.
</div>
{fieldCoversNow(field)
? <div style={muted}>It has the winds for bursts now, until their fallout is down.</div>
: <div style={warning}>
It is too old for bursts now: their fallout comes down over {LANDING_HOURS} hours, past
its end. {weather.enabled ? "Download it again." : "Turn on the download to get a new one."}
</div>}
</>
: <div style={muted}>No forecast has been downloaded.</div>}
</div>
</>;
}

View file

@ -0,0 +1,170 @@
import React from "react";
import MarkdownIt from "markdown-it";
import DOMPurify from "dompurify";
import {useLocalStorage} from "./Common";
import {Button, ButtonGroup, Loading, Message} from "./ui";
/*
* Raw HTML in the file is escaped, not parsed: markdown files arrive with downloads, and the preview
* renders on the API's origin. `validateLink` (on by default) refuses javascript:, vbscript:, file:,
* and non-image data: URLs. DOMPurify runs anyway, so neither guard is the only one.
*/
const markdown = new MarkdownIt({html: false, linkify: true});
// A URL with a scheme (https:, mailto:, ...) points somewhere other than the media directory.
const URL_WITH_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
/**
* Resolve a URL written in a markdown file against the file's own media URL, the way a browser
* would resolve it against a document in that directory.
*
* Returns the URL unchanged if it is not relative, or null if it climbs out of the media directory;
* only media is served relative to a file.
*/
function resolveRelativeURL(url, fileURL) {
if (!url || URL_WITH_SCHEME.test(url) || url.startsWith('/') || url.startsWith('#')) {
return url;
}
const resolved = new URL(url, new URL(fileURL, window.location.origin));
if (!resolved.pathname.startsWith('/media/')) {
return null;
}
return resolved.pathname + resolved.search + resolved.hash;
}
function rewriteURL(token, attr, fileURL) {
const url = token.attrGet(attr);
if (url === null) {
return;
}
const resolved = resolveRelativeURL(url, fileURL);
if (resolved === null) {
token.attrs = token.attrs.filter(([name]) => name !== attr);
} else {
token.attrSet(attr, resolved);
}
}
function openInNewTab(token) {
const href = token.attrGet('href');
// Following a link would close the preview; a fragment stays within the document.
if (href && !href.startsWith('#')) {
token.attrSet('target', '_blank');
token.attrSet('rel', 'noopener noreferrer');
}
}
/** An image the preview may load: one served by this WROLPi, or embedded in the file. */
function isLocalImage(src) {
return !src || src.startsWith('data:') || (src.startsWith('/') && !src.startsWith('//'));
}
/**
* Replace an image from another site with a link to it. Loading it would tell that site who is
* reading the file and when (a tracking pixel), so the reader chooses whether to follow it.
*
* Inside a link (a README badge) the image becomes the outer link's text; links cannot nest.
*/
function replaceRemoteImage(state, image, insideLink) {
const src = image.attrGet('src');
const text = new state.Token('text', '', 0);
text.content = image.content || src;
if (insideLink) {
return [text];
}
const linkOpen = new state.Token('link_open', 'a', 1);
linkOpen.attrSet('href', src);
openInNewTab(linkOpen);
return [linkOpen, text, new state.Token('link_close', 'a', -1)];
}
markdown.core.ruler.push('wrolpi_media_urls', (state) => {
const {fileURL} = state.env;
for (const token of state.tokens) {
if (!token.children) {
continue;
}
let insideLink = false;
token.children = token.children.flatMap(child => {
if (child.type === 'image') {
rewriteURL(child, 'src', fileURL);
return isLocalImage(child.attrGet('src')) ? [child] : replaceRemoteImage(state, child, insideLink);
} else if (child.type === 'link_open') {
insideLink = true;
rewriteURL(child, 'href', fileURL);
openInNewTab(child);
} else if (child.type === 'link_close') {
insideLink = false;
}
return [child];
});
}
});
/** Render markdown to sanitized HTML. Relative URLs resolve against `fileURL`, the file's /media/ URL. */
export function renderMarkdown(text, fileURL) {
const html = markdown.render(text, {fileURL});
return DOMPurify.sanitize(html, {ADD_ATTR: ['target']});
}
export function isMarkdownFile(mimetype, lowerPath) {
// By suffix too, so a markdown file whose stored type is still text/plain (or a language libmagic
// guessed) is not shown raw; the 2026_10_05_1200 migration retags those rows, a refresh does not.
return mimetype.startsWith('text/markdown')
|| (mimetype.startsWith('text/') && (lowerPath.endsWith('.md') || lowerPath.endsWith('.markdown')));
}
/** Preview a markdown file, formatted or as its raw source. */
export function MarkdownPreview({url}) {
const [formatted, setFormatted] = useLocalStorage('markdownPreviewFormatted', true);
const [text, setText] = React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const controller = new AbortController();
setText(null);
setError(null);
fetch(url, {signal: controller.signal})
.then(response => {
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
return response.text();
})
.then(setText)
.catch(e => {
if (e.name !== 'AbortError') {
console.error(e);
setError(e.message);
}
});
return () => controller.abort();
}, [url]);
const html = React.useMemo(() => text === null ? null : renderMarkdown(text, url), [text, url]);
let body;
if (error) {
body = <Message kind='error' title='Could not load file'>{error}</Message>;
} else if (text === null) {
body = <Loading/>;
} else if (formatted) {
body = <div className='markdown-body' dangerouslySetInnerHTML={{__html: html}}/>;
} else {
body = <pre className='markdown-raw' data-testid='markdown-raw'>{text}</pre>;
}
return <>
<ButtonGroup>
<Button size='small' variant={formatted ? 'filled' : 'default'} onClick={() => setFormatted(true)}>
Formatted
</Button>
<Button size='small' variant={formatted ? 'default' : 'filled'} onClick={() => setFormatted(false)}>
Raw
</Button>
</ButtonGroup>
<div className='markdown-preview'>
{body}
</div>
</>
}

View file

@ -0,0 +1,198 @@
import React from 'react';
import {fireEvent, screen, waitFor} from '@testing-library/react';
import {isMarkdownFile, MarkdownPreview, renderMarkdown} from './MarkdownPreview';
import {renderUI} from '../test-utils';
const FILE_URL = '/media/notes/water/storage.md';
/** Render markdown into a detached element so assertions read the DOM, not the HTML string. */
const renderToDOM = (text, fileURL = FILE_URL) => {
const div = document.createElement('div');
div.innerHTML = renderMarkdown(text, fileURL);
return div;
};
describe('renderMarkdown', () => {
test('formats headings, emphasis, lists, code, and tables', () => {
const div = renderToDOM([
'# Water',
'',
'Rotate *every* barrel.',
'',
'- one',
'- two',
'',
'```',
'boil 1 minute',
'```',
'',
'| a | b |',
'|---|---|',
'| 1 | 2 |',
].join('\n'));
expect(div.querySelector('h1').textContent).toBe('Water');
expect(div.querySelector('em').textContent).toBe('every');
expect(div.querySelectorAll('ul li')).toHaveLength(2);
expect(div.querySelector('pre code').textContent).toBe('boil 1 minute\n');
expect(div.querySelectorAll('table td')).toHaveLength(2);
});
test('raw HTML in the file is shown as text, never parsed', () => {
const div = renderToDOM('<script>alert(1)</script>\n\n<img src=x onerror="alert(2)">');
expect(div.querySelector('script')).toBeNull();
expect(div.querySelector('img')).toBeNull();
expect(div.textContent).toContain('<script>alert(1)</script>');
});
test('script URLs are not turned into links', () => {
const div = renderToDOM('[click](javascript:alert(1))');
expect(div.querySelector('a')).toBeNull();
});
test('relative images resolve against the markdown file directory', () => {
const div = renderToDOM('![pump](images/hand%20pump.png)\n\n![tank](../tank.jpg)');
const [pump, tank] = div.querySelectorAll('img');
expect(pump.getAttribute('src')).toBe('/media/notes/water/images/hand%20pump.png');
expect(tank.getAttribute('src')).toBe('/media/notes/tank.jpg');
});
test('relative links resolve against the markdown file directory and open a new tab', () => {
const a = renderToDOM('[filters](filters.md#ceramic)').querySelector('a');
expect(a.getAttribute('href')).toBe('/media/notes/water/filters.md#ceramic');
expect(a.getAttribute('target')).toBe('_blank');
});
test('a relative URL that climbs out of the media directory is dropped', () => {
const div = renderToDOM('[api](../../../api/status)\n\n![x](../../../../x.png)');
expect(div.querySelector('a').hasAttribute('href')).toBe(false);
expect(div.querySelector('img').hasAttribute('src')).toBe(false);
});
test.each([
['https://tracker.example/pixel.gif'],
['http://tracker.example/pixel.gif'],
// Protocol-relative: starts with a slash, but loads from another host.
['//tracker.example/pixel.gif'],
])('an image from another site (%s) is not loaded, it becomes a link', (src) => {
const div = renderToDOM(`![pixel](${src})`);
expect(div.querySelector('img')).toBeNull();
const a = div.querySelector('a');
expect(a.getAttribute('href')).toBe(src);
expect(a.textContent).toBe('pixel');
expect(a.getAttribute('target')).toBe('_blank');
expect(a.getAttribute('rel')).toBe('noopener noreferrer');
});
test('an image from another site with no alt text is labeled by its URL', () => {
const a = renderToDOM('![](https://example.com/a.png)').querySelector('a');
expect(a.textContent).toBe('https://example.com/a.png');
});
test('an image from another site inside a link becomes the link text, not a nested link', () => {
// The badge pattern common in READMEs.
const div = renderToDOM('[![build status](https://ci.example/badge.svg)](https://ci.example/project)');
expect(div.querySelector('img')).toBeNull();
const links = div.querySelectorAll('a');
expect(links).toHaveLength(1);
expect(links[0].getAttribute('href')).toBe('https://ci.example/project');
expect(links[0].textContent).toBe('build status');
});
test('media and embedded data images still load', () => {
const [media, data] = renderToDOM('![a](/media/x/a.png)\n\n![b](data:image/png;base64,AAAA)')
.querySelectorAll('img');
expect(media.getAttribute('src')).toBe('/media/x/a.png');
expect(data.getAttribute('src')).toBe('data:image/png;base64,AAAA');
});
test('external links open in a new tab without an opener', () => {
const a = renderToDOM('<https://example.com/page>').querySelector('a');
expect(a.getAttribute('href')).toBe('https://example.com/page');
expect(a.getAttribute('target')).toBe('_blank');
expect(a.getAttribute('rel')).toBe('noopener noreferrer');
});
test('absolute and fragment URLs are left alone', () => {
const [root, fragment] = renderToDOM('[root](/files)\n\n[top](#top)').querySelectorAll('a');
expect(root.getAttribute('href')).toBe('/files');
expect(fragment.getAttribute('href')).toBe('#top');
expect(fragment.hasAttribute('target')).toBe(false);
});
});
describe('MarkdownPreview', () => {
const SOURCE = '# Water storage\n\nRotate *every* six months.\n';
beforeEach(() => {
window.localStorage.clear();
global.fetch = jest.fn(() => Promise.resolve({
ok: true,
text: () => Promise.resolve(SOURCE),
}));
});
afterEach(() => {
delete global.fetch;
});
test('fetches the file and shows it formatted', async () => {
renderUI(<MarkdownPreview url={FILE_URL}/>);
const heading = await screen.findByRole('heading', {name: 'Water storage'});
expect(heading.tagName).toBe('H1');
expect(global.fetch).toHaveBeenCalledWith(FILE_URL, expect.anything());
});
test('Raw shows the unformatted source, and the choice is remembered', async () => {
const {unmount} = renderUI(<MarkdownPreview url={FILE_URL}/>);
await screen.findByRole('heading', {name: 'Water storage'});
fireEvent.click(screen.getByRole('button', {name: 'Raw'}));
expect(screen.queryByRole('heading')).toBeNull();
expect(screen.getByTestId('markdown-raw').textContent).toBe(SOURCE);
// The next preview opens in the mode the reader chose last.
unmount();
renderUI(<MarkdownPreview url={FILE_URL}/>);
await waitFor(() => expect(screen.getByTestId('markdown-raw').textContent).toBe(SOURCE));
expect(screen.queryByRole('heading')).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Formatted'}));
expect(screen.getByRole('heading', {name: 'Water storage'})).toBeTruthy();
});
test('a failed fetch shows an error instead of loading forever', async () => {
global.fetch = jest.fn(() => Promise.resolve({ok: false, status: 404, statusText: 'Not Found'}));
renderUI(<MarkdownPreview url={FILE_URL}/>);
expect(await screen.findByText(/404 Not Found/)).toBeTruthy();
});
});
describe('isMarkdownFile', () => {
test.each([
['text/markdown', 'notes/a.md', true],
// A stored type from before text/markdown existed; refresh does not retag unchanged files.
['text/plain', 'notes/a.md', true],
['text/plain', 'notes/a.markdown', true],
['text/plain', 'notes/a.txt', false],
// A suffix alone is not enough; a binary file named .md is not markdown.
['application/octet-stream', 'notes/a.md', false],
])('%s %s -> %s', (mimetype, lowerPath, expected) => {
expect(isMarkdownFile(mimetype, lowerPath)).toBe(expected);
});
});

View file

@ -0,0 +1,179 @@
// The 3D previews render the real loaders against the installed three. Only the WebGL renderer is
// faked (jsdom has no WebGL); parsing, meshing and framing all run, and the dimensions line is
// only shown once a model has been loaded.
import React from 'react';
import {act, screen, waitFor} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {modelCameraDistance, STLPreviewModal, ThreeMFPreviewModal} from './FilePreview';
import {zipSync} from 'three/examples/jsm/libs/fflate.module.js';
jest.mock('three', () => {
const actual = jest.requireActual('three');
class FakeWebGLRenderer {
constructor() {
this.domElement = global.document.createElement('canvas');
}
setClearColor() {
}
setPixelRatio() {
}
setSize() {
}
render() {
}
dispose() {
}
}
return {...actual, WebGLRenderer: FakeWebGLRenderer};
});
// One right triangle, legs of 2 along X and 1 along Y.
const ASCII_STL = `solid ASCII
facet normal 0 0 1
outer loop
vertex 0 0 0
vertex 2 0 0
vertex 0 1 0
endloop
endfacet
endsolid
`;
function binaryStl() {
// 80-byte header, uint32 triangle count, then one 50-byte triangle: normal, three vertices.
const buffer = new ArrayBuffer(84 + 50);
const view = new DataView(buffer);
view.setUint32(80, 1, true);
const floats = [0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0];
floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true));
return buffer;
}
function threeMF() {
const model = `<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
<resources>
<object id="1" type="model">
<mesh>
<vertices>
<vertex x="0" y="0" z="0"/>
<vertex x="2" y="0" z="0"/>
<vertex x="0" y="1" z="0"/>
</vertices>
<triangles>
<triangle v1="0" v2="1" v3="2"/>
</triangles>
</mesh>
</object>
</resources>
<build>
<item objectid="1"/>
</build>
</model>`;
const rels = `<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Target="/3D/3dmodel.model" Id="rel0"
Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>
</Relationships>`;
// Copy into this realm's Uint8Array: fflate tells files from folders with `instanceof`, and
// Node's TextEncoder returns a Uint8Array from another realm than jsdom's.
const bytes = (text) => Uint8Array.from(new TextEncoder().encode(text));
const zipped = zipSync({'_rels/.rels': bytes(rels), '3D/3dmodel.model': bytes(model)});
return zipped.buffer.slice(zipped.byteOffset, zipped.byteOffset + zipped.byteLength);
}
function serve(body) {
const bytes = typeof body === 'string' ? new TextEncoder().encode(body).buffer : body;
global.fetch = jest.fn(async () => ({
ok: true,
status: 200,
statusText: 'OK',
headers: new Headers(),
arrayBuffer: async () => bytes,
}));
}
beforeEach(() => {
global.ResizeObserver = class {
observe() {
}
disconnect() {
}
};
});
afterEach(() => {
delete global.fetch;
});
// The triangle spans 2 along X and 1 along Y, and is flat in Z; its bounding radius is half the
// box diagonal. Which extent reads as Height depends on how the viewer orients the model.
async function expectTriangleDimensions({height, length}) {
await waitFor(() => expect(screen.getByText(/Width:/)).toBeInTheDocument(), {timeout: 5000});
const line = screen.getByText(/Width:/).closest('div').textContent;
expect(line).toContain('Width: 2.00');
expect(line).toContain(`Height: ${height}`);
expect(line).toContain(`Length: ${length}`);
expect(line).toContain('Bounding Radius: 1.12');
}
// Models are Z-up, so the flat triangle lies down: its Y extent reads as Length.
const TRIANGLE_DIMENSIONS = {height: '0.00', length: '1.00'};
describe('STL preview', () => {
it('loads an ASCII STL file', async () => {
serve(ASCII_STL);
await act(async () => renderWithProviders(<STLPreviewModal previewFile={{path: 'models/part.stl'}}/>));
await expectTriangleDimensions(TRIANGLE_DIMENSIONS);
// three's FileLoader fetches a Request.
expect(global.fetch.mock.calls[0][0].url).toContain('/media/models/part.stl');
});
it('loads a binary STL file', async () => {
serve(binaryStl());
await act(async () => renderWithProviders(<STLPreviewModal previewFile={{path: 'models/part.stl'}}/>));
await expectTriangleDimensions(TRIANGLE_DIMENSIONS);
});
});
describe('3MF preview', () => {
it('loads a 3MF file', async () => {
serve(threeMF());
await act(async () => renderWithProviders(<ThreeMFPreviewModal previewFile={{path: 'models/part.3mf'}}/>));
await expectTriangleDimensions(TRIANGLE_DIMENSIONS);
});
});
describe('modelCameraDistance', () => {
// Half the angle a sphere of `radius` fills when seen from `distance`.
const sphereHalfAngle = (radius, distance) => Math.asin(radius / distance);
const halfVertical = (fov) => (fov * Math.PI) / 360;
const halfHorizontal = (fov, aspect) => Math.atan(Math.tan(halfVertical(fov)) * aspect);
it.each([
['a wide viewer', 2],
['a square viewer', 1],
['a tall, narrow viewer', 0.5],
])('fits the whole bounding sphere in %s, with little to spare', (_, aspect) => {
const radius = 24;
const fov = 50;
const distance = modelCameraDistance(radius, fov, aspect);
const narrowest = Math.min(halfVertical(fov), halfHorizontal(fov, aspect));
// Every point of the sphere is in view...
expect(sphereHalfAngle(radius, distance)).toBeLessThanOrEqual(narrowest);
// ...and the sphere fills at least 90% of the narrower field of view.
expect(sphereHalfAngle(radius, distance)).toBeGreaterThan(narrowest * 0.9);
});
it('stands back in proportion to the model', () => {
expect(modelCameraDistance(10, 50, 1.5)).toBeCloseTo(modelCameraDistance(1, 50, 1.5) * 10);
});
});

View file

@ -21,6 +21,8 @@ import {HELP_VIEWER_URI, NAME, navColorHexMap} from "./Vars";
import {useOverflowNav} from "../hooks/useOverflowNav"; import {useOverflowNav} from "../hooks/useOverflowNav";
import {defaultNavColor, navBarStyle, useNavColors} from "../themes/navColors"; import {defaultNavColor, navBarStyle, useNavColors} from "../themes/navColors";
import _ from "lodash"; import _ from "lodash";
import {BookmarksMenuContents, EDIT_BOOKMARKS_PATH} from "./Bookmarks";
import {VPN_SETTINGS_PATH} from "./admin/VpnSection";
function updateFavicon(colorName) { function updateFavicon(colorName) {
// Fall back to violet if invalid color // Fall back to violet if invalid color
@ -60,16 +62,24 @@ const allLinks = [
{text: 'Files', to: '/files', key: 'files'}, {text: 'Files', to: '/files', key: 'files'},
{text: 'Playlists', to: '/playlists', key: 'playlists'}, {text: 'Playlists', to: '/playlists', key: 'playlists'},
{text: 'Zim', to: '/zim', key: 'zim'}, {text: 'Zim', to: '/zim', key: 'zim'},
{text: 'Repos', to: '/repos', key: 'repos'},
{text: 'Inventory', to: '/inventory', key: 'inventory'}, {text: 'Inventory', to: '/inventory', key: 'inventory'},
// No `end` on these two: a tab stays current for the pages beneath it, and `end` would // No `end` on these two: a tab stays current for the pages beneath it, and `end` would
// drop the mark the moment either grows a sub-page. // drop the mark the moment either grows a sub-page.
{to: '/more/calculators', text: 'Calculators', key: 'calculators'}, {to: '/more/calculators', text: 'Calculators', key: 'calculators'},
// The user's bookmarks, read from BookmarksContext when rendered. No `to`: it is a
// menu, and its items are not sections of the app.
{text: 'Bookmarks', key: 'bookmarks', bookmarks: true},
{text: 'Flasher', to: '/flasher', key: 'flasher'}, {text: 'Flasher', to: '/flasher', key: 'flasher'},
{text: 'Extension', to: '/extension', key: 'extension'},
{to: '/more/statistics', text: 'Statistics', key: 'statistics'}, {to: '/more/statistics', text: 'Statistics', key: 'statistics'},
]; ];
function MenuLink({link}) { function MenuLink({link}) {
// A top-level tab rendered directly in the bar (not inside a dropdown). // A top-level tab rendered directly in the bar (not inside a dropdown).
if (link.bookmarks) {
return <BookmarksDropdown link={link}/>
}
if (link.links) { if (link.links) {
return <DropdownLinks link={link}/> return <DropdownLinks link={link}/>
} }
@ -85,13 +95,31 @@ function MenuLink({link}) {
</NavLink> </NavLink>
} }
function DropdownMenuItem({link}) { function DropdownMenuItem({link, nested = true}) {
// An item inside a Menu.Dropdown: the mobile hamburger menu, or the desktop // An item inside a Menu.Dropdown: the mobile hamburger menu, or the desktop
// "More" overflow menu. // "More" overflow menu. `nested` allows flyout submenus, which the hamburger
// declines: a flyout opens on hover, and a phone has none.
if (link.bookmarks) {
if (nested) {
return <Menu.Sub>
<Menu.Sub.Target>
<Menu.Sub.Item>{link.text}</Menu.Sub.Item>
</Menu.Sub.Target>
<Menu.Sub.Dropdown>
<BookmarksMenuContents nested/>
</Menu.Sub.Dropdown>
</Menu.Sub>
}
return <React.Fragment>
<Menu.Divider/>
<Menu.Label>{link.text}</Menu.Label>
<BookmarksMenuContents nested={false}/>
<Menu.Divider/>
</React.Fragment>
}
if (link.links) { if (link.links) {
// Mantine's Menu does not nest submenus without extra plumbing; a labelled, // A labelled, indented group stands in for a submenu here. No current data uses
// indented group stands in for one. No current data uses this path (no // this path (no allLinks entry has its own `links`).
// allLinks entry has its own `links`).
return <React.Fragment> return <React.Fragment>
<Menu.Label>{link.text}</Menu.Label> <Menu.Label>{link.text}</Menu.Label>
{link.links.map(l => <DropdownMenuItem key={l.key} link={l}/>)} {link.links.map(l => <DropdownMenuItem key={l.key} link={l}/>)}
@ -141,6 +169,11 @@ NavDropdownTrigger.displayName = 'NavDropdownTrigger';
* the hooks that would answer it cannot be called in a loop. * the hooks that would answer it cannot be called in a loop.
*/ */
export const isLinkActive = (pathname, link) => { export const isLinkActive = (pathname, link) => {
// The Bookmarks menu owns only its editor page: a bookmark pointing at /videos does
// not make the menu own the Videos section.
if (link.bookmarks) {
return pathname === EDIT_BOOKMARKS_PATH || pathname.startsWith(`${EDIT_BOOKMARKS_PATH}/`);
}
// An off-site link (Help) is never the current section. // An off-site link (Help) is never the current section.
if (!link.to || /^[a-z]+:\/\//i.test(link.to)) return false; if (!link.to || /^[a-z]+:\/\//i.test(link.to)) return false;
const to = link.to.length > 1 ? link.to.replace(/\/+$/, '') : link.to; const to = link.to.length > 1 ? link.to.replace(/\/+$/, '') : link.to;
@ -175,6 +208,24 @@ function DropdownLinks({link}) {
</Menu> </Menu>
} }
/**
* The Bookmarks tab: a dropdown that opens on hover as well as on click, holding the
* user's bookmarks and the link to edit them. Marked current on the editor page only
* (see isLinkActive).
*/
function BookmarksDropdown({link}) {
const {pathname} = useLocation();
const holdsCurrent = isLinkActive(pathname, link);
return <Menu position='bottom-start' withinPortal trigger='click-hover' openDelay={100} closeDelay={200}>
<Menu.Target>
<NavDropdownTrigger text={link.text} className={holdsCurrent ? 'active' : undefined}/>
</Menu.Target>
<Menu.Dropdown>
<BookmarksMenuContents nested/>
</Menu.Dropdown>
</Menu>
}
function MobileMenu({links}) { function MobileMenu({links}) {
// The mobile hamburger menu: an icon-only trigger holding every link. // The mobile hamburger menu: an icon-only trigger holding every link.
return <Menu position='bottom-end' withinPortal> return <Menu position='bottom-end' withinPortal>
@ -182,7 +233,7 @@ function MobileMenu({links}) {
<IconButton icon={IconMenu2} label='Menu' variant='subtle'/> <IconButton icon={IconMenu2} label='Menu' variant='subtle'/>
</Menu.Target> </Menu.Target>
<Menu.Dropdown> <Menu.Dropdown>
{links.map(link => <DropdownMenuItem key={link.key} link={link}/>)} {links.map(link => <DropdownMenuItem key={link.key} link={link} nested={false}/>)}
</Menu.Dropdown> </Menu.Dropdown>
</Menu> </Menu>
} }
@ -425,11 +476,25 @@ export function NavBar() {
</Tooltip>; </Tooltip>;
} }
// Torrents only reach the Internet through the VPN; while it is not connected they are stopped. Shown only when
// there are torrents, so a WROLPi which does not use them never sees it.
const torrents = status && status.torrents;
let torrentsIcon;
if (torrents && torrents.count > 0 && torrents.vpn_state !== 'connected') {
const label = torrents.vpn_state === 'wrol_mode'
? 'Torrents are stopped: WROL Mode is on'
: 'Torrents are stopped: the VPN is not connected';
const icon = <Icon data-testid='torrentsVpnIcon' name='share' size='large'
style={{color: colorVar(lowWarningColor)}} label={label}/>;
torrentsIcon = <Tooltip label={label}><Link to={VPN_SETTINGS_PATH}>{icon}</Link></Tooltip>;
}
const icons = <React.Fragment> const icons = <React.Fragment>
<NavIconWrapper>{apiDownIcon}</NavIconWrapper> <NavIconWrapper>{apiDownIcon}</NavIconWrapper>
<NavIconWrapper>{processingIcon}</NavIconWrapper> <NavIconWrapper>{processingIcon}</NavIconWrapper>
<NavIconWrapper>{upgradeIcon}</NavIconWrapper> <NavIconWrapper>{upgradeIcon}</NavIconWrapper>
<NavIconWrapper>{driveHealthIcon}</NavIconWrapper> <NavIconWrapper>{driveHealthIcon}</NavIconWrapper>
<NavIconWrapper>{torrentsIcon}</NavIconWrapper>
<NavIconWrapper>{powerIcon}</NavIconWrapper> <NavIconWrapper>{powerIcon}</NavIconWrapper>
<NavIconWrapper>{warningIcon}</NavIconWrapper> <NavIconWrapper>{warningIcon}</NavIconWrapper>
<NavIconWrapper><ShareButton asIcon/></NavIconWrapper> <NavIconWrapper><ShareButton asIcon/></NavIconWrapper>

View file

@ -231,3 +231,126 @@ describe('NavBar current tab', () => {
expect(ruleBody('\\.mantine-Menu-item\\.active')).toMatch(/background:|font-weight:/); expect(ruleBody('\\.mantine-Menu-item\\.active')).toMatch(/background:|font-weight:/);
}); });
}); });
describe('NavBar bookmarks', () => {
const {BookmarksContext} = require('../contexts/BookmarksContext');
const bookmarks = [
{id: 1, name: 'Channels', url: '/videos/channel', new_tab: false},
{id: 2, name: 'Services', children: [{id: 3, name: 'Jellyfin', url: ':8096/', new_tab: true}]},
];
const renderWithBookmarks = (route, nodes) => render(<NavBar/>, {
route,
withMedia: true,
contexts: [
[FileWorkerStatusContext, fileWorkerStatus],
[BookmarksContext, {bookmarks: nodes, error: null, refresh: jest.fn()}],
],
});
it('Extension follows Flasher', () => {
renderNav('/');
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
.map(el => el.textContent.trim());
expect(texts[texts.indexOf('Flasher') + 1]).toBe('Extension');
});
it('sits between Calculators and Flasher', () => {
renderNav('/');
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
.map(el => el.textContent.trim());
const at = texts.indexOf('Bookmarks');
expect(at).toBeGreaterThan(0);
expect(texts[at - 1]).toBe('Calculators');
expect(texts[at + 1]).toBe('Flasher');
});
it('opens on click with the bookmarks, a directory flyout, and the edit link', async () => {
useRealRects();
renderWithBookmarks('/', bookmarks);
await userEvent.click(screen.getByRole('button', {name: /Bookmarks/}));
const channels = await screen.findByRole('menuitem', {name: 'Channels'});
expect(channels).toHaveAttribute('href', '/videos/channel');
expect(channels).not.toHaveAttribute('target');
// A directory is a submenu; its bookmarks appear once it is hovered.
expect(screen.queryByRole('menuitem', {name: 'Jellyfin'})).not.toBeInTheDocument();
await userEvent.hover(screen.getByRole('menuitem', {name: 'Services'}));
// `hidden`: the flyout is placed by floating-ui, which jsdom cannot lay out, so it
// stays hidden to accessibility queries even though it has rendered.
const jellyfin = await screen.findByRole('menuitem', {name: 'Jellyfin', hidden: true});
expect(jellyfin).toHaveAttribute('href', `${window.location.protocol}//${window.location.hostname}:8096/`);
expect(jellyfin).toHaveAttribute('target', '_blank');
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks', hidden: true})).toHaveAttribute('href', '/more/bookmarks');
});
it('offers the edit link even with no bookmarks, so the feature can be found', async () => {
useRealRects();
renderWithBookmarks('/', []);
await userEvent.click(screen.getByRole('button', {name: /Bookmarks/}));
expect(await screen.findByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
expect(screen.getAllByRole('menuitem')).toHaveLength(1);
});
it('is marked current on the editor page, and never for a bookmark pointing at a section', () => {
renderWithBookmarks('/more/bookmarks', bookmarks);
expect(screen.getByRole('button', {name: /Bookmarks/})).toHaveClass('active');
expect(currentTab()).toEqual([]);
});
it('marks More when the editor page is folded inside it', () => {
useBarWidth(200);
renderWithBookmarks('/more/bookmarks', bookmarks);
expect(screen.getByRole('button', {name: /More/})).toHaveClass('active');
});
it('does not own the section a bookmark points at', () => {
renderWithBookmarks('/videos/channel', bookmarks);
expect(screen.getByRole('button', {name: /Bookmarks/})).not.toHaveClass('active');
expect(currentTab()).toEqual(['Videos']);
});
it('lists bookmarks as a labelled group in the mobile menu', async () => {
useViewport('mobile');
useRealRects();
renderWithBookmarks('/', bookmarks);
await userEvent.click(screen.getByRole('button', {name: 'Menu'}));
expect(await screen.findByRole('menuitem', {name: 'Channels'})).toBeInTheDocument();
// No flyout on a phone: the directory's bookmarks are listed directly.
expect(screen.getByRole('menuitem', {name: 'Jellyfin'})).toBeInTheDocument();
expect(screen.getByText('Services')).toBeInTheDocument();
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
});
});
describe('NavBar torrents warning', () => {
const {statusFixture} = require('../test-fixtures');
const renderWithTorrents = (torrents) => render(<NavBar/>, {
route: '/',
withMedia: true,
status: {status: statusFixture({torrents})},
contexts: [[FileWorkerStatusContext, fileWorkerStatus]],
});
it('warns when torrents exist but the VPN they use is not connected', () => {
renderWithTorrents({count: 2, vpn_state: 'connecting', running: true});
expect(screen.getAllByLabelText('Torrents are stopped: the VPN is not connected').length).toBeGreaterThan(0);
});
it('says when WROL Mode stopped them', () => {
renderWithTorrents({count: 1, vpn_state: 'wrol_mode', running: true});
expect(screen.getAllByLabelText('Torrents are stopped: WROL Mode is on').length).toBeGreaterThan(0);
});
it('is silent while the VPN is connected, or without torrents', () => {
const {unmount} = renderWithTorrents({count: 2, vpn_state: 'connected', running: true});
expect(screen.queryByTestId('torrentsVpnIcon')).not.toBeInTheDocument();
unmount();
renderWithTorrents({count: 0, vpn_state: 'stopped', running: false});
expect(screen.queryByTestId('torrentsVpnIcon')).not.toBeInTheDocument();
});
});

View file

@ -0,0 +1,174 @@
import React from 'react';
import {act, render, screen} from '../test-utils';
import {OtherSearchView} from './Search';
import {searchChannels, searchCollections, searchRepos} from '../api';
// What the search page's Other tab shows for each state of useSearchChannels. "No Channels"
// must only appear once the server has confirmed there are none.
jest.mock('../api', () => ({
...jest.requireActual('../api'),
searchChannels: jest.fn(),
searchCollections: jest.fn(),
searchRepos: jest.fn(),
}));
const NO_CHANNELS = /No Channels/;
beforeEach(() => {
searchChannels.mockReset();
searchRepos.mockReset();
searchRepos.mockResolvedValue({repos: [], total: 0});
searchCollections.mockReset();
searchCollections.mockResolvedValue({collections: []});
});
test('pending: shows a loader, not "No Channels"', () => {
searchChannels.mockReturnValue(new Promise(() => {
}));
const {container} = render(<OtherSearchView loading={false}/>);
expect(container.querySelector('.wrolpi-loading')).toBeInTheDocument();
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
});
test('failed: shows an error, not "No Channels"', async () => {
searchChannels.mockResolvedValue(undefined);
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
});
try {
render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText(/Could not fetch the channels/)).toBeInTheDocument();
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
} finally {
spy.mockRestore();
}
});
test('empty: shows "No Channels"', async () => {
searchChannels.mockResolvedValue({channels: []});
render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText(NO_CHANNELS)).toBeInTheDocument();
});
test('loaded: lists the channels', async () => {
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText('Cooking')).toBeInTheDocument();
expect(screen.queryByText(NO_CHANNELS)).not.toBeInTheDocument();
});
describe('Repos', () => {
test('pending: the Repos section loads while Channels are shown', async () => {
searchChannels.mockResolvedValue({channels: []});
searchRepos.mockReturnValue(new Promise(() => {
}));
const {container} = render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText(NO_CHANNELS)).toBeInTheDocument();
expect(container.querySelector('.wrolpi-loading')).toBeInTheDocument();
expect(screen.queryByText('No Repos')).not.toBeInTheDocument();
});
test('empty: shows "No Repos"', async () => {
searchChannels.mockResolvedValue({channels: []});
render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText('No Repos')).toBeInTheDocument();
});
test('failed: shows an error only in the Repos section', async () => {
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
searchRepos.mockRejectedValue(new Error('boom'));
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
});
try {
render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText('Cooking')).toBeInTheDocument();
expect(screen.getByText(/Could not fetch the repos/)).toBeInTheDocument();
} finally {
spy.mockRestore();
}
});
test('loaded: lists repos by the search, with their README headline', async () => {
searchChannels.mockResolvedValue({channels: []});
searchRepos.mockResolvedValue({
total: 1, repos: [{
id: 7, name: 'kiwix-tools', tag_name: null,
// The server escapes the README; only the highlight is markup.
readme_headline: 'Serve <b>Zim</b> files &lt;script&gt;',
}],
});
const searchParams = new URLSearchParams('q=zim&tag=Software');
const {container} = render(<OtherSearchView loading={false}/>, {query: {searchParams}});
await act(async () => {
});
expect(searchRepos).toHaveBeenCalledWith('zim', ['Software']);
expect(screen.getByText('kiwix-tools').closest('a')).toHaveAttribute('href', '/repos/7');
expect(container.querySelector('u').textContent).toBe('Zim');
expect(container.querySelector('script')).toBeNull();
expect(screen.getByText(/files <script>/)).toBeInTheDocument();
});
});
// Domains and Playlists are Collections searched by kind.
describe.each([
['domain', 'Domains', 'example.com', '/archives?domain=example.com'],
['playlist', 'Playlists', 'Road Trip', '/playlists/3'],
])('%s Collections', (kind, title, name, href) => {
const collectionsOf = (wanted, collections) => (k) => Promise.resolve({collections: k === wanted ? collections : []});
test(`empty: shows "No ${title}"`, async () => {
searchChannels.mockResolvedValue({channels: []});
render(<OtherSearchView loading={false}/>, {query: {searchParams: new URLSearchParams('q=nothing')}});
await act(async () => {
});
expect(screen.getByText(`No ${title}`)).toBeInTheDocument();
});
test('nothing to search by: shows none without fetching', async () => {
searchChannels.mockResolvedValue({channels: []});
render(<OtherSearchView loading={false}/>);
await act(async () => {
});
expect(screen.getByText(`No ${title}`)).toBeInTheDocument();
expect(searchCollections).not.toHaveBeenCalled();
});
test(`failed: shows an error only in the ${title} section`, async () => {
searchChannels.mockResolvedValue({channels: [{id: 1, name: 'Cooking'}]});
searchCollections.mockImplementation(k => k === kind ? Promise.reject(new Error('boom')) : Promise.resolve({collections: []}));
const spy = jest.spyOn(console, 'error').mockImplementation(() => {
});
try {
render(<OtherSearchView loading={false}/>, {query: {searchParams: new URLSearchParams('q=x')}});
await act(async () => {
});
expect(screen.getByText('Cooking')).toBeInTheDocument();
expect(screen.getByText(new RegExp(`Could not fetch the ${title.toLowerCase()}`))).toBeInTheDocument();
} finally {
spy.mockRestore();
}
});
test('loaded: lists them by the search and tags, linked', async () => {
searchChannels.mockResolvedValue({channels: []});
searchCollections.mockImplementation(collectionsOf(kind, [{id: 3, name, kind, tag_name: null}]));
const searchParams = new URLSearchParams('q=road&tag=News');
render(<OtherSearchView loading={false}/>, {query: {searchParams}});
await act(async () => {
});
expect(searchCollections).toHaveBeenCalledWith(kind, ['News'], 'road');
expect(screen.getByText(name).closest('a')).toHaveAttribute('href', href);
});
});

View file

@ -0,0 +1,37 @@
// QR codes for a phone to scan: the code itself, a modal which shows one, and a button which opens it.
import React, {useState} from "react";
import QRCode from "react-qr-code";
import {IconButton, Modal} from "./ui";
// A scannable QR code of `value`. `style` adds to (or replaces) the white field around it.
export function QRCodeImage({value, size = 300, style}) {
// `media`: a QR code needs real black-on-white contrast to scan, so its white field is filtered
// as a unit by night mode rather than sitting on screen as a lit panel.
return <div className='media'
style={{display: 'inline-block', backgroundColor: '#ffffff', padding: '1em', ...style}}>
<QRCode value={value} size={size} title={value}/>
</div>;
}
// A modal which shows a QR code of `value`, then `children` (if any) beneath it.
export function QRCodeModal({open, onClose, header, value, children}) {
return <Modal size='small' open={open} onClose={onClose} closeIcon>
{header && <Modal.Header>{header}</Modal.Header>}
<Modal.Content>
<QRCodeImage value={value}/>
{children}
</Modal.Content>
</Modal>;
}
// A QR code icon button which opens a QRCodeModal of `value`. `label` names the button; the modal's
// header defaults to it.
export function QRCodeButton({value, label, header, color, size, children}) {
const [open, setOpen] = useState(false);
return <>
<IconButton icon='qrcode' label={label} color={color} size={size} onClick={() => setOpen(true)}/>
<QRCodeModal open={open} onClose={() => setOpen(false)} header={header ?? label} value={value}>
{children}
</QRCodeModal>
</>;
}

View file

@ -0,0 +1,39 @@
import React from 'react';
import {fireEvent, screen, waitFor, within} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {QRCodeButton, QRCodeImage} from './QRCode';
describe('QRCode', () => {
it('draws the code on a white field which night mode filters as a unit', () => {
renderWithProviders(<QRCodeImage value='https://example.com/a' size={128}/>);
// react-qr-code titles its svg with the value.
const svg = screen.getByTitle('https://example.com/a').closest('svg');
expect(svg).toHaveAttribute('height', '128');
const field = svg.parentElement;
expect(field).toHaveClass('media');
expect(field).toHaveStyle({backgroundColor: '#ffffff'});
});
it('opens a modal of the code from its button, then closes it', async () => {
renderWithProviders(<QRCodeButton value='WIFI:S:x;;' label='Show the code' header='Scan this'>
<p>Beneath the code</p>
</QRCodeButton>);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', {name: 'Show the code'}));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Scan this')).toBeInTheDocument();
expect(within(dialog).getByTitle('WIFI:S:x;;')).toBeInTheDocument();
expect(within(dialog).getByText('Beneath the code')).toBeInTheDocument();
fireEvent.keyDown(dialog, {key: 'Escape'});
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
});
it('titles the modal with the button label when no header is given', async () => {
renderWithProviders(<QRCodeButton value='x' label='Join the hotspot'/>);
fireEvent.click(screen.getByRole('button', {name: 'Join the hotspot'}));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Join the hotspot')).toBeInTheDocument();
});
});

1062
app/src/components/Repos.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,394 @@
import React from 'react';
import {Route, Routes} from 'react-router';
import {act, fireEvent, render, screen, waitFor, within} from '../test-utils';
import {
RepoEditPage,
RepoImportPage,
repoNameFromURL,
RepoNewPage,
ReposPage,
RepoViewPage,
safeRepoHref,
} from './Repos';
import {
createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoLog, getRepoTree, importRepo, inspectRepoImport,
updateRepo,
} from '../api';
import {FilePreviewContext} from './FilePreview';
jest.mock('../api', () => ({
...jest.requireActual('../api'),
createRepo: jest.fn(),
deleteRepo: jest.fn(),
fetchRepos: jest.fn(),
getFile: jest.fn(),
getRepo: jest.fn(),
getRepoLog: jest.fn(),
getRepoTree: jest.fn(),
importRepo: jest.fn(),
inspectRepoImport: jest.fn(),
updateRepo: jest.fn(),
}));
// The directory picker searches the server; picking a directory is all these specs need.
jest.mock('./Common', () => ({
...jest.requireActual('./Common'),
DirectorySearch: ({onSelect}) => <button type='button' onClick={() => onSelect('code/kiwix-tools')}>
Pick directory
</button>,
}));
// The README is fetched from the media server; its rendering is MarkdownPreview's own spec.
jest.mock('./MarkdownPreview', () => ({
...jest.requireActual('./MarkdownPreview'),
MarkdownPreview: ({url}) => <div data-testid='markdown-preview'>{url}</div>,
}));
const repoFixture = (overrides = {}) => ({
id: 1, collection_id: 10, name: 'kiwix-tools', tag_name: null, description: null,
url: 'https://github.com/kiwix/kiwix-tools', mode: 'full', branch: null, default_branch: 'main',
head_sha: '3f9c2a1e7b', head_message: 'Fix the mimetype', head_date: '2026-09-30T14:02:00Z',
size: 1000, directory: 'repos/kiwix-tools', frequency: 604800, download_error: null,
...overrides,
});
const treeFixture = {
path: '',
readme_path: 'README.md',
entries: [
{name: 'src', path: 'src', is_dir: true, size: null},
{name: 'README.md', path: 'README.md', is_dir: false, size: 120},
],
};
const flush = () => act(async () => {
});
beforeEach(() => jest.clearAllMocks());
describe('safeRepoHref', () => {
it('only links https URLs', () => {
expect(safeRepoHref('https://github.com/a/b')).toBe('https://github.com/a/b');
expect(safeRepoHref('javascript:alert(1)')).toBeNull();
expect(safeRepoHref('http://github.com/a/b')).toBeNull();
expect(safeRepoHref('file:///etc/passwd')).toBeNull();
expect(safeRepoHref('not a url')).toBeNull();
});
});
describe('repoNameFromURL', () => {
it('is the last path segment, without .git or a branch', () => {
expect(repoNameFromURL('https://github.com/kiwix/kiwix-tools.git')).toBe('kiwix-tools');
expect(repoNameFromURL('https://github.com/kiwix/kiwix-tools/tree/dev')).toBe('kiwix-tools');
expect(repoNameFromURL('https://gitlab.com/group/sub/project/')).toBe('project');
expect(repoNameFromURL('nope')).toBe('');
});
});
describe('ReposPage', () => {
it('lists repos, linking each to its page', async () => {
fetchRepos.mockResolvedValue([
repoFixture(),
repoFixture({id: 2, name: 'gone', download_error: 'git ls-remote failed', head_sha: null}),
]);
render(<ReposPage/>, {route: '/repos'});
await flush();
expect(screen.getAllByText('kiwix-tools')[0].closest('a')).toHaveAttribute('href', '/repos/1');
expect(screen.getAllByText('gone')[0].closest('a')).toHaveAttribute('href', '/repos/2');
expect(screen.getByText('New Repo').closest('a')).toHaveAttribute('href', '/repos/new');
});
it('shows a repo which is never updated', async () => {
fetchRepos.mockResolvedValue([repoFixture({frequency: 0})]);
render(<ReposPage/>, {route: '/repos'});
await flush();
expect(screen.getAllByText('Never').length).toBeGreaterThan(0);
});
it('explains an empty list', async () => {
fetchRepos.mockResolvedValue([]);
render(<ReposPage/>, {route: '/repos'});
await flush();
expect(screen.getByText(/No repos yet/)).toBeInTheDocument();
});
});
function renderViewPage({repo, tree = treeFixture, query = {}, setPreviewFile = jest.fn()} = {}) {
getRepo.mockResolvedValue(repo);
getRepoTree.mockResolvedValue(tree);
return render(<Routes><Route path='/repos/:repoId' element={<RepoViewPage/>}/></Routes>, {
route: '/repos/1',
query,
contexts: [[FilePreviewContext, {setPreviewFile}]],
});
}
describe('RepoViewPage', () => {
it('shows the latest commit, the files, and the README', async () => {
renderViewPage({repo: repoFixture()});
await flush();
expect(getRepoTree).toHaveBeenCalledWith('1', '');
expect(screen.getByText('3f9c2a1')).toBeInTheDocument();
expect(screen.getByText('Fix the mimetype')).toBeInTheDocument();
expect(screen.getByText('main')).toBeInTheDocument();
expect(screen.getByText('(default)')).toBeInTheDocument();
expect(screen.getByText('https://github.com/kiwix/kiwix-tools').closest('a'))
.toHaveAttribute('href', 'https://github.com/kiwix/kiwix-tools');
expect(screen.getByText('src')).toBeInTheDocument();
expect(screen.getByTestId('markdown-preview')).toHaveTextContent('/media/repos/kiwix-tools/README.md');
});
it('opens a directory through the URL, and a file in the preview', async () => {
const updateQuery = jest.fn();
const setPreviewFile = jest.fn();
const file = {path: 'repos/kiwix-tools/README.md', mimetype: 'text/markdown', size: 120};
getFile.mockResolvedValue(file);
renderViewPage({repo: repoFixture(), query: {updateQuery}, setPreviewFile});
await flush();
fireEvent.click(screen.getByText('src'));
expect(updateQuery).toHaveBeenCalledWith({path: 'src'}, false);
fireEvent.click(screen.getAllByText('README.md')[0]);
await flush();
expect(getFile).toHaveBeenCalledWith('repos/kiwix-tools/README.md', true);
expect(setPreviewFile).toHaveBeenCalledWith(file);
});
it('lists the directory in the URL, with a way back up', async () => {
const tree = {path: 'src/lib', readme_path: null, entries: [{name: 'a.c', path: 'src/lib/a.c', is_dir: false}]};
const updateQuery = jest.fn();
renderViewPage({repo: repoFixture(), tree, query: {searchParams: new URLSearchParams('path=src/lib'), updateQuery}});
await flush();
expect(getRepoTree).toHaveBeenCalledWith('1', 'src/lib');
expect(screen.queryByTestId('markdown-preview')).not.toBeInTheDocument();
fireEvent.click(screen.getByText('..'));
expect(updateQuery).toHaveBeenCalledWith({path: 'src'}, false);
// The breadcrumb's root.
fireEvent.click(screen.getAllByText('kiwix-tools').find(i => i.tagName === 'BUTTON'));
expect(updateQuery).toHaveBeenCalledWith({path: ''}, false);
});
it('offers a ZIP of the files', async () => {
renderViewPage({repo: repoFixture()});
await flush();
const link = screen.getByText('Download ZIP').closest('a');
expect(link).toHaveAttribute('href', expect.stringMatching(/\/api\/repos\/1\/archive\.zip$/));
expect(link).toHaveAttribute('download');
});
it('shows the history instead of the files', async () => {
getRepoLog.mockResolvedValue({
total: 51,
commits: [{sha: 'abcdef1234', author: 'Ada', date: '2026-09-30T14:02:00Z', message: 'Fix the mimetype'}],
});
const updateQuery = jest.fn();
renderViewPage({repo: repoFixture(), query: {searchParams: new URLSearchParams('view=history'), updateQuery}});
await flush();
expect(getRepoLog).toHaveBeenCalledWith(1, 0, 50);
expect(getRepoTree).not.toHaveBeenCalled();
expect(screen.getByText('51 commits')).toBeInTheDocument();
expect(screen.getByText('abcdef1')).toBeInTheDocument();
expect(screen.getByText('Ada')).toBeInTheDocument();
// The next page is appended.
getRepoLog.mockResolvedValue({
total: 51,
commits: [{sha: '0123456789', author: 'Ben', date: '2026-09-01T00:00:00Z', message: 'Older'}],
});
fireEvent.click(screen.getByText('Load more'));
await flush();
expect(getRepoLog).toHaveBeenLastCalledWith(1, 1, 50);
expect(screen.getByText('abcdef1')).toBeInTheDocument();
expect(screen.getByText('0123456')).toBeInTheDocument();
fireEvent.click(screen.getByText('Files'));
expect(updateQuery).toHaveBeenCalledWith({view: null}, false);
});
it('explains a repo that is not downloaded yet', async () => {
renderViewPage({repo: repoFixture({head_sha: null, head_message: null, head_date: null})});
await flush();
expect(screen.getByText('Not downloaded yet')).toBeInTheDocument();
expect(getRepoTree).not.toHaveBeenCalled();
expect(screen.queryByText('Download ZIP')).not.toBeInTheDocument();
expect(screen.queryByText('History')).not.toBeInTheDocument();
});
it('keeps showing the files when the last update failed', async () => {
renderViewPage({repo: repoFixture({download_error: 'Traceback...\nDownloadError: git ls-remote failed (128)'})});
await flush();
expect(screen.getByText('The last update failed')).toBeInTheDocument();
expect(screen.getByText(/git ls-remote failed/)).toBeInTheDocument();
expect(screen.getByText('src')).toBeInTheDocument();
});
it('says a repo which is never updated is only updated on request', async () => {
renderViewPage({repo: repoFixture({frequency: 0, download_error: 'git ls-remote failed (128)'})});
await flush();
expect(screen.getByText('The last update failed')).toBeInTheDocument();
expect(screen.getByText(/never updated automatically/)).toBeInTheDocument();
expect(screen.queryByText(/will be tried again/)).not.toBeInTheDocument();
});
it('never links an upstream that is not https', async () => {
renderViewPage({repo: repoFixture({url: 'javascript:alert(1)'})});
await flush();
expect(screen.queryByText('javascript:alert(1)')).not.toBeInTheDocument();
});
});
describe('RepoNewPage', () => {
it('adds a repo, then opens it', async () => {
createRepo.mockResolvedValue(repoFixture({id: 5}));
render(<Routes>
<Route path='/repos/new' element={<RepoNewPage/>}/>
<Route path='/repos/:repoId' element={<div>repo page</div>}/>
</Routes>, {route: '/repos/new'});
const add = screen.getByText('Add Repo').closest('button');
expect(add).toBeDisabled();
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'git@github.com:a/b'}});
expect(add).toBeDisabled();
expect(screen.getByText('Must be an https:// URL')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}});
expect(screen.getByPlaceholderText('kiwix-tools')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ' dev '}});
fireEvent.click(screen.getByText('Pick directory'));
fireEvent.click(add);
await flush();
expect(createRepo).toHaveBeenCalledWith({
url: 'https://github.com/kiwix/kiwix-tools', name: null, tag_name: null, frequency: 604800,
mode: 'full', branch: 'dev', submodules: false, description: null, directory: 'code/kiwix-tools',
});
expect(screen.getByText('repo page')).toBeInTheDocument();
});
});
describe('RepoEditPage', () => {
function renderEditPage(repo) {
getRepo.mockResolvedValue(repo);
return render(<Routes>
<Route path='/repos/:repoId/edit' element={<RepoEditPage/>}/>
<Route path='/repos' element={<div>repos page</div>}/>
</Routes>, {route: '/repos/1/edit'});
}
it('saves the settings', async () => {
updateRepo.mockResolvedValue(repoFixture());
renderEditPage(repoFixture({branch: 'dev', description: 'Tools'}));
await flush();
expect(screen.getByLabelText('Branch')).toHaveValue('dev');
expect(screen.getByLabelText('Include submodules')).not.toBeChecked();
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ''}});
fireEvent.click(screen.getByLabelText('Include submodules'));
fireEvent.click(screen.getByText('Save'));
await flush();
expect(updateRepo).toHaveBeenCalledWith('1', {
description: 'Tools', frequency: 604800, mode: 'full', branch: '', submodules: true,
});
});
it('keeps a repo which is never updated', async () => {
updateRepo.mockResolvedValue(repoFixture({frequency: 0}));
renderEditPage(repoFixture({frequency: 0}));
await flush();
expect(screen.getByDisplayValue('Never')).toBeInTheDocument();
fireEvent.click(screen.getByText('Save'));
await flush();
expect(updateRepo).toHaveBeenCalledWith('1', expect.objectContaining({frequency: 0}));
});
it('deletes the repo, and its files only when asked', async () => {
deleteRepo.mockResolvedValue(undefined);
renderEditPage(repoFixture());
await flush();
fireEvent.click(screen.getByText('Delete'));
const dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByLabelText(/Also delete its files/));
fireEvent.click(within(dialog).getByText('Delete'));
await flush();
expect(deleteRepo).toHaveBeenCalledWith('1', true);
expect(screen.getByText('repos page')).toBeInTheDocument();
});
});
describe('RepoImportPage', () => {
const inspection = (overrides = {}) => ({
directory: 'code/kiwix-tools', origin: 'git@github.com:kiwix/kiwix-tools.git',
url: 'https://github.com/kiwix/kiwix-tools', name: 'kiwix-tools', branch: 'main',
head_sha: 'abcdef1234', head_message: 'Local work', head_date: '2026-09-30T14:02:00Z', local_commits: 2,
shallow: false, ignored: false,
...overrides,
});
function renderImportPage() {
return render(<Routes>
<Route path='/repos/import' element={<RepoImportPage/>}/>
<Route path='/repos/:repoId' element={<div>repo page</div>}/>
</Routes>, {route: '/repos/import'});
}
it('inspects the directory, warns about local commits, and imports once confirmed', async () => {
inspectRepoImport.mockResolvedValue({inspection: inspection()});
importRepo.mockResolvedValue(repoFixture({id: 9}));
renderImportPage();
fireEvent.click(screen.getByText('Pick directory'));
expect(await screen.findByText('2 commits are not on the remote')).toBeInTheDocument();
expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null, '');
// Inspected again with the URL the import will use.
await waitFor(() => expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null,
'https://github.com/kiwix/kiwix-tools'));
expect(screen.getByText('git@github.com:kiwix/kiwix-tools.git')).toBeInTheDocument();
expect(screen.getByText(/Its files are indexed/)).toBeInTheDocument();
// The URL comes from the origin.
expect(screen.getByLabelText(/^URL/)).toHaveValue('https://github.com/kiwix/kiwix-tools');
const button = screen.getByText('Import').closest('button');
expect(button).toBeDisabled();
fireEvent.click(screen.getByLabelText(/I understand/));
expect(button).toBeEnabled();
fireEvent.click(button);
await flush();
expect(importRepo).toHaveBeenCalledWith({
directory: 'code/kiwix-tools', confirm: true, url: 'https://github.com/kiwix/kiwix-tools', name: null,
tag_name: null, frequency: 604800, mode: 'full', branch: null, submodules: false,
});
expect(screen.getByText('repo page')).toBeInTheDocument();
});
it('asks for the URL when the clone has no https origin', async () => {
inspectRepoImport.mockResolvedValue({inspection: inspection({origin: null, url: null, local_commits: 0})});
renderImportPage();
fireEvent.click(screen.getByText('Pick directory'));
expect(await screen.findByText(/no https:\/\/ origin/)).toBeInTheDocument();
fireEvent.click(screen.getByLabelText(/I understand/));
expect(screen.getByText('Import').closest('button')).toBeDisabled();
fireEvent.change(screen.getByLabelText(/^URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}});
expect(screen.getByText('Import').closest('button')).toBeEnabled();
});
it('explains a directory which cannot be imported', async () => {
inspectRepoImport.mockResolvedValue({error: 'code/kiwix-tools is not a git clone'});
renderImportPage();
fireEvent.click(screen.getByText('Pick directory'));
expect(await screen.findByText('code/kiwix-tools is not a git clone')).toBeInTheDocument();
expect(screen.queryByText('Import')).not.toBeInTheDocument();
});
it('says when the files are not indexed', async () => {
inspectRepoImport.mockResolvedValue({inspection: inspection({ignored: true})});
renderImportPage();
fireEvent.click(screen.getByText('Pick directory'));
expect(await screen.findByText(/Its files are not indexed/)).toBeInTheDocument();
});
});

View file

@ -1,17 +1,27 @@
import React, {useState} from "react"; import React, {useState} from "react";
import {Link, Route, Routes, useLocation, useNavigate} from "react-router"; import {Link, Route, Routes, useLocation, useNavigate} from "react-router";
import {FilesSearchView, SearchViewButton} from "./Files"; import {FilesSearchView, SearchViewButton} from "./Files";
import {useLatestRequest, usePages, useSearchChannels, useSearchDate, useSearchDeep, useSearchFilter} from "../hooks/customHooks"; import {
useLatestRequest,
usePages,
useSearchChannels,
useSearchDate,
useSearchDeep,
useSearchFilter,
useSearchCollections,
useSearchRepos,
} from "../hooks/customHooks";
import {ShortcutHint} from "./ShortcutHint"; import {ShortcutHint} from "./ShortcutHint";
import {ZimSearchView} from "./Zim"; import {ZimSearchView} from "./Zim";
import {MapSearchView} from "./MapSearchView"; import {MapSearchView} from "./MapSearchView";
import {searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions} from "../api"; import {searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions} from "../api";
import {filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common"; import {ErrorMessage, filterToMimetypes, fuzzyMatch, normalizeEstimate, SearchResultsInput, TabLinks} from "./Common";
import _ from "lodash"; import _ from "lodash";
import {TagsContext} from "../Tags"; import {TagsContext} from "../Tags";
import {Accordion, Header, Icon, Label, Loading, Panel, Stack} from "./ui"; import {Accordion, Header, Icon, Label, Loading, Panel, Stack} from "./ui";
import {QueryContext} from "../contexts/contexts"; import {QueryContext} from "../contexts/contexts";
import {KeyboardShortcutsContext} from "../contexts/KeyboardShortcutsContext"; import {KeyboardShortcutsContext} from "../contexts/KeyboardShortcutsContext";
import {HeadlineText} from "./Headline";
const SUGGESTED_APPS = [ const SUGGESTED_APPS = [
{location: '/admin', title: 'Downloads', description: 'View and control your downloads'}, {location: '/admin', title: 'Downloads', description: 'View and control your downloads'},
@ -39,11 +49,6 @@ const SUGGESTED_APPS = [
{location: '/videos/channel', title: 'Channels', description: 'View the Channels of your Videos'}, {location: '/videos/channel', title: 'Channels', description: 'View the Channels of your Videos'},
{location: '/zim', title: 'Zim', description: 'View your Zims'}, {location: '/zim', title: 'Zim', description: 'View your Zims'},
{location: '/zim/manage', title: 'Manage Zim', description: 'Manage your Zims'}, {location: '/zim/manage', title: 'Manage Zim', description: 'Manage your Zims'},
{
location: '/more/calculators?calc=temperature',
title: 'Temperature Calculator',
description: 'Convert Celsius, Fahrenheit, Kelvin'
},
{ {
location: '/more/calculators?calc=electrical', location: '/more/calculators?calc=electrical',
title: 'Electrical Calculator', title: 'Electrical Calculator',
@ -81,7 +86,9 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
// archive/video/doc/etc. // archive/video/doc/etc.
const model_ = searchParams.get('model') || model; const model_ = searchParams.get('model') || model;
const anySearch = (!datesIsEmpty) || searchStr || (activeTags && activeTags.length > 0) || filter || model; const anyTag = searchParams.get('anyTag') === 'true';
const anySearch = (!datesIsEmpty) || searchStr || (activeTags && activeTags.length > 0) || anyTag || filter
|| model;
const isEmpty = !anySearch; const isEmpty = !anySearch;
const setSearchStr = (value) => { const setSearchStr = (value) => {
@ -111,7 +118,6 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
setTags(newTags); setTags(newTags);
} }
const anyTag = searchParams.get('anyTag') === 'true';
const setAnyTag = (value) => { const setAnyTag = (value) => {
updateQuery({tag: [], anyTag: value ? 'true' : null}); updateQuery({tag: [], anyTag: value ? 'true' : null});
} }
@ -131,12 +137,15 @@ export const useSearch = (defaultLimit = 48, totalPages = 0, emptySearch = false
} }
export function useSuggestions(searchStr, tagNames, filter, anyTag) { export function useSuggestions(searchStr, tagNames, filter, anyTag) {
// The general groups are null until the suggestion request returns: an empty list means the
// server found none, and the dropdown may say "No results" only for that.
const defaultSuggestions = { const defaultSuggestions = {
fileGroups: [], fileGroups: [],
channels: [], channels: null,
domains: [], domains: null,
authors: [], authors: null,
subjects: [], subjects: null,
repos: null,
zimsEstimates: [], zimsEstimates: [],
} }
const [suggestions, setSuggestions] = React.useState(defaultSuggestions); const [suggestions, setSuggestions] = React.useState(defaultSuggestions);
@ -150,7 +159,8 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
const {data: mapData, sendRequest: sendMapRequest, loading: mapLoading} = useLatestRequest(500); const {data: mapData, sendRequest: sendMapRequest, loading: mapLoading} = useLatestRequest(500);
React.useEffect(() => { React.useEffect(() => {
if (searchStr || (tagNames && tagNames.length > 0)) { const hasTags = tagNames && tagNames.length > 0;
if (searchStr || hasTags || anyTag) {
const mimetypes = filterToMimetypes(filter); const mimetypes = filterToMimetypes(filter);
setSuggestions(defaultSuggestions); setSuggestions(defaultSuggestions);
if (searchStr && searchStr.length > 0) { if (searchStr && searchStr.length > 0) {
@ -160,8 +170,11 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
} }
// The files estimate always uses deep search server-side, so users know results are possible. // The files estimate always uses deep search server-side, so users know results are possible.
sendFilesRequest(async () => await searchEstimateFiles(searchStr, tagNames, mimetypes, months, dateRange, anyTag)); sendFilesRequest(async () => await searchEstimateFiles(searchStr, tagNames, mimetypes, months, dateRange, anyTag));
if (searchStr || hasTags) {
// Zims and the Other tab have no "any tag" search; they need a search string or tag names.
sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames)); sendZimRequest(async () => await searchEstimateZims(searchStr, tagNames));
sendOtherRequest(async () => await searchEstimateOthers(tagNames)); sendOtherRequest(async () => await searchEstimateOthers(tagNames, searchStr));
}
} }
}, [ }, [
searchStr, searchStr,
@ -183,6 +196,7 @@ export function useSuggestions(searchStr, tagNames, filter, anyTag) {
domains: generalData.domains, domains: generalData.domains,
authors: generalData.authors, authors: generalData.authors,
subjects: generalData.subjects, subjects: generalData.subjects,
repos: generalData.repos,
} }
}); });
} }
@ -310,6 +324,13 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
}) })
} }
} }
if (newSuggestions.repos && newSuggestions.repos.length > 0) {
results.repos = {
name: 'Repos', results: newSuggestions.repos.map(i => {
return {type: 'repo', title: i.name, id: i.id, location: `/repos/${i.id}`}
})
}
}
if (newSuggestions.authors && newSuggestions.authors.length > 0) { if (newSuggestions.authors && newSuggestions.authors.length > 0) {
results.authors = { results.authors = {
name: 'Authors', results: newSuggestions.authors.map(i => { name: 'Authors', results: newSuggestions.authors.map(i => {
@ -401,10 +422,11 @@ export function useSearchSuggestions(defaultSearchStr, defaultTagNames, anyTag)
zims: zimSum, zims: zimSum,
otherSum: otherSum, otherSum: otherSum,
mapPlaces: newSuggestions.mapPlaces || 0, mapPlaces: newSuggestions.mapPlaces || 0,
channels: newSuggestions.channels.length, channels: newSuggestions.channels?.length,
domains: newSuggestions.domains.length, domains: newSuggestions.domains?.length,
authors: newSuggestions.authors?.length, authors: newSuggestions.authors?.length,
subjects: newSuggestions.subjects?.length, subjects: newSuggestions.subjects?.length,
repos: newSuggestions.repos?.length,
tags: matchingTags?.length, tags: matchingTags?.length,
apps: matchingApps?.length, apps: matchingApps?.length,
}); });
@ -541,31 +563,99 @@ function SearchChannelPreview({channel}) {
</div> </div>
} }
function OtherSearchView({loading}) { function SearchCollectionPreview({collection, to}) {
const {searchParams} = React.useContext(QueryContext); const {SingleTag} = React.useContext(TagsContext);
const [activeValue, setActiveValue] = React.useState('channels'); return <div>
const activeTags = searchParams.getAll('tag'); <span style={{display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'}}>
const {channels, loading: channelsLoading} = useSearchChannels(activeTags); <Link to={to}>{collection.name}</Link>
{collection.tag_name && <SingleTag name={collection.tag_name}/>}
if (loading || channelsLoading) { </span>
return <Panel><Loading/></Panel> </div>
} }
return <Accordion value={activeValue} onChange={setActiveValue}> function SearchRepoPreview({repo}) {
<Accordion.Item value='channels'> const {SingleTag} = React.useContext(TagsContext);
return <div>
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'}}>
<Link to={`/repos/${repo.id}`}>{repo.name}</Link>
{repo.tag_name && <SingleTag name={repo.tag_name}/>}
</span>
{/* The server escapes the README; only its <b> highlights are markup. */}
{repo.readme_headline && <div><small><HeadlineText headline={repo.readme_headline}/></small></div>}
</div>
}
function OtherSearchSection({value, title, items, preview, emptyText, errorText}) {
let body;
if (items === null) {
body = <Loading/>;
} else if (items === undefined) {
body = <ErrorMessage>{errorText}</ErrorMessage>;
} else {
body = <Stack gap='xs'>{!_.isEmpty(items) ? items.map(preview) : emptyText}</Stack>;
}
return <Accordion.Item value={value}>
<Accordion.Control> <Accordion.Control>
<span style={{display: 'inline-flex', alignItems: 'center', gap: 8}}> <span style={{display: 'inline-flex', alignItems: 'center', gap: 8}}>
<Header as='h3' style={{margin: 0}}>Channels</Header> <Header as='h3' style={{margin: 0}}>{title}</Header>
<Label>{normalizeEstimate(channels.length)}</Label> {Array.isArray(items) && <Label>{normalizeEstimate(items.length)}</Label>}
</span> </span>
</Accordion.Control> </Accordion.Control>
<Accordion.Panel> <Accordion.Panel>{body}</Accordion.Panel>
<Stack gap='xs'>
{!_.isEmpty(channels) ?
channels.map(i => <SearchChannelPreview key={i.id} channel={i}/>)
: 'No Channels'}
</Stack>
</Accordion.Panel>
</Accordion.Item> </Accordion.Item>
}
// Each section's items follow useSearchChannels, useSearchCollections, or useSearchRepos: null = pending,
// undefined = fetch failed, [] = none.
export function OtherSearchView({loading}) {
const {searchParams} = React.useContext(QueryContext);
const [activeValues, setActiveValues] = React.useState(['channels', 'domains', 'playlists', 'repos']);
const activeTags = searchParams.getAll('tag');
const searchStr = searchParams.get('q') || '';
const {channels, loading: channelsLoading} = useSearchChannels(activeTags, searchStr);
const {collections: domains} = useSearchCollections('domain', searchStr, activeTags);
const {collections: playlists} = useSearchCollections('playlist', searchStr, activeTags);
const {repos} = useSearchRepos(searchStr, activeTags);
if (loading || channelsLoading || channels === null) {
return <Panel><Loading/></Panel>
} else if (channels === undefined) {
return <Panel><ErrorMessage>Could not fetch the channels.</ErrorMessage></Panel>
}
return <Accordion multiple value={activeValues} onChange={setActiveValues}>
<OtherSearchSection
value='channels'
title='Channels'
items={channels}
preview={i => <SearchChannelPreview key={i.id} channel={i}/>}
emptyText='No Channels'
errorText='Could not fetch the channels.'
/>
<OtherSearchSection
value='domains'
title='Domains'
items={domains}
preview={i => <SearchCollectionPreview key={i.id} collection={i}
to={`/archives?domain=${encodeURIComponent(i.name)}`}/>}
emptyText='No Domains'
errorText='Could not fetch the domains.'
/>
<OtherSearchSection
value='playlists'
title='Playlists'
items={playlists}
preview={i => <SearchCollectionPreview key={i.id} collection={i} to={`/playlists/${i.id}`}/>}
emptyText='No Playlists'
errorText='Could not fetch the playlists.'
/>
<OtherSearchSection
value='repos'
title='Repos'
items={repos}
preview={i => <SearchRepoPreview key={i.id} repo={i}/>}
emptyText='No Repos'
errorText='Could not fetch the repos.'
/>
</Accordion> </Accordion>
} }

View file

@ -94,6 +94,41 @@ describe('SearchFilterButton', () => {
expect(spy.mock.calls[0][0]).toMatchObject({order: '-size'}); expect(spy.mock.calls[0][0]).toMatchObject({order: '-size'});
}); });
it('Rank always sorts the most relevant first, and has no direction', async () => {
const rankOrders = [{value: 'rank', text: 'Rank'}, ...videoOrders];
const spy = jest.fn();
// The previous sort was descending; Rank must not inherit it as `-rank` (least relevant first).
renderButton({sorts: rankOrders}, {order: '-size'}, spy);
fireEvent.click(screen.getByText('Filter'));
fireEvent.click(await screen.findByText('Rank'));
expect(screen.queryByText('Descending')).toBeNull();
expect(screen.queryByText('Ascending')).toBeNull();
fireEvent.click(screen.getByText('Done'));
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.mock.calls[0][0]).toMatchObject({order: 'rank'});
});
it('Done rewrites an old `-rank` link to the most relevant first', async () => {
const rankOrders = [{value: 'rank', text: 'Rank'}, ...videoOrders];
const spy = jest.fn();
renderButton({sorts: rankOrders}, {order: '-rank'}, spy);
fireEvent.click(screen.getByText('Filter'));
fireEvent.click(await screen.findByText('Done'));
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.mock.calls[0][0]).toMatchObject({order: 'rank'});
});
it('a sort chosen after Rank is descending', async () => {
const rankOrders = [{value: 'rank', text: 'Rank'}, ...videoOrders];
const spy = jest.fn();
renderButton({sorts: rankOrders}, {order: 'rank'}, spy);
fireEvent.click(screen.getByText('Filter'));
fireEvent.click(await screen.findByText('Size'));
expect(screen.getByText('Descending')).toBeInTheDocument();
fireEvent.click(screen.getByText('Done'));
expect(spy.mock.calls[0][0]).toMatchObject({order: '-size'});
});
it('Clear All resets results-per-page to the default on close', async () => { it('Clear All resets results-per-page to the default on close', async () => {
const spy = jest.fn(); const spy = jest.fn();
renderButton({sorts: videoOrders}, {l: '96'}, spy); renderButton({sorts: videoOrders}, {l: '96'}, spy);

View file

@ -0,0 +1,159 @@
import React from 'react';
import {act, render, screen} from '../test-utils';
import {useSearchSuggestions} from './Search';
import {TagsContext} from '../Tags';
import {tagsContextFixture} from '../test-fixtures';
import {
searchEstimateFiles, searchEstimateMap, searchEstimateOthers, searchEstimateZims, searchSuggestions,
} from '../api';
// The global search dropdown's groups are built from useSuggestions. A "Channels: No results" row
// may only appear once the suggestion request has come back empty, never before the user has
// typed, and never while the request is pending.
jest.mock('../api', () => ({
...jest.requireActual('../api'),
searchSuggestions: jest.fn(),
searchEstimateFiles: jest.fn(),
searchEstimateMap: jest.fn(),
searchEstimateOthers: jest.fn(),
searchEstimateZims: jest.fn(),
}));
const DEBOUNCE = 500;
const pending = () => new Promise(() => {
});
let hook;
function Probe() {
hook = useSearchSuggestions('', [], false);
return <pre data-testid='results'>{JSON.stringify(hook.suggestionsResults)}</pre>;
}
const results = () => JSON.parse(screen.getByTestId('results').textContent);
const renderProbe = () => render(<Probe/>, {
contexts: [[TagsContext, tagsContextFixture({fuzzyMatchTagsByName: () => []})]],
});
beforeEach(() => {
jest.useFakeTimers();
searchEstimateFiles.mockReturnValue(pending());
searchEstimateMap.mockReturnValue(pending());
searchEstimateOthers.mockReturnValue(pending());
searchEstimateZims.mockReturnValue(pending());
});
afterEach(() => {
jest.useRealTimers();
jest.clearAllMocks();
});
test('no Channels group before anything has been searched', () => {
searchSuggestions.mockReturnValue(pending());
renderProbe();
expect(results().channels).toBeUndefined();
});
test('no Channels group while the suggestion request is pending', () => {
searchSuggestions.mockReturnValue(pending());
renderProbe();
act(() => {
hook.setSearchStr('foo');
});
expect(results().channels).toBeUndefined();
act(() => {
jest.advanceTimersByTime(DEBOUNCE);
});
expect(searchSuggestions).toHaveBeenCalledWith('foo');
expect(results().channels).toBeUndefined();
expect(hook.loading).toBe(true);
});
test('a Channels "No results" row once the server said there are none', async () => {
let resolve;
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
renderProbe();
act(() => {
hook.setSearchStr('foo');
});
act(() => {
jest.advanceTimersByTime(DEBOUNCE);
});
await act(async () => {
resolve({channels: [], domains: [], authors: [], subjects: []});
});
expect(results().channels.results).toEqual([{title: 'No results'}]);
});
test('Channels rows once the server found some', async () => {
let resolve;
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
renderProbe();
act(() => {
hook.setSearchStr('foo');
});
act(() => {
jest.advanceTimersByTime(DEBOUNCE);
});
await act(async () => {
resolve({channels: [{id: 3, name: 'Food'}], domains: [], authors: [], subjects: []});
});
expect(results().channels.results.map(i => i.title)).toEqual(['Food']);
});
test('Repos rows link to each repo, and the Other estimate gets the search', async () => {
let resolve;
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
renderProbe();
act(() => {
hook.setSearchStr('kiwix');
});
act(() => {
jest.advanceTimersByTime(DEBOUNCE);
});
await act(async () => {
resolve({channels: [], domains: [], authors: [], subjects: [], repos: [{id: 4, name: 'kiwix-tools'}]});
});
expect(results().repos.results).toEqual([{type: 'repo', title: 'kiwix-tools', id: 4, location: '/repos/4'}]);
// Repos count toward the Other tab by their name and README, not only by tag.
expect(searchEstimateOthers).toHaveBeenCalledWith([], 'kiwix');
});
test('no Repos group when none match', async () => {
let resolve;
searchSuggestions.mockReturnValue(new Promise(res => resolve = res));
renderProbe();
act(() => {
hook.setSearchStr('foo');
});
act(() => {
jest.advanceTimersByTime(DEBOUNCE);
});
await act(async () => {
resolve({channels: [], domains: [], authors: [], subjects: [], repos: []});
});
expect(results().repos).toBeUndefined();
});
function AnyTagProbe() {
hook = useSearchSuggestions('', [], true);
return null;
}
test('Any Tag alone counts the tagged files, without a search string', () => {
render(<AnyTagProbe/>, {
contexts: [[TagsContext, tagsContextFixture({fuzzyMatchTagsByName: () => []})]],
});
act(() => {
jest.advanceTimersByTime(DEBOUNCE);
});
expect(searchEstimateFiles).toHaveBeenCalledTimes(1);
expect(searchEstimateFiles.mock.calls[0][5]).toBe(true);
// Zims and the Other tab cannot search by "any tag"; without a search string they have nothing to count.
expect(searchEstimateZims).not.toHaveBeenCalled();
expect(searchEstimateOthers).not.toHaveBeenCalled();
expect(searchSuggestions).not.toHaveBeenCalled();
});

Some files were not shown because too many files have changed in this diff Show more