Let the owner change regions by place name, without a restart

The p2p node can now add and drop regions while running (SetRegions):
topics, validators, subscriptions and per-region peer discovery start and
stop with them, and a newly followed region catches up by sync.

PUT /api/v1/regions (owner token) applies a change and the node saves it in
regions.json, which wins over --region from then on. The owner's browser
gets a "Regions" page: search a place by name (GeoNames cities, offline,
CC BY 4.0), follow its cell plus any cell within about 40 km.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 10:28:16 +01:00
co-authored by Claude Sonnet 5.5
parent e7bec4fb63
commit fd439710df
24 changed files with 70080 additions and 42 deletions
+16
View File
@@ -28,6 +28,14 @@ Owners publish from the same screen: "New listing" takes a title, price and
pasted coordinates (only a ~1 km area is published, never the address), and pasted coordinates (only a ~1 km area is published, never the address), and
listings can be edited, renewed (30 days, manually) or deleted there. listings can be edited, renewed (30 days, manually) or deleted there.
**Regions** are the areas a node keeps listings for (3-character geohash cells,
about 100 to 150 km wide). `--region` sets them the first time. After that the
owner changes them in the browser: "My listings", then "Regions". Search a place
by name (Bonn, Cologne, München, …); the page offers the place's own cell and any
cell within about 40 km, and the change applies at once, without a restart. The
choice is kept in `regions.json` in the data directory and wins over `--region`
from then on (delete the file to go back to the flag).
Nodes find each other through a bootstrap list in DNS (`allmende.stinnesbeck.com`), Nodes find each other through a bootstrap list in DNS (`allmende.stinnesbeck.com`),
the peers they met last time, a DHT per region, and mDNS on the local network. the peers they met last time, a DHT per region, and mDNS on the local network.
Add your own bootstrap peers with `--bootstrap /ip4/<addr>/tcp/<port>/p2p/<peer id>` Add your own bootstrap peers with `--bootstrap /ip4/<addr>/tcp/<port>/p2p/<peer id>`
@@ -91,3 +99,11 @@ needs. `nix flake check` builds the package and boots a NixOS VM that tests the
module. After changing `go.mod`, update `vendorHash` in `nix/package.nix`. module. After changing `go.mod`, update `vendorHash` in `nix/package.nix`.
Licensed under the [GNU AGPL-3.0](LICENSE): free for everyone, and it stays free. Licensed under the [GNU AGPL-3.0](LICENSE): free for everyone, and it stays free.
## Third-party data
The place names the region picker searches (`web/static/places.tsv`) come from
[GeoNames](https://www.geonames.org/) (cities with more than 15,000 inhabitants),
licensed [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), with a few
German names added by hand. `web/scripts/places.mjs` rebuilds the file from
GeoNames' `cities15000.txt`. The page credits GeoNames wherever places are searched.
+87
View File
@@ -0,0 +1,87 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/p2p"
)
// regionsFile remembers the regions an owner chose in the browser. Once it
// exists it decides which regions the node follows; --region only seeds it.
const regionsFile = "regions.json"
// loadRegions returns the regions saved in dir; ok is false if none were saved.
func loadRegions(dir string) (regions []string, ok bool, err error) {
data, err := os.ReadFile(filepath.Join(dir, regionsFile))
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
var f struct {
Regions []string `json:"regions"`
}
if err := json.Unmarshal(data, &f); err != nil {
return nil, false, fmt.Errorf("%s: %w", regionsFile, err)
}
for _, r := range f.Regions {
if !listing.ValidRegion(r) {
return nil, false, fmt.Errorf("%s: %q is not a region", regionsFile, r)
}
}
return f.Regions, len(f.Regions) > 0, nil
}
// saveRegions writes the regions so a restart keeps them. The file is replaced
// whole, so a crash never leaves half of one.
func saveRegions(dir string, regions []string) error {
data, err := json.MarshalIndent(map[string][]string{"regions": regions}, "", " ")
if err != nil {
return err
}
tmp, err := os.CreateTemp(dir, regionsFile+".*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), filepath.Join(dir, regionsFile))
}
// regionKeeper applies a change of regions to the running node and saves it.
type regionKeeper struct {
node *p2p.Node
dir string
mu sync.Mutex // one change at a time
}
func (k *regionKeeper) Regions() []string { return k.node.Regions() }
func (k *regionKeeper) SetRegions(regions []string) error {
k.mu.Lock()
defer k.mu.Unlock()
before := k.node.Regions()
if err := k.node.SetRegions(regions); err != nil {
return err
}
if err := saveRegions(k.dir, regions); err != nil {
// Not remembered means the change would silently vanish at the next
// start: undo it instead.
k.node.SetRegions(before)
return err
}
return nil
}
+58
View File
@@ -0,0 +1,58 @@
package main
import (
"os"
"path/filepath"
"reflect"
"testing"
)
func TestRegionsAreSavedAndLoaded(t *testing.T) {
dir := t.TempDir()
if _, ok, err := loadRegions(dir); ok || err != nil {
t.Fatalf("nothing saved yet: ok=%v err=%v", ok, err)
}
want := []string{"u1j", "u1x"}
if err := saveRegions(dir, want); err != nil {
t.Fatal(err)
}
got, ok, err := loadRegions(dir)
if err != nil || !ok || !reflect.DeepEqual(got, want) {
t.Fatalf("loaded %v ok=%v err=%v, want %v", got, ok, err, want)
}
// Saving again replaces the file whole and leaves no temporary files.
if err := saveRegions(dir, []string{"u30"}); err != nil {
t.Fatal(err)
}
if got, _, _ := loadRegions(dir); !reflect.DeepEqual(got, []string{"u30"}) {
t.Fatalf("after replacing: %v", got)
}
entries, _ := os.ReadDir(dir)
if len(entries) != 1 {
t.Fatalf("stray files: %v", entries)
}
}
func TestBrokenRegionFilesAreReportedNotIgnored(t *testing.T) {
for name, content := range map[string]string{
"not json": "u1j",
"not a region": `{"regions":["u1j","hello"]}`,
"empty regions": `{"regions":[]}`,
} {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, regionsFile), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
_, ok, err := loadRegions(dir)
switch name {
case "empty regions":
if ok || err != nil {
t.Errorf("%s: ok=%v err=%v, want it treated as not set", name, ok, err)
}
default:
if err == nil {
t.Errorf("%s: no error, a broken file must not silently change what the node follows", name)
}
}
}
}
+15
View File
@@ -11,6 +11,7 @@ import (
"os" "os"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"syscall" "syscall"
"time" "time"
@@ -52,6 +53,19 @@ func cmdRun(args []string) error {
"how many new conversations each of your listings can start per day") "how many new conversations each of your listings can start per day")
fs.Parse(args) fs.Parse(args)
// Regions the owner chose in the browser win over --region, which then only
// says where a node starts the first time.
saved, ok, err := loadRegions(*data)
if err != nil {
return err
}
if ok {
if len(regions) > 0 && !slices.Equal(regions, saved) {
slog.Info("using the regions chosen in the browser, not --region; delete "+regionsFile+" to use --region again",
"regions", saved)
}
regions = saved
}
// A bootstrap node may follow no region: it then only helps others connect. // A bootstrap node may follow no region: it then only helps others connect.
if len(regions) == 0 && !*public { if len(regions) == 0 && !*public {
return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)") return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)")
@@ -120,6 +134,7 @@ func cmdRun(args []string) error {
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty, Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
MessageDifficulty: *msgDifficulty, MessageDifficulty: *msgDifficulty,
Inbox: in, Inbox: in,
RegionKeeper: &regionKeeper{node: node, dir: *data},
}) })
ln, err := net.Listen("tcp", *httpAddr) ln, err := net.Listen("tcp", *httpAddr)
+60 -1
View File
@@ -14,6 +14,7 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"slices"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -49,6 +50,26 @@ type Config struct {
// Inbox is the owner's conversations. Without it the owner endpoints are // Inbox is the owner's conversations. Without it the owner endpoints are
// absent; relaying messages for buyers still works. // absent; relaying messages for buyers still works.
Inbox *inbox.Inbox Inbox *inbox.Inbox
// RegionKeeper lets the owner change the regions the node follows while it
// runs. Without it Regions is fixed and the endpoint is absent.
RegionKeeper RegionKeeper
}
// RegionKeeper holds the regions a node follows: it applies and remembers a change.
type RegionKeeper interface {
Regions() []string
SetRegions([]string) error
}
// MaxRegions is how many regions one node may follow: it replicates everything
// in them, so this keeps "follow the world" from being one click.
const MaxRegions = 20
func (s *server) regions() []string {
if s.RegionKeeper != nil {
return s.RegionKeeper.Regions()
}
return s.Regions
} }
type server struct { type server struct {
@@ -72,6 +93,9 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create)) mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update)) mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove)) mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
if cfg.RegionKeeper != nil {
mux.HandleFunc("PUT /api/v1/regions", s.admin(s.putRegions))
}
// Messaging: public relay endpoints for buyers' browsers... // Messaging: public relay endpoints for buyers' browsers...
mux.HandleFunc("POST /api/v1/messages", s.postMessage) mux.HandleFunc("POST /api/v1/messages", s.postMessage)
@@ -131,7 +155,7 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
"addrs": s.Node.Addrs(), "addrs": s.Node.Addrs(),
"author": s.Device.Cert.Author, "author": s.Device.Cert.Author,
"device": s.Device.Cert.Device, "device": s.Device.Cert.Device,
"regions": s.Regions, "regions": s.regions(),
"peers": s.Node.PeerCount(), "peers": s.Node.PeerCount(),
"listings": n, "listings": n,
// Lets the browser report how much anti-spam work a listing carries. // Lets the browser report how much anti-spam work a listing carries.
@@ -266,6 +290,41 @@ func (s *server) admin(next http.HandlerFunc) http.HandlerFunc {
} }
} }
// putRegions changes the regions the node follows, at once and for good.
func (s *server) putRegions(w http.ResponseWriter, r *http.Request) {
var body struct {
Regions []string `json:"regions"`
}
if !decodeBody(w, r, &body) {
return
}
var regions []string
for _, raw := range body.Regions {
region := strings.ToLower(strings.TrimSpace(raw))
if !listing.ValidRegion(region) {
fail(w, http.StatusBadRequest, fmt.Sprintf(
"%q is not a region: use %d geohash characters, e.g. u1j for Bonn", raw, listing.RegionPrecision))
return
}
if !slices.Contains(regions, region) {
regions = append(regions, region)
}
}
switch {
case len(regions) == 0:
fail(w, http.StatusBadRequest, "choose at least one region")
return
case len(regions) > MaxRegions:
fail(w, http.StatusBadRequest, fmt.Sprintf("that is too many regions (at most %d)", MaxRegions))
return
}
if err := s.RegionKeeper.SetRegions(regions); err != nil {
fail(w, http.StatusInternalServerError, "could not change the regions: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"regions": s.RegionKeeper.Regions()})
}
func (s *server) readDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) { func (s *server) readDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody)) dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
dec.DisallowUnknownFields() dec.DisallowUnknownFields()
+73
View File
@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors"
"io" "io"
"log/slog" "log/slog"
"net/http" "net/http"
@@ -300,3 +301,75 @@ func TestStatus(t *testing.T) {
t.Fatal("status must never expose the admin token") t.Fatal("status must never expose the admin token")
} }
} }
// keeper is a RegionKeeper that follows the node's real regions.
type keeper struct {
node *p2p.Node
fail error
}
func (k *keeper) Regions() []string { return k.node.Regions() }
func (k *keeper) SetRegions(r []string) error {
if k.fail != nil {
return k.fail
}
return k.node.SetRegions(r)
}
func TestOwnerChangesTheRegions(t *testing.T) {
k := &keeper{}
f := newFixture(t, token, func(c *Config) {
k.node = c.Node
c.RegionKeeper = k
})
regions := func() []string {
_, body := f.do(t, "GET", "/api/v1/status", "", false)
var st struct {
Regions []string `json:"regions"`
}
_ = json.Unmarshal(body, &st)
return st.Regions
}
if got := regions(); len(got) != 1 || got[0] != "u1x" {
t.Fatalf("regions = %v", got)
}
if code, _ := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, false); code != 401 {
t.Fatalf("without the token: %d, want 401", code)
}
code, body := f.do(t, "PUT", "/api/v1/regions", `{"regions":[" U1J ","u1x","u1j"]}`, true)
if code != 200 {
t.Fatalf("PUT: %d %s", code, body)
}
if got := regions(); len(got) != 2 || got[0] != "u1x" || got[1] != "u1j" {
t.Fatalf("regions after the change (case and repeats tidied) = %v", got)
}
for name, tc := range map[string]struct{ body, want string }{
"not a region": {`{"regions":["u1j","nope"]}`, "not a region"},
"none": {`{"regions":[]}`, "at least one"},
"unknown field": {`{"regions":["u1j"],"x":1}`, "invalid JSON"},
"too many": {`{"regions":["u00","u01","u02","u03","u04","u05","u06","u07","u08","u09","u0b",` +
`"u0c","u0d","u0e","u0f","u0g","u0h","u0j","u0k","u0m","u0n"]}`, "too many"},
} {
code, body := f.do(t, "PUT", "/api/v1/regions", tc.body, true)
if code != 400 || !strings.Contains(string(body), tc.want) {
t.Errorf("%s: %d %s, want 400 containing %q", name, code, body, tc.want)
}
}
if got := regions(); len(got) != 2 {
t.Fatalf("a refused change must change nothing, regions = %v", got)
}
k.fail = errors.New("disk full")
if code, body := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, true); code != 500 || !strings.Contains(string(body), "disk full") {
t.Fatalf("a failing keeper: %d %s", code, body)
}
}
func TestRegionsCannotBeChangedWithoutAKeeper(t *testing.T) {
f := newFixture(t, token)
if code, _ := f.do(t, "PUT", "/api/v1/regions", `{"regions":["u1j"]}`, true); code == 200 {
t.Fatal("regions changed on a node that has no keeper")
}
}
+31 -15
View File
@@ -41,15 +41,28 @@ func (n *Node) startDiscovery() error {
} }
n.dht = d n.dht = d
rd := drouting.NewRoutingDiscovery(d) rd := drouting.NewRoutingDiscovery(d)
for _, r := range n.cfg.Regions { n.mu.Lock()
ns := regionNamespace + r n.rd = rd
n.wg.Add(2) runs := make(map[string]*regionRun, len(n.regions))
go n.advertise(rd, ns) for r, run := range n.regions {
go n.findPeers(rd, r, ns) runs[r] = run
}
n.mu.Unlock()
for r, run := range runs {
n.discoverRegion(run.ctx, rd, r)
} }
return nil return nil
} }
// discoverRegion advertises this node under the region and looks for others,
// until ctx ends (the region is dropped or the node stops).
func (n *Node) discoverRegion(ctx context.Context, rd *drouting.RoutingDiscovery, region string) {
ns := regionNamespace + region
n.wg.Add(2)
go n.advertise(ctx, rd, ns)
go n.findPeers(ctx, rd, region, ns)
}
func (n *Node) discoverInterval() time.Duration { func (n *Node) discoverInterval() time.Duration {
if n.cfg.DiscoverInterval > 0 { if n.cfg.DiscoverInterval > 0 {
return n.cfg.DiscoverInterval return n.cfg.DiscoverInterval
@@ -58,11 +71,14 @@ func (n *Node) discoverInterval() time.Duration {
} }
// sleep waits for d or until the node stops; false means it stopped. // sleep waits for d or until the node stops; false means it stopped.
func (n *Node) sleep(d time.Duration) bool { func (n *Node) sleep(d time.Duration) bool { return sleepCtx(n.ctx, d) }
// sleepCtx waits for d or until ctx ends; false means it ended.
func sleepCtx(ctx context.Context, d time.Duration) bool {
t := time.NewTimer(d) t := time.NewTimer(d)
defer t.Stop() defer t.Stop()
select { select {
case <-n.ctx.Done(): case <-ctx.Done():
return false return false
case <-t.C: case <-t.C:
return true return true
@@ -71,16 +87,16 @@ func (n *Node) sleep(d time.Duration) bool {
// advertise keeps this node findable under the region's name. Until the // advertise keeps this node findable under the region's name. Until the
// routing table has a peer in it there is nowhere to publish, so it retries. // routing table has a peer in it there is nowhere to publish, so it retries.
func (n *Node) advertise(rd *drouting.RoutingDiscovery, ns string) { func (n *Node) advertise(rctx context.Context, rd *drouting.RoutingDiscovery, ns string) {
defer n.wg.Done() defer n.wg.Done()
back := n.backoff() back := n.backoff()
for { for {
wait := back.next() wait := back.next()
ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second) ctx, cancel := context.WithTimeout(rctx, 30*time.Second)
ttl, err := rd.Advertise(ctx, ns) ttl, err := rd.Advertise(ctx, ns)
cancel() cancel()
switch { switch {
case n.ctx.Err() != nil: case rctx.Err() != nil:
return return
case err != nil: case err != nil:
n.log.Debug("advertise", "ns", ns, "err", err) // retried soon, then less often n.log.Debug("advertise", "ns", ns, "err", err) // retried soon, then less often
@@ -89,7 +105,7 @@ func (n *Node) advertise(rd *drouting.RoutingDiscovery, ns string) {
wait = ttl * 3 / 4 // refresh before the record lapses wait = ttl * 3 / 4 // refresh before the record lapses
back.reset() back.reset()
} }
if !n.sleep(wait) { if !sleepCtx(rctx, wait) {
return return
} }
} }
@@ -120,22 +136,22 @@ func (b *backoff) bump() {
} }
// findPeers connects to other nodes of the region that the DHT knows. // findPeers connects to other nodes of the region that the DHT knows.
func (n *Node) findPeers(rd *drouting.RoutingDiscovery, region, ns string) { func (n *Node) findPeers(rctx context.Context, rd *drouting.RoutingDiscovery, region, ns string) {
defer n.wg.Done() defer n.wg.Done()
back := n.backoff() back := n.backoff()
for { for {
if !n.sleep(back.next()) { if !sleepCtx(rctx, back.next()) {
return return
} }
back.bump() back.bump()
if len(n.RegionPeers(region)) >= enoughRegionPeers { if len(n.RegionPeers(region)) >= enoughRegionPeers {
continue continue
} }
ctx, cancel := context.WithTimeout(n.ctx, 30*time.Second) ctx, cancel := context.WithTimeout(rctx, 30*time.Second)
found, err := rd.FindPeers(ctx, ns, discovery.Limit(findLimit)) found, err := rd.FindPeers(ctx, ns, discovery.Limit(findLimit))
if err != nil { if err != nil {
cancel() cancel()
if n.ctx.Err() == nil { if rctx.Err() == nil {
n.log.Debug("find peers", "ns", ns, "err", err) n.log.Debug("find peers", "ns", ns, "err", err)
} }
continue continue
+105 -5
View File
@@ -17,6 +17,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"slices"
"sync" "sync"
"time" "time"
@@ -28,6 +29,7 @@ import (
"github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/discovery/mdns" "github.com/libp2p/go-libp2p/p2p/discovery/mdns"
drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing"
"github.com/libp2p/go-libp2p/p2p/host/autorelay" "github.com/libp2p/go-libp2p/p2p/host/autorelay"
madns "github.com/multiformats/go-multiaddr-dns" madns "github.com/multiformats/go-multiaddr-dns"
@@ -104,6 +106,8 @@ type Node struct {
topics map[string]*pubsub.Topic topics map[string]*pubsub.Topic
msgTopics map[string]*pubsub.Topic msgTopics map[string]*pubsub.Topic
subscribed []string subscribed []string
regions map[string]*regionRun
rd *drouting.RoutingDiscovery // nil without a DHT
boot *bootstrapper boot *bootstrapper
dht *dht.IpfsDHT dht *dht.IpfsDHT
syncing map[peer.ID]bool syncing map[peer.ID]bool
@@ -184,6 +188,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
cancel: cancel, cancel: cancel,
topics: map[string]*pubsub.Topic{}, topics: map[string]*pubsub.Topic{},
msgTopics: map[string]*pubsub.Topic{}, msgTopics: map[string]*pubsub.Topic{},
regions: map[string]*regionRun{},
syncing: map[peer.ID]bool{}, syncing: map[peer.ID]bool{},
boot: boot, boot: boot,
} }
@@ -356,7 +361,7 @@ func (n *Node) startRevocations() error {
n.wg.Add(1) n.wg.Add(1)
go func() { go func() {
defer n.wg.Done() defer n.wg.Done()
n.consume(sub, func(msg *pubsub.Message) { n.consume(n.ctx, sub, func(msg *pubsub.Message) {
r, ok := msg.ValidatorData.(*identity.Revocation) r, ok := msg.ValidatorData.(*identity.Revocation)
if !ok { if !ok {
return return
@@ -369,6 +374,90 @@ func (n *Node) startRevocations() error {
return nil return nil
} }
// regionRun is what a followed region keeps running; dropping the region stops it.
type regionRun struct {
ctx context.Context
cancel context.CancelFunc
subs []*pubsub.Subscription
}
// Regions lists the regions this node follows now, in the order they were added.
func (n *Node) Regions() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.subscribed...)
}
// SetRegions makes the node follow exactly these regions, without a restart:
// new ones are joined (and peers looked for), dropped ones are left. Listings
// already stored stay stored. Nothing changes if a region is invalid.
func (n *Node) SetRegions(regions []string) error {
want := make([]string, 0, len(regions))
for _, r := range regions {
if !listing.ValidRegion(r) {
return fmt.Errorf("p2p: invalid region %q (want %d geohash characters)", r, listing.RegionPrecision)
}
if !slices.Contains(want, r) {
want = append(want, r)
}
}
have := n.Regions()
added := false
for _, r := range want {
if !slices.Contains(have, r) {
if err := n.subscribeRegion(r); err != nil {
return err
}
added = true
}
}
if added {
// What was published before is not gossiped again: ask the peers we
// already know for what they hold in the new regions.
for _, p := range n.host.Network().Peers() {
n.syncSoon(p)
}
}
for _, r := range have {
if !slices.Contains(want, r) {
n.unsubscribeRegion(r)
}
}
return nil
}
func (n *Node) unsubscribeRegion(region string) {
n.mu.Lock()
run := n.regions[region]
delete(n.regions, region)
n.subscribed = slices.DeleteFunc(n.subscribed, func(r string) bool { return r == region })
listings, messages := n.topics[region], n.msgTopics[region]
delete(n.topics, region)
delete(n.msgTopics, region)
n.mu.Unlock()
if run == nil {
return
}
run.cancel()
for _, s := range run.subs {
s.Cancel()
}
for name, t := range map[string]*pubsub.Topic{
listingTopicPrefix + region: listings,
messageTopicPrefix + region: messages,
} {
if t == nil {
continue
}
if err := t.Close(); err != nil {
n.log.Debug("leave topic", "topic", name, "err", err)
}
if err := n.ps.UnregisterTopicValidator(name); err != nil {
n.log.Debug("remove validator", "topic", name, "err", err)
}
}
}
func (n *Node) subscribeRegion(region string) error { func (n *Node) subscribeRegion(region string) error {
t, err := n.regionTopic(region) t, err := n.regionTopic(region)
if err != nil { if err != nil {
@@ -378,13 +467,20 @@ func (n *Node) subscribeRegion(region string) error {
if err != nil { if err != nil {
return err return err
} }
rctx, cancel := context.WithCancel(n.ctx)
run := &regionRun{ctx: rctx, cancel: cancel, subs: []*pubsub.Subscription{sub}}
n.mu.Lock() n.mu.Lock()
n.subscribed = append(n.subscribed, region) n.subscribed = append(n.subscribed, region)
n.regions[region] = run
rd := n.rd
n.mu.Unlock() n.mu.Unlock()
if rd != nil {
n.discoverRegion(rctx, rd, region)
}
n.wg.Add(1) n.wg.Add(1)
go func() { go func() {
defer n.wg.Done() defer n.wg.Done()
n.consume(sub, func(msg *pubsub.Message) { n.consume(rctx, sub, func(msg *pubsub.Message) {
l, ok := msg.ValidatorData.(*listing.Listing) l, ok := msg.ValidatorData.(*listing.Listing)
if !ok { if !ok {
return return
@@ -405,10 +501,13 @@ func (n *Node) subscribeRegion(region string) error {
if err != nil { if err != nil {
return err return err
} }
n.mu.Lock()
run.subs = append(run.subs, msub)
n.mu.Unlock()
n.wg.Add(1) n.wg.Add(1)
go func() { go func() {
defer n.wg.Done() defer n.wg.Done()
n.consume(msub, func(msg *pubsub.Message) { n.consume(rctx, msub, func(msg *pubsub.Message) {
e, ok := msg.ValidatorData.(*message.Envelope) e, ok := msg.ValidatorData.(*message.Envelope)
if !ok { if !ok {
return return
@@ -469,9 +568,10 @@ func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
return t, nil return t, nil
} }
func (n *Node) consume(sub *pubsub.Subscription, handle func(*pubsub.Message)) { // consume handles what arrives on sub until ctx ends or the subscription is cancelled.
func (n *Node) consume(ctx context.Context, sub *pubsub.Subscription, handle func(*pubsub.Message)) {
for { for {
msg, err := sub.Next(n.ctx) msg, err := sub.Next(ctx)
if err != nil { if err != nil {
return return
} }
+61
View File
@@ -324,3 +324,64 @@ func TestBadBootstrapAddressRejectedUpFront(t *testing.T) {
t.Fatal("malformed bootstrap address accepted") t.Fatal("malformed bootstrap address accepted")
} }
} }
func TestRegionsChangeWhileRunning(t *testing.T) {
a := startNode(t, nil, "u1x")
b := startNode(t, nil, "u30")
connect(t, b, a)
first := a.listing(t, "u1xjhx")
if err := a.Publish(context.Background(), first); err != nil {
t.Fatal(err)
}
time.Sleep(500 * time.Millisecond)
if count(b) != 0 {
t.Fatal("b received a listing of a region it does not follow")
}
// Following u1x as well: what was published before arrives by sync, what
// is published from now on by gossip.
if err := b.SetRegions([]string{"u30", "u1x", "u1x"}); err != nil {
t.Fatal(err)
}
if got := b.Regions(); len(got) != 2 || got[0] != "u30" || got[1] != "u1x" {
t.Fatalf("regions = %v", got)
}
eventually(t, "b catches up on u1x", func() bool { return count(b) == 1 })
eventually(t, "a sees b on the u1x topic", func() bool { return len(a.RegionPeers("u1x")) == 1 })
if err := a.Publish(context.Background(), a.listing(t, "u1xjhy")); err != nil {
t.Fatal(err)
}
eventually(t, "b receives gossip of the new region", func() bool { return count(b) == 2 })
// Dropping it again: b leaves the topic, nothing more arrives, and what
// was stored stays.
if err := b.SetRegions([]string{"u30"}); err != nil {
t.Fatal(err)
}
if got := b.Regions(); len(got) != 1 || got[0] != "u30" {
t.Fatalf("regions = %v", got)
}
eventually(t, "a no longer sees b on u1x", func() bool { return len(a.RegionPeers("u1x")) == 0 })
if err := a.Publish(context.Background(), a.listing(t, "u1xjhz")); err != nil {
t.Fatal(err)
}
time.Sleep(500 * time.Millisecond)
if count(b) != 2 {
t.Fatalf("b has %d listings, want the 2 it had", count(b))
}
// And back: the region can be followed again.
if err := b.SetRegions([]string{"u30", "u1x"}); err != nil {
t.Fatal(err)
}
eventually(t, "b follows u1x again and catches up", func() bool { return count(b) == 3 })
// Nothing changes on a bad region.
if err := b.SetRegions([]string{"u1x", "no"}); err == nil {
t.Fatal("an invalid region was accepted")
}
if got := b.Regions(); len(got) != 2 {
t.Fatalf("regions changed to %v", got)
}
}
+382 -20
View File
@@ -212,6 +212,31 @@ var de = {
"own.login": "Anmelden", "own.login": "Anmelden",
"own.loginBad": "Der Knoten hat den Token abgelehnt.", "own.loginBad": "Der Knoten hat den Token abgelehnt.",
"own.logout": "Abmelden", "own.logout": "Abmelden",
"reg.title": "Regionen",
"reg.intro": "Dein Knoten h\xE4lt die Anzeigen dieser Regionen bereit und gibt sie an andere weiter. Suche einen Ort, zum Beispiel Bonn oder Hamburg. Die \xC4nderung gilt sofort und bleibt nach einem Neustart erhalten.",
"reg.search": "Ort suchen",
"reg.placeholder": "z. B. Bonn, K\xF6ln, Hamburg",
"reg.results": "Gefundene Orte",
"reg.none": "Dazu habe ich keinen Ort gefunden. Pr\xFCfe die Schreibweise, oder gib unten ein Regionsk\xFCrzel ein.",
"reg.noPlaces": "Die Ortsliste konnte nicht geladen werden. Du kannst unten Regionsk\xFCrzel eingeben.",
"reg.cellsTitle": "Regionen rund um {place}",
"reg.cellsHelp": "Eine Region ist ein Gebiet von etwa 100 bis 150 km Breite. Liegt der Ort nahe am Rand, kommt die Nachbarregion dazu, damit dir Anzeigen gleich hinter der Grenze nicht fehlen. Nimm den Haken heraus, was du nicht brauchst.",
"reg.here": "hier",
"reg.add": "Hinzuf\xFCgen",
"reg.chosen": "Ausgew\xE4hlte Regionen",
"reg.nothing": "Noch keine Region ausgew\xE4hlt.",
"reg.remove": "{region} entfernen",
"reg.codes": "Oder Regionsk\xFCrzel eingeben",
"reg.codesHelp": "F\xFCr alle, die sie kennen: drei Zeichen wie u1j, mehrere mit Komma getrennt.",
"reg.badCode": "\u201E{code}\u201C ist keine Region: es m\xFCssen genau 3 Zeichen sein (Ziffern und Buchstaben au\xDFer a, i, l, o).",
"reg.needOne": "W\xE4hle mindestens eine Region.",
"reg.tooMany": "Das sind zu viele Regionen (h\xF6chstens {max}).",
"reg.save": "Speichern",
"reg.saving": "Speichert \u2026",
"reg.saved": "Gespeichert. Der Knoten folgt jetzt diesen Regionen.",
"reg.failed": "Das hat nicht geklappt.",
"reg.signedOut": "Du bist abgemeldet. Melde dich unter \u201EMeine Anzeigen\u201C neu an.",
"reg.credit": "Ortsnamen: GeoNames (geonames.org), Lizenz CC BY 4.0.",
"own.listings": "Deine Anzeigen", "own.listings": "Deine Anzeigen",
"own.none": "Dein Knoten hat keine aktiven Anzeigen.", "own.none": "Dein Knoten hat keine aktiven Anzeigen.",
"own.perMonth": "/ Monat", "own.perMonth": "/ Monat",
@@ -436,6 +461,31 @@ var en = {
"own.login": "Sign in", "own.login": "Sign in",
"own.loginBad": "The node rejected the token.", "own.loginBad": "The node rejected the token.",
"own.logout": "Sign out", "own.logout": "Sign out",
"reg.title": "Regions",
"reg.intro": "Your node keeps the listings of these regions and passes them on to others. Search for a place, for example Bonn or Hamburg. A change applies at once and survives a restart.",
"reg.search": "Search for a place",
"reg.placeholder": "e.g. Bonn, Cologne, Hamburg",
"reg.results": "Places found",
"reg.none": "I found no place for that. Check the spelling, or enter a region code below.",
"reg.noPlaces": "The list of places could not be loaded. You can enter region codes below.",
"reg.cellsTitle": "Regions around {place}",
"reg.cellsHelp": "A region is an area roughly 100 to 150 km across. If the place is near an edge, the neighbouring region is included so you do not miss listings just across the border. Untick what you do not need.",
"reg.here": "here",
"reg.add": "Add",
"reg.chosen": "Chosen regions",
"reg.nothing": "No region chosen yet.",
"reg.remove": "Remove {region}",
"reg.codes": "Or enter region codes",
"reg.codesHelp": "For those who know them: three characters like u1j, several separated by commas.",
"reg.badCode": "\u201C{code}\u201D is not a region: it must be exactly 3 characters (digits and letters except a, i, l, o).",
"reg.needOne": "Choose at least one region.",
"reg.tooMany": "That is too many regions (at most {max}).",
"reg.save": "Save",
"reg.saving": "Saving \u2026",
"reg.saved": "Saved. The node now follows these regions.",
"reg.failed": "That did not work.",
"reg.signedOut": "You are signed out. Sign in again under \u201CMy listings\u201D.",
"reg.credit": "Place names: GeoNames (geonames.org), licence CC BY 4.0.",
"own.listings": "Your listings", "own.listings": "Your listings",
"own.none": "Your node has no active listings.", "own.none": "Your node has no active listings.",
"own.perMonth": "/ month", "own.perMonth": "/ month",
@@ -711,7 +761,7 @@ function keepFresh(alive, run, ms = FOREGROUND_MS, doc = document) {
schedule(); schedule();
} }
// node_modules/@noble/ciphers/utils.js // ../../web/node_modules/@noble/ciphers/utils.js
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
function isBytes(a) { function isBytes(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
@@ -890,7 +940,7 @@ function copyBytes(bytes2) {
return Uint8Array.from(abytes(bytes2)); return Uint8Array.from(abytes(bytes2));
} }
// node_modules/@noble/ciphers/_arx.js // ../../web/node_modules/@noble/ciphers/_arx.js
var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0)); var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))(); var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))(); var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
@@ -1020,7 +1070,7 @@ function createCipher(core, opts) {
}; };
} }
// node_modules/@noble/ciphers/_poly1305.js // ../../web/node_modules/@noble/ciphers/_poly1305.js
function u8to16(a, i) { function u8to16(a, i) {
return a[i++] & 255 | (a[i++] & 255) << 8; return a[i++] & 255 | (a[i++] & 255) << 8;
} }
@@ -1271,7 +1321,7 @@ var Poly1305 = class {
}; };
var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
// node_modules/@noble/ciphers/chacha.js // ../../web/node_modules/@noble/ciphers/chacha.js
function chachaCore(s, k, n, out, cnt, rounds = 20) { function chachaCore(s, k, n, out, cnt, rounds = 20) {
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
@@ -1421,7 +1471,7 @@ var chacha20poly1305 = /* @__PURE__ */ wrapCipher(
/* @__PURE__ */ _poly1305_aead(chacha20) /* @__PURE__ */ _poly1305_aead(chacha20)
); );
// node_modules/@noble/hashes/_u64.js // ../../web/node_modules/@noble/hashes/_u64.js
var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))(); var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
var _32n = /* @__PURE__ */ BigInt(32); var _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) { function fromBig(n, le = false) {
@@ -1464,7 +1514,7 @@ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
// node_modules/@noble/hashes/utils.js // ../../web/node_modules/@noble/hashes/utils.js
function isBytes2(a) { function isBytes2(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
} }
@@ -1629,7 +1679,7 @@ var oidNist = (suffix) => ({
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
}); });
// node_modules/@noble/hashes/_md.js // ../../web/node_modules/@noble/hashes/_md.js
function Chi(a, b, c) { function Chi(a, b, c) {
return a & b ^ ~a & c; return a & b ^ ~a & c;
} }
@@ -1760,7 +1810,7 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
327033209 327033209
]); ]);
// node_modules/@noble/hashes/sha2.js // ../../web/node_modules/@noble/hashes/sha2.js
var SHA256_K = /* @__PURE__ */ Uint32Array.from([ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
1116352408, 1116352408,
1899447441, 1899447441,
@@ -2157,7 +2207,7 @@ var sha512 = /* @__PURE__ */ createHasher(
/* @__PURE__ */ oidNist(3) /* @__PURE__ */ oidNist(3)
); );
// node_modules/@noble/curves/utils.js // ../../web/node_modules/@noble/curves/utils.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function aarray(item, title, inner = () => { function aarray(item, title, inner = () => {
}) { }) {
@@ -2278,7 +2328,7 @@ function validateObject(object, fields = {}, optFields = {}, title = "object") {
iter(optFields, true); iter(optFields, true);
} }
// node_modules/@noble/curves/abstract/modular.js // ../../web/node_modules/@noble/curves/abstract/modular.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
var _0n2 = /* @__PURE__ */ BigInt(0); var _0n2 = /* @__PURE__ */ BigInt(0);
var _1n2 = /* @__PURE__ */ BigInt(1); var _1n2 = /* @__PURE__ */ BigInt(1);
@@ -2708,7 +2758,7 @@ function Field(ORDER, opts = {}) {
return new _Field(ORDER, opts); return new _Field(ORDER, opts);
} }
// node_modules/@noble/curves/abstract/curve.js // ../../web/node_modules/@noble/curves/abstract/curve.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
var _0n3 = /* @__PURE__ */ BigInt(0); var _0n3 = /* @__PURE__ */ BigInt(0);
var _1n3 = /* @__PURE__ */ BigInt(1); var _1n3 = /* @__PURE__ */ BigInt(1);
@@ -3096,7 +3146,7 @@ function createKeygen(randomSecretKey, getPublicKey) {
}; };
} }
// node_modules/@noble/curves/abstract/edwards.js // ../../web/node_modules/@noble/curves/abstract/edwards.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
var _0n4 = /* @__PURE__ */ BigInt(0); var _0n4 = /* @__PURE__ */ BigInt(0);
var _1n4 = /* @__PURE__ */ BigInt(1); var _1n4 = /* @__PURE__ */ BigInt(1);
@@ -3548,7 +3598,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
}); });
} }
// node_modules/@noble/curves/abstract/montgomery.js // ../../web/node_modules/@noble/curves/abstract/montgomery.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
var _0n5 = /* @__PURE__ */ BigInt(0); var _0n5 = /* @__PURE__ */ BigInt(0);
var _1n5 = /* @__PURE__ */ BigInt(1); var _1n5 = /* @__PURE__ */ BigInt(1);
@@ -3696,7 +3746,7 @@ function montgomery(curveDef) {
}); });
} }
// node_modules/@noble/curves/ed25519.js // ../../web/node_modules/@noble/curves/ed25519.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
var _0n6 = /* @__PURE__ */ BigInt(0); var _0n6 = /* @__PURE__ */ BigInt(0);
var _1n6 = /* @__PURE__ */ BigInt(1); var _1n6 = /* @__PURE__ */ BigInt(1);
@@ -3797,7 +3847,7 @@ var x25519 = /* @__PURE__ */ (() => {
}); });
})(); })();
// node_modules/@noble/hashes/hmac.js // ../../web/node_modules/@noble/hashes/hmac.js
var _HMAC = class { var _HMAC = class {
oHash; oHash;
iHash; iHash;
@@ -3874,7 +3924,7 @@ var hmac = /* @__PURE__ */ (() => {
return hmac_; return hmac_;
})(); })();
// node_modules/@noble/hashes/hkdf.js // ../../web/node_modules/@noble/hashes/hkdf.js
var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
function expand(hash, prk, info, length = 32, _recycled) { function expand(hash, prk, info, length = 32, _recycled) {
@@ -4815,6 +4865,9 @@ async function putAddress(listing, a) {
async function deleteAddress(listing) { async function deleteAddress(listing) {
await call("DELETE", `/api/v1/listings/${e(listing)}/address`); await call("DELETE", `/api/v1/listings/${e(listing)}/address`);
} }
async function setRegions(regions) {
return (await call("PUT", "/api/v1/regions", { regions })).regions;
}
async function createListing(d) { async function createListing(d) {
return await call("POST", "/api/v1/listings", d); return await call("POST", "/api/v1/listings", d);
} }
@@ -4885,7 +4938,7 @@ async function showOwner(listingId, thread) {
let threads = []; let threads = [];
let msgs = []; let msgs = [];
let filter = "all"; let filter = "all";
let loaded2 = false; let loaded3 = false;
const notice = h("p", { class: "error", role: "alert" }); const notice = h("p", { class: "error", role: "alert" });
const listingsBox = h("div", { class: "olist" }); const listingsBox = h("div", { class: "olist" });
const listingsPane = h( const listingsPane = h(
@@ -4894,6 +4947,7 @@ async function showOwner(listingId, thread) {
h("h2", { class: "pane-title" }, t("own.listings")), h("h2", { class: "pane-title" }, t("own.listings")),
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))), h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
listingsBox, listingsBox,
h("p", null, h("a", { class: "btn", href: "#/mine/regions" }, t("reg.title"))),
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))) h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout")))
); );
const reqTitle = h("h2", { class: "pane-title" }); const reqTitle = h("h2", { class: "pane-title" });
@@ -4937,7 +4991,7 @@ async function showOwner(listingId, thread) {
const kindLabel = (k) => k === "rent" || k === "sale" ? t(`kind.${k}`) : k ?? ""; const kindLabel = (k) => k === "rent" || k === "sale" ? t(`kind.${k}`) : k ?? "";
function renderListings() { function renderListings() {
clear(listingsBox); clear(listingsBox);
if (loaded2 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none"))); if (loaded3 && mine2.length === 0) listingsBox.append(h("p", { class: "muted" }, t("own.none")));
for (const m of mine2) { for (const m of mine2) {
const sub = [kindLabel(m.kind), m.price ? price({ price: m.price }) : ""].filter(Boolean).join(" \xB7 "); const sub = [kindLabel(m.kind), m.price ? price({ price: m.price }) : ""].filter(Boolean).join(" \xB7 ");
listingsBox.append( listingsBox.append(
@@ -4994,7 +5048,7 @@ async function showOwner(listingId, thread) {
} }
const shown = threads.filter((x) => filter === "all" || (filter === "reply" ? x.needs_reply : x.hidden > 0)); const shown = threads.filter((x) => filter === "all" || (filter === "reply" ? x.needs_reply : x.hidden > 0));
clear(reqBox); clear(reqBox);
if (loaded2 && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch"))); if (loaded3 && shown.length === 0) reqBox.append(h("p", { class: "muted" }, t("own.noMatch")));
for (const th of shown) { for (const th of shown) {
reqBox.append( reqBox.append(
h( h(
@@ -5047,7 +5101,7 @@ async function showOwner(listingId, thread) {
} }
if (gen !== state.generation) return; if (gen !== state.generation) return;
notice.textContent = ""; notice.textContent = "";
loaded2 = true; loaded3 = true;
renderAll(); renderAll();
} }
renderListings(); renderListings();
@@ -5679,6 +5733,313 @@ async function showPublish(editId) {
syncKind(); syncKind();
} }
// src/places.ts
function fold(s) {
return s.normalize("NFD").replace(/\p{M}/gu, "").replace(/ß/g, "ss").toLowerCase();
}
function unTranslit(s) {
return s.replace(/ae/g, "a").replace(/oe/g, "o").replace(/ue/g, "u");
}
function parsePlaces(tsv) {
const out = [];
for (const line of tsv.split("\n")) {
if (!line) continue;
const [name, ascii, lat, lon, cc, pop, alt] = line.split(" ");
if (!name || lat === void 0 || lon === void 0) continue;
const alts = alt ? alt.split("|") : [];
const keys = [name, ...alts].map(fold);
if (ascii) keys.push(fold(ascii));
out.push({ name, lat: Number(lat), lon: Number(lon), cc: cc ?? "", population: Number(pop) || 0, alts, keys });
}
return out;
}
function score(key, q) {
if (key === q) return 0;
if (key.startsWith(q)) return 1;
if (key.split(/[\s-]+/).some((w) => w.startsWith(q))) return 2;
return q.length >= 3 && key.includes(q) ? 3 : 4;
}
function searchPlaces(places, query, limit = 8) {
const q1 = fold(query.trim());
if (q1.length < 2) return [];
const qs = [.../* @__PURE__ */ new Set([q1, unTranslit(q1)])];
const hits = [];
for (const p of places) {
let best = 4;
let bestKey = 0;
for (let i = 0; i < p.keys.length; i++) {
for (const q of qs) {
const s = score(p.keys[i], q);
if (s < best) [best, bestKey] = [s, i];
}
}
if (best < 4) {
const matched = bestKey >= 1 && bestKey <= p.alts.length ? p.alts[bestKey - 1] : null;
hits.push({ m: { place: p, matched }, s: best });
}
}
hits.sort((a, b) => a.s - b.s || b.m.place.population - a.m.place.population);
return hits.slice(0, limit).map((h2) => h2.m);
}
var KM_PER_DEGREE = 111.2;
function cellsNear(lat, lon, km = 40) {
const cell = (la, lo) => encodeGeohash(Math.max(-89.999, Math.min(89.999, la)), ((lo + 180) % 360 + 360) % 360 - 180, 3);
const out = [cell(lat, lon)];
const dLat = 1 / KM_PER_DEGREE;
const dLon = 1 / (KM_PER_DEGREE * Math.max(0.05, Math.cos(lat * Math.PI / 180)));
for (const r of [km / 2, km]) {
for (let i = 0; i < 16; i++) {
const a = i / 16 * 2 * Math.PI;
const c = cell(lat + Math.sin(a) * r * dLat, lon + Math.cos(a) * r * dLon);
if (!out.includes(c)) out.push(c);
}
}
return out;
}
function biggestPlaceByCell(places) {
const by = /* @__PURE__ */ new Map();
for (const p of places) {
const c = encodeGeohash(p.lat, p.lon, 3);
const cur = by.get(c);
if (!cur || p.population > cur.population) by.set(c, p);
}
return by;
}
var loaded2 = null;
function loadPlaces() {
loaded2 ??= fetch("places.tsv").then((r) => {
if (!r.ok) throw new Error(`${r.status}`);
return r.text();
}).then(parsePlaces).catch((e2) => {
loaded2 = null;
throw e2;
});
return loaded2;
}
// src/regions.ts
var CODE = /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/;
var MAX_REGIONS = 20;
function countryName(cc) {
try {
return new Intl.DisplayNames([lang], { type: "region" }).of(cc) ?? cc;
} catch {
return cc;
}
}
function errText(e2) {
if (e2 instanceof Unauthorized) return t("reg.signedOut");
if (e2 && typeof e2 === "object" && "message" in e2) return String(e2.message);
return typeof e2 === "string" ? e2 : t("reg.failed");
}
function regionPicker(opts) {
const chosen = [...opts.initial];
let places = [];
let biggest = /* @__PURE__ */ new Map();
const label2 = (code) => {
const p = biggest.get(code);
return p ? `${code} \xB7 ${p.name}` : code;
};
const chips = h("ul", { class: "rp-chips", "aria-label": t("reg.chosen") });
const drawChips = () => {
clear(chips);
if (chosen.length === 0) append(chips, [h("li", { class: "muted" }, t("reg.nothing"))]);
for (const code of chosen) {
append(chips, [
h(
"li",
{ class: "rp-chip" },
h("span", null, label2(code)),
h(
"button",
{
type: "button",
class: "rp-chip-x",
"aria-label": t("reg.remove", { region: label2(code) }),
onclick: () => {
chosen.splice(chosen.indexOf(code), 1);
drawChips();
}
},
"\xD7"
)
)
]);
}
};
const results = h("ul", { class: "rp-results", role: "listbox", "aria-label": t("reg.results") });
const cellsBox = h("div", { class: "rp-cells" });
const hint = h("p", { class: "muted small", "aria-live": "polite" });
const showCells = (place) => {
clear(cellsBox);
clear(results);
const cells = cellsNear(place.lat, place.lon);
const boxes = cells.map((code, i) => {
const box = h("input", { type: "checkbox", name: `cell-${code}`, checked: true, "aria-label": code });
return { code, box, row: h("label", { class: "rp-cell" }, box, h("span", null, `${label2(code)}${i === 0 ? ` (${t("reg.here")})` : ""}`)) };
});
append(cellsBox, [
h("h2", null, t("reg.cellsTitle", { place: place.name })),
h("p", { class: "muted small" }, t("reg.cellsHelp")),
...boxes.map((b) => b.row),
h(
"div",
{ class: "actions" },
h(
"button",
{
type: "button",
class: "btn",
onclick: () => {
for (const b of boxes) if (b.box.checked && !chosen.includes(b.code)) chosen.push(b.code);
clear(cellsBox);
search2.value = "";
drawChips();
}
},
t("reg.add")
)
)
]);
};
const showMatches = (matches) => {
clear(results);
for (const m of matches) {
const p = m.place;
append(results, [
h(
"li",
{ role: "option" },
h(
"button",
{ type: "button", class: "rp-result", onclick: () => showCells(p) },
h("strong", null, p.name),
m.matched ? ` (${m.matched})` : "",
h("span", { class: "muted" }, ` \xB7 ${countryName(p.cc)}`)
)
)
]);
}
};
const search2 = h("input", {
type: "search",
name: "place",
autocomplete: "off",
spellcheck: "false",
placeholder: t("reg.placeholder"),
"aria-label": t("reg.search"),
disabled: true
// until the list of places has loaded: an early search would find nothing
});
search2.addEventListener("input", () => {
clear(cellsBox);
const q = search2.value;
if (q.trim().length < 2) {
clear(results);
hint.textContent = "";
return;
}
const found = searchPlaces(places, q);
showMatches(found);
hint.textContent = found.length === 0 ? t("reg.none") : "";
});
void loadPlaces().then(
(p) => {
places = p;
biggest = biggestPlaceByCell(p);
search2.disabled = false;
drawChips();
},
() => {
hint.textContent = t("reg.noPlaces");
}
);
const codes = h("input", { type: "text", name: "regions", placeholder: "u1j", autocomplete: "off", spellcheck: "false", "aria-label": t("reg.codes") });
const problem = h("p", { class: "error", role: "alert" });
const go = h("button", { type: "submit", class: "btn primary" }, opts.submitLabel);
const form = h(
"form",
{
class: "stack regions",
onsubmit: (ev) => {
ev.preventDefault();
problem.textContent = "";
for (const raw of codes.value.split(/[\s,;]+/).filter(Boolean)) {
const code = raw.toLowerCase();
if (!CODE.test(code)) {
problem.textContent = t("reg.badCode", { code: raw });
return;
}
if (!chosen.includes(code)) chosen.push(code);
}
codes.value = "";
drawChips();
if (chosen.length === 0) {
problem.textContent = t("reg.needOne");
return;
}
if (chosen.length > MAX_REGIONS) {
problem.textContent = t("reg.tooMany", { max: MAX_REGIONS });
return;
}
go.disabled = true;
const label3 = go.textContent;
go.textContent = t("reg.saving");
opts.onSubmit([...chosen]).catch((e2) => {
problem.textContent = errText(e2);
go.disabled = false;
go.textContent = label3;
});
}
},
h("label", null, t("reg.search"), search2),
hint,
results,
cellsBox,
h("h2", null, t("reg.chosen")),
chips,
h("label", null, t("reg.codes"), codes),
h("p", { class: "muted small" }, t("reg.codesHelp")),
problem,
h("div", { class: "actions" }, go),
h("p", { class: "muted small" }, t("reg.credit"))
);
drawChips();
return form;
}
function showRegions(message = "") {
const root = document.getElementById("app");
document.body.classList.remove("wide");
clear(root);
if (!getToken()) {
location.hash = "#/mine";
return;
}
const picker = regionPicker({
initial: state.node?.regions ?? [],
submitLabel: t("reg.save"),
onSubmit: async (regions) => {
const now = await setRegions(regions);
if (state.node) state.node.regions = now;
const statusEl2 = document.getElementById("status");
if (statusEl2 && state.node) {
statusEl2.textContent = t("status.line", { listings: state.node.listings, peers: state.node.peers, regions: now.join(", ") });
}
showRegions(t("reg.saved"));
}
});
append(root, [
h(
"section",
{ class: "panel" },
h("h1", null, t("reg.title")),
h("p", { class: "muted" }, t("reg.intro")),
h("p", { class: "ok", role: "status" }, message),
picker
)
]);
}
// src/main.ts // src/main.ts
var PAGE = 20; var PAGE = 20;
var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/; var GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
@@ -5980,6 +6341,7 @@ function route() {
} else if (m) void showDetail(m[1], m[2]); } else if (m) void showDetail(m[1], m[2]);
else if (c) void showConversation(c[1], c[2], c[3]); else if (c) void showConversation(c[1], c[2], c[3]);
else if (path === "/messages") showInbox(); else if (path === "/messages") showInbox();
else if (path === "/mine/regions") showRegions();
else if (path === "/mine/new") void showPublish(); else if (path === "/mine/new") void showPublish();
else if (edit) void showPublish(edit[1]); else if (edit) void showPublish(edit[1]);
else if (own) void showOwner(own[1], own[2]); else if (own) void showOwner(own[1], own[2]);
+34247
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -269,6 +269,16 @@ label.check { flex-direction: row; align-items: center; gap: 8px; }
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } .badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.badge.warn { color: var(--warn); background: var(--warn-bg); } .badge.warn { color: var(--warn); background: var(--warn-bg); }
.badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); } .badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); }
/* the region picker */
.rp-chips, .rp-results { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
.rp-results { flex-direction: column; flex-wrap: nowrap; }
.rp-chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 4px 2px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 999px; }
.rp-chip-x { border: 0; background: none; cursor: pointer; font-size: 1.1rem; line-height: 1; padding: 2px 8px; color: inherit; }
.rp-result { width: 100%; text-align: left; background: none; border: 1px solid transparent; border-radius: 6px; padding: 8px; cursor: pointer; color: inherit; font: inherit; }
.rp-result:hover, .rp-result:focus-visible { border-color: var(--line); background: var(--bg); }
.rp-cells { display: grid; gap: 6px; }
.stack label.rp-cell { flex-direction: row; align-items: center; gap: 8px; color: inherit; font-size: 1rem; }
p.ok { color: var(--ok); }
.chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; } .chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
.chip { .chip {
min-height: 2.25rem; min-height: 2.25rem;
+67
View File
@@ -0,0 +1,67 @@
// Builds static/places.tsv, the offline list of place names the region picker
// searches, from GeoNames' cities15000.txt (https://download.geonames.org/export/dump/).
//
// curl -O https://download.geonames.org/export/dump/cities15000.zip && unzip cities15000.zip
// node scripts/places.mjs cities15000.txt > static/places.tsv
//
// The data is © GeoNames, licensed CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/):
// the app credits it where places are searched. The output is committed, so
// building the UI needs no download.
//
// One place per line: name, ASCII name, lat, lon, country, population, and for
// larger cities the other Latin-script names people use (Köln: Cologne, Colonia).
// Searching works offline; nothing about where a person looks leaves the device.
import { readFileSync } from "node:fs";
const file = process.argv[2];
if (!file) {
console.error("usage: node scripts/places.mjs cities15000.txt > static/places.tsv");
process.exit(2);
}
const LATIN = /^[\p{Script=Latin}\p{M}\p{Zs}'.\-]+$/u;
const ALT_MIN_POPULATION = 100_000; // exonyms matter for big cities only
const ALT_MAX = 30;
// German names that GeoNames' English-named entries do not carry ("Munich" has
// no "München"), keyed by "English name|country".
const GERMAN = {
"Munich|DE": "München", "Nuremberg|DE": "Nürnberg", "Prague|CZ": "Prag", "Geneva|CH": "Genf",
"Milan|IT": "Mailand", "Rome|IT": "Rom", "Florence|IT": "Florenz", "Venice|IT": "Venedig",
"Naples|IT": "Neapel", "Turin|IT": "Turin", "Warsaw|PL": "Warschau", "Copenhagen|DK": "Kopenhagen",
"Brussels|BE": "Brüssel", "Lisbon|PT": "Lissabon", "Athens|GR": "Athen", "Vienna|AT": "Wien",
"Cologne|DE": "Köln", "Hanover|DE": "Hannover", "Saint Petersburg|RU": "Sankt Petersburg",
"Moscow|RU": "Moskau", "Kyiv|UA": "Kiew", "Bucharest|RO": "Bukarest", "Belgrade|RS": "Belgrad",
"Seville|ES": "Sevilla", "Basel|CH": "Basel", "Bern|CH": "Bern", "Lucerne|CH": "Luzern",
"Strasbourg|FR": "Straßburg", "Luxembourg|LU": "Luxemburg", "Antwerp|BE": "Antwerpen",
};
const fold = (s) =>s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
const out = [];
for (const line of readFileSync(file, "utf8").split("\n")) {
if (!line) continue;
const f = line.split("\t");
const [, name, ascii, alternates, lat, lon, , , cc] = f;
const population = Number(f[14]);
let alts = [];
if (population >= ALT_MIN_POPULATION) {
const have = new Set([fold(name), fold(ascii)]);
for (const a of alternates.split(",")) {
// Skip other scripts, codes ("CGN"), romanisations with apostrophes
// ("K'oln"), lower-case transliterations ("klwn"), and what we already have.
if (a.length < 4 || !LATIN.test(a) || a === a.toUpperCase() || a.includes("'")) continue;
if (a[0] !== a[0].toUpperCase() || have.has(fold(a))) continue;
have.add(fold(a));
alts.push(a);
}
// Names without spaces first (Cologne before "Colonia Claudia Ara Agrippinensium").
alts = alts.sort((x, y) => x.split(" ").length - y.split(" ").length || x.length - y.length).slice(0, ALT_MAX);
}
const de = GERMAN[`${name}|${cc}`];
if (de && fold(de) !== fold(name) && !alts.some((a) => fold(a) === fold(de))) alts.unshift(de);
out.push([name, ascii === name ? "" : ascii, Number(lat).toFixed(2), Number(lon).toFixed(2), cc, population, alts.join("|")].join("\t"));
}
process.stdout.write(out.join("\n") + "\n");
+54
View File
@@ -115,6 +115,33 @@ const de = {
"own.login": "Anmelden", "own.login": "Anmelden",
"own.loginBad": "Der Knoten hat den Token abgelehnt.", "own.loginBad": "Der Knoten hat den Token abgelehnt.",
"own.logout": "Abmelden", "own.logout": "Abmelden",
"reg.title": "Regionen",
"reg.intro":
"Dein Knoten hält die Anzeigen dieser Regionen bereit und gibt sie an andere weiter. Suche einen Ort, zum Beispiel Bonn oder Hamburg. Die Änderung gilt sofort und bleibt nach einem Neustart erhalten.",
"reg.search": "Ort suchen",
"reg.placeholder": "z. B. Bonn, Köln, Hamburg",
"reg.results": "Gefundene Orte",
"reg.none": "Dazu habe ich keinen Ort gefunden. Prüfe die Schreibweise, oder gib unten ein Regionskürzel ein.",
"reg.noPlaces": "Die Ortsliste konnte nicht geladen werden. Du kannst unten Regionskürzel eingeben.",
"reg.cellsTitle": "Regionen rund um {place}",
"reg.cellsHelp":
"Eine Region ist ein Gebiet von etwa 100 bis 150 km Breite. Liegt der Ort nahe am Rand, kommt die Nachbarregion dazu, damit dir Anzeigen gleich hinter der Grenze nicht fehlen. Nimm den Haken heraus, was du nicht brauchst.",
"reg.here": "hier",
"reg.add": "Hinzufügen",
"reg.chosen": "Ausgewählte Regionen",
"reg.nothing": "Noch keine Region ausgewählt.",
"reg.remove": "{region} entfernen",
"reg.codes": "Oder Regionskürzel eingeben",
"reg.codesHelp": "Für alle, die sie kennen: drei Zeichen wie u1j, mehrere mit Komma getrennt.",
"reg.badCode": "„{code}“ ist keine Region: es müssen genau 3 Zeichen sein (Ziffern und Buchstaben außer a, i, l, o).",
"reg.needOne": "Wähle mindestens eine Region.",
"reg.tooMany": "Das sind zu viele Regionen (höchstens {max}).",
"reg.save": "Speichern",
"reg.saving": "Speichert …",
"reg.saved": "Gespeichert. Der Knoten folgt jetzt diesen Regionen.",
"reg.failed": "Das hat nicht geklappt.",
"reg.signedOut": "Du bist abgemeldet. Melde dich unter „Meine Anzeigen“ neu an.",
"reg.credit": "Ortsnamen: GeoNames (geonames.org), Lizenz CC BY 4.0.",
"own.listings": "Deine Anzeigen", "own.listings": "Deine Anzeigen",
"own.none": "Dein Knoten hat keine aktiven Anzeigen.", "own.none": "Dein Knoten hat keine aktiven Anzeigen.",
"own.perMonth": "/ Monat", "own.perMonth": "/ Monat",
@@ -362,6 +389,33 @@ const en: Record<keyof typeof de, string> = {
"own.login": "Sign in", "own.login": "Sign in",
"own.loginBad": "The node rejected the token.", "own.loginBad": "The node rejected the token.",
"own.logout": "Sign out", "own.logout": "Sign out",
"reg.title": "Regions",
"reg.intro":
"Your node keeps the listings of these regions and passes them on to others. Search for a place, for example Bonn or Hamburg. A change applies at once and survives a restart.",
"reg.search": "Search for a place",
"reg.placeholder": "e.g. Bonn, Cologne, Hamburg",
"reg.results": "Places found",
"reg.none": "I found no place for that. Check the spelling, or enter a region code below.",
"reg.noPlaces": "The list of places could not be loaded. You can enter region codes below.",
"reg.cellsTitle": "Regions around {place}",
"reg.cellsHelp":
"A region is an area roughly 100 to 150 km across. If the place is near an edge, the neighbouring region is included so you do not miss listings just across the border. Untick what you do not need.",
"reg.here": "here",
"reg.add": "Add",
"reg.chosen": "Chosen regions",
"reg.nothing": "No region chosen yet.",
"reg.remove": "Remove {region}",
"reg.codes": "Or enter region codes",
"reg.codesHelp": "For those who know them: three characters like u1j, several separated by commas.",
"reg.badCode": "“{code}” is not a region: it must be exactly 3 characters (digits and letters except a, i, l, o).",
"reg.needOne": "Choose at least one region.",
"reg.tooMany": "That is too many regions (at most {max}).",
"reg.save": "Save",
"reg.saving": "Saving …",
"reg.saved": "Saved. The node now follows these regions.",
"reg.failed": "That did not work.",
"reg.signedOut": "You are signed out. Sign in again under “My listings”.",
"reg.credit": "Place names: GeoNames (geonames.org), licence CC BY 4.0.",
"own.listings": "Your listings", "own.listings": "Your listings",
"own.none": "Your node has no active listings.", "own.none": "Your node has no active listings.",
"own.perMonth": "/ month", "own.perMonth": "/ month",
+2
View File
@@ -7,6 +7,7 @@ import { contactPanel, showConversation, showInbox } from "./chat.ts";
import { showOwner } from "./owner.ts"; import { showOwner } from "./owner.ts";
import { getToken, setToken } from "./ownerApi.ts"; import { getToken, setToken } from "./ownerApi.ts";
import { showPublish } from "./publish.ts"; import { showPublish } from "./publish.ts";
import { showRegions } from "./regions.ts";
import { state, verifyOpts } from "./state.ts"; import { state, verifyOpts } from "./state.ts";
import { verifyListing, type Listing, type Verdict } from "./verify.ts"; import { verifyListing, type Listing, type Verdict } from "./verify.ts";
@@ -357,6 +358,7 @@ function route(): void {
} else if (m) void showDetail(m[1]!, m[2]!); } else if (m) void showDetail(m[1]!, m[2]!);
else if (c) void showConversation(c[1]!, c[2]!, c[3]!); else if (c) void showConversation(c[1]!, c[2]!, c[3]!);
else if (path === "/messages") showInbox(); else if (path === "/messages") showInbox();
else if (path === "/mine/regions") showRegions();
else if (path === "/mine/new") void showPublish(); else if (path === "/mine/new") void showPublish();
else if (edit) void showPublish(edit[1]); else if (edit) void showPublish(edit[1]);
else if (own) void showOwner(own[1], own[2]); else if (own) void showOwner(own[1], own[2]);
+1
View File
@@ -90,6 +90,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
h("h2", { class: "pane-title" }, t("own.listings")), h("h2", { class: "pane-title" }, t("own.listings")),
h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))), h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))),
listingsBox, listingsBox,
h("p", null, h("a", { class: "btn", href: "#/mine/regions" }, t("reg.title"))),
h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))), h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))),
); );
+5
View File
@@ -176,6 +176,11 @@ export async function deleteAddress(listing: string): Promise<void> {
} }
/** Publishes a new listing. The node signs it and mines its proof-of-work, which takes a few seconds. */ /** Publishes a new listing. The node signs it and mines its proof-of-work, which takes a few seconds. */
/** Makes the node follow exactly these regions, now and after a restart; returns what it follows. */
export async function setRegions(regions: string[]): Promise<string[]> {
return ((await call("PUT", "/api/v1/regions", { regions })) as { regions: string[] }).regions;
}
export async function createListing(d: Draft): Promise<Listing> { export async function createListing(d: Draft): Promise<Listing> {
return (await call("POST", "/api/v1/listings", d)) as Listing; return (await call("POST", "/api/v1/listings", d)) as Listing;
} }
+138
View File
@@ -0,0 +1,138 @@
// Finding regions by place name, offline.
//
// A region is a 3-character geohash cell, about 150 km wide: right for the
// network, meaningless to a person. This turns "Bonn" or "Cologne" into the
// cell(s) to follow, using a list of cities shipped with the page
// (places.tsv, GeoNames, CC-BY 4.0; see scripts/places.mjs). Nothing about what
// a person looks for leaves the device.
import { encodeGeohash } from "./geohash.ts";
export interface Place {
name: string;
lat: number;
lon: number;
/** ISO country code. */
cc: string;
population: number;
/** Other names people use (Köln: Cologne). */
alts: string[];
/** Folded search keys for the name and every alternative, in that order. */
keys: string[];
}
export interface Match {
place: Place;
/** The name that matched, when it is not the place's main name. */
matched: string | null;
}
/** Lower case, no diacritics, ß as ss: "Zürich", "zurich" and "ZÜRICH" are one key. */
export function fold(s: string): string {
return s.normalize("NFD").replace(/\p{M}/gu, "").replace(/ß/g, "ss").toLowerCase();
}
/** How a German keyboard without umlauts writes them: "muenchen" → "munchen". */
function unTranslit(s: string): string {
return s.replace(/ae/g, "a").replace(/oe/g, "o").replace(/ue/g, "u");
}
/** Reads places.tsv: name, ASCII name, lat, lon, country, population, alternatives. */
export function parsePlaces(tsv: string): Place[] {
const out: Place[] = [];
for (const line of tsv.split("\n")) {
if (!line) continue;
const [name, ascii, lat, lon, cc, pop, alt] = line.split("\t");
if (!name || lat === undefined || lon === undefined) continue;
const alts = alt ? alt.split("|") : [];
const keys = [name, ...alts].map(fold);
if (ascii) keys.push(fold(ascii)); // "Koeln": searchable, but shown as "Köln"
out.push({ name, lat: Number(lat), lon: Number(lon), cc: cc ?? "", population: Number(pop) || 0, alts, keys });
}
return out;
}
function score(key: string, q: string): number {
if (key === q) return 0;
if (key.startsWith(q)) return 1;
if (key.split(/[\s-]+/).some((w) => w.startsWith(q))) return 2;
return q.length >= 3 && key.includes(q) ? 3 : 4;
}
/** The best matches for what the person typed: exact names first, then by size. */
export function searchPlaces(places: Place[], query: string, limit = 8): Match[] {
const q1 = fold(query.trim());
if (q1.length < 2) return [];
const qs = [...new Set([q1, unTranslit(q1)])];
const hits: { m: Match; s: number }[] = [];
for (const p of places) {
let best = 4;
let bestKey = 0;
for (let i = 0; i < p.keys.length; i++) {
for (const q of qs) {
const s = score(p.keys[i]!, q);
if (s < best) [best, bestKey] = [s, i];
}
}
if (best < 4) {
// Indexes past the alternatives are the ASCII spelling of the main name.
const matched = bestKey >= 1 && bestKey <= p.alts.length ? p.alts[bestKey - 1]! : null;
hits.push({ m: { place: p, matched }, s: best });
}
}
hits.sort((a, b) => a.s - b.s || b.m.place.population - a.m.place.population);
return hits.slice(0, limit).map((h) => h.m);
}
const KM_PER_DEGREE = 111.2;
/**
* The cells to follow for a place: the one it lies in, then any other cell
* within about `km` of it, so a city near a cell's edge does not miss the
* listings just across it. The place's own cell comes first.
*/
export function cellsNear(lat: number, lon: number, km = 40): string[] {
const cell = (la: number, lo: number) =>
encodeGeohash(Math.max(-89.999, Math.min(89.999, la)), ((((lo + 180) % 360) + 360) % 360) - 180, 3);
const out = [cell(lat, lon)];
const dLat = 1 / KM_PER_DEGREE;
const dLon = 1 / (KM_PER_DEGREE * Math.max(0.05, Math.cos((lat * Math.PI) / 180)));
// Two rings (half and full distance) in 16 directions: a cell clipping the
// circle anywhere is hit by one of them.
for (const r of [km / 2, km]) {
for (let i = 0; i < 16; i++) {
const a = (i / 16) * 2 * Math.PI;
const c = cell(lat + Math.sin(a) * r * dLat, lon + Math.cos(a) * r * dLon);
if (!out.includes(c)) out.push(c);
}
}
return out;
}
/** The largest known place of each cell, to label a code with a name a person knows. */
export function biggestPlaceByCell(places: Place[]): Map<string, Place> {
const by = new Map<string, Place>();
for (const p of places) {
const c = encodeGeohash(p.lat, p.lon, 3);
const cur = by.get(c);
if (!cur || p.population > cur.population) by.set(c, p);
}
return by;
}
let loaded: Promise<Place[]> | null = null;
/** Fetches places.tsv once. Failing is not fatal: region codes can still be typed. */
export function loadPlaces(): Promise<Place[]> {
loaded ??= fetch("places.tsv")
.then((r) => {
if (!r.ok) throw new Error(`${r.status}`);
return r.text();
})
.then(parsePlaces)
.catch((e) => {
loaded = null; // try again next time
throw e;
});
return loaded;
}
+258
View File
@@ -0,0 +1,258 @@
// Choosing the regions a node follows, by place name.
//
// The owner's "Regions" page. A person searches a place ("Bonn", "Cologne"),
// sees the cells around it (the one it lies in and any within about 40 km),
// unticks what they do not want, and adds them. Region codes can still be
// typed for those who know them. Saving changes what the node follows at once.
import { append, clear, h } from "./dom.ts";
import { lang, t } from "./i18n.ts";
import { Unauthorized, getToken, setRegions } from "./ownerApi.ts";
import { biggestPlaceByCell, cellsNear, loadPlaces, searchPlaces, type Match, type Place } from "./places.ts";
import { state } from "./state.ts";
const CODE = /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/;
const MAX_REGIONS = 20;
function countryName(cc: string): string {
try {
return new Intl.DisplayNames([lang], { type: "region" }).of(cc) ?? cc;
} catch {
return cc;
}
}
function errText(e: unknown): string {
if (e instanceof Unauthorized) return t("reg.signedOut");
if (e && typeof e === "object" && "message" in e) return String((e as { message: unknown }).message);
return typeof e === "string" ? e : t("reg.failed");
}
export interface PickerOptions {
/** Regions already followed. */
initial: string[];
submitLabel: string;
/** Saves the choice; a rejection is shown to the person and they can try again. */
onSubmit: (regions: string[]) => Promise<void>;
}
/** The whole picker: search, chosen regions, code entry and a save button. */
export function regionPicker(opts: PickerOptions): HTMLElement {
const chosen: string[] = [...opts.initial];
let places: Place[] = [];
let biggest = new Map<string, Place>();
const label = (code: string): string => {
const p = biggest.get(code);
return p ? `${code} · ${p.name}` : code;
};
const chips = h("ul", { class: "rp-chips", "aria-label": t("reg.chosen") });
const drawChips = () => {
clear(chips);
if (chosen.length === 0) append(chips, [h("li", { class: "muted" }, t("reg.nothing"))]);
for (const code of chosen) {
append(chips, [
h(
"li",
{ class: "rp-chip" },
h("span", null, label(code)),
h(
"button",
{
type: "button",
class: "rp-chip-x",
"aria-label": t("reg.remove", { region: label(code) }),
onclick: () => {
chosen.splice(chosen.indexOf(code), 1);
drawChips();
},
},
"×",
),
),
]);
}
};
// --- search ---
const results = h("ul", { class: "rp-results", role: "listbox", "aria-label": t("reg.results") });
const cellsBox = h("div", { class: "rp-cells" });
const hint = h("p", { class: "muted small", "aria-live": "polite" });
const showCells = (place: Place) => {
clear(cellsBox);
clear(results);
const cells = cellsNear(place.lat, place.lon);
const boxes = cells.map((code, i) => {
const box = h("input", { type: "checkbox", name: `cell-${code}`, checked: true, "aria-label": code });
return { code, box, row: h("label", { class: "rp-cell" }, box, h("span", null, `${label(code)}${i === 0 ? ` (${t("reg.here")})` : ""}`)) };
});
append(cellsBox, [
h("h2", null, t("reg.cellsTitle", { place: place.name })),
h("p", { class: "muted small" }, t("reg.cellsHelp")),
...boxes.map((b) => b.row),
h(
"div",
{ class: "actions" },
h(
"button",
{
type: "button",
class: "btn",
onclick: () => {
for (const b of boxes) if (b.box.checked && !chosen.includes(b.code)) chosen.push(b.code);
clear(cellsBox);
search.value = "";
drawChips();
},
},
t("reg.add"),
),
),
]);
};
const showMatches = (matches: Match[]) => {
clear(results);
for (const m of matches) {
const p = m.place;
append(results, [
h(
"li",
{ role: "option" },
h(
"button",
{ type: "button", class: "rp-result", onclick: () => showCells(p) },
h("strong", null, p.name),
m.matched ? ` (${m.matched})` : "",
h("span", { class: "muted" }, ` · ${countryName(p.cc)}`),
),
),
]);
}
};
const search = h("input", {
type: "search",
name: "place",
autocomplete: "off",
spellcheck: "false",
placeholder: t("reg.placeholder"),
"aria-label": t("reg.search"),
disabled: true, // until the list of places has loaded: an early search would find nothing
});
search.addEventListener("input", () => {
clear(cellsBox);
const q = search.value;
if (q.trim().length < 2) {
clear(results);
hint.textContent = "";
return;
}
const found = searchPlaces(places, q);
showMatches(found);
hint.textContent = found.length === 0 ? t("reg.none") : "";
});
void loadPlaces().then(
(p) => {
places = p;
biggest = biggestPlaceByCell(p);
search.disabled = false;
drawChips(); // names for the codes already chosen
},
() => {
hint.textContent = t("reg.noPlaces");
},
);
// --- codes and saving ---
const codes = h("input", { type: "text", name: "regions", placeholder: "u1j", autocomplete: "off", spellcheck: "false", "aria-label": t("reg.codes") });
const problem = h("p", { class: "error", role: "alert" });
const go = h("button", { type: "submit", class: "btn primary" }, opts.submitLabel);
const form = h(
"form",
{
class: "stack regions",
onsubmit: (ev) => {
ev.preventDefault();
problem.textContent = "";
for (const raw of codes.value.split(/[\s,;]+/).filter(Boolean)) {
const code = raw.toLowerCase();
if (!CODE.test(code)) {
problem.textContent = t("reg.badCode", { code: raw });
return;
}
if (!chosen.includes(code)) chosen.push(code);
}
codes.value = "";
drawChips();
if (chosen.length === 0) {
problem.textContent = t("reg.needOne");
return;
}
if (chosen.length > MAX_REGIONS) {
problem.textContent = t("reg.tooMany", { max: MAX_REGIONS });
return;
}
go.disabled = true;
const label = go.textContent;
go.textContent = t("reg.saving");
opts.onSubmit([...chosen]).catch((e) => {
problem.textContent = errText(e);
go.disabled = false;
go.textContent = label;
});
},
},
h("label", null, t("reg.search"), search),
hint,
results,
cellsBox,
h("h2", null, t("reg.chosen")),
chips,
h("label", null, t("reg.codes"), codes),
h("p", { class: "muted small" }, t("reg.codesHelp")),
problem,
h("div", { class: "actions" }, go),
h("p", { class: "muted small" }, t("reg.credit")),
);
drawChips();
return form;
}
/** The owner's "Regions" page: shows what the node follows and changes it. */
export function showRegions(message = ""): void {
const root = document.getElementById("app")!;
document.body.classList.remove("wide");
clear(root);
if (!getToken()) {
location.hash = "#/mine"; // the sign-in form
return;
}
const picker = regionPicker({
initial: state.node?.regions ?? [],
submitLabel: t("reg.save"),
onSubmit: async (regions) => {
const now = await setRegions(regions);
if (state.node) state.node.regions = now;
const statusEl = document.getElementById("status");
if (statusEl && state.node) {
statusEl.textContent = t("status.line", { listings: state.node.listings, peers: state.node.peers, regions: now.join(", ") });
}
showRegions(t("reg.saved")); // the page again, showing what is followed now
},
});
append(root, [
h(
"section",
{ class: "panel" },
h("h1", null, t("reg.title")),
h("p", { class: "muted" }, t("reg.intro")),
h("p", { class: "ok", role: "status" }, message),
picker,
),
]);
}
+34247
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -269,6 +269,16 @@ label.check { flex-direction: row; align-items: center; gap: 8px; }
.badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } .badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
.badge.warn { color: var(--warn); background: var(--warn-bg); } .badge.warn { color: var(--warn); background: var(--warn-bg); }
.badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); } .badge.muted { color: var(--muted); background: transparent; border: 1px solid var(--line); }
/* the region picker */
.rp-chips, .rp-results { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
.rp-results { flex-direction: column; flex-wrap: nowrap; }
.rp-chip { display: inline-flex; align-items: center; gap: 4px; padding: 2px 4px 2px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 999px; }
.rp-chip-x { border: 0; background: none; cursor: pointer; font-size: 1.1rem; line-height: 1; padding: 2px 8px; color: inherit; }
.rp-result { width: 100%; text-align: left; background: none; border: 1px solid transparent; border-radius: 6px; padding: 8px; cursor: pointer; color: inherit; font: inherit; }
.rp-result:hover, .rp-result:focus-visible { border-color: var(--line); background: var(--bg); }
.rp-cells { display: grid; gap: 6px; }
.stack label.rp-cell { flex-direction: row; align-items: center; gap: 8px; color: inherit; font-size: 1rem; }
p.ok { color: var(--ok); }
.chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; } .chips-row { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
.chip { .chip {
min-height: 2.25rem; min-height: 2.25rem;
+6 -1
View File
@@ -211,9 +211,14 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
res.writeHead(code, { "Content-Type": "application/json" }); res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body)); res.end(JSON.stringify(body));
}; };
if (url.pathname === "/places.tsv") {
// A static file of the UI, as the real node serves it.
res.writeHead(200, { "Content-Type": "text/tab-separated-values" });
return void res.end(readFileSync(new URL("../static/places.tsv", import.meta.url)));
}
// The owner's token-protected routes are played by the test, if it sets `owner`. // The owner's token-protected routes are played by the test, if it sets `owner`.
const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname); const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname);
if (writesListing || /^\/api\/v1\/(mine|inbox)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) { if (writesListing || /^\/api\/v1\/(mine|inbox|regions)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
let body = ""; let body = "";
req.on("data", (c) => (body += c)); req.on("data", (c) => (body += c));
req.on("end", () => { req.on("end", () => {
+54
View File
@@ -41,6 +41,11 @@ function fakeNode() {
s.calls.push({ method: r.method, path: r.path + (r.query.size ? "?" + r.query : ""), body: r.body, auth: r.auth }); s.calls.push({ method: r.method, path: r.path + (r.query.size ? "?" + r.query : ""), body: r.body, auth: r.auth });
if (r.auth !== `Bearer ${s.token}`) return { status: 401, body: { error: "unauthorized" } }; if (r.auth !== `Bearer ${s.token}`) return { status: 401, body: { error: "unauthorized" } };
if (r.path === "/api/v1/mine") return { status: 200, body: s.mine }; if (r.path === "/api/v1/mine") return { status: 200, body: s.mine };
if (r.path === "/api/v1/regions" && r.method === "PUT") {
const { regions } = JSON.parse(r.body) as { regions: string[] };
if (regions.includes("zzz")) return { status: 400, body: { error: `"zzz" is not a region: use 3 geohash characters` } };
return { status: 200, body: { regions } };
}
if (r.path === "/api/v1/inbox") return { status: 200, body: s.threads.filter((t) => t.listing === r.query.get("listing")) }; if (r.path === "/api/v1/inbox") return { status: 200, body: s.threads.filter((t) => t.listing === r.query.get("listing")) };
const th = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(r.path); const th = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(r.path);
if (th) { if (th) {
@@ -383,3 +388,52 @@ test("signing out forgets the token", async () => {
assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), null); assert.equal(page!.window.sessionStorage.getItem("allmende.owner.token"), null);
await page!.waitFor(() => q("nav a[href='#/mine']") === null, "the owner link to vanish"); await page!.waitFor(() => q("nav a[href='#/mine']") === null, "the owner link to vanish");
}); });
test("the owner picks regions by place name and the node follows them at once", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
qa(".pane-listings a").find((a) => a.textContent === "Regions")!.click();
await page!.waitFor(() => q('[name="place"]') !== null, "the regions page");
assert.ok(q(".rp-chips")!.textContent!.includes("u1x"), "what the node follows now");
const search = q<HTMLInputElement>('[name="place"]')!;
await page!.waitFor(() => !search.disabled, "the place list is loaded");
search.value = "köln";
search.dispatchEvent(new page!.window.Event("input", { bubbles: true }));
await page!.waitFor(() => q(".rp-result") !== null, "a result");
q(".rp-result")!.click();
await page!.waitFor(() => /Regions around/.test(text()), "the cells around it");
button("Add")!.click();
assert.ok(qa(".rp-chip").length >= 2, "the new regions are added next to the old one");
submit(q("form")!);
await page!.waitFor(() => /Saved/.test(text()), "saved");
const put = node.s.calls.find((c) => c.method === "PUT" && c.path === "/api/v1/regions")!;
assert.equal(put.auth, `Bearer ${TOKEN}`, "only the owner can change regions");
const sent = (JSON.parse(put.body) as { regions: string[] }).regions;
assert.equal(sent[0], "u1x");
assert.ok(sent.includes("u1j"), `Köln's own cell is followed: ${sent}`);
assert.ok(q("#status")!.textContent!.includes(sent.join(", ")), "the status line shows the new regions");
});
test("a region the node refuses is explained and the page stays usable", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");
location_(`#/mine/regions`);
await page!.waitFor(() => q('[name="regions"]') !== null, "the regions page");
q<HTMLInputElement>('[name="regions"]')!.value = "zzz";
submit(q("form")!);
await page!.waitFor(() => /not a region/.test(text()), "the node's explanation");
assert.ok(!button("Save")?.disabled, "saving can be tried again");
});
test("without signing in the regions page leads to the sign-in", async () => {
open("#/mine/regions");
await page!.waitFor(() => q('input[name="token"]') !== null, "the sign-in form");
assert.equal(node.s.calls.length, 0);
});
/** Moves the open page to another hash, as a click on a link would. */
function location_(hash: string): void {
page!.window.location.hash = hash;
}
+93
View File
@@ -0,0 +1,93 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { decodeGeohash, encodeGeohash } from "../src/geohash.ts";
import { biggestPlaceByCell, cellsNear, fold, parsePlaces, searchPlaces } from "../src/places.ts";
// The real list the app ships.
const places = parsePlaces(readFileSync(new URL("../static/places.tsv", import.meta.url), "utf8"));
const first = (q: string) => searchPlaces(places, q, 1)[0];
test("the list is worldwide and big enough", () => {
assert.ok(places.length > 30_000);
});
test("names are found however they are spelled", () => {
assert.equal(first("Bonn")?.place.name, "Bonn");
assert.equal(first("bonn")?.place.name, "Bonn");
assert.equal(first("köln")?.place.name, "Köln");
assert.equal(first("koeln")?.place.name, "Köln");
assert.equal(first("KOELN")?.place.name, "Köln");
assert.equal(first("zurich")?.place.name, "Zürich");
assert.equal(first("Zürich")?.place.name, "Zürich");
assert.equal(first("Frankfurt am Main")?.place.cc, "DE");
});
test("other languages' names lead to the place, and say what matched", () => {
const c = first("cologne");
assert.equal(c?.place.name, "Köln");
assert.equal(c?.matched, "Cologne");
assert.equal(first("münchen")?.place.cc, "DE", "Munich, found by its German name");
assert.equal(first("muenchen")?.place.cc, "DE");
assert.equal(first("nuernberg")?.place.cc, "DE");
assert.equal(first("prag")?.place.cc, "CZ");
assert.equal(first("wien")?.place.cc, "AT");
assert.equal(first("Köln")?.matched, null, "the main name is not repeated");
});
test("the big city wins over a small namesake, and prefixes work", () => {
const vienna = searchPlaces(places, "vienna", 5);
assert.equal(vienna[0]!.place.cc, "AT");
assert.ok(vienna.some((m) => m.place.cc === "US"), "the others are still offered");
const ham = searchPlaces(places, "ham", 8).map((m) => m.place.name);
assert.ok(ham.includes("Hamburg") || ham.includes("Hamm"), ham.join());
assert.deepEqual(searchPlaces(places, "b"), [], "one letter is too little to search");
assert.deepEqual(searchPlaces(places, "qqqzzzxxx"), []);
assert.deepEqual(searchPlaces(places, " "), []);
});
test("folding ignores case, accents and ß", () => {
assert.equal(fold("Zürich"), "zurich");
assert.equal(fold("Straße"), "strasse");
assert.equal(fold("ÅRHUS"), "arhus");
});
test("a place gives the cell it lies in first", () => {
const bonn = first("Bonn")!.place;
const cells = cellsNear(bonn.lat, bonn.lon);
assert.equal(cells[0], encodeGeohash(bonn.lat, bonn.lon, 3));
assert.equal(cells[0], "u1j", "Bonn, the project's default region");
assert.equal(new Set(cells).size, cells.length);
assert.ok(cells.every((c) => /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/.test(c)));
});
test("only a place near a cell's edge brings in its neighbour", () => {
const cell = decodeGeohash("u1j")!;
// The middle of the cell is far from every edge.
assert.deepEqual(cellsNear(cell.lat, cell.lon), ["u1j"]);
// 10 km inside the east edge: the next cell east is within reach.
const kmPerLon = 111.2 * Math.cos((cell.lat * Math.PI) / 180);
const nearEast = cellsNear(cell.lat, cell.lon + cell.lonErr - 10 / kmPerLon);
assert.equal(nearEast[0], "u1j");
assert.ok(nearEast.length >= 2, "the eastern neighbour");
// At this latitude a cell is only about 100 km wide, so its middle is 50 km
// from the edges: out of a 40 km reach, inside an 80 km one.
assert.ok(cell.lonErr * kmPerLon > 45 && cell.lonErr * kmPerLon < 55);
assert.ok(cellsNear(cell.lat, cell.lon, 80).length >= 2, "the reach is a parameter");
});
test("places at the edge of the map still give valid cells", () => {
for (const [lat, lon] of [[89.99, 0], [-89.99, 10], [0, 179.99], [0, -179.99], [64.1, -21.9]] as const) {
const cells = cellsNear(lat, lon);
assert.ok(cells.length >= 1 && cells.every((c) => c.length === 3), `${lat},${lon}: ${cells}`);
}
});
test("a cell is named after the biggest place in it", () => {
const byCell = biggestPlaceByCell(places);
const bonn = first("Bonn")!.place;
const named = byCell.get("u1j")!;
assert.ok(named.population >= bonn.population, `${named.name} is at least as big as Bonn`);
assert.equal(byCell.get("000"), undefined, "an empty cell (open ocean) has no name");
});