A small, read-only web app for browsing and searching the music library of the Synology
mediaserver PostgreSQL database. A SQLite search index is built from the source
database to create search facets that are surfaced through a full-text query interface and
facet filters. The album display retrieves album cover, booklet, comments and other metadata
from the Synology API. The app also signs in Synology users and plays albums and
tracks natively in the browser, with the Synology Audio Station web app kept as an
optional fallback. See docs/native-playback.md for the
design and current status.
- Backend: Node.js + Express +
pg+ the built-innode:sqlitemodule, written in TypeScript. - Frontend: vanilla TypeScript (no framework), compiled to ES modules.
- No database migrations and no write queries.
- Album grid sorted by latest upload date (
MAX(date)). - Tracks stored under
LOOSE_TRACKS_FOLDERSprefixes (covers collections, random-track folders, …) stay fully searchable in Tracks mode, but the albums they name do not appear in the Albums view or its facet counts. - Multi-CD albums whose titles differ only by a whitespace-separated
// <disc label>suffix are merged into one album; the original titles (including the labels) remain searchable. - An Albums / Tracks switch in the header changes the result list. Track
results are compact rows with album artwork, title and artist, album name,
the track's own genre/region pills, duration, and (when signed in) a
per-track Play control. The mode is stored in the URL (
view=tracks) and in browser history. - Native playback in a fixed footer player with play/pause, restart,
previous/next, an interactive seek bar, elapsed/remaining time, cover and
metadata, volume/mute, keyboard shortcuts, OS media-session controls
(metadata, artwork, timeline, and media keys), and a play queue. While
playing, the player holds a best-effort screen wake lock (when
SCREEN_WAKE_LOCK_ENABLEDis on and the browser allows it), which keeps the page from being hidden at a track boundary on Android. Play controls and the footer are only shown while signed in. Album Play queues the album; a track Play queues the whole album and starts at the clicked track. The queue supports removing, reordering, clearing, and click-to-play, advances automatically with a preloaded next track, and survives a page reload paused (the restored queue appears after sign-in). Tracks whose format the browser cannot decode are marked with an unsupported-format warning and can use the Audio Station fallback. Clicking the album-dialog cover or the player-footer cover opens a full-size lightbox; the X button, Escape, or the dark backdrop dismisses it. The lightbox uses the album folder's original cover image when available and falls back to Audio Station's 480px cover otherwise. - Play all beside the result count starts a lazily refilled queue from the
current search results. In Albums mode it queues every track of every
matching album; in Tracks mode it queues the matching tracks. The visible
queue stays at
PAGE_SIZEitems (48 by default), fetching more from the original query as playback advances and dropping played history at each refill. The source keeps its own query, sort, and mode even if the visible search changes, and survives a page reload until another Play action replaces it. - A view switch at the right of the results header offers Grid,
Cover Flow, and World map album layouts, one icon per mode. Cover
Flow adds a 3D carousel with drag, wheel, and arrow-key navigation,
reflections, and click/Enter activation that opens the album dialog. The
caption below the flow matches the grid: the album title opens the dialog
and each artist name runs an artist search. The choice is remembered in
localStorage(happy-trails.album-view) and recorded in the URL aslayout=coverfloworlayout=map(grid is the unparameterized default), so Back/Forward restore it; the switch is hidden in Tracks mode. - World map plots the current page on an offline Natural Earth basemap in the Equal Earth projection, with countries tinted by a deterministic pastel palette. Albums are grouped by place and shown as fanned cover pins; clicking a cover opens the album dialog. An album with several disjoint regions appears at each when no region filter is active; with a region filter, it is pinned only in the selected region(s). Load more appends the next page's pins. The map can be made full-screen. If the map data fails to load, a Retry action reloads both the country lookup and the basemap. Albums without a resolved region appear in a collapsible Not on the map section beneath the filters in the left sidebar; unmapped tags are called out there, while albums with no region tag are listed without an extra label.
- Long genre/region lists end in a clickable +N more pill in album cards, the album dialog, and track rows. It expands the list to every tag and switches to Show less to collapse it again.
- Genre facet with facet search and multi-select. Counts follow the result
mode: number of albums in Albums mode, number of tracks in Tracks mode. Each
selection adds a
genre:"<name>"term to the search bar. - Country and region tags in the genre column (Brazil, France, Corsica,
Catalonia, …) are detected and exposed as a separate Regions facet, with
their own filter. Selections add
region:"<name>"terms. The genre facet contains only non-location tags. - A Series facet lists braced series names and
SERIES_ALLOWLISTmatches with album or track counts, ordered by occurrence. It is a checkbox list: each selection addsserie:"<name>"to the search bar joined withOR(a match-any selection), and Clear removes them. - Genre and region facets each have Match any / Match all modes. Any
joins the selected terms with
ORin the search bar; All joins them withAND. The two facet groups are combined withAND. - Genre, region, and series sections are collapsible and start collapsed; toggling one does not affect the others. Each list shows about seven rows by default, and Show all expands it to roughly three times that height.
- Free-text album/artist/track search with case-, accent-, and
ligature-insensitive matching (
SorenfindsSøren,caeterafindscætera,BjorkfindsBjörk). Track-level artists are searchable throughartist:in both modes. The search box is compact: desktop keeps the applied query in a trigger field, while phones show only a magnifier button. Clicking, tapping, or focusing it opens a search dialog; it submits on Enter or the phone keyboard's Go/Search key, and Escape, the backdrop, or the close button discard an unsubmitted draft. The dialog is full-width on phones and spans from the brand to the search box over the header row on desktop, with a footer summarizing the recognized fields and operators. - Fielded search syntax:
album:"abbey road" artist:beatles,track:"come together",genre:"Jazz" region:"Brazil",composer:jobim,serie:"Rock Candy",source:"Bonus Tracks", combined withAND,OR, implicit AND, and parentheses. Quoted values are matched as contiguous phrases. A query made only of plain keywords is treated as one phrase; useANDto combine independent words. The?button beside the search control opens a collapsible Help dialog with Keyboard shortcuts, Search syntax, and About Happy Trails sections, including clickable examples, package author/contributor links, and a bug/feedback link. - Keyboard shortcuts:
/opens the search dialog and?opens the help dialog. With the player open,Spacetoggles playback,←/→seek,Shift+←/→skip tracks,↑/↓adjust volume,Mmutes, andRrestarts the current track. The help dialog lists these plus the Cover Flow and map keys. - Album and artist names are search shortcuts in cards and in the album dialog;
genre tags add a
genre:"<name>"term and region tags add aregion:"<name>"term everywhere. Name links clear facet selections, while tag chips add to them. - Multi-artist values are parsed into individual artists, including
comma-separated lists; a configurable exception list keeps names such as
Earth, Wind & Firetogether. Each detected name is its own search link in cards, the dialog header, and track artist lines. - The server checks for database changes every 60 seconds by default and silently rebuilds the snapshot when needed. The header Refresh control enables when a newer snapshot is available and reloads the current view; it never triggers a rebuild itself.
- A two-section Sort menu: Sort by (Added on, Released on, Artist name, Album name) and Order (Ascending / Descending), each with a check mark on the active choice. Changing one preserves the other. The default is Added on + Descending. Missing years and track dates always sort last.
- Album dialog with the full track list and duration. Composer tags appear as a separate italic Composer line when they differ from the track and album artists; each composer name is a link that runs a top-level search. When a track has genre or region tags beyond the set shared by every track in the album, those specific tags appear as clickable pills under the track title, while the album header keeps the full union. When a search narrows the tracks, the dialog defaults to matching tracks and offers a Matching tracks / Show all toggle; if every track matches, the toggle is omitted. Album Play follows the current toggle state. Merged multi-CD albums group tracks under their original disc labels, since disc numbers frequently collide across the source titles.
- The album dialog header shows a pill for each series the album belongs to,
directly below the genre/region tags. Clicking a pill runs the equivalent
serie:"<name>"search. - Track comments are aggregated across an album's tracks, deduplicated, and
shown in the album dialog header beneath the tag and series pills. Absolute
http(s)URLs inside comments are clickable and open in a new tab. - Album covers from Synology AudioStation, proxied and cached by the server. Albums without covers keep the generated gradient/initials cover.
- A pill for every PDF in the album folder (for example Artwork and Booklet), labelled with the filename minus its extension. The server lists the folder through Synology FileStation and streams each PDF to the browser, which opens it with its normal PDF viewer.
- Sign in with your own Synology account, then Play hands an album to Audio Station: the server replaces the Audio Station web-player queue with the album's tracks and opens Audio Station. Each track row also has a small blue play control that queues just that track. No audio player lives in this app. Play controls are hidden until the app session is authenticated.
- Shareable URL state
(
?q=genre%3A%22Jazz%22+region%3A%22France%22&sort=artist&order=asc&view=tracks). Facet selections are encoded asgenre:/region:/serie:terms inq, andview=tracksselects the track list. - Browser Back/Forward replays searches, filters, sorts, and album dialogs. Opening an album records a history entry; closing it consumes that entry, and Forward reopens it.
- Light/dark colour schemes, keyboard navigation,
/opens the search dialog. - Responsive layout for narrow screens, with an icon-only search control and a full-width search sheet on phones.
- Node.js 24 or newer (the server uses the built-in
node:sqlitemodule). gitavailable tonpm install; the Cover Flow component is a pinned GitHub dependency (see .npmrc).- Read access to a PostgreSQL database containing the
musictable. - A writable local directory for the SQLite search index (default
$TMPDIR/happy-trails-index), orINDEX_DB_DIR=:memory:to avoid disk writes. See Index storage. - Optional: Read access to the
tracktable and a Synology DSM URL for Audio Station playback. A DSM service account is optional and used for album covers and artwork lookups; users sign in with their own account to play.
cd happy-trails
npm install
cp .env.example .env # then edit the connection settings
npm run build
npm startOpen http://127.0.0.1:3000.
The .env.example in this checkout is already configured for the mediaserver
database on localhost; the password is taken from ~/.pgpass by
node-postgres, so no secret is stored in the file.
The server also reads the workspace-level ../.env, where the existing
Synology settings live as DSADDR / DSUSER / DSPASSWD (or set DSM_URL /
DSM_USER / DSM_PASS in this app's .env):
DSM_URL(orDSADDR) is required for user sign-in and playback.DSM_USER/DSM_PASSare an optional service account used for album covers and artwork lookups. It needs read access to the music share. Users sign in with their own DSM account in the app to play.
Without a DSM URL, the app still runs with generated covers and no Play links.
The search index is written to $TMPDIR/happy-trails-index by default. Set
INDEX_DB_DIR to a stable local directory in .env, or use
INDEX_DB_DIR=:memory:; see Index storage.
For development, run the client bundler, the TypeScript typecheck watcher, and the server with auto-restart:
npm run devnpm run dev runs esbuild in watch mode, rebuilds public/client/main.js and
main.css, type-checks the client, and restarts the API with tsx watch.
Other useful scripts:
| Script | Purpose |
|---|---|
npm run build |
Build server (dist/) and the client bundle (public/client/) |
npm run build:places |
Regenerate the map country lookup and world basemap from Natural Earth |
npm run audit:places |
Audit live region tags against the place catalog (requires database access) |
npm run typecheck |
Type-check both targets without emitting |
npm start |
Run the built server |
npm run dev |
Watch client, typecheck, and server |
Build the image (the app, server, and compiled client are all included; .env
is deliberately not baked into it):
docker build -t happy-trails .If Docker's embedded DNS is unreliable on the build host, build with
docker build --network=host -t happy-trails ..
Run it with the environment file mounted read-only:
docker run --rm -p 3000:3000 \
-v happy-trails-index:/data \
-v "$PWD/.env:/app/.env:ro" \
-v "$HOME/.pgpass:/home/node/.pgpass:ro" \
happy-trailsOpen http://localhost:3000.
The /data volume holds the disposable SQLite search index; the image sets
INDEX_DB_DIR=/data/index and runs as the unprivileged node user. See
Index storage for named volumes, host bind mounts, and the
:memory: alternative.
Notes:
- The mounted
.envis read from/app/.env. The container forcesHOST=0.0.0.0and defaultsPORT=3000, overriding those values in.env; override the port with-e PORT=8080and map-p 8080:8080. ~/.pgpassis not part of the image. Either mount it as shown above, or putPGPASSWORD/DATABASE_URLin the mounted.env.- The mounted
.envmust be readable by the container'snodeuser (UID 1000); mode644is sufficient. The same applies to a mounted.pgpassif the host user does not have UID 1000. - The image runs as the unprivileged
nodeuser and health-checks/api/status. The HTTP server starts immediately;/api/statusreportsready:falsewhile the first index builds, and data endpoints return503until it is ready. - The index volume must be writable by UID 1000. A named volume mounted at
/datainherits the image's ownership; a host bind mount needs its directory owned by UID 1000.
The search index is a disposable SQLite database rebuilt from PostgreSQL at
startup (and whenever the change fingerprint moves). It is written to
INDEX_DB_DIR, which defaults to $TMPDIR/happy-trails-index (usually
/tmp/happy-trails-index). Each build gets a unique file; after a successful
build the new file is published and the old file is deleted. A startup sweep
removes files left behind by a crash.
In file-backed mode the build runs in a worker thread: the main thread
keeps serving the previous index (or 503 on the very first build) while the
worker reads PostgreSQL and writes the new file. :memory: mode builds in the
main thread because an in-memory SQLite database cannot be handed to another
thread.
INDEX_DB_DIR=:memory: keeps the index in the Node process instead. That uses
more memory and needs no writable directory; it is useful for development,
small libraries, or a container without a writable volume.
Use a local filesystem directory. Do not place it on an SMB/NFS share:
SQLite relies on POSIX locking and local file semantics. Mount or provide the
containing directory, never a single .sqlite file — the app replaces the
file on every rebuild.
Disk usage is about 350–400 MB for a 410k-track library, and roughly double that during a rebuild while the old and new files coexist. Leave 1–2 GB free.
The default writes to $TMPDIR/happy-trails-index. To choose a stable
location:
mkdir -p /var/lib/happy-trails/index
chmod 700 /var/lib/happy-trails/index
INDEX_DB_DIR=/var/lib/happy-trails/index npm startFor the in-memory behavior:
INDEX_DB_DIR=:memory: npm startThe directory must be writable by the user running the server. The startup
sweep deletes happy-trails-index-* files in that directory, so use a
dedicated directory per running instance; do not point two live servers at
the same directory.
The image creates /data/index, gives it to the node user, and sets
INDEX_DB_DIR=/data/index. Mount a volume at /data so the index does not
land on the container's writable layer:
docker run --rm -p 3000:3000 \
-v happy-trails-index:/data \
-v "$PWD/.env:/app/.env:ro" \
-v "$HOME/.pgpass:/home/node/.pgpass:ro" \
happy-trailsA named volume is the least surprising option; Docker manages its ownership,
and it can be removed with docker volume rm (Compose prefixes the volume name
with the project). The index does not need to survive restarts.
To keep the file on a specific host directory (for example an SSD volume), use a bind mount. The host directory must be writable by UID 1000:
sudo mkdir -p /volume1/docker/happy-trails/index
sudo chown -R 1000:1000 /volume1/docker/happy-trails
docker run --rm -p 3000:3000 \
-v /volume1/docker/happy-trails:/data \
-v "$PWD/.env:/app/.env:ro" \
happy-trailsCompose:
services:
happy-trails:
image: happy-trails
ports: ["3000:3000"]
env_file: .env
volumes:
- happy-trails-index:/data
volumes:
happy-trails-index:Notes:
- Mount the directory (
/dataor/data/index), never a singleindex.sqlitefile. - Do not use a
tmpfsmount if you want the memory savings; a tmpfs index is an in-memory database with extra steps. UseINDEX_DB_DIR=:memory:if you want RAM instead of disk. - Keep the volume on a local disk. Avoid network-backed volume plugins and SMB/NFS bind mounts.
- The index is ephemeral. Mounting a volume does not currently avoid the startup rebuild; the server always rebuilds from PostgreSQL.
- Use one running instance per index directory. The startup sweep removes
stale
happy-trails-index-*files and would delete another live instance's index.
On a 410k-track library the on-disk index measures ~373 MB, with a ~43–46 s
total worker build, ~560–600 MB peak build RSS, and ~75 MB steady process RSS;
the OS page cache holds the file and is reclaimable. :memory: mode peaks
around 920 MB RSS. Query latency is effectively the same once the file is in
page cache.
All variables are optional; see .env.example.
| Variable | Default | Description |
|---|---|---|
DATABASE_URL |
— | Full libpq URL. If unset, standard PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD apply. |
HOST |
127.0.0.1 |
Interface to bind. Use 0.0.0.0 to expose the app on the LAN. |
PORT |
3000 |
HTTP port. |
TRUST_PROXY |
off | Express trust proxy setting. Set it to the reverse proxy's address/CIDR, a preset such as loopback, or a hop count when the app sits behind a trusted proxy, so req.ip is the real client IP for login rate limiting (and req.secure is correct for cookie flags). Do not enable it on a directly exposed port. |
LOGIN_RATE_LIMIT_MAX |
20 |
Failed sign-ins allowed per client IP per window; further attempts get 429 with Retry-After. |
LOGIN_ACCOUNT_LIMIT_MAX |
5 |
Failed sign-ins allowed per account per window, regardless of client IP. |
LOGIN_RATE_LIMIT_WINDOW_MS |
900000 |
Login rate-limit window (15 minutes). |
MUSIC_SCHEMA |
public |
Schema containing the tables. Must be a plain identifier. |
MUSIC_TABLE |
music |
Table to read. Must be a plain identifier. |
TRACK_TABLE |
track |
Table used to map a music path to an AudioStation cover id. |
INDEX_DB_DIR |
$TMPDIR/happy-trails-index |
Directory for the on-disk SQLite search index. Must be writable and on a local filesystem; use a dedicated directory per running instance. Set to :memory: to keep the index in RAM. See Index storage. |
DSM_URL |
— | Synology DSM base URL; required for user sign-in, native streaming, and album covers. Falls back to DSADDR. |
NATIVE_PLAYBACK_ENABLED |
true |
Expose GET /api/stream/:id for the native player. Requires DSM_URL. Set to false to use the Audio Station handoff only. |
AUDIO_STATION_FALLBACK_ENABLED |
true |
Keep the Audio Station handoff available as a fallback. Also requires a resolved DSM_FRONTEND_URL (or DSM_URL). |
SCREEN_WAKE_LOCK_ENABLED |
true |
Keep the screen awake while the native player is playing. Uses the browser Screen Wake Lock API; best-effort and only while the page is visible. Set to false to disable. |
DSM_FRONTEND_URL |
value of DSM_URL |
Synology DSM frontend URL for playback redirection. A full http(s) URL is used verbatim; empty falls back to DSM_URL / DSADDR. Otherwise use :port to keep the host the browser used and change only the port (for example :5001); path rewriting is not supported. With :port, the host must match DSM_FRONTEND_ALLOWED_ORIGINS. |
DSM_FRONTEND_ALLOWED_ORIGINS |
— | Comma-separated exact origins the app is served from (scheme://host[:port], no path), for example https://mediatheque.example:8443,https://nas-local:8443. Required when DSM_FRONTEND_URL is :port. A request whose Host (or X-Forwarded-Host, for proxies that rewrite it) matches an entry uses that origin; any other host disables the redirect. The entry's scheme is also used for the redirect, so list the scheme DSM is served under (normally the same as the app). Origin and Referer are never trusted for this. |
DSM_USER / DSM_PASS |
— | Optional service account used for album covers, full-resolution original covers, and artwork lookups. It needs read access to the music share. Falls back to DSUSER / DSPASSWD; playback uses each user's own sign-in. |
DSM_TLS_REJECT_UNAUTHORIZED |
false |
Verify the NAS TLS certificate (the stock certificate is self-signed). |
DSM_TIMEOUT_MS |
10000 |
Timeout for Synology requests. |
COVER_CACHE_TTL_MS |
86400000 |
Server-side cover cache TTL. |
COVER_CACHE_ENTRIES |
500 |
Maximum cached covers (LRU); 0 disables the cache. |
LIBRARY_CHECK_MS |
60000 |
Delay before checking the music table for changes; a detected change triggers a silent rebuild. The next check is scheduled after the previous check and any rebuild finish, so a rebuild longer than this interval delays the next check rather than overlapping it. LIBRARY_REFRESH_MS is accepted as a legacy fallback. |
PAGE_SIZE |
48 |
Results per page for the Albums and Tracks views, the default limit for API requests that omit it, and the visible Play all queue window. The client reads the effective value from /api/status. |
MAX_PAGE_SIZE |
200 |
Upper bound for any API limit; PAGE_SIZE is clamped to it. |
ARTIST_SEPARATOR_WORDS |
feat., com, part., avec, with, et, e, con, vs., mit |
Additional comma-separated words that separate multiple artists; appended to the defaults. One-letter words match case-sensitively. |
ARTIST_EXCEPTIONS |
Earth, Wind & Fire; Florence + The Machine; Simon & Garfunkel; Crosby, Stills, Nash & Young |
Additional artist names kept intact. Entries are separated by a vertical-bar character because the names contain commas; appended to the defaults. |
REGION_TAGS |
— | Additional genre tags to classify as countries/regions, separated by a vertical-bar character. ISO country names, macro-regions, and common subnational regions are detected automatically. |
SERIES_DENYLIST |
— | Series names that remove an album from all series when found anywhere in its title. Separate entries with a vertical-bar character; matching ignores case, accents, and apostrophes. |
SERIES_ALLOWLIST |
— | Additional series names matched anywhere in an album title that has no {...} series. Entries are checked in configured order and only the first match is retained for the album. Separate entries with a vertical-bar character; matching ignores case, accents, and apostrophes. |
LOOSE_TRACKS_FOLDERS |
— | Folder prefixes holding loose tracks, such as covers collections and random-track folders. Tracks under them stay fully indexed and searchable in Tracks mode, but the albums they name are hidden from the Albums view, album-mode Play all, and album facet counts. Entries are path prefixes (the whole subtree is covered), separated by a vertical-bar character; trailing slashes are ignored. |
DB_STATEMENT_TIMEOUT_MS |
30000 |
Per-query statement timeout. |
When DSM (nginx) terminates TLS and forwards to the app, Express sees the
proxy as the socket peer. Set TRUST_PROXY so login rate limiting sees the
real client IP and mw_session gets the Secure flag. Per-account rate
limiting works either way.
-
Keep the app port off the LAN. Bind the published container port to loopback so clients must go through the proxy and cannot forge forwarding headers themselves:
docker run --rm -p 127.0.0.1:3000:3000 ...
In Container Manager, bind the published port to
localhost. -
Trust exactly one hop:
TRUST_PROXY=1
DSM's reverse proxy normally sends
X-Forwarded-For(appending the real client) andX-Forwarded-Proto. You can confirm by temporarily loggingreq.socket.remoteAddressandreq.headers['x-forwarded-for']for one request;req.ipshould be the browser's address, not the Docker gateway. -
If the port must be exposed, use the proxy's address or subnet instead of a hop count, so only proxy connections can influence
req.ip:docker network inspect bridge -f '{{(index .IPAM.Config 0).Gateway}}' # TRUST_PROXY=172.17.0.1 (or the bridge subnet, e.g. 172.17.0.0/16)
-
TRUST_PROXY=loopbackis only right when the proxy connects from127.0.0.1(Docker host networking or the app running directly on DSM). With ordinary bridge networking the app sees the bridge gateway, soloopbacksilently disables per-IP limiting and cookieSecure.
Never use TRUST_PROXY=true: with an appending proxy, Express would trust a
client-supplied X-Forwarded-For entry. Leave TRUST_PROXY unset when the app
is accessed directly.
The repository includes a Caddyfile that serves the app on port
8080 to other devices on the local network. Keep the app on its default
loopback bind:
HOST=127.0.0.1
PORT=3000
TRUST_PROXY=loopbackTRUST_PROXY=loopback makes Express trust Caddy's forwarding headers when Caddy
runs on the same host. If Caddy runs in a container, use the bridge address or
subnet instead, as described above.
Start the app, then from the repository root:
caddy run --config CaddyfileBrowse to http://<laptop-lan-ip>:8080. The Caddyfile forwards Range requests
and disables response buffering for the Audio Station stream. It also disables
Caddy's admin endpoint so the standalone proxy can run alongside a Caddy system
service; remove the admin off block if this is your only Caddy instance. The
default block is plain HTTP; sign-in sends DSM credentials, so use it only on a
trusted LAN or uncomment the tls internal HTTPS example and trust Caddy's
local CA on the client devices.
If the page works from the laptop but not from other LAN devices, allow the port through the host firewall. On Ubuntu/Pop!_OS with UFW:
sudo ufw allow from 192.168.0.0/24 to any port 8080 proto tcp
sudo ufw status verboseAdjust the subnet to match the LAN. If the devices are on a guest Wi-Fi or an AP with client isolation, they will still be unable to reach the laptop.
If you use the Audio Station fallback with DSM_FRONTEND_URL=:port, add the
Caddy origin (for example http://192.168.1.20:8080) to
DSM_FRONTEND_ALLOWED_ORIGINS.
The mediaserver database holds >400k tracks across >30k raw album titles (before merging
multi-CD variants). Parsing the comma-separated genre column and grouping by
album in SQL on every request is slow (multi-second queries on the production
dataset), so the server aggregates the library at startup and rebuilds it
silently when its periodic change check detects new data (see below):
The aggregated rows are parsed and written to a SQLite database (on disk by
default; see Index storage).
The genre string is split on commas, trimmed, deduplicated, and stored in
genres/album_genres or regions/album_regions, depending on whether the
tag is a country/region name. Album titles are normalised by stripping a
whitespace-separated // ... suffix; rows that end up with the same title and
artist are merged: track counts and durations are summed, the newest upload
date wins, and tags are unioned. Parsed artists and the original raw titles are
kept in album_artists and album_sources. Distinct non-empty comment
values are trimmed, deduplicated across the album's tracks and merged source
titles, and stored per album in album_comments; the album dialog renders them
in sorted order in its header and linkifies absolute http(s) URLs. The
original raw titles, all track-level artists, and composer tags are folded into
the FTS search text, so labels such as "The Vanilla Tapes", guest artists, and
composers still match.
Every music row is also written to a tracks table with its title, track
artist, album artist, raw source title, composer, and its own genre/region
display names and keys, plus a separate track_search FTS index. Track search
uses the track's own tags for genre: and region: filters; album-title and
serie: terms resolve through the album. track: searches track titles and,
in Albums mode, finds albums that contain a matching track. In file-backed mode
the aggregation and SQLite build run in a worker thread; the main thread keeps
serving the previous index and the server listens from startup.
See
docs/sqlite-index.md for the schema and query
equivalents.
Folder prefixes in LOOSE_TRACKS_FOLDERS (covers collections, random tracks,
…) change album visibility, not indexing. An album is flagged track_only when
every one of its raw titles consists solely of tracks under those prefixes. Such
albums keep their track counts, tags, sources, and comments in the index, and
their tracks remain in the Tracks view, but the albums are omitted from the
Albums listing, album-mode Play all, the status album total, and the album side
of facet counts. A mixed album with at least one track outside a loose folder
stays visible with its normal counts. Facet rows carry both counts, precomputed
at build time: albumCount counts visible albums; trackCount counts every
indexed track, using the track's own genre/region tags and its album's series,
so it matches the Tracks-mode filter result. The client displays the count for
the active mode and hides rows whose active-mode count is zero.
Country/region detection uses Intl.DisplayNames for ISO 3166 country names in
English, French, German, Spanish, Portuguese, and Italian, plus UN M49
macro-regions and a curated list of subnational regions, historical countries,
and spelling variants (Corsica, Catalonia, Andalusia, Byelorussia,
Zaire, …). Matching is exact after folding case, accents, and apostrophe
variants; REGION_TAGS adds site-specific names. Compound tags such as
Jazz/Brazil are still treated as genres because only whole tags are
classified.
Search folding lowercases the text, applies Unicode NFKD, removes combining
marks, and maps Latin letters that NFKD leaves intact (ø→o, æ→ae,
œ→oe, ß→ss, ł→l, đ→d, ð→d, þ→th, ı→i, and a few
others). The folded text is stored in albums.search_text, and queries are
folded with the same function, so accented and unaccented searches match in
either direction. album_search is an FTS5 table using the trigram
tokenizer, which preserves substring semantics; phrases shorter than three
characters fall back to an exact instr() scan.
The search expression parser supports plain keyword phrases, album:,
artist:, track:, serie:, composer:, source:, genre:, and region:
fields, quoted phrases, implicit/explicit AND, OR, and parentheses. Field
terms target dedicated folded columns; each FTS term is evaluated once in a
materialized CTE so OR expressions do not rescan the FTS index per album.
Composer values come from the track-level composer column populated from
FLAC/ID3 tags.
Series/label values are extracted from {...} groups in the album title. Each
group is split on / (spaces are optional), and every resulting token is a
distinct series; no other tokenizing is applied, so {A, B}, {A feat. B},
and {Earth, Wind & Fire} stay one name each. Every group in a title
contributes its tokens.
SERIES_ALLOWLIST adds series names for album titles that have no {...}
tokens. Each allowlist entry is matched as a substring anywhere in the title
(case, accents, and apostrophes are ignored); entries are checked in configured
order, and only the first match is retained for the album. Albums with braced
series are not considered for the allowlist.
SERIES_DENYLIST replaces SERIES_EXCEPTIONS and is applied last. If any
denylist entry occurs anywhere in the album title, the album is removed from
all series, whether the series came from braces or the allowlist. There are
no default entries.
Values are stored in album_series, matched exactly with serie: (alias
label:), and are also part of the all-field text.
Artist parsing applies to the effective album artist and to each track artist.
A punctuation run is a separator only when whitespace surrounds it, so
Artist A & Artist B, Artist A / Artist B, and Artist A - Artist B split,
while AC/DC, Jay-Z, and R.E.M. stay intact. A comma followed by
whitespace is also a separator, so A, B, C becomes three names; A,B
without the following space is left intact.
Names listed in ARTIST_EXCEPTIONS are masked before separator processing and
restored verbatim, so Earth, Wind & Fire and Florence + The Machine stay
intact. The defaults also include Simon & Garfunkel and Crosby, Stills, Nash &
Young; ARTIST_EXCEPTIONS adds more (separated by a vertical-bar character
because the names contain commas).
Matching is case-insensitive and whole-name only, but the original spelling is
preserved.
Words listed in ARTIST_SEPARATOR_WORDS are separators when they are
standalone words surrounded by whitespace; the defaults are
feat., com, part., avec, with, et, e, con, vs., mit, and
ARTIST_SEPARATOR_WORDS adds more. One-letter words are matched
case-sensitively, so E Street Band is not
split. Parsed names are exposed as
artists in the API and rendered as separate search links (joined by ·);
the original string remains in artist/albumArtist.
Genres and regions are matched case-insensitively; region keys also fold
accents and apostrophe variants. Facet counts are the number of merged albums
carrying each tag. The UI writes selections as genre: / region: query
terms: any joins the terms with OR, all with AND, and the genre and
region groups are combined with AND. Sorting uses precomputed dense ranks
that reproduce the old Intl.Collator ordering, including its
case/accent-insensitive ties. Filtering, searching, and pagination are single
SQLite queries; the current dataset answers typical searches in a few
milliseconds.
Instead of rebuilding on a fixed interval, the server runs a cheap aggregate
every LIBRARY_CHECK_MS (default 60s): row count, MAX(date), MAX(mdate),
SUM(filesize), and MAX(id) over fs_online rows. If it differs from the
fingerprint stored with the current snapshot, the server rebuilds in the
background, swaps the snapshot atomically, and increments libraryVersion.
/api/status exposes libraryVersion, lastCheckedAt, refreshing, and
checkIntervalMs; /api/albums and /api/genres include the
libraryVersion of the snapshot they served.
Checks are serial: the next check is scheduled only after the previous check
(including any worker rebuild) finishes. A rebuild longer than
LIBRARY_CHECK_MS therefore delays the next check rather than overlapping it
or queueing a second rebuild. Changes made during a rebuild are not lost; the
next check compares the live fingerprint with the one stored at the start of
the build and rebuilds again if it moved. The rebuilding guard is a second
safety net against concurrent rebuilds.
The frontend polls /api/status every 30s (paused while the tab is hidden).
It compares the server's version with the version of the data it rendered.
When they differ, the header Refresh button lights up with a dot; clicking it
re-fetches genres and albums for the current search/filters (resetting
pagination to the first page), clears the track cache, and updates the loaded
version. It never triggers a rebuild. A failed rebuild keeps serving the old
snapshot, and the button stays disabled until a newer version exists.
The fingerprint catches inserts/deletes (count/id), uploads (date), and most
metadata/file changes (mdate/size). An update that changes none of those
fields would not be seen; a DB trigger or pg_stat_user_tables counters can be
added if that matters. The check is a cheap scan (sub-second); the rebuild is
the expensive part (~43–46s on the reference library, in a worker thread).
Track lists are not cached: opening an album issues a parameterized,
index-backed query against music for every raw title merged into it, and
returns the current rows. The response carries each track's original title,
composer tag, and source title, so the dialog can group merged CDs under their
labels (Main album, The Vanilla Tapes, CD02 …) instead of relying on disc
numbers that often repeat across the sources. Composer tags are surfaced under
the track artist only when they add information (they are suppressed when
equal to the track or album artist), and each parsed composer name links to a
top-level search. The client caches responses for the lifetime of the page.
Covers are fetched through the server; the optional cover service account is
never exposed to the browser. Each merged album keeps a representative file path (preferring the
main, unsuffixed source). When a cover is requested, the server resolves that
path to track.id — music.id uses a different sequence — and calls the
AudioStation cover API with id=music_<track.id> and output_default=false,
so albums without artwork produce a 404 instead of Synology's generic image.
The UI then keeps the generated gradient cover. Cover bytes are cached in a
bounded LRU (COVER_CACHE_ENTRIES) and served with a one-day browser cache;
the client requests them lazily as cards become visible.
Album booklet PDFs use Synology FileStation. The representative media path is
/volume1/music/...; FileStation addresses the same file as /music/..., so
the server strips the volume prefix and lists that folder with
SYNO.FileStation.List (list). Every regular file whose name ends in .pdf
(case-insensitive) becomes a pill in the album dialog, labelled with its
filename minus the final extension and sorted naturally. Each pill opens
GET /api/albums/:key/artworks/:filename, which streams the file through
SYNO.FileStation.Download (mode=open) and forwards browser range requests,
so the browser's own PDF viewer can open and seek in even very large booklets
without buffering them in server memory. Filenames are validated as single
path segments and the Content-Disposition header is sanitized. The folder
listing is cached briefly in memory; empty listings are retried sooner than
non-empty ones. The service account needs read access to the music share.
Region tags are the only input to the map geolocation layer. The server
classifies genre tags as regions during index building; the map never parses
album or artist text. Country names and coordinates are generated from
Natural Earth (public domain) and
Intl.DisplayNames in the catalogue's six languages, then merged with the
manual catalog in
src/shared/placeCatalog.ts.
Catalog entries add cities, subnational regions, macro-regions, historical names, spelling variants, and coordinate overrides:
{
name: 'Vancouver',
tier: 'city',
countryCode: 'CA',
lat: 49.2827,
lon: -123.1207,
}tier is city, subnational, country, or macro; countryCode is the ISO
alpha-2 parent/sovereign country. Because the catalog also feeds region-tag
recognition, adding an entry makes that name a region tag (visible in the
Regions facet and region: searches) and requires an index rebuild. Manual
entries take priority over the generated country lookup.
The generated assets are committed under public/map/: places.json maps
folded country names to locations, and world-110m.geojson is the compact
basemap. Regenerate them with npm run build:places (the script downloads
Natural Earth data and caches it under node_modules/.cache/). The app never
fetches map data from a third party at runtime. Map mode renders these assets
with a lazily loaded Leaflet chunk (BSD-2-Clause); its
license is included in the generated third-party notices. Leaflet core does not
ship Equal Earth, so the map registers a small custom L.CRS built from the
Equal Earth formulas in
src/shared/equalEarth.ts; no projection plugin
is needed. Map pins group albums by resolved location, fan out co-located
covers, and open the album dialog when a cover is activated.
npm run audit:places checks the live library against the catalog and reports
unresolved region tags, city-name candidates, compound tags containing place
names, and catalog entries no longer present. It also skips a small denylist of
genre/people names that are not places (Americana, Berber, Turkestan,
Roma). Compound tags containing / or + are normalized manually in the
track metadata; the audit lists them with their place parts to support that
cleanup.
Every committed search, facet change, match-mode change, sort change, view-mode change, and clear action pushes a browser history entry whose URL carries the filter and layout state. A search is applied only when it is submitted from the search dialog, so each submission is one entry; typing a draft changes neither the URL nor the results. Escape, the backdrop, and the close button discard the draft and leave the header showing the last applied query. Back returns to the previous applied query rather than stepping through every keystroke. Loading more albums, scroll position, map pan/zoom, and full-screen changes are not part of the recorded state.
Opening an album pushes another entry. The full album summary is stored in
history.state (the URL is unchanged), so Back closes the dialog and returns to
the previous search/filter state, while Forward reopens it even though the
album list may have been reloaded. Closing the dialog with its close button,
Escape, or the backdrop calls history.back(), which consumes the modal entry
instead of leaving a stale one. Searches and filter changes started from inside
the dialog close it for navigation but keep the dialog entry behind the new
state, so Back reopens the album. A page reload also restores an open dialog
from history.state.
Native playback streams a track through GET /api/stream/:id, which proxies
Synology's AudioStation/stream.cgi with the signed-in user's session. The
browser never receives the DSM token or cookies. Range requests are forwarded,
so the footer player can seek. The footer player, preload/advance logic, queue
editing, and persistence are described in
docs/native-playback.md.
Play controls on album cards, the album dialog, and track rows start native
playback. They, and the footer, are only shown while signed in; the stream
endpoint independently returns 401 without a session. Album Play queues the
whole album; a track Play also queues the whole album but starts at the clicked
track.
Ctrl/Cmd-click (or a middle-click) on a Play link opens the Audio Station
handoff instead. The album dialog also shows a secondary Audio Station link
when the fallback is enabled, and an unplayable track's error state links to
it.
The Audio Station handoff below remains available as a fallback when
AUDIO_STATION_FALLBACK_ENABLED is true and a frontend target is configured.
Users sign in with their own DSM account from the app's header. The browser
posts the username and password to POST /api/session/login; the server
verifies them with SYNO.API.Auth and keeps a DsmClient for that user in an
in-memory session (8 hour TTL), referenced by an HttpOnly mw_session cookie.
Passwords are never written to disk or returned to the browser; the in-memory
client retains them only so it can renew an expired DSM token. Signing out (or
restarting the server) drops the session. Accounts with two-factor
authentication are not supported.
Play links point at GET /play/:key in a new tab. The card Play chips and the
dialog Play button are only rendered while the app session is authenticated;
signing out removes them. Without a signed-in app session, the route queues
nothing and redirects to /?login=1&play=…; the app opens the sign-in dialog
and continues to playback after a successful sign-in. The dialog Play button
follows the Matching tracks / Show all toggle: matching mode passes the
current search as q and queues only matching tracks, while Show all queues the
whole album. With a session, the route resolves the album's source titles to
AudioStation song ids by joining music to track on path, ordered by source
title, disc, and track.
It uses that user's DSM client to replace the Audio Station web-player queue
(web_player.cgi method=updateplaylist) with those music_<track.id> songs
and play=true. The existing queue length is read first and passed as
limit, so the queue is replaced instead of appended. The update call carries
the session token in an X-SYNO-TOKEN header (the query-string form is not
accepted), then the route redirects with 303 to
<DSM>/?launchApp=SYNO.SDS.AudioStation.Application.
The queued album belongs to the signed-in DSM user, so the browser must also be signed into DSM (in that browser) as the same user for Audio Station to show the queue. Browsers normally do not allow Audio Station to start audio without a user gesture, so press the player's Play button once if playback does not start by itself.
Notes on the data:
- "Latest upload date" uses
date.mdateis the media server's modification time, which changes when files or metadata are touched and would make edited albums look newly added, so it is not used for the "Added on" sort. Both columns are wall-clocktimestampvalues without a zone; they are displayed as recorded rather than converted between time zones. - Tracks with
fs_online = falseare excluded. - Albums with no
album_artistfall back to the track artist; albums without an artist fall back toUnknown Artist; a missing/empty album title becomes(Unknown Album). - The multi-CD suffix must be preceded by whitespace. Titles that use
//inline without spaces (there is one such title in the current library) are left untouched. - Some genre values are inconsistent in the source data (for example
Bossa Nova,Bossa Nova. Jazz, andBossa Nova+Jazzare three genres). The facets mirror the data rather than trying to normalise those labels. Country/region detection also works on whole tags only, soJazz/Brazilremains a genre even thoughBrazilalone is a region. Detection classifies tags individually rather than canonicalising them, so multilingual variants such asGermany/Allemagnecan appear as separate region entries.
If the database is unavailable at startup, the HTTP server still starts and returns an explanatory error; the UI retries automatically and the change check keeps retrying in the background.
The suite is deterministic and does not require PostgreSQL, DSM, or network access. It uses synthetic album/track fixtures and fake cover, session, and playback services. tests/helpers/test-env.ts is loaded with node --import before the app config, clearing the search-related overrides (SERIES_ALLOWLIST, SERIES_EXCEPTIONS, ARTIST_SEPARATOR_WORDS, ARTIST_EXCEPTIONS, REGION_TAGS, LOOSE_TRACKS_FOLDERS) so a developer .env cannot change fixture results.
npm run test:install-browsers # once per machine/CI
npm run lint # ESLint
npm run typecheck # server, client, and tests
npm test # API + search + artwork + client + all UI browsers
npm run test:chromium # backend + Chromium UI
npm run test:firefox # backend + Firefox UI
npm run test:webkit # backend + WebKit UI
npm run test:api # Express endpoints
npm run test:artwork # media-path to FileStation path mapping
npm run test:client # pure client queue-source/window unit tests
npm run test:config # DSM frontend URL parsing
npm run test:search # parser + SQLite search/tag combinations
npm run test:security # proof-of-vulnerability audit suite
npm run test:ui # Playwright UI tests (Chromium + Firefox + WebKit)
npm run test:ui:chromium # Playwright, Chromium only
npm run test:ui:firefox # Playwright, Firefox only
npm run test:ui:webkit # Playwright, WebKit only
npm run test:ui:headed # Playwright with visible browsersOn Linux, npx playwright install --with-deps chromium firefox webkit installs
the required system libraries (it needs sudo). If every WebKit test fails
immediately with Host system is missing dependencies or libavif13, the
WebKit browser cannot launch, so even non-audio tests fail before the page
opens. Install the system dependencies once:
sudo npx playwright install-deps webkit
# On Ubuntu 22.04 / Pop!_OS 22.04, the fallback build may instead need:
sudo apt install libavif13CI installs WebKit with --with-deps. Playwright's WebKit is desktop WebKit,
not Apple Safari; real Safari/iOS behavior still needs a device or cloud-browser
check.
- API tests start the real Express app via
createApp()with an injected fixture index. - Stream tests cover native playback auth,
Range/HEADforwarding, MIME normalization, missing tracks, unsupported ranges, disabled playback, and DSM failure mapping. - Search tests cover bare and fielded terms, quoted phrases,
AND/OR, parentheses, aliases, accent folding, composer search, genre/region modes, combinations, the album and track indexes,track:-in-Albums matching, and file-backed index creation/cleanup plus the worker handoff (persist/open). - Artwork tests cover the
/volumeN/shareto/sharepath conversion used by FileStation. - UI tests use a fixture server with expanded sample data, so facet counts, artist punctuation, composer links, sign-in/Play visibility, album PDF pill visibility, the Albums/Tracks switch, compact track rows, Back/Forward search/mode/dialog restoration, help popups, and the sticky error banner are checked against stable data. The player tests cover album and track-started album queues, transport controls, seeking, queue reorder/removal, volume/mute, keyboard shortcuts, unsupported-format warnings, reload persistence, playback continuing while album dialogs open, and Play all in both modes including page-size-based refills after the visible query changes.
- Pure client tests cover the Play all window/cursor arithmetic in
src/client/queueSource.ts; backend tests cover the album-mode flattening order and pagination. - Assertions use set relationships (unions/intersections), field membership, ordering, pagination slices, and UI-versus-API totals instead of fixed catalogue result counts.
- Playwright is configured in
playwright.config.tswith Chromium, Firefox, and WebKit projects; it startstests/fixtures/ui-server.tson port 4173 and builds the client before running. The player tests use a silent synthetic WAV, so local runs do not produce sound. .github/workflows/ci.ymlruns lint, typecheck, backend tests, and Playwright tests on every push and pull request.
Most endpoints return JSON; cover and artwork endpoints return images or PDFs,
and the /play endpoints redirect to DSM or render a small HTML error page.
Package metadata for Help → About Happy Trails, read from the repository's
package.json and normalized for the browser: name, version, description,
author and contributors (each with a name and an optional http(s) URL),
issuesUrl from bugs.url, and homepageUrl. Only http:/https: links are
accepted.
{
"name": "happy-trails",
"version": "4.4.0",
"description": "Browse the Synology mediaserver music library.",
"author": { "name": "Karim Ratib", "url": "https://karimratib.me/" },
"contributors": [
{ "name": "deepseek-v4-flash", "url": "https://platform.deepseek.com/" }
],
"issuesUrl": "https://github.com/infojunkie/happy-trails/issues",
"homepageUrl": "https://github.com/infojunkie/happy-trails#happy-trails"
}Index state and library totals. libraryVersion identifies the current
snapshot; clients compare it with the version of the data they loaded to decide
whether the Refresh control is enabled. albumCount counts albums visible in
the Albums view (loose-track collections are excluded); trackCount counts
every indexed track. pageSize is the effective PAGE_SIZE (clamped by
MAX_PAGE_SIZE), which the client uses for paging and the Play all queue
window. lastCheckedAt and refreshing describe the change-detection loop. playbackEnabled is true when a DSM URL is
configured, i.e. when users can sign in and use the Play links.
screenWakeLockEnabled controls whether the native player may hold a screen
wake lock while it is playing.
{
"ready": true,
"albumCount": 33356,
"trackCount": 410089,
"libraryVersion": 1,
"lastRefreshed": "2026-11-02T12:00:00.000Z",
"lastCheckedAt": "2026-11-02T12:00:30.000Z",
"refreshing": false,
"checkIntervalMs": 60000,
"pageSize": 48,
"error": null,
"playbackEnabled": true,
"nativePlaybackEnabled": true,
"audioStationFallbackEnabled": true,
"screenWakeLockEnabled": true
}All genres, regions, and series with both their album and track counts. The
client displays albumCount in Albums mode and trackCount in Tracks mode;
counts are sorted by album count then name. key is the normalised value
accepted by the matching filter or used by the series radio list.
totalAlbums counts visible albums (loose-track collections are excluded);
libraryVersion identifies the snapshot the counts came from.
albumCount counts visible albums carrying the tag. trackCount counts every
indexed track carrying it: for genres and regions, each track's own tags; for
series, the tracks of albums in that series. Track counts include tracks whose
album is hidden by LOOSE_TRACKS_FOLDERS, so they match the result of the same
filter in Tracks mode. A facet whose every album is hidden has
albumCount: 0 and is not rendered in Albums mode.
{
"totalAlbums": 33356,
"libraryVersion": 1,
"genres": [
{ "key": "jazz", "name": "Jazz", "albumCount": 8726, "trackCount": 91234 }
],
"regions": [
{ "key": "ethiopia", "name": "Ethiopia", "albumCount": 42, "trackCount": 511 }
],
"series": [
{ "key": "rock candy", "name": "Rock Candy", "albumCount": 228, "trackCount": 2954 }
]
}| Parameter | Description |
|---|---|
q |
Search expression, up to 200 characters. Supports plain keyword phrases and album:, artist:, track:, genre:, region:, serie:, composer:, and source: fields with quoted phrases and AND/OR; see Search syntax. Genre and region facets are expressed here too. |
sort |
added (default), released, artist, or album. |
order |
desc (default) or asc. Missing years/dates sort last in both directions. |
offset |
Default 0. |
limit |
Default PAGE_SIZE (48), maximum MAX_PAGE_SIZE (200). |
The response's libraryVersion is the version of the snapshot used for the
listing; compare it with /api/status before deciding to reload.
{
"total": 8726,
"offset": 0,
"limit": 48,
"libraryVersion": 1,
"albums": [
{
"key": "WyJEYW5hbWEiLCJBcmF0IEtpbG8iXQ",
"album": "Danama",
"artist": "Arat Kilo",
"artists": ["Arat Kilo"],
"year": 2025,
"trackCount": 12,
"duration": 3046,
"latest": "2026-10-13T19:25:15",
"genres": ["Jazz", "Funk"],
"regions": ["Ethiopia", "France"],
"series": [],
"comments": ["https://aratkilo.bandcamp.com/album/danama"]
}
]
}duration is in seconds. key is an opaque base64url value identifying the
(album, artist) pair. series lists the series/label names the album belongs
to, in index order. comments contains the album's distinct non-empty track
comments, deduplicated and sorted; the client renders http(s) URLs in them as
external links.
track: is also accepted here: it matches track titles and returns the albums
that contain a matching track, using the track index.
Returns one album summary by the opaque key from the album listing, in the
same shape as an albums[] entry. The track list uses it to open the album
dialog without loading the album listing. Returns 404 for an unknown key.
The q parameter accepts field:value terms. A plain list of keywords searches
all fields as one contiguous phrase, and a single bare term likewise searches
every field. Field values containing spaces or parentheses must be quoted; a
quoted value is matched as a contiguous phrase rather than as separate words.
| Field | Matches |
|---|---|
album |
Merged album title and all raw source titles. |
artist |
Effective album artist, parsed artists, and track-level artists in Albums mode; the track artist or album artist in Tracks mode. |
track |
Track titles. In Albums mode, returns albums that contain a matching track. |
genre |
Genre tags, excluding country/region tags, matched exactly (genres is an alias). |
region |
Country/region tags from the genre column, matched exactly (regions is an alias). |
serie |
Series/label names from {...} groups split on /, plus the first matching SERIES_ALLOWLIST entry found anywhere in a title without braces. Matched exactly. Albums whose title contains a SERIES_DENYLIST entry are omitted entirely. label is an alias. |
composer |
Composer tag values from the FLAC/ID3 metadata (composers is an alias). |
source |
Raw source titles only, such as multi-CD labels (disc is an alias). In Tracks mode, this track's raw source title. |
all / any |
All indexed fields, equivalent to a bare term. |
In Tracks mode, terms are evaluated per track. genre: and region: match
each track's own tags, while serie: remains album-level. The sidebar follows
the mode: album counts in Albums mode, track counts in Tracks mode (labelled
“Count of matching tracks”); both are computed so each count equals what
selecting that filter returns.
A query made only of unquoted keywords is treated as one contiguous phrase:
abbey road behaves like "abbey road". Use abbey AND road to search the
words independently. For expressions containing fields, operators, or quotes,
adjacent terms are implicitly ANDed. Operators are case-insensitive; AND
binds more tightly than OR; parentheses group expressions. Matching is
case-, accent-, and ligature-insensitive, including quoted phrases.
album:"abbey road"
artist:beatles OR artist:stones
genre:"Jazz" region:"Brazil"
composer:"Antonio Carlos Jobim"
serie:"Rock Candy"
(album:road OR album:street) artist:beatles
source:"Vanilla Tapes"
track:"Freddie Freeloader"
Unknown field names are treated as ordinary text, so titles containing colons
still work. An incomplete or malformed expression falls back to the previous
all-field token search. NOT/negation is not supported.
Track-level counterpart to /api/albums, used by the Tracks result list.
| Parameter | Description |
|---|---|
q |
The same search syntax. Bare terms match the track title, artists, source title, composer, album title, the track's own genre/region tags, and album series names. artist: matches the track or album artist; genre: and region: are exact per-track tag filters; serie: is an exact album-level filter. |
sort |
added (default; per-track upload date), released, artist, or album. |
order |
desc (default) or asc. |
offset |
Default 0. |
limit |
Default PAGE_SIZE (48), maximum MAX_PAGE_SIZE (200). |
Each row includes the music.id (the id /play/track/:id accepts), the visible
artist and parsed artists, the album artist, the opaque albumKey and
merged album title, the raw sourceAlbum, disc/track/duration, and this
track's own genres/regions for the pills. genre: and region: filter by
those track tags; serie: remains album-level. Sidebar facet counts are album
counts. An empty q lists every track.
{
"total": 410089,
"offset": 0,
"limit": 48,
"libraryVersion": 1,
"tracks": [
{
"id": 3644554,
"title": "Nahel",
"artist": "Arat Kilo",
"artists": ["Arat Kilo"],
"albumArtist": "Arat Kilo",
"albumKey": "WyJEYW5hbWEiLCJBcmF0IEtpbG8iXQ",
"album": "Danama",
"sourceAlbum": "Danama",
"year": 2025,
"track": 1,
"disc": 0,
"duration": 235,
"genres": ["Jazz", "Funk"],
"regions": ["Ethiopia", "France"]
}
]
}Flat, track-level pages for the Play all queue source.
| Parameter | Description |
|---|---|
mode |
Required. tracks returns tracks matching the query per track; albums selects matching albums and returns all tracks of those albums. |
q |
The same search syntax as /api/albums or /api/tracks. |
sort |
added (default), released, artist, or album. In Albums mode the album sort is applied first, then each album's disc/track order. |
order |
desc (default) or asc. |
offset |
Default 0. Track-level offset. |
limit |
Default PAGE_SIZE (48), maximum MAX_PAGE_SIZE (200). |
The response has the same shape as /api/tracks: total, offset, limit,
tracks, and libraryVersion. total is always a track count, including in
Albums mode. Unknown modes return 400. The client uses this endpoint both for
the first Play all page and for later lazy refills; it never materializes the
full result set.
Returns the tracks of every raw album title merged into the album, ordered by
disc, track number, and title. sourceAlbums lists the raw titles in display
order, each track's sourceAlbum identifies the title it came from,
composer is the nullable track-level composer tag, composers contains the
individual names parsed from it, and matches says whether the track matches
the optional q search expression. genre is the raw track genre tag;
genres and regions split and deduplicate it into display names, using the
same genre/region classification as the album listing. key is the value from
the album listing.
q uses the same syntax as /api/albums; filtering is evaluated per track, so
composer:beatles flags only tracks with a matching composer and
track:"come together" flags only matching track titles.
{
"album": "Danama",
"artist": "Arat Kilo",
"sourceAlbums": ["Danama"],
"tracks": [
{
"id": 3644554,
"title": "Nahel",
"artist": "Arat Kilo",
"artists": ["Arat Kilo"],
"albumArtist": "Arat Kilo",
"composer": null,
"composers": [],
"matches": true,
"sourceAlbum": "Danama",
"genre": "Jazz, Funk, Ethiopia, France",
"genres": ["Jazz", "Funk"],
"regions": ["Ethiopia", "France"],
"year": 2025,
"track": 1,
"disc": 0,
"duration": 235,
"bitrate": 873000,
"frequency": 44100
}
]
}Returns the album artwork as image/jpeg or image/png with
Cache-Control: private, max-age=86400 and an ETag. Returns 404 when the
album has no artwork, covers are not configured, or the path cannot be resolved
to an AudioStation song; 400 for an invalid album key. The client falls back
to its generated cover on any failure.
Streams the full-resolution cover image from the album folder through
FileStation. Synology's AudioStation cover API only exposes a 480px JPEG, even
for view=original; the original is normally Folder.jpg (or a similarly
named image) beside the tracks. The server checks common names such as
Folder.jpg, cover.jpg, front.jpg, and their PNG/JPEG variants, then
streams the first match with Range support. Returns 404 when the album
folder has no recognized cover file, covers are not configured, or the album
has no representative path; 400 for an invalid key. The lightbox falls back
to /api/albums/:key/cover when this endpoint returns an error. The configured
DSM service account needs FileStation read access to the music share.
Returns { "pdfs": [{ "name": "Artwork.pdf", "label": "Artwork" }, ...] } for
every PDF in the album folder, sorted naturally by filename. label is the
filename with its final extension removed. Returns 200 with an empty array
when the album has no representative path, the folder has no PDFs, or DSM is
not configured, and 400 for an invalid album key. The response uses a
five-minute private browser cache.
Streams the named PDF with Content-Type: application/pdf and
Content-Disposition: inline (ASCII fallback plus an RFC 5987 filename), so the
browser opens it in its default PDF viewer. filename must be a single path
segment ending in .pdf; traversal-shaped names return 400. Range requests
are forwarded to FileStation; a 206 response includes Content-Range.
Returns 404 when the PDF is absent or FileStation is not configured and 502
when Synology fails while opening the file. Files are relayed as streams, so
large booklets are not buffered in memory.
GET /api/session returns { "authenticated": boolean, "account": string | null }
for the browser's current DSM session.
POST /api/session/login accepts JSON { "username": "...", "password": "..." },
verifies the credentials with Synology, and sets an HttpOnly mw_session
cookie. Returns { "authenticated": true, "account": "..." }. Incorrect
credentials return 401 with an error message; 2FA accounts are rejected.
Passwords are not written to disk or echoed back.
POST /api/session/logout destroys the server-side session and clears the
cookie.
Streams one track for the native player. Requires a signed-in mw_session.
musicId is the track's music.id; the server maps it to the Audio Station
song id (music_<track.id>) and proxies AudioStation/stream.cgi. Range and
If-Range are forwarded and 206/Content-Range/Accept-Ranges are passed
back, so seeking works. Unknown tracks return 404, an unsigned session 401,
an out-of-range request 416, and a DSM failure 502. Responses are
Cache-Control: private, max-age=3600. The endpoint is unavailable (503) when
NATIVE_PLAYBACK_ENABLED=false.
The Audio Station fallback target for album Play links; it is an HTML/redirect
endpoint rather than JSON. If the browser has no signed-in DSM session, it redirects to
/?login=1&play=… (plus playQuery=… when filtering is active) so the app can
show the sign-in dialog. Otherwise it queues the album in Audio Station using
that user's session (replacing the web-player queue) and redirects 303 to the
Audio Station app. With a q query parameter, only tracks matching that
expression are queued. An invalid key shows an HTML 400 page; a playback
failure shows an HTML error page with a link to Audio Station. This route
changes playback state and is meant to be opened in a browser tab.
The Audio Station fallback target for per-track Play controls. id is the
track's music.id. It follows the same sign-in and redirect flow as the album
Play endpoint, but queues only that track in Audio Station. Signed-out requests redirect to
/?login=1&playTrack=…; invalid ids show an HTML 400 page, and playback
failures show the standard HTML error page. This route changes playback state.
Errors use { "error": "message" }. Unknown API routes return 404;
an album key that cannot be decoded returns 400; a valid key with no rows
returns 404.
happy-trails/
├── src/
│ ├── server/
│ │ ├── about.ts package.json metadata for the Help dialog
│ │ ├── app.ts Express routes and static files
│ │ ├── artists.ts Configurable multi-artist parser
│ │ ├── artwork.ts FileStation PDF listing and original-cover lookup/streaming
│ │ ├── config.ts Environment configuration
│ │ ├── covers.ts Bounded cover cache and cover lookup
│ │ ├── db.ts Pool and SQL queries
│ │ ├── dsm.ts Synology login, covers, FileStation, audio, and web-player client
│ │ ├── index.ts Startup and shutdown
│ │ ├── library.ts Index lifecycle, rebuilds, and change detection
│ │ ├── playback.ts Native stream proxy and Audio Station handoff
│ │ ├── regions.ts Country/region tag detection
│ │ ├── search.ts Folding, album keys, and title normalisation
│ │ ├── searchQuery.ts Fielded search expression parser
│ │ ├── sqlite.ts SQLite schema, bulk load, and query layer
│ │ └── userSessions.ts Per-browser DSM sign-in sessions
│ ├── client/
│ │ ├── api.ts API client
│ │ ├── dom.ts Safe createElement helper
│ │ ├── format.ts Duration/date formatting
│ │ ├── linkify.ts Plain-text comment URL linkification
│ │ ├── main.ts State, rendering, and events
│ │ ├── lightbox.ts Shared full-size cover lightbox
│ │ ├── map.ts Lazy-loaded Leaflet map, cover pins, and full-screen
│ │ ├── player.ts Footer player, preload/advance, queue, and persistence
│ │ └── queueSource.ts Play all source cursor and sliding-window arithmetic
│ └── shared/
│ ├── equalEarth.ts Equal Earth projection formulas
│ ├── placeCatalog.ts Manual cities/regions/overrides and non-place denylist
│ ├── placeLookup.ts Catalog + generated country lookup resolution
│ ├── text.ts Folding and region keys shared with the browser
│ └── types.ts Shared API types and sort keys
├── public/
│ ├── index.html
│ ├── styles.css App stylesheet, linked after the generated vendor CSS
│ ├── client/ Generated esbuild bundle (main.js) and vendor CSS
│ └── map/ Generated country lookup and Natural Earth basemap
├── tests/
│ ├── api/ Express endpoint tests
│ ├── artwork/ FileStation path-mapping tests
│ ├── client/ Pure queue-source/window tests
│ ├── config/ DSM frontend URL parsing tests
│ ├── search/ Parser and SQLite search tests
│ ├── ui/ Playwright browser tests
│ ├── fixtures/ Synthetic album/track data and UI fixture server
│ └── helpers/ Test server, HTTP helpers, and test env isolation
├── Caddyfile Optional LAN reverse proxy with streaming support
├── docs/native-playback.md Native playback design, API findings, and stages
├── .github/workflows/ CI: lint, typecheck, backend and UI tests
├── eslint.config.js ESLint flat config
├── playwright.config.ts Fixture-server-backed browser tests
├── scripts/audit-places.mjs Live region-tag/place-catalog audit
├── scripts/build-client.mjs esbuild bundle, vendor CSS, and license notices
├── scripts/build-place-data.mjs Natural Earth lookup and basemap generator
├── scripts/dev.mjs Runs the client bundler, typecheck, and server watchers
├── tsconfig.test.json Typechecks the test suite
└── .env.example
Cover Flow uses the MIT-licensed
@northstarxyzz/coverflow
component. esbuild bundles it and its stylesheet into
public/client/main.js / main.css; the build also writes the dependency
license and third-party notices to public/third-party-notices.txt.
- The app only issues
SELECTqueries against PostgreSQL; it writes only its disposable SQLite index. - The index contains every album and every track. The sum of the per-album
track counts is checked against the inserted track rows at build time.
Measured on a 410k-track library: about 373 MB on disk, ~43–46 s total
worker build, ~560–600 MB peak build RSS, and ~75 MB steady process
RSS; the OS page cache holds the file and is reclaimable. With
INDEX_DB_DIR=:memory:the index uses ~373 MB of process memory and peaks around 920 MB RSS. A rebuild keeps the old snapshot alive while building the new one; on disk that means two files (~750 MB) and in memory two databases. Re-measure after schema or build-path changes. - In file-backed mode the build runs in a worker thread, so the HTTP event loop
stays responsive. The server listens immediately at startup;
/api/statusreportsready:falseand data endpoints return503until the first worker build finishes. A change-triggered rebuild serves the old snapshot throughout.:memory:mode builds in the main thread. - Change checks are serial: the next check starts
LIBRARY_CHECK_MS(default 60s) after the previous check and any rebuild finish, not on a fixed wall clock, so a long rebuild delays the next check instead of overlapping it. - Open pages poll
/api/statusevery 30s and reuse the old snapshot until the user clicks the enabled Refresh control. A rebuild failure leaves the old snapshot in place and is reported througherror. - Static files are served with ETags. JSON API responses use
Cache-Control: no-store; cover images use a one-day private browser cache, and artwork availability uses five minutes. - Covers require the
tracktable and, if configured, the optional DSM service account. Artwork PDFs require that account plus FileStation read access to the music share. Playback requires thetracktable, aDSM_URL, and each user's own DSM sign-in. If the NAS is unreachable, cover requests fail (the UI keeps its generated placeholders), the Artwork button stays hidden, the native player shows an error in the footer, and the Audio Station fallback shows an HTML error page; the rest of the app is unaffected. - Sign-in sessions live in server memory with an 8-hour TTL; restarting the server signs everyone out. Passwords are kept in memory (inside the user's DSM client) so expired tokens can be renewed, but are never written to disk, logged, or returned to the browser. Two-factor-authenticated DSM accounts are not supported.
- The sign-in form sends credentials to this Node server. It binds to
127.0.0.1by default; if you expose it on a LAN, put it behind HTTPS (for example a reverse proxy) and do not send DSM passwords over plain HTTP. - Native playback depends on the browser's codecs. The library is almost entirely FLAC and MP3, which play in current Chromium and Firefox. WMA files (about 0.08% of the library) are not playable natively; use the Audio Station fallback for them. No server-side transcoding is performed.
- The Audio Station fallback replaces Audio Station's web-player queue under the signed-in user and supports up to 8192 songs. The browser opening Audio Station must also be signed into DSM as that same user to see the queue. Browsers may require one press of Audio Station's Play button because they block autoplay.
GET /play/:keychanges playback state. Do not expose it to untrusted users without adding authentication.- TLS certificate verification for the NAS is disabled by default because DSM
ships a self-signed certificate. Enable it with
DSM_TLS_REJECT_UNAUTHORIZED=trueif your NAS has a trusted certificate. - The server binds to
127.0.0.1by default because the catalogue may expose personal library metadata. SetHOST=0.0.0.0deliberately if LAN access is wanted.




